Elffuss BraidHub

kikocis/continue public

Merge branch 'main' of https://github.com/continuedev/continue into exigow/add-e2e-workaround
Changesetc302a3f43ba7e0fbcfbaf8e734b0612f03fbb72a060de4266bb1792ab6562208
AuthorDallin Romney <dallinromney@gmail.com> · 2025-09-10 18:55 -07:00
CommitterDallin Romney <dallinromney@gmail.com> · 2025-09-10 18:55 -07:00
Parents753e021a1971, 91ef819325d3

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
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 +18 −2
@@ -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,6 +94,13 @@
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: |
@@ -128,14 +136,22 @@
128136 shell: bash
129137 run: |
130138 cd extensions/intellij
131- mv video build/reports
139+ if [ -d "video" ]; then
140+ mv video build/reports
141+ else
142+ echo "No video directory found to move"
143+ fi
132144
133145 - name: Copy logs
134146 if: ${{ failure() }}
135147 shell: bash
136148 run: |
137149 cd extensions/intellij
138- mv build/idea-sandbox/system/log/ build/reports
150+ if [ -d "build/idea-sandbox/system/log/" ]; then
151+ mv build/idea-sandbox/system/log/ build/reports
152+ else
153+ echo "No log directory found to copy"
154+ fi
139155
140156 - name: Save fails report
141157 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@b3f4b82600f603ca28c65a319b80ec36c4644ed7
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@b3f4b82600f603ca28c65a319b80ec36c4644ed7
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 +31 −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 }}
@@ -172,16 +189,25 @@
172189 package: ${{ fromJson(needs.get-packages-matrix.outputs.packages) }}
173190 steps:
174191 - uses: actions/checkout@v5
192+ with:
193+ fetch-depth: 0 # Needed for git diff to work
175194 - name: Setup packages
176195 uses: ./.github/actions/setup-packages
177196
197+ - name: Check if LLM-related files changed
198+ id: llm-changes
199+ uses: ./.github/actions/check-llm-changes
200+ with:
201+ is_fork: ${{ github.event.pull_request.head.repo.fork == true }}
202+ is_dependabot: ${{ github.actor == 'dependabot[bot]' }}
203+
178204 - name: Test and check ${{ matrix.package }}
179205 run: |
180206 cd packages/${{ matrix.package }}
181207 npm ci
182208 npm test
183209 env:
184- IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}
210+ IGNORE_API_KEY_TESTS: ${{ steps.llm-changes.outputs.ignore_api_tests }}
185211 OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
186212 ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
187213 GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
@@ -198,7 +224,7 @@
198224 test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
199225 steps:
200226 - uses: actions/checkout@v5
201- - uses: actions/setup-node@v4
227+ - uses: actions/setup-node@v5
202228 with:
203229 node-version-file: ".nvmrc"
204230
@@ -316,7 +342,7 @@
316342 runs-on: ubuntu-latest
317343 steps:
318344 - uses: actions/checkout@v5
319- - uses: actions/setup-node@v4
345+ - uses: actions/setup-node@v5
320346 with:
321347 node-version: 20
322348
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
added .github/workflows/respond-to-cubic.yaml +277 −0
@@ -0,0 +1,277 @@
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+ if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
25+ echo "contains_mention=true" >> $GITHUB_OUTPUT
26+ else
27+ echo "contains_mention=false" >> $GITHUB_OUTPUT
28+ fi
29+
30+ - name: Add eyes reaction to comment
31+ if: steps.check-mention.outputs.contains_mention == 'true'
32+ uses: actions/github-script@v8
33+ with:
34+ script: |
35+ await github.rest.reactions.createForIssueComment({
36+ owner: context.repo.owner,
37+ repo: context.repo.repo,
38+ comment_id: ${{ github.event.comment.id }},
39+ content: 'eyes'
40+ });
41+
42+ - name: Checkout PR branch
43+ if: steps.check-mention.outputs.contains_mention == 'true'
44+ uses: actions/checkout@v5
45+ with:
46+ token: ${{ secrets.GITHUB_TOKEN }}
47+ fetch-depth: 0
48+
49+ - name: Get PR information
50+ if: steps.check-mention.outputs.contains_mention == 'true'
51+ id: pr-info
52+ uses: actions/github-script@v8
53+ with:
54+ script: |
55+ const { data: pr } = await github.rest.pulls.get({
56+ owner: context.repo.owner,
57+ repo: context.repo.repo,
58+ pull_number: context.issue.number
59+ });
60+
61+ core.setOutput('head_ref', pr.head.ref);
62+ core.setOutput('head_sha', pr.head.sha);
63+ return pr;
64+
65+ - name: Checkout PR branch
66+ if: steps.check-mention.outputs.contains_mention == 'true'
67+ run: |
68+ git checkout ${{ steps.pr-info.outputs.head_ref }}
69+
70+ - name: Setup Node.js
71+ if: steps.check-mention.outputs.contains_mention == 'true'
72+ uses: actions/setup-node@v5
73+ with:
74+ node-version: "20"
75+
76+ - name: Install Continue CLI globally
77+ if: steps.check-mention.outputs.contains_mention == 'true'
78+ run: npm i -g @continuedev/cli
79+
80+ - name: Start remote session
81+ if: steps.check-mention.outputs.contains_mention == 'true'
82+ id: remote-session
83+ env:
84+ CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
85+ run: |
86+ # Create the prompt for remote session
87+ PROMPT="Please help with the following request from @${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}:
88+
89+ ${{ github.event.comment.body }}
90+
91+ Please analyze the current PR, understand the request, implement the necessary changes, and commit them to this branch."
92+
93+ # Start remote session and capture JSON output
94+ SESSION_OUTPUT=$(echo "$PROMPT" | cn remote -s --config continuedev/address-code-review --branch ${{ steps.pr-info.outputs.head_ref }})
95+ echo "Raw session output: $SESSION_OUTPUT"
96+
97+ # Extract URL from JSON output
98+ SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty')
99+
100+ if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then
101+ echo "Failed to extract session URL from output: $SESSION_OUTPUT"
102+ exit 1
103+ fi
104+
105+ echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT
106+ echo "✅ Started remote session: $SESSION_URL"
107+
108+ - name: Comment with session URL
109+ if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
110+ uses: actions/github-script@v8
111+ with:
112+ script: |
113+ const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
114+ > ${{ github.event.comment.body }}`;
115+
116+ await github.rest.issues.createComment({
117+ owner: context.repo.owner,
118+ repo: context.repo.repo,
119+ issue_number: context.issue.number,
120+ body: commentBody
121+ });
122+
123+ - name: Log session details
124+ if: steps.check-mention.outputs.contains_mention == 'true'
125+ run: |
126+ echo "✅ Successfully started remote session for comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}"
127+ echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
128+ echo "Original comment: ${{ github.event.comment.body }}"
129+
130+ respond-to-review-comment:
131+ # Only run on pull request review comments
132+ if: github.event_name == 'pull_request_review_comment'
133+ runs-on: ubuntu-latest
134+
135+ steps:
136+ - name: Check if comment contains @continuedev
137+ id: check-mention
138+ run: |
139+ if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
140+ echo "contains_mention=true" >> $GITHUB_OUTPUT
141+ else
142+ echo "contains_mention=false" >> $GITHUB_OUTPUT
143+ fi
144+
145+ - name: Add eyes reaction to comment
146+ if: steps.check-mention.outputs.contains_mention == 'true'
147+ uses: actions/github-script@v8
148+ with:
149+ script: |
150+ await github.rest.reactions.createForPullRequestReviewComment({
151+ owner: context.repo.owner,
152+ repo: context.repo.repo,
153+ comment_id: ${{ github.event.comment.id }},
154+ content: 'eyes'
155+ });
156+
157+ - name: Checkout PR branch
158+ if: steps.check-mention.outputs.contains_mention == 'true'
159+ uses: actions/checkout@v5
160+ with:
161+ token: ${{ secrets.GITHUB_TOKEN }}
162+ fetch-depth: 0
163+ ref: ${{ github.event.pull_request.head.ref }}
164+
165+ - name: Setup Node.js
166+ if: steps.check-mention.outputs.contains_mention == 'true'
167+ uses: actions/setup-node@v5
168+ with:
169+ node-version: "20"
170+
171+ - name: Install Continue CLI globally
172+ if: steps.check-mention.outputs.contains_mention == 'true'
173+ run: npm i -g @continuedev/cli
174+
175+ - name: Get review context
176+ if: steps.check-mention.outputs.contains_mention == 'true'
177+ id: review-context
178+ uses: actions/github-script@v8
179+ with:
180+ script: |
181+ let reviewContext = '';
182+
183+ // Check if this comment is a reply to another review comment
184+ if (context.payload.comment.in_reply_to_id) {
185+ try {
186+ const { data: originalComment } = await github.rest.pulls.getReviewComment({
187+ owner: context.repo.owner,
188+ repo: context.repo.repo,
189+ comment_id: context.payload.comment.in_reply_to_id
190+ });
191+
192+ reviewContext = `**Original review comment by @${originalComment.user.login}:**
193+ ${originalComment.body}
194+
195+ **Reply by @${{ github.event.comment.user.login }}:**
196+ ${{ github.event.comment.body }}`;
197+ } catch (error) {
198+ console.log('Could not fetch original comment, using current comment only');
199+ reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:**
200+ ${{ github.event.comment.body }}`;
201+ }
202+ } else {
203+ reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:**
204+ ${{ github.event.comment.body }}`;
205+ }
206+
207+ core.setOutput('context', reviewContext);
208+
209+ - name: Start remote session
210+ if: steps.check-mention.outputs.contains_mention == 'true'
211+ id: remote-session
212+ env:
213+ CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
214+ run: |
215+ # Debug: Echo the branch we're starting the session on
216+ echo "Starting remote session on branch: ${{ github.event.pull_request.head.ref }}"
217+
218+ # Create a temporary file for the prompt to handle special characters and newlines properly
219+ cat > /tmp/prompt.txt << 'PROMPT_EOF'
220+ Please help with the following code review discussion from PR #${{ github.event.pull_request.number }}:
221+
222+ **File:** ${{ github.event.comment.path }}
223+ **Line:** ${{ github.event.comment.line || github.event.comment.original_line || 'N/A' }}
224+
225+ ${{ steps.review-context.outputs.context }}
226+
227+ 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.
228+ PROMPT_EOF
229+
230+ # Debug output
231+ echo "PROMPT content:"
232+ cat /tmp/prompt.txt
233+
234+ # Start remote session and capture JSON output
235+ echo "Starting cn with prompt..."
236+ SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --config continuedev/address-code-review --branch ${{ github.event.pull_request.head.ref }})
237+ echo "Raw session output: $SESSION_OUTPUT"
238+
239+ # Extract URL from JSON output
240+ SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty')
241+
242+ if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then
243+ echo "Failed to extract session URL from output: $SESSION_OUTPUT"
244+ exit 1
245+ fi
246+
247+ echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT
248+ echo "✅ Started remote session: $SESSION_URL"
249+
250+ - name: Comment with session URL
251+ if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
252+ uses: actions/github-script@v8
253+ with:
254+ script: |
255+ const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
256+ > ${{ github.event.comment.body }}`;
257+
258+ const commentParams = {
259+ owner: context.repo.owner,
260+ repo: context.repo.repo,
261+ pull_number: ${{ github.event.pull_request.number }},
262+ body: commentBody,
263+ commit_id: '${{ github.event.pull_request.head.sha }}',
264+ path: '${{ github.event.comment.path }}',
265+ in_reply_to: ${{ github.event.comment.id }}
266+ };
267+
268+ await github.rest.pulls.createReviewComment(commentParams);
269+
270+ - name: Log session details
271+ if: steps.check-mention.outputs.contains_mention == 'true'
272+ run: |
273+ echo "✅ Successfully started remote session for review comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}"
274+ echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
275+ echo "File: ${{ github.event.comment.path }}"
276+ echo "Line: ${{ github.event.comment.line }}"
277+ echo "Original comment: ${{ github.event.comment.body }}"
modified .github/workflows/reusable-release.yml +4 −1
@@ -51,8 +51,11 @@
5151 with:
5252 fetch-depth: 0
5353
54+ - name: Setup packages
55+ uses: ./.github/actions/setup-packages
56+
5457 - name: Use Node.js from .nvmrc
55- uses: actions/setup-node@v4
58+ uses: actions/setup-node@v5
5659 with:
5760 node-version-file: ".nvmrc"
5861
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 +43 −0
@@ -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": "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 +62 −0
@@ -311,6 +311,68 @@
311311 "close": true,
312312 "focus": false
313313 }
314+ },
315+ {
316+ "label": "cli:build",
317+ "type": "npm",
318+ "script": "build",
319+ "group": "build",
320+ "presentation": {
321+ "echo": true,
322+ "reveal": "silent",
323+ "focus": false,
324+ "panel": "shared",
325+ "showReuseMessage": true,
326+ "clear": false
327+ },
328+ "problemMatcher": ["$tsc"],
329+ "options": {
330+ "cwd": "${workspaceFolder}/extensions/cli"
331+ }
332+ },
333+ {
334+ "label": "cli:test",
335+ "type": "npm",
336+ "script": "test",
337+ "group": "test",
338+ "presentation": {
339+ "echo": true,
340+ "reveal": "always",
341+ "focus": false,
342+ "panel": "shared",
343+ "showReuseMessage": true,
344+ "clear": false
345+ },
346+ "options": {
347+ "cwd": "${workspaceFolder}/extensions/cli"
348+ }
349+ },
350+ {
351+ "label": "watch-logs",
352+ "type": "shell",
353+ "command": "npm run watch:logs",
354+ "isBackground": true,
355+ "problemMatcher": {
356+ "pattern": {
357+ "regexp": "^$",
358+ "file": 1,
359+ "location": 2,
360+ "message": 3
361+ },
362+ "background": {
363+ "activeOnStart": true,
364+ "beginsPattern": "^.*$",
365+ "endsPattern": "^.*$"
366+ }
367+ },
368+ "presentation": {
369+ "reveal": "always",
370+ "panel": "new",
371+ "focus": false
372+ },
373+ "options": {
374+ "cwd": "${workspaceFolder}/extensions/cli"
375+ }
314376 }
315377 ]
316378 }
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 +78 −8
@@ -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
@@ -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,6 +157,24 @@
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."
@@ -163,8 +186,55 @@
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()
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/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,
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 +40 −59
@@ -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,
@@ -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,21 @@
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+ const orgPolicy = PolicySingleton.getInstance().policy;
549+ if (orgPolicy?.policy?.allowMcpServers === false) {
550+ await mcpManager.shutdown();
551+ } else {
552+ mcpManager.setConnections(
553+ (config.experimental?.modelContextProtocolServers ?? []).map(
554+ (server, index) => ({
555+ id: `continue-mcp-server-${index + 1}`,
556+ name: `MCP Server`,
557+ ...server,
558+ }),
559+ ),
560+ false,
561+ );
562+ }
583563
584564 // Handle experimental modelRole config values for apply and edit
585565 const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;
@@ -654,6 +634,7 @@
654634 apiKeyLocation: llm.apiKeyLocation,
655635 envSecretLocations: llm.envSecretLocations,
656636 sourceFile: llm.sourceFile,
637+ isFromAutoDetect: llm.isFromAutoDetect,
657638 };
658639 }
659640
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 −22
@@ -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
@@ -285,6 +278,9 @@
285278 rules: newConfig.rules,
286279 enableExperimentalTools:
287280 newConfig.experimental?.enableExperimentalTools ?? false,
281+ isSignedIn,
282+ isRemote: await ide.isWorkspaceRemote(),
283+ modelName: newConfig.selectedModelByRole.chat?.model,
288284 }),
289285 );
290286
@@ -333,12 +329,14 @@
333329 }
334330 }
335331
336- if (
337- PolicySingleton.getInstance().policy?.policy?.allowAnonymousTelemetry ===
338- false
339- ) {
332+ // Org policies
333+ const policy = PolicySingleton.getInstance().policy?.policy;
334+ if (policy?.allowAnonymousTelemetry === false) {
340335 newConfig.allowAnonymousTelemetry = false;
341336 }
337+ if (policy?.allowCodebaseIndexing === false) {
338+ newConfig.disableIndexing = true;
339+ }
342340
343341 // Setup telemetry only after (and if) we know it is enabled
344342 await Telemetry.setup(
@@ -373,7 +371,7 @@
373371 const useOnPremProxy =
374372 controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl;
375373
376- const env = await getControlPlaneEnv(ideSettingsPromise);
374+ const env = await getControlPlaneEnv(Promise.resolve(ideSettings));
377375 let controlPlaneProxyUrl: string = useOnPremProxy
378376 ? controlPlane?.proxyUrl
379377 : 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/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 +31 −62
@@ -14,18 +14,8 @@
1414 } from "@continuedev/config-yaml";
1515 import { dirname } from "node:path";
1616
17-import {
18- ContinueConfig,
19- IContextProvider,
20- IDE,
21- IdeInfo,
22- IdeSettings,
23- ILLMLogger,
24-} from "../..";
17+import { ContinueConfig, IDE, IdeInfo, IdeSettings, ILLMLogger } from "../..";
2518 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";
2919 import { ControlPlaneClient } from "../../control-plane/client";
3020 import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
3121 import { getAllPromptFiles } from "../../promptFiles/getPromptFiles";
@@ -35,8 +25,10 @@
3525 import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
3626 import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
3727 import { getControlPlaneEnvSync } from "../../control-plane/env";
38-import { getToolsForIde } from "../../tools";
28+import { PolicySingleton } from "../../control-plane/PolicySingleton";
29+import { getBaseToolDefinitions } from "../../tools";
3930 import { getCleanUriPath } from "../../util/uri";
31+import { loadConfigContextProviders } from "../loadContextProviders";
4032 import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
4133 import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks";
4234 import { LocalPlatformClient } from "./LocalPlatformClient";
@@ -177,7 +169,7 @@
177169
178170 const continueConfig: ContinueConfig = {
179171 slashCommands: [],
180- tools: await getToolsForIde(ide),
172+ tools: getBaseToolDefinitions(),
181173 mcpServerStatuses: [],
182174 contextProviders: [],
183175 modelsByRole: {
@@ -376,60 +368,37 @@
376368 });
377369 }
378370
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,
371+ const { providers, errors: contextErrors } = loadConfigContextProviders(
372+ config.context,
373+ !!config.docs?.length,
374+ ideInfo.ideType,
384375 );
385376
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- }
377+ continueConfig.contextProviders = providers;
378+ localErrors.push(...contextErrors);
415379
416380 // Trigger MCP server refreshes (Config is reloaded again once connected!)
417381 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- );
382+ const orgPolicy = PolicySingleton.getInstance().policy;
383+ if (orgPolicy?.policy?.allowMcpServers === false) {
384+ await mcpManager.shutdown();
385+ } else {
386+ mcpManager.setConnections(
387+ (config.mcpServers ?? []).map((server) => ({
388+ id: server.name,
389+ name: server.name,
390+ sourceFile: server.sourceFile,
391+ transport: {
392+ type: "stdio",
393+ args: [],
394+ ...(server as any), // TODO: fix the types on mcpServers in config-yaml
395+ },
396+ timeout: server.connectionTimeout,
397+ })),
398+ false,
399+ { ide },
400+ );
401+ }
433402
434403 return { config: continueConfig, errors: localErrors };
435404 }
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 +4 −1
@@ -32,12 +32,14 @@
3232 ideSettings,
3333 llmLogger,
3434 config,
35+ isFromAutoDetect,
3536 }: {
3637 model: ModelConfig;
3738 uniqueId: string;
3839 ideSettings: IdeSettings;
3940 llmLogger: ILLMLogger;
4041 config: ContinueConfig;
42+ isFromAutoDetect?: boolean;
4143 }): Promise<BaseLLM | undefined> {
4244 const cls = getModelClass(model);
4345
@@ -71,6 +73,7 @@
7173 nextEdit: model.capabilities?.includes("next_edit"),
7274 },
7375 autocompleteOptions: model.autocompleteOptions,
76+ isFromAutoDetect,
7477 };
7578
7679 // Model capabilities - need to be undefined if not found
@@ -173,7 +176,6 @@
173176 if (modelName === AUTODETECT) {
174177 return undefined;
175178 }
176-
177179 return await modelConfigToBaseLLM({
178180 model: {
179181 ...model,
@@ -184,6 +186,7 @@
184186 ideSettings,
185187 llmLogger,
186188 config,
189+ isFromAutoDetect: true,
187190 });
188191 }),
189192 );
modified core/context/mcp/MCPConnection.ts +23 −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,
@@ -393,6 +392,11 @@
393392 case "websocket":
394393 return new WebSocketClientTransport(new URL(options.transport.url));
395394 case "sse":
395+ const sseAgent =
396+ options.transport.requestOptions?.verifySsl === false
397+ ? new HttpsAgent({ rejectUnauthorized: false })
398+ : undefined;
399+
396400 return new SSEClientTransport(new URL(options.transport.url), {
397401 eventSourceInit: {
398402 fetch: (input, init) =>
@@ -404,17 +408,27 @@
404408 | Record<string, string>
405409 | undefined),
406410 },
411+ ...(sseAgent && { agent: sseAgent }),
407412 }),
408413 },
409- requestInit: { headers: options.transport.requestOptions?.headers },
414+ requestInit: {
415+ headers: options.transport.requestOptions?.headers,
416+ ...(sseAgent && { agent: sseAgent }),
417+ },
410418 });
411419 case "streamable-http":
412- return new StreamableHTTPClientTransport(
413- new URL(options.transport.url),
414- {
415- requestInit: { headers: options.transport.requestOptions?.headers },
420+ const { url, requestOptions } = options.transport;
421+ const streamableAgent =
422+ requestOptions?.verifySsl === false
423+ ? new HttpsAgent({ rejectUnauthorized: false })
424+ : undefined;
425+
426+ return new StreamableHTTPClientTransport(new URL(url), {
427+ requestInit: {
428+ headers: requestOptions?.headers,
429+ ...(streamableAgent && { agent: streamableAgent }),
416430 },
417- );
431+ });
418432 default:
419433 throw new Error(
420434 `Unsupported transport type: ${(options.transport as any).type}`,
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/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 +4 −5
@@ -11,7 +11,7 @@
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 { IDE, ModelDescription } from "../index.js";
1515 import { Logger } from "../util/Logger.js";
1616
1717 import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js";
@@ -44,8 +44,7 @@
4444 export class ControlPlaneClient {
4545 constructor(
4646 readonly sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
47- private readonly ideSettingsPromise: Promise<IdeSettings>,
48- private readonly ideInfoPromise: Promise<IdeInfo>,
47+ private readonly ide: IDE,
4948 ) {}
5049
5150 async resolveFQSNs(
@@ -90,9 +89,9 @@
9089 throw new Error("No access token");
9190 }
9291
93- const env = await getControlPlaneEnv(this.ideSettingsPromise);
92+ const env = await getControlPlaneEnv(this.ide.getIdeSettings());
9493 const url = new URL(path, env.CONTROL_PLANE_URL).toString();
95- const ideInfo = await this.ideInfoPromise;
94+ const ideInfo = await this.ide.getIdeInfo();
9695
9796 const resp = await fetch(url, {
9897 ...init,
modified core/core.ts +69 −21
@@ -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";
@@ -30,8 +29,9 @@
3029 import { Telemetry } from "./util/posthog";
3130 import {
3231 isProcessBackgrounded,
32+ killTerminalProcess,
3333 markProcessAsBackgrounded,
34-} from "./util/processTerminalBackgroundStates";
34+} from "./util/processTerminalStates";
3535 import { getSymbolsForManyFiles } from "./util/treeSitter";
3636 import { TTS } from "./util/tts";
3737
@@ -51,6 +51,7 @@
5151 import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
5252 import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
5353 import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
54+import { createNewAssistantFile } from "./config/createNewAssistantFile";
5455 import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
5556 import { CodebaseRulesCache } from "./config/markdown/loadCodebaseRules";
5657 import {
@@ -138,7 +139,7 @@
138139
139140 const ideInfoPromise = messenger.request("getIdeInfo", undefined);
140141 const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
141- const sessionInfoPromise = messenger.request(
142+ const initialSessionInfoPromise = messenger.request(
142143 "getControlPlaneSessionInfo",
143144 {
144145 silent: true,
@@ -148,9 +149,8 @@
148149
149150 this.configHandler = new ConfigHandler(
150151 this.ide,
151- ideSettingsPromise,
152152 this.llmLogger,
153- sessionInfoPromise,
153+ initialSessionInfoPromise,
154154 );
155155
156156 this.docsService = DocsService.createSingleton(
@@ -175,6 +175,13 @@
175175 }
176176 };
177177
178+ this.codeBaseIndexer = new CodebaseIndexer(
179+ this.configHandler,
180+ this.ide,
181+ this.messenger,
182+ this.globalContext.get("indexingPaused"),
183+ );
184+
178185 this.configHandler.onConfigUpdate((result) => {
179186 void (async () => {
180187 const serializedResult =
@@ -187,6 +194,12 @@
187194 selectedOrgId: this.configHandler.currentOrg?.id ?? null,
188195 });
189196
197+ if (await this.codeBaseIndexer.wasAnyOneIndexAdded()) {
198+ await this.codeBaseIndexer.refreshCodebaseIndex(
199+ await this.ide.getWorkspaceDirs(),
200+ );
201+ }
202+
190203 // update additional submenu context providers registered via VSCode API
191204 const additionalProviders =
192205 this.configHandler.getAdditionalSubmenuContextProviders();
@@ -198,13 +211,6 @@
198211 })();
199212 });
200213
201- this.codeBaseIndexer = new CodebaseIndexer(
202- this.configHandler,
203- this.ide,
204- this.messenger,
205- this.globalContext.get("indexingPaused"),
206- );
207-
208214 // Dev Data Logger
209215 const dataLogger = DataLogger.getInstance();
210216 dataLogger.core = this;
@@ -354,6 +360,13 @@
354360 );
355361 });
356362
363+ on("config/newAssistantFile", async (msg) => {
364+ await createNewAssistantFile(this.ide, undefined);
365+ await this.configHandler.reloadConfig(
366+ "Assistant file created (config/newAssistantFile message)",
367+ );
368+ });
369+
357370 on("config/addLocalWorkspaceBlock", async (msg) => {
358371 await createNewWorkspaceBlockFile(this.ide, msg.data.blockType);
359372 await this.configHandler.reloadConfig(
@@ -661,6 +674,8 @@
661674 return queue.dequeueProcessed() || null;
662675 });
663676
677+ // NOTE: This is not used unless prefetch is used.
678+ // At this point this is not used because I opted to rely on the model to return multiple diffs than to use prefetching.
664679 on("nextEdit/queue/processOne", async (msg) => {
665680 console.log("nextEdit/queue/processOne");
666681 const { ctx, recentlyVisitedRanges, recentlyEditedRanges } = msg.data;
@@ -959,6 +974,10 @@
959974 on("docs/getDetails", async (msg) => {
960975 return await this.docsService.getDetails(msg.data.startUrl);
961976 });
977+ on("docs/getIndexedPages", async (msg) => {
978+ const pages = await this.docsService.getIndexedPages(msg.data.startUrl);
979+ return Array.from(pages);
980+ });
962981
963982 on("didChangeSelectedProfile", async (msg) => {
964983 if (msg.data.id) {
@@ -996,6 +1015,37 @@
9961015 this.handleToolCall(toolCall),
9971016 );
9981017
1018+ on(
1019+ "tools/evaluatePolicy",
1020+ async ({ data: { toolName, basePolicy, args } }) => {
1021+ const { config } = await this.configHandler.loadConfig();
1022+ if (!config) {
1023+ throw new Error("Config not loaded");
1024+ }
1025+
1026+ const tool = config.tools.find((t) => t.function.name === toolName);
1027+ if (!tool) {
1028+ // Tool not found, return base policy
1029+ return { policy: basePolicy };
1030+ }
1031+
1032+ // Extract display value for specific tools
1033+ let displayValue: string | undefined;
1034+ if (toolName === "runTerminalCommand" && args.command) {
1035+ displayValue = args.command as string;
1036+ }
1037+
1038+ // If tool has evaluateToolCallPolicy function, use it
1039+ if (tool.evaluateToolCallPolicy) {
1040+ const evaluatedPolicy = tool.evaluateToolCallPolicy(basePolicy, args);
1041+ return { policy: evaluatedPolicy, displayValue };
1042+ }
1043+
1044+ // Otherwise return base policy unchanged
1045+ return { policy: basePolicy, displayValue };
1046+ },
1047+ );
1048+
9991049 on("isItemTooBig", async ({ data: { item } }) => {
10001050 return this.isItemTooBig(item);
10011051 });
@@ -1013,6 +1063,10 @@
10131063 },
10141064 );
10151065
1066+ on("process/killTerminalProcess", async ({ data: { toolCallId } }) => {
1067+ await killTerminalProcess(toolCallId);
1068+ });
1069+
10161070 on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
10171071 const isValid = setMdmLicenseKey(licenseKey);
10181072 return isValid;
@@ -1273,15 +1327,9 @@
12731327 throw new Error("No chat model selected");
12741328 }
12751329
1276- const provider =
1277- config.contextProviders?.find(
1278- (provider) => provider.description.title === name,
1279- ) ??
1280- [
1281- // user doesn't need these in their config.json for the shortcuts to work
1282- // option+enter
1283- new CurrentFileContextProvider({}),
1284- ].find((provider) => provider.description.title === name);
1330+ const provider = config.contextProviders?.find(
1331+ (provider) => provider.description.title === name,
1332+ );
12851333 if (!provider) {
12861334 return [];
12871335 }
modified core/edit/recursiveStream.ts +0 −1
@@ -8,7 +8,6 @@
88 const DUD_PROMPT_LOG: PromptLog = {
99 modelTitle: "",
1010 modelProvider: "",
11- completionOptions: { model: "" },
1211 prompt: "",
1312 completion: "",
1413 };
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-});
deleted core/edit/searchAndReplace/findSearchMatch.ts +0 −359
@@ -1,359 +0,0 @@
1-/**
2- * Represents a basic match result with start and end character positions
3- */
4-interface BasicMatchResult {
5- /** The starting character index of the match in the file content */
6- startIndex: number;
7- /** The ending character index of the match in the file content */
8- endIndex: number;
9-}
10-
11-/**
12- * Represents a match result with start and end character positions
13- */
14-export interface SearchMatchResult extends BasicMatchResult {
15- /** The name of the strategy that successfully matched */
16- strategyName: string;
17-}
18-
19-/**
20- * Strategy function type for finding matches
21- */
22-type MatchStrategy = (
23- fileContent: string,
24- searchContent: string,
25-) => BasicMatchResult | null;
26-
27-/**
28- * Exact string matching strategy
29- */
30-function exactMatch(
31- fileContent: string,
32- searchContent: string,
33-): BasicMatchResult | null {
34- const exactIndex = fileContent.indexOf(searchContent);
35- if (exactIndex !== -1) {
36- return {
37- startIndex: exactIndex,
38- endIndex: exactIndex + searchContent.length,
39- };
40- }
41- return null;
42-}
43-
44-/**
45- * Trimmed content matching strategy
46- * Finds content where the search content (when trimmed) matches content in the file,
47- * and returns the span that includes the file content's whitespace
48- */
49-function trimmedMatch(
50- fileContent: string,
51- searchContent: string,
52-): BasicMatchResult | null {
53- 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++;
82- }
83-
84- return {
85- startIndex,
86- endIndex,
87- };
88-}
89-
90-/**
91- * Whitespace-ignored matching strategy
92- * Removes all whitespace from both content and search, then finds the match
93- */
94-function whitespaceIgnoredMatch(
95- fileContent: string,
96- searchContent: string,
97-): BasicMatchResult | null {
98- // Remove all whitespace (spaces, tabs, newlines, etc.)
99- const strippedFileContent = fileContent.replace(/\s/g, "");
100- const strippedSearchContent = searchContent.replace(/\s/g, "");
101-
102- if (strippedSearchContent === "") {
103- return null; // Empty search after stripping whitespace
104- }
105-
106- const strippedIndex = strippedFileContent.indexOf(strippedSearchContent);
107- if (strippedIndex === -1) {
108- return null;
109- }
110-
111- // Map the stripped position back to the original file content
112- let originalStartIndex = 0;
113- let strippedCharCount = 0;
114-
115- // Find the original position by counting non-whitespace characters
116- for (let i = 0; i < fileContent.length; i++) {
117- if (strippedCharCount === strippedIndex) {
118- originalStartIndex = i;
119- break;
120- }
121- if (!/\s/.test(fileContent[i])) {
122- strippedCharCount++;
123- }
124- }
125-
126- // Find the end position by counting the length of the search content
127- let originalEndIndex = originalStartIndex;
128- let matchedChars = 0;
129-
130- for (
131- let i = originalStartIndex;
132- i < fileContent.length && matchedChars < strippedSearchContent.length;
133- i++
134- ) {
135- if (!/\s/.test(fileContent[i])) {
136- matchedChars++;
137- }
138- originalEndIndex = i + 1;
139- }
140-
141- return {
142- startIndex: originalStartIndex,
143- endIndex: originalEndIndex,
144- };
145-}
146-
147-/**
148- * Calculate the Jaro similarity between two strings
149- */
150-function jaroSimilarity(s1: string, s2: string): number {
151- if (s1 === s2) return 1.0;
152- if (s1.length === 0 || s2.length === 0) return 0.0;
153-
154- const matchDistance = Math.floor(Math.max(s1.length, s2.length) / 2) - 1;
155- if (matchDistance < 0) return 0.0;
156-
157- const s1Matches = new Array(s1.length).fill(false);
158- const s2Matches = new Array(s2.length).fill(false);
159-
160- let matches = 0;
161- let transpositions = 0;
162-
163- // Find matches
164- for (let i = 0; i < s1.length; i++) {
165- const start = Math.max(0, i - matchDistance);
166- const end = Math.min(i + matchDistance + 1, s2.length);
167-
168- for (let j = start; j < end; j++) {
169- if (s2Matches[j] || s1[i] !== s2[j]) continue;
170- s1Matches[i] = true;
171- s2Matches[j] = true;
172- matches++;
173- break;
174- }
175- }
176-
177- if (matches === 0) return 0.0;
178-
179- // Count transpositions
180- let k = 0;
181- for (let i = 0; i < s1.length; i++) {
182- if (!s1Matches[i]) continue;
183- while (!s2Matches[k]) k++;
184- if (s1[i] !== s2[k]) transpositions++;
185- k++;
186- }
187-
188- return (
189- (matches / s1.length +
190- matches / s2.length +
191- (matches - transpositions / 2) / matches) /
192- 3.0
193- );
194-}
195-
196-/**
197- * Calculate the Jaro-Winkler similarity between two strings
198- */
199-function jaroWinklerSimilarity(
200- s1: string,
201- s2: string,
202- prefixScale = 0.1,
203-): number {
204- const jaroSim = jaroSimilarity(s1, s2);
205-
206- if (jaroSim < 0.7) return jaroSim;
207-
208- // Calculate common prefix length (up to 4 characters)
209- let prefixLength = 0;
210- const maxPrefix = Math.min(4, Math.min(s1.length, s2.length));
211-
212- for (let i = 0; i < maxPrefix; i++) {
213- if (s1[i] === s2[i]) {
214- prefixLength++;
215- } else {
216- break;
217- }
218- }
219-
220- return jaroSim + prefixLength * prefixScale * (1 - jaroSim);
221-}
222-
223-/**
224- * Find the best fuzzy match for search content in file content using Jaro-Winkler
225- */
226-function findFuzzyMatch(
227- fileContent: string,
228- searchContent: string,
229- threshold: number = 0.9,
230-): BasicMatchResult | null {
231- const searchLines = searchContent.split("\n");
232- const fileLines = fileContent.split("\n");
233-
234- let bestMatch: BasicMatchResult | null = null;
235- let bestSimilarity = 0;
236-
237- // Try matching the search content as a whole block
238- const searchBlock = searchContent.trim();
239- if (searchBlock.length > 5) {
240- // Require minimum length for meaningful matches
241- // Use sliding window approach for multi-line search
242- for (let i = 0; i <= fileLines.length - searchLines.length; i++) {
243- const candidateLines = fileLines.slice(i, i + searchLines.length);
244- const candidateBlock = candidateLines.join("\n").trim();
245-
246- if (candidateBlock.length < 5) continue; // Skip very short blocks
247-
248- const similarity = jaroWinklerSimilarity(searchBlock, candidateBlock);
249-
250- if (similarity >= threshold && similarity > bestSimilarity) {
251- // Calculate character positions
252- const linesBeforeMatch = fileLines.slice(0, i);
253- const startIndex =
254- linesBeforeMatch.join("\n").length +
255- (linesBeforeMatch.length > 0 ? 1 : 0);
256- const endIndex = startIndex + candidateBlock.length;
257-
258- bestMatch = {
259- startIndex,
260- endIndex,
261- };
262- bestSimilarity = similarity;
263- }
264- }
265- }
266-
267- // Also try line-by-line matching for better granularity
268- for (
269- let searchLineIdx = 0;
270- searchLineIdx < searchLines.length;
271- searchLineIdx++
272- ) {
273- const searchLine = searchLines[searchLineIdx].trim();
274- if (searchLine.length === 0 || searchLine.length < 3) continue; // Skip very short lines
275-
276- for (let fileLineIdx = 0; fileLineIdx < fileLines.length; fileLineIdx++) {
277- const fileLine = fileLines[fileLineIdx].trim();
278- if (fileLine.length === 0 || fileLine.length < 3) continue; // Skip very short lines
279-
280- const similarity = jaroWinklerSimilarity(searchLine, fileLine);
281-
282- if (similarity >= threshold && similarity > bestSimilarity) {
283- // Calculate character positions for the line
284- const linesBeforeMatch = fileLines.slice(0, fileLineIdx);
285- const startIndex =
286- linesBeforeMatch.join("\n").length +
287- (linesBeforeMatch.length > 0 ? 1 : 0);
288- const endIndex = startIndex + fileLines[fileLineIdx].length;
289-
290- bestMatch = {
291- startIndex,
292- endIndex,
293- };
294- bestSimilarity = similarity;
295- }
296- }
297- }
298-
299- return bestMatch;
300-}
301-
302-/**
303- * Ordered list of matching strategies to try with their names
304- */
305-const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [
306- { strategy: exactMatch, name: "exactMatch" },
307- { strategy: trimmedMatch, name: "trimmedMatch" },
308- { strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" },
309- { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" },
310-];
311-
312-/**
313- * Find the exact match position for search content in file content.
314- * Uses multiple matching strategies in order of preference.
315- *
316- * Matching Strategy:
317- * 1. If search content is empty, matches at the beginning of file (position 0)
318- * 2. Try each matching strategy in order until one succeeds
319- *
320- * @param fileContent - The complete content of the file to search in
321- * @param searchContent - The content to search for
322- * @param config - Configuration options for matching behavior
323- * @returns Match result with character positions, or null if no match found
324- */
325-export function findSearchMatch(
326- fileContent: string,
327- searchContent: string,
328-): SearchMatchResult | null {
329- // Handle truly empty search content
330- if (searchContent === "") {
331- return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
332- }
333-
334- // Handle whitespace-only search content that trims to empty
335- const trimmedSearchContent = searchContent.trim();
336- 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
347- return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
348- }
349-
350- // Try each matching strategy in order
351- for (const { strategy, name } of matchingStrategies) {
352- const result = strategy(fileContent, searchContent);
353- if (result !== null) {
354- return { ...result, strategyName: name };
355- }
356- }
357-
358- return null;
359-}
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-}
modified core/edit/streamDiffLines.ts +18 −17
@@ -108,23 +108,24 @@
108108
109109 // Rules can be included with edit prompt
110110 // 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;
111+ const systemMessage =
112+ rulesToInclude || llm.baseChatSystemMessage
113+ ? getSystemMessageWithRules({
114+ availableRules: rulesToInclude ?? [],
115+ userMessage:
116+ typeof prompt === "string"
117+ ? ({
118+ role: "user",
119+ content: prompt,
120+ } as UserChatMessage)
121+ : (findLast(
122+ prompt,
123+ (msg) => msg.role === "user" || msg.role === "tool",
124+ ) as UserChatMessage | ToolResultChatMessage | undefined),
125+ baseSystemMessage: llm.baseChatSystemMessage,
126+ contextItems: [],
127+ }).systemMessage
128+ : undefined;
128129
129130 if (systemMessage) {
130131 if (typeof prompt === "string") {
modified core/index.d.ts +18 −7
@@ -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>;
@@ -456,7 +461,6 @@
456461 export interface PromptLog {
457462 modelTitle: string;
458463 modelProvider: string;
459- completionOptions: CompletionOptions;
460464 prompt: string;
461465 completion: string;
462466 }
@@ -666,6 +670,7 @@
666670 env?: Record<string, string | number | boolean>;
667671
668672 sourceFile?: string;
673+ isFromAutoDetect?: boolean;
669674 }
670675
671676 type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
@@ -1070,11 +1075,6 @@
10701075 codeBaseIndexer?: CodebaseIndexer;
10711076 }
10721077
1073-export type ToolPolicy =
1074- | "allowedWithPermission"
1075- | "allowedWithoutPermission"
1076- | "disabled";
1077-
10781078 export interface Tool {
10791079 type: "function";
10801080 function: {
@@ -1099,6 +1099,10 @@
10991099 exampleArgs?: Array<[string, string | number]>;
11001100 };
11011101 defaultToolPolicy?: ToolPolicy;
1102+ evaluateToolCallPolicy?: (
1103+ basePolicy: ToolPolicy,
1104+ parsedArgs: Record<string, unknown>,
1105+ ) => ToolPolicy;
11021106 }
11031107
11041108 interface ToolChoice {
@@ -1111,6 +1115,9 @@
11111115 export interface ConfigDependentToolParams {
11121116 rules: RuleWithSource[];
11131117 enableExperimentalTools: boolean;
1118+ isSignedIn: boolean;
1119+ isRemote: boolean;
1120+ modelName: string | undefined;
11141121 }
11151122
11161123 export type GetTool = (params: ConfigDependentToolParams) => Tool;
@@ -1174,6 +1181,7 @@
11741181 configurationStatus?: LLMConfigurationStatuses;
11751182
11761183 sourceFile?: string;
1184+ isFromAutoDetect?: boolean;
11771185 }
11781186
11791187 export interface JSONEmbedOptions {
@@ -1342,6 +1350,7 @@
13421350 codeWrap?: boolean;
13431351 showSessionTabs?: boolean;
13441352 autoAcceptEditToolDiffs?: boolean;
1353+ continueAfterToolRejection?: boolean;
13451354 }
13461355
13471356 export interface ContextMenuConfig {
@@ -1604,6 +1613,7 @@
16041613 aiGatewaySlug?: string;
16051614 useLegacyCompletionsEndpoint?: boolean;
16061615 deploymentId?: string;
1616+ isFromAutoDetect?: boolean;
16071617 }
16081618
16091619 // config.json
@@ -1681,6 +1691,7 @@
16811691 experimental?: ExperimentalConfig;
16821692 /** Analytics configuration */
16831693 analytics?: AnalyticsConfig;
1694+ docs?: SiteIndexingConfig[];
16841695 data?: DataDestination[];
16851696 }
16861697
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 +21 −0
@@ -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 +161 −44
@@ -1,11 +1,100 @@
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";
75
8-export const DEFAULT_IGNORE_FILETYPES = [
6+// Security-focused ignore patterns - these should always be excluded for security reasons
7+export const DEFAULT_SECURITY_IGNORE_FILETYPES = [
8+ // Environment and configuration files with secrets
9+ "*.env",
10+ "*.env.*",
11+ ".env*",
12+ "config.json",
13+ "config.yaml",
14+ "config.yml",
15+ "settings.json",
16+ "appsettings.json",
17+ "appsettings.*.json",
18+
19+ // Certificate and key files
20+ "*.key",
21+ "*.pem",
22+ "*.p12",
23+ "*.pfx",
24+ "*.crt",
25+ "*.cer",
26+ "*.jks",
27+ "*.keystore",
28+ "*.truststore",
29+
30+ // Database files that may contain sensitive data
31+ "*.db",
32+ "*.sqlite",
33+ "*.sqlite3",
34+ "*.mdb",
35+ "*.accdb",
36+
37+ // Credential and secret files
38+ "*.secret",
39+ "*.secrets",
40+ "credentials",
41+ "credentials.*",
42+ "auth.json",
43+ "token",
44+ "token.*",
45+ "*.token",
46+
47+ // Backup files that might contain sensitive data
48+ "*.bak",
49+ "*.backup",
50+ "*.old",
51+ "*.orig",
52+
53+ // Docker secrets
54+ "docker-compose.override.yml",
55+ "docker-compose.override.yaml",
56+
57+ // SSH and GPG
58+ "id_rsa",
59+ "id_dsa",
60+ "id_ecdsa",
61+ "id_ed25519",
62+ "*.ppk",
63+ "*.gpg",
64+];
65+
66+export const DEFAULT_SECURITY_IGNORE_DIRS = [
67+ // Environment and configuration directories
68+ ".env/",
69+ "env/",
70+
71+ // Cloud provider credential directories
72+ ".aws/",
73+ ".gcp/",
74+ ".azure/",
75+ ".kube/",
76+ ".docker/",
77+
78+ // Secret directories
79+ "secrets/",
80+ ".secrets/",
81+ "private/",
82+ ".private/",
83+ "certs/",
84+ "certificates/",
85+ "keys/",
86+ ".ssh/",
87+ ".gnupg/",
88+ ".gpg/",
89+
90+ // Temporary directories that might contain sensitive data
91+ "tmp/secrets/",
92+ "temp/secrets/",
93+ ".tmp/",
94+];
95+
96+// Additional non-security patterns for general indexing exclusion
97+export const ADDITIONAL_INDEXING_IGNORE_FILETYPES = [
998 "*.DS_Store",
1099 "*-lock.json",
11100 "*.lock",
@@ -46,8 +135,6 @@
46135 "*.mpeg",
47136 "*.mov",
48137 "*.mp3",
49- "*.mp4",
50- "*.mkv",
51138 "*.mkv",
52139 "*.webm",
53140 "*.jar",
@@ -56,20 +143,15 @@
56143 "*.pqt",
57144 "*.wav",
58145 "*.webp",
59- "*.db",
60- "*.sqlite",
61146 "*.wasm",
62147 "*.plist",
63148 "*.profraw",
64149 "*.gcda",
65150 "*.gcno",
66151 "go.sum",
67- "*.env",
68152 "*.gitignore",
69153 "*.gitkeep",
70154 "*.continueignore",
71- "config.json",
72- "config.yaml",
73155 "*.csv",
74156 "*.uasset",
75157 "*.pdb",
@@ -78,19 +160,13 @@
78160 "*.swp",
79161 "*.jsonl",
80162 // "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt
163+ // Application specific
164+ ".continue/",
81165 ];
82166
83-export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES);
84-export const DEFAULT_IGNORE_DIRS = [
167+export const ADDITIONAL_INDEXING_IGNORE_DIRS = [
85168 ".git/",
86169 ".svn/",
87- ".vscode/",
88- ".idea/",
89- ".vs/",
90- "venv/",
91- ".venv/",
92- "env/",
93- ".env/",
94170 "node_modules/",
95171 "dist/",
96172 "build/",
@@ -100,7 +176,6 @@
100176 "bin/",
101177 ".pytest_cache/",
102178 ".vscode-test/",
103- ".continue/",
104179 "__pycache__/",
105180 "site-packages/",
106181 ".gradle/",
@@ -108,42 +183,84 @@
108183 ".cache/",
109184 "gems/",
110185 "vendor/",
186+
187+ ".venv/",
188+ "venv/",
189+
190+ ".vscode/",
191+ ".idea/",
192+ ".vs/",
193+];
194+
195+// Combined patterns: security + additional
196+export const DEFAULT_IGNORE_FILETYPES = [
197+ ...DEFAULT_SECURITY_IGNORE_FILETYPES,
198+ ...ADDITIONAL_INDEXING_IGNORE_FILETYPES,
199+];
200+
201+export const DEFAULT_IGNORE_DIRS = [
202+ ...DEFAULT_SECURITY_IGNORE_DIRS,
203+ ...ADDITIONAL_INDEXING_IGNORE_DIRS,
111204 ];
112205
206+// Create ignore instances
207+export const defaultSecurityIgnoreFile = ignore().add(
208+ DEFAULT_SECURITY_IGNORE_FILETYPES,
209+);
210+export const defaultSecurityIgnoreDir = ignore().add(
211+ DEFAULT_SECURITY_IGNORE_DIRS,
212+);
213+export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES);
113214 export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS);
114215
216+// String representations
217+export const DEFAULT_SECURITY_IGNORE =
218+ DEFAULT_SECURITY_IGNORE_FILETYPES.join("\n") +
219+ "\n" +
220+ DEFAULT_SECURITY_IGNORE_DIRS.join("\n");
221+
115222 export const DEFAULT_IGNORE =
116223 DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n");
117224
225+// Combined ignore instances
226+export const defaultFileAndFolderSecurityIgnores = ignore()
227+ .add(defaultSecurityIgnoreFile)
228+ .add(defaultSecurityIgnoreDir);
229+
118230 export const defaultIgnoreFileAndDir = ignore()
119231 .add(defaultIgnoreFile)
120232 .add(defaultIgnoreDir);
121233
234+export function isSecurityConcern(filePathOrUri: string) {
235+ if (!filePathOrUri) {
236+ return false;
237+ }
238+ let filepath = filePathOrUri;
239+ try {
240+ filepath = fileURLToPath(filePathOrUri);
241+ } catch {}
242+ if (path.isAbsolute(filepath)) {
243+ const dir = path.dirname(filepath).split(/\/|\\/).at(-1) ?? "";
244+ const basename = path.basename(filepath);
245+ filepath = `${dir ? dir + "/" : ""}${basename}`;
246+ }
247+ if (!filepath) {
248+ return false;
249+ }
250+ return defaultFileAndFolderSecurityIgnores.ignores(filepath);
251+}
252+
253+export function throwIfFileIsSecurityConcern(filepath: string) {
254+ if (isSecurityConcern(filepath)) {
255+ throw new Error(
256+ `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.`,
257+ );
258+ }
259+}
260+
122261 export function gitIgArrayFromFile(file: string) {
123262 return file
124263 .split(/\r?\n/) // Split on new line
125264 .map((l) => l.trim()) // Remove whitespace
126265 .filter((l) => !/^#|^$/.test(l)); // Remove empty lines
127266 }
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 +1 −1
@@ -177,7 +177,7 @@
177177 // NOTE: When updating this list,
178178 // update core/nextEdit/templating/NextEditPromptEngine.ts as well.
179179 const MODEL_SUPPORTS_NEXT_EDIT: string[] = [
180- NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
180+ NEXT_EDIT_MODELS.MERCURY_CODER,
181181 NEXT_EDIT_MODELS.INSTINCT,
182182 ];
183183
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/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.ts +23 −23
@@ -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,11 @@
3130 TemplateType,
3231 Usage,
3332 } from "../index.js";
33+import { Logger } from "../util/Logger.js";
3434 import mergeJson from "../util/merge.js";
3535 import { renderChatMessage } from "../util/messageContent.js";
3636 import { isOllamaInstalled } from "../util/ollamaHelper.js";
37-import { Telemetry } from "../util/posthog.js";
37+import { TokensBatchingService } from "../util/TokensBatchingService.js";
3838 import { withExponentialBackoff } from "../util/withExponentialBackoff.js";
3939
4040 import {
@@ -191,6 +191,8 @@
191191 //URI to local block defining this LLM
192192 sourceFile?: string;
193193
194+ isFromAutoDetect?: boolean;
195+
194196 private _llmOptions: LLMOptions;
195197
196198 protected openaiAdapter?: BaseLlmApi;
@@ -294,6 +296,7 @@
294296
295297 this.autocompleteOptions = options.autocompleteOptions;
296298 this.sourceFile = options.sourceFile;
299+ this.isFromAutoDetect = options.isFromAutoDetect;
297300 }
298301
299302 get contextLength() {
@@ -343,15 +346,11 @@
343346 let generatedTokens = this.countTokens(completion);
344347 let thinkingTokens = thinking ? this.countTokens(thinking) : 0;
345348
346- void Telemetry.capture(
347- "tokens_generated",
348- {
349- model: model,
350- provider: this.providerName,
351- promptTokens: promptTokens,
352- generatedTokens: generatedTokens,
353- },
354- true,
349+ TokensBatchingService.getInstance().addTokens(
350+ model,
351+ this.providerName,
352+ promptTokens,
353+ generatedTokens,
355354 );
356355
357356 void DevDataSqliteDb.logTokensGenerated(
@@ -371,8 +370,17 @@
371370 },
372371 });
373372
374- if (error !== undefined) {
375- if (error === "cancel" || error.name === "AbortError") {
373+ if (typeof error === "undefined") {
374+ interaction?.logItem({
375+ kind: "success",
376+ promptTokens,
377+ generatedTokens,
378+ thinkingTokens,
379+ usage,
380+ });
381+ return "success";
382+ } else {
383+ if (error === "cancel" || error?.name?.includes("AbortError")) {
376384 interaction?.logItem({
377385 kind: "cancel",
378386 promptTokens,
@@ -394,15 +402,6 @@
394402 });
395403 return "error";
396404 }
397- } else {
398- interaction?.logItem({
399- kind: "success",
400- promptTokens,
401- generatedTokens,
402- thinkingTokens,
403- usage,
404- });
405- return "success";
406405 }
407406 }
408407
@@ -616,6 +615,7 @@
616615 kind: "chunk",
617616 chunk: formattedContent,
618617 });
618+
619619 completion += formattedContent;
620620 yield content;
621621 }
@@ -631,6 +631,7 @@
631631 kind: "chunk",
632632 chunk,
633633 });
634+
634635 completion += chunk;
635636 yield chunk;
636637 }
@@ -1143,7 +1144,6 @@
11431144 modelProvider: this.underlyingProviderName,
11441145 prompt,
11451146 completion,
1146- completionOptions,
11471147 };
11481148 }
11491149
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/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 +4 −1
@@ -513,7 +513,10 @@
513513 // The second-to-last because it retrieves potentially already cached contents,
514514 // The last one because we want it cached for later retrieval.
515515 // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
516- if (this.cacheBehavior?.cacheConversation) {
516+ if (
517+ this.cacheBehavior?.cacheConversation ||
518+ this.completionOptions.promptCaching
519+ ) {
517520 this._addCachingToLastTwoUserMessages(converted);
518521 }
519522
modified core/llm/llms/Inception.ts +96 −1
@@ -1,6 +1,8 @@
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 { UNIQUE_TOKEN } from "../../nextEdit/constants.js";
46 import OpenAI from "./OpenAI.js";
57
68 /**
@@ -32,6 +34,26 @@
3234 return true;
3335 }
3436
37+ // It seems like this should be inherited automatically from the parent OpenAI class, but it sometimes doesn't.
38+ // protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [
39+ // "chat",
40+ // "embed",
41+ // "list",
42+ // "rerank",
43+ // "streamChat",
44+ // "streamFim",
45+ // ];
46+
47+ protected modifyChatBody(
48+ body: ChatCompletionCreateParams,
49+ ): ChatCompletionCreateParams {
50+ const hasNextEditCapability = this.capabilities?.nextEdit ?? false;
51+
52+ // Add the nextEdit parameter for Inception-specific routing.
53+ (body as any).nextEdit = hasNextEditCapability;
54+ return body;
55+ }
56+
3557 async *_streamFim(
3658 prefix: string,
3759 suffix: string,
@@ -67,6 +89,79 @@
6789 yield chunk.choices[0].text;
6890 }
6991 }
92+
93+ protected async *_streamChat(
94+ messages: ChatMessage[],
95+ signal: AbortSignal,
96+ options: CompletionOptions,
97+ ): AsyncGenerator<ChatMessage> {
98+ if (this.isNextEdit(messages)) {
99+ messages = this.removeNextEditToken(messages);
100+
101+ // Use edit/completions endpoint.
102+ const endpoint = new URL("edit/completions", this.apiBase);
103+
104+ const resp = await this.fetch(endpoint, {
105+ method: "POST",
106+ body: JSON.stringify({
107+ model: options.model,
108+ messages: messages,
109+ max_tokens: options.maxTokens,
110+ temperature: options.temperature,
111+ top_p: options.topP,
112+ frequency_penalty: options.frequencyPenalty,
113+ presence_penalty: options.presencePenalty,
114+ stop: options.stop,
115+ stream: true,
116+ }),
117+ headers: {
118+ "Content-Type": "application/json",
119+ Accept: "application/json",
120+ Authorization: `Bearer ${this.apiKey}`,
121+ },
122+ signal,
123+ });
124+
125+ for await (const chunk of streamSse(resp)) {
126+ if (chunk.choices?.[0]?.delta?.content) {
127+ yield {
128+ role: "assistant",
129+ content: chunk.choices[0].delta.content,
130+ };
131+ }
132+ }
133+ } else {
134+ // Use regular chat/completions endpoint - call parent OpenAI implementation.
135+ yield* super._streamChat(messages, signal, options);
136+ }
137+ }
138+
139+ private isNextEdit(messages: ChatMessage[]): boolean {
140+ // Check if any message contains the unique next edit token.
141+ return messages.some(
142+ (message) =>
143+ typeof message.content === "string" &&
144+ message.content.endsWith(UNIQUE_TOKEN),
145+ );
146+ }
147+
148+ private removeNextEditToken(messages: ChatMessage[]): ChatMessage[] {
149+ const lastMessage = messages[messages.length - 1];
150+
151+ if (
152+ typeof lastMessage?.content === "string" &&
153+ lastMessage.content.endsWith(UNIQUE_TOKEN)
154+ ) {
155+ const cleanedMessages = [...messages];
156+ cleanedMessages[cleanedMessages.length - 1] = {
157+ ...lastMessage,
158+ content: lastMessage.content.slice(0, -UNIQUE_TOKEN.length),
159+ };
160+ return cleanedMessages;
161+ }
162+
163+ return messages;
164+ }
70165 }
71166
72167 export default Inception;
modified core/llm/llms/Ollama.ts +35 −19
@@ -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;
@@ -420,24 +422,35 @@
420422 signal,
421423 });
422424
423- function convertChatMessage(res: OllamaChatResponse): ChatMessage {
425+ function convertChatMessage(res: OllamaChatResponse): ChatMessage[] {
424426 if ("error" in res) {
425427 throw new Error(res.error);
426428 }
427- if (res.message.role === "tool") {
429+
430+ const { role, content, thinking, tool_calls: toolCalls } = res.message;
431+
432+ if (role === "tool") {
428433 throw new Error(
429- "Unexpected message received from ollama with role = tool",
434+ "Unexpected message received from Ollama with role = tool",
430435 );
431436 }
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) {
437+
438+ if (role === "assistant") {
439+ const thinkingMessage: ThinkingChatMessage | null = thinking
440+ ? { role: "thinking", content: thinking }
441+ : null;
442+
443+ if (thinkingMessage && !content) {
444+ // When Streaming you can't have both thinking and content
445+ return [thinkingMessage];
446+ }
447+ // Either not thinking, or not streaming
448+ const chatMessage: ChatMessage = { role: "assistant", content };
449+
450+ if (toolCalls?.length) {
438451 // Continue handles the response as a tool call delta but
439452 // But ollama returns the full object in one response with no streaming
440- chatMessage.toolCalls = res.message.tool_calls.map((tc) => ({
453+ chatMessage.toolCalls = toolCalls.map((tc) => ({
441454 type: "function",
442455 id: `tc_${uuidv4()}`, // Generate a proper UUID with a prefix
443456 function: {
@@ -446,13 +459,13 @@
446459 },
447460 }));
448461 }
449- return chatMessage;
450- } else {
451- return {
452- role: res.message.role,
453- content: res.message.content,
454- };
462+
463+ // Return both thinking and chat messages if applicable
464+ return thinkingMessage ? [thinkingMessage, chatMessage] : [chatMessage];
455465 }
466+
467+ // Fallback for all other roles
468+ return [{ role, content }];
456469 }
457470
458471 if (chatOptions.stream === false) {
@@ -460,7 +473,9 @@
460473 return; // Aborted by user
461474 }
462475 const json = (await response.json()) as OllamaChatResponse;
463- yield convertChatMessage(json);
476+ for (const msg of convertChatMessage(json)) {
477+ yield msg;
478+ }
464479 } else {
465480 let buffer = "";
466481 for await (const value of streamResponse(response)) {
@@ -475,8 +490,9 @@
475490 if (chunk.trim() !== "") {
476491 try {
477492 const j = JSON.parse(chunk) as OllamaChatResponse;
478- const chatMessage = convertChatMessage(j);
479- yield chatMessage;
493+ for (const msg of convertChatMessage(j)) {
494+ yield msg;
495+ }
480496 } catch (e) {
481497 throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
482498 }
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 +2 −0
@@ -53,6 +53,7 @@
5353 import Scaleway from "./Scaleway";
5454 import SiliconFlow from "./SiliconFlow";
5555 import ContinueProxy from "./stubs/ContinueProxy";
56+import TARS from "./TARS";
5657 import TestLLM from "./Test";
5758 import TextGenWebUI from "./TextGenWebUI";
5859 import Together from "./Together";
@@ -116,6 +117,7 @@
116117 Inception,
117118 Voyage,
118119 LlamaStack,
120+ TARS,
119121 ];
120122
121123 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/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/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 +40 −0
@@ -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 };
@@ -336,6 +375,7 @@
336375 [/deepseek/, /r1|reasoner/],
337376 [/gemini/, /2\.5/, /pro/],
338377 [/gpt/, /4/],
378+ [/gpt-5/],
339379 [/claude/, /sonnet/, /3\.5|3\.7|3-5|3-7|-4/],
340380 [/claude/, /opus/, /-4/],
341381 ];
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 +9 −1
@@ -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,
@@ -49,8 +50,8 @@
4950 ControlPlaneSessionInfo,
5051 } from "../control-plane/AuthTypes";
5152 import { FreeTrialStatus } from "../control-plane/client";
52-import { NextEditOutcome } from "../nextEdit/types";
5353 import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue";
54+import { NextEditOutcome } from "../nextEdit/types";
5455
5556 export enum OnboardingModes {
5657 API_KEY = "API Key",
@@ -86,6 +87,7 @@
8687 ];
8788 "config/addLocalWorkspaceBlock": [{ blockType: BlockType }, void];
8889 "config/newPromptFile": [undefined, void];
90+ "config/newAssistantFile": [undefined, void];
8991 "config/ideSettingsUpdate": [IdeSettings, void];
9092 "config/getSerializedProfileInfo": [
9193 undefined,
@@ -284,6 +286,7 @@
284286 "docs/getSuggestedDocs": [undefined, void];
285287 "docs/initStatuses": [undefined, void];
286288 "docs/getDetails": [{ startUrl: string }, DocsIndexingDetails];
289+ "docs/getIndexedPages": [{ startUrl: string }, string[]];
287290 addAutocompleteModel: [{ model: ModelDescription }, void];
288291
289292 "auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }];
@@ -291,6 +294,10 @@
291294 { toolCall: ToolCall },
292295 { contextItems: ContextItem[]; errorMessage?: string },
293296 ];
297+ "tools/evaluatePolicy": [
298+ { toolName: string; basePolicy: ToolPolicy; args: Record<string, unknown> },
299+ { policy: ToolPolicy; displayValue?: string },
300+ ];
294301 "clipboardCache/add": [{ content: string }, void];
295302 "controlPlane/openUrl": [{ path: string; orgSlug?: string }, void];
296303 "controlPlane/getEnvironment": [undefined, ControlPlaneEnv];
@@ -306,5 +313,6 @@
306313 ];
307314 "process/markAsBackgrounded": [{ toolCallId: string }, void];
308315 "process/isBackgrounded": [{ toolCallId: string }, boolean];
316+ "process/killTerminalProcess": [{ toolCallId: string }, void];
309317 "mdm/setLicenseKey": [{ licenseKey: string }, boolean];
310318 };
modified core/protocol/passThrough.ts +4 −0
@@ -18,6 +18,7 @@
1818 "devdata/log",
1919 "config/addModel",
2020 "config/newPromptFile",
21+ "config/newAssistantFile",
2122 "config/ideSettingsUpdate",
2223 "config/addLocalWorkspaceBlock",
2324 "config/getSerializedProfileInfo",
@@ -70,12 +71,14 @@
7071 "indexing/setPaused",
7172 "docs/initStatuses",
7273 "docs/getDetails",
74+ "docs/getIndexedPages",
7375 //
7476 "onboarding/complete",
7577 "addAutocompleteModel",
7678 "didChangeSelectedProfile",
7779 "didChangeSelectedOrg",
7880 "tools/call",
81+ "tools/evaluatePolicy",
7982 "controlPlane/getEnvironment",
8083 "controlPlane/getFreeTrialStatus",
8184 "controlPlane/getModelsAddOnUpgradeUrl",
@@ -83,6 +86,7 @@
8386 "isItemTooBig",
8487 "process/markAsBackgrounded",
8588 "process/isBackgrounded",
89+ "process/killTerminalProcess",
8690 ];
8791
8892 // 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 +4 −0
@@ -12,6 +12,8 @@
1212 import { lsToolImpl } from "./implementations/lsTool";
1313 import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile";
1414 import { readFileImpl } from "./implementations/readFile";
15+
16+import { readFileRangeImpl } from "./implementations/readFileRange";
1517 import { requestRuleImpl } from "./implementations/requestRule";
1618 import { runTerminalCommandImpl } from "./implementations/runTerminalCommand";
1719 import { searchWebImpl } from "./implementations/searchWeb";
@@ -145,6 +147,8 @@
145147 switch (functionName) {
146148 case BuiltInToolNames.ReadFile:
147149 return await readFileImpl(args, extras);
150+ case BuiltInToolNames.ReadFileRange:
151+ return await readFileRangeImpl(args, extras);
148152 case BuiltInToolNames.CreateNewFile:
149153 return await createNewFileImpl(args, extras);
150154 case BuiltInToolNames.GrepSearch:
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/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";
added core/tools/definitions/multiEdit.ts +117 −0
@@ -0,0 +1,117 @@
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+If you want to create a new file, use:
54+- A new file path, including new directory if needed
55+- First edit: empty old_string and the new file's contents as new_string
56+- Subsequent edits are not allowed - there is no need since you are creating
57+- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required
58+
59+WARNINGS:
60+- If earlier edits affect the text that later edits are trying to find, files can become mangled
61+- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace)
62+- The tool will fail if edits.old_string and edits.new_string are the same - they MUST be different`,
63+ parameters: {
64+ type: "object",
65+ required: ["filepath", "edits"],
66+ properties: {
67+ filepath: {
68+ type: "string",
69+ description:
70+ "The path to the file to modify, relative to the root of the workspace",
71+ },
72+ edits: {
73+ type: "array",
74+ description:
75+ "Array of edit operations to perform sequentially on the file",
76+ items: {
77+ type: "object",
78+ required: ["old_string", "new_string"],
79+ properties: {
80+ old_string: {
81+ type: "string",
82+ description:
83+ "The text to replace (exact match including whitespace/indentation)",
84+ },
85+ new_string: {
86+ type: "string",
87+ description:
88+ "The text to replace it with. MUST be different than old_string.",
89+ },
90+ replace_all: {
91+ type: "boolean",
92+ description:
93+ "Replace all occurrences of old_string (default false) in the file",
94+ },
95+ },
96+ },
97+ },
98+ },
99+ },
100+ },
101+ systemMessageDescription: {
102+ 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.
103+
104+ For example, you could respond with:`,
105+ exampleArgs: [
106+ ["filepath", "path/to/file.ts"],
107+ [
108+ "edits",
109+ `[
110+ { "old_string": "const oldVar = 'value'", "new_string": "const newVar = 'updated'" },
111+ { "old_string": "oldFunction()", "new_string": "newFunction()", "replace_all": true }
112+]`,
113+ ],
114+ ],
115+ },
116+ defaultToolPolicy: "allowedWithPermission",
117+};
modified core/tools/definitions/readCurrentlyOpenFile.ts +1 −1
@@ -13,7 +13,7 @@
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: {},
added core/tools/definitions/readFileRange.ts +51 −0
@@ -0,0 +1,51 @@
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+ "viewed 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+};
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-};
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: "find and replace in {{{ filepath }}}",
16+ isCurrently: "finding and replacing in {{{ filepath }}}",
17+ hasAlready: "found and replaced in {{{ 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/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 +2 −2
@@ -29,8 +29,8 @@
2929
3030 if (truncated) {
3131 contextItems.push({
32- name: "Diff truncation warning",
33- description: "Informs that git diff was truncated",
32+ name: "Truncation warning",
33+ description: "",
3434 content: `The git diff was truncated because it exceeded ${DEFAULT_GIT_DIFF_LINE_LIMIT} lines. Consider viewing specific files or focusing on smaller changes.`,
3535 });
3636 }
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,42 +1,53 @@
1-import { ConfigDependentToolParams, IDE, Tool } from "..";
1+import { ConfigDependentToolParams, Tool } from "..";
22 import * as toolDefinitions from "./definitions";
33
44 // 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 = () => [
5+export const getBaseToolDefinitions = () => [
106 toolDefinitions.readFileTool,
7+
118 toolDefinitions.createNewFileTool,
129 toolDefinitions.runTerminalCommandTool,
1310 toolDefinitions.globSearchTool,
14- toolDefinitions.searchWebTool,
1511 toolDefinitions.viewDiffTool,
1612 toolDefinitions.readCurrentlyOpenFileTool,
1713 toolDefinitions.lsTool,
1814 toolDefinitions.createRuleBlock,
1915 toolDefinitions.fetchUrlContentTool,
16+ toolDefinitions.singleFindAndReplaceTool,
2017 ];
2118
2219 export const getConfigDependentToolDefinitions = (
2320 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-];
21+): Tool[] => {
22+ const { modelName, isSignedIn, enableExperimentalTools, isRemote } = params;
23+ const tools: Tool[] = [];
24+
25+ tools.push(toolDefinitions.requestRuleTool(params));
26+
27+ if (isSignedIn) {
28+ // Web search is only available for signed-in users
29+ tools.push(toolDefinitions.searchWebTool);
30+ }
31+
32+ if (enableExperimentalTools) {
33+ tools.push(
34+ toolDefinitions.viewRepoMapTool,
35+ toolDefinitions.viewSubdirectoryTool,
36+ toolDefinitions.codebaseTool,
37+ toolDefinitions.readFileRangeTool,
38+ );
39+ }
40+
41+ if (modelName?.includes("claude") || modelName?.includes("gpt-5")) {
42+ tools.push(toolDefinitions.multiEditTool);
43+ } else {
44+ tools.push(toolDefinitions.editFileTool);
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 +51 −0
@@ -56,3 +56,54 @@
5656 const result = getMCPToolName(server, tool);
5757 expect(result).toBe("gitlab_create_merge_request");
5858 });
59+
60+test("getMCPToolName - handles server names with special characters (parentheses)", () => {
61+ const server = createMcpServer("Linear MCP (SSE)");
62+ const tool = createMCPTool("create_issue");
63+
64+ const result = getMCPToolName(server, tool);
65+ // Should only contain alphanumeric characters and underscores
66+ expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
67+ expect(result).toBe("linear_mcp_sse_create_issue");
68+});
69+
70+test("getMCPToolName - handles server names with dots and other special characters", () => {
71+ const server = createMcpServer("My.Server@Test!");
72+ const tool = createMCPTool("test_action");
73+
74+ const result = getMCPToolName(server, tool);
75+ // Should only contain alphanumeric characters and underscores
76+ expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
77+ expect(result).toBe("my_server_test_test_action");
78+});
79+
80+test("getMCPToolName - handles server names with multiple consecutive special characters", () => {
81+ const server = createMcpServer("Server@@##Name");
82+ const tool = createMCPTool("action");
83+
84+ const result = getMCPToolName(server, tool);
85+ // Should only contain alphanumeric characters and underscores (no hyphens or multiple underscores)
86+ expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
87+ expect(result).toBe("server_name_action");
88+});
89+
90+test("getMCPToolName - handles server names with hyphens", () => {
91+ const server = createMcpServer("My-Server-Name");
92+ const tool = createMCPTool("test_action");
93+
94+ const result = getMCPToolName(server, tool);
95+ // Should only contain alphanumeric characters and underscores
96+ expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
97+ expect(result).toBe("my_server_name_test_action");
98+});
99+
100+test("getMCPToolName - handles multiple consecutive underscores in server name", () => {
101+ const server = createMcpServer("Linear__MCP");
102+ const tool = createMCPTool("create_issue");
103+
104+ const result = getMCPToolName(server, tool);
105+ // Should only contain alphanumeric characters and single underscores
106+ expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
107+ expect(result).not.toMatch(/__/);
108+ expect(result).toBe("linear_mcp_create_issue");
109+});
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 +1 −0
@@ -39,6 +39,7 @@
3939 */
4040 hasDismissedConfigTsNoticeJetBrains: boolean;
4141 hasAlreadyCreatedAPromptFile: boolean;
42+ hasShownUnsupportedPlatformWarning: boolean;
4243 showConfigUpdateToast: boolean;
4344 isSupportedLanceDbCpuTargetForLinux: boolean;
4445 sharedConfig: SharedConfigSchema;
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/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 +7 −4
@@ -30,10 +30,13 @@
3030 const content = fs.readFileSync(filepath, "utf8");
3131
3232 let sessions = safeParseArray<SessionMetadata>(content) ?? [];
33- sessions = sessions.filter((session: any) => {
34- // Filter out old format
35- return typeof session.session_id !== "string";
36- });
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) {
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/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/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-remix.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
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 +83 −0
@@ -0,0 +1,83 @@
1+---
2+title: "Tetrate Agent Router Service"
3+sidebarTitle: "Tetrate Agent Router Service"
4+slug: ../tetrate-agent-router-service
5+---
6+
7+The **Tetrate Agent Router Service** provides a unified Gateway for accessing various AI models with fast inference capabilities as well as embedding services.
8+
9+This gateway acts as an intelligent router that can distribute requests across multiple model providers, offering enterprise-grade reliability and performance optimization.
10+
11+## Getting Started
12+
13+1. Obtain an API key from the [Agent Router Service portal](https://api.router.tetrate.ai/)
14+2. Configure Continue to use Agent Router Service as your model provider
15+
16+## Configuring Models
17+
18+You can also quickly use models from Tetrate on the Cotninue Hub by visiting Tetrate on the Continue Hub [here](https://hub.continue.dev/tetrate). The easiest way if you don't see the model you want to use is to remix one of the models on the Tetrate page and change the model to the one you want to use.
19+
20+![Remix a model from Tetrate on Continue Hub](../assets/tetrate-remix.png)
21+
22+### Available Models
23+
24+Agent Router Service supports routing to various models.
25+Go to the [Agent Router Service model catalog](https://router.tetrate.ai/models) for a full list of supported models.
26+
27+## Configuration Options
28+
29+As Agent Router Service is an OpenAI API compatible provider, you can configure it like any other OpenAI API compatible provider. Therefore you will be setting `provider: openai` and `apiBase: https://api.router.tetrate.ai/v1`.
30+
31+Update your Continue configuration file (`~/.continue/config.yaml`) with your Agent Router Service API key:
32+
33+### On your local machine
34+
35+#### In your config.yaml
36+
37+```yaml title="config.yaml"
38+models:
39+ - name: <MODEL_NAME>
40+ provider: openai
41+ model: <MODEL_ID>
42+ apiKey: <TETRATE_API_KEY>
43+ apiBase: https://api.router.tetrate.ai/v1
44+```
45+
46+#### As a local model block
47+
48+Review the configuration reference for [model blocks](/reference#models) and using [local blocks](/reference#local-blocks). Ensure you look at the roles and capabilities section and review the [model capabilities guide](/customize/deep-dives/model-capabilities).
49+
50+```yaml title="model_name.yaml"
51+ name: <MODEL_NAME>
52+ models:
53+ - name: <MODEL_NAME>
54+ provider: openai
55+ model: <MODEL_ID>
56+ apiKey: ${{ inputs.TETRATE_API_KEY }}
57+ apiBase: https://api.router.tetrate.ai/v1
58+ roles:
59+ - chat
60+ - edit
61+ - apply
62+ capabilities:
63+ - tool_use
64+```
65+
66+### On Model Block on Continue Hub
67+Learn how to use model blocks on Continue Hub [here](/hub/blocks/create-a-block).
68+
69+```yaml title="model_name.yaml"
70+ name: <MODEL_NAME>
71+ models:
72+ - name: <MODEL_NAME>
73+ provider: openai
74+ model: <MODEL_ID>
75+ apiKey: ${{ inputs.TETRATE_API_KEY }}
76+ apiBase: https://api.router.tetrate.ai/v1
77+ roles:
78+ - chat
79+ - edit
80+ - apply
81+ capabilities:
82+ - tool_use
83+```
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.
modified docs/customize/model-roles/autocomplete.mdx +6 −1
@@ -6,13 +6,18 @@
66 sidebar_position: 2
77 ---
88
9+import { ModelRecommendations } from '/snippets/ModelRecommendations.jsx'
10+
11+
912 An "autocomplete model" is an LLM that is trained on a special format called fill-in-the-middle (FIM). This format is designed to be given the prefix and suffix of a code file and predict what goes between. This task is very specific, which on one hand means that the models can be smaller (even a 3B parameter model can perform well). On the other hand, this means that Chat models, though larger, will often perform poorly even with extensive prompting.
1013
1114 In Continue, autocomplete models are used to display inline [Autocomplete](../../features/autocomplete/quick-start) suggestions as you type. Autocomplete models are designated by adding the `autocomplete` to the model's `roles` in `config.yaml`.
1215
1316 ## Recommended Autocomplete models
1417
15-Visit the [Autocomplete Deep Dive](../deep-dives/autocomplete) for recommended models and more details.
18+<ModelRecommendations role="autocomplete" />
19+
20+Visit the [Autocomplete Deep Dive](../deep-dives/autocomplete) for detailed setup instructions and configuration options.
1621
1722 ## Prompt templating
1823
modified docs/customize/model-roles/chat.mdx +15 −11
@@ -5,30 +5,34 @@
55 sidebar_position: 1
66 ---
77
8+import { ModelRecommendations } from '/snippets/ModelRecommendations.jsx'
9+
10+
811 A "chat model" is an LLM that is trained to respond in a conversational format. Because they should be able to answer general questions and generate complex code, the best chat models are typically large, often 405B+ parameters.
912
10-In Continue, these models are used for normal [Chat](../../features/chat/quick-start) and [VS Code actions](../deep-dives/vscode-actions). The selected chat model will also be used for [Edit](../../features/edit/quick-start) and [Apply](./apply) if no `edit` or `apply` models are specified, respectively.
13+In Continue, these models are used for normal [Chat](../../features/chat/quick-start). The selected chat model will also be used for [Edit](../../features/edit/quick-start) and [Apply](./apply.mdx) if no `edit` or `apply` models are specified, respectively.
1114
1215 ## Recommended Chat models
1316
17+<ModelRecommendations role="chat_edit" />
1418 ## Best overall experience
1519
1620 For the best overall Chat experience, you will want to use a 400B+ parameter model or one of the frontier models.
1721
18-### Claude Sonnet 3.7 from Anthropic
22+### Claude Opus 4.1 and Claude Sonnet 4 from Anthropic
1923
20-Our current top recommendation is Claude 3.7 Sonnet from [Anthropic](../model-providers/top-level/anthropic).
24+Our current top recommendations are Claude Opus 4.1 and Claude Sonnet 4 from [Anthropic](../model-providers/top-level/anthropic).
2125
2226 <Tabs>
2327 <Tab title="Hub">
24- View the [Claude 3.7 Sonnet model block](https://hub.continue.dev/anthropic/claude-3-7-sonnet) on the hub.
28+ View the [Claude Opus 4.1 model block](https://hub.continue.dev/anthropic/claude-4-1-opus) or [Claude Sonnet 4 model block](https://hub.continue.dev/anthropic/claude-4-sonnet) on the hub.
2529 </Tab>
2630 <Tab title="YAML">
2731 ```yaml title="config.yaml"
2832 models:
29- - name: Claude 3.7 Sonnet
33+ - name: Claude Opus 4.1
3034 provider: anthropic
31- model: claude-3-7-sonnet-latest
35+ model: claude-4-1-opus
3236 apiKey: <YOUR_ANTHROPIC_API_KEY>
3337 ```
3438 </Tab>
@@ -37,9 +41,9 @@
3741 {
3842 "models": [
3943 {
40- "title": "Claude 3.5 Sonnet",
44+ "title": "Claude Opus 4.1",
4145 "provider": "anthropic",
42- "model": "claude-3-5-sonnet-latest",
46+ "model": "claude-4-1-opus",
4347 "apiKey": "<YOUR_ANTHROPIC_API_KEY>"
4448 }
4549 ]
@@ -152,7 +156,7 @@
152156
153157 ### Grok-2 from xAI
154158
155-If you prefer to use a model from [xAI](../model-providers/top-level/xAI), then we recommend Grok-2.
159+If you prefer to use a model from [xAI](../model-providers/more/xAI), then we recommend Grok-2.
156160
157161 <Tabs>
158162 <Tab title="Hub">
@@ -222,7 +226,7 @@
222226
223227 ### Llama 3.1 8B
224228
225-If your local machine can run an 8B parameter model, then we recommend running Llama 3.1 8B on your machine (e.g. using [Ollama](../model-providers/top-level/ollama) or [LM Studio](../model-providers/more/lmstudio)).
229+If your local machine can run an 8B parameter model, then we recommend running Llama 3.1 8B on your machine (e.g. using [Ollama](../model-providers/top-level/ollama) or [LM Studio](../model-providers/top-level/lmstudio)).
226230
227231 <Tabs>
228232 <Tab title="Hub">
@@ -311,7 +315,7 @@
311315
312316 ### DeepSeek Coder 2 16B
313317
314-If your local machine can run a 16B parameter model, then we recommend running DeepSeek Coder 2 16B (e.g. using [Ollama](../model-providers/top-level/ollama.mdx) or [LM Studio](../model-providers/more/lmstudio.mdx)).
318+If your local machine can run a 16B parameter model, then we recommend running DeepSeek Coder 2 16B (e.g. using [Ollama](../model-providers/top-level/ollama) or [LM Studio](../model-providers/top-level/lmstudio)).
315319
316320 <Tabs>
317321 {/* HUB_TODO nonexistent blocks */}
modified docs/customize/model-roles/edit.mdx +5 −0
@@ -4,6 +4,7 @@
44 keywords: [edit, editing, model, role]
55 sidebar_position: 3
66 ---
7+import { ModelRecommendations } from '/snippets/ModelRecommendations.jsx'
78
89 It's often useful to select a different model to respond to Edit prompts than for chat prompts, as Edits are often more code-specific and may require less conversational readability.
910
@@ -44,6 +45,10 @@
4445
4546 Explore edit models in [the hub](https://hub.continue.dev/explore/models?roles=edit). Generally, our recommendations for Edit overlap with recommendations for Chat.
4647
48+## Model Recommendations
49+
50+<ModelRecommendations role="chat_edit" />
51+
4752 ## Prompt templating
4853
4954 You can customize the prompt template used for editing code by setting the `promptTemplates.edit` property in your model configuration. Continue uses [Handlebars syntax](https://handlebarsjs.com/guide/) for templating.
modified docs/customize/model-roles/embeddings.mdx +6 −2
@@ -19,6 +19,10 @@
1919
2020 ## Recommended embedding models
2121
22+<Info>
23+ See our [comprehensive model recommendations](/customization/models#recommended-models) for the best embedding models comparison.
24+</Info>
25+
2226 If you have the ability to use any model, we recommend `voyage-code-3`, which is listed below along with the rest of the options for embeddings models.
2327
2428 If you want to generate embeddings locally, we recommend using `nomic-embed-text` with [Ollama](../model-providers/top-level/ollama#embeddings-model).
@@ -134,7 +138,7 @@
134138
135139 ### Mistral
136140
137-See [here](../model-providers/top-level/mistral#how-to-configure-mistral-embeddings-models) for instructions on how to use Mistral for embeddings.
141+See [here](../model-providers/more/mistral#how-to-configure-mistral-embeddings-models) for instructions on how to use Mistral for embeddings.
138142
139143 ### NVIDIA
140144
@@ -150,4 +154,4 @@
150154
151155 ### LMStudio
152156
153-See [here](../model-providers/more/lmstudio#embeddings-model) for instructions on how to use LMStudio for embeddings.
157+See [here](../model-providers/top-level/lmstudio#embeddings-model) for instructions on how to use LMStudio for embeddings.
modified docs/customize/model-roles/intro.mdx +1 −1
@@ -16,7 +16,7 @@
1616
1717 ## Selecting model roles
1818
19-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.
19+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.
2020
2121 <Frame>
2222 <img src="/images/settings-model-roles-5e5f8a6bd9137b70cf94178a7e45847c.png" />
modified docs/customize/model-roles/reranking.mdx +4 −0
@@ -11,6 +11,10 @@
1111
1212 ## Recommended reranking models
1313
14+<Info>
15+ For a comparison of all reranking models including open and closed options, see our [comprehensive model recommendations](/customization/models#recommended-models).
16+</Info>
17+
1418 If you have the ability to use any model, we recommend `rerank-2` by Voyage AI, which is listed below along with the rest of the options for rerankers.
1519
1620 ### Voyage AI
modified docs/customize/overview.mdx +8 −8
@@ -3,17 +3,11 @@
33 description: "Explore Continue's advanced capabilities for power users and complex development scenarios."
44 ---
55
6-## Context Providers
7-
8-Master how Continue understands your codebase with powerful context providers for code, documentation, and more.
9-
10-[Explore Context Providers →](/customize/custom-providers)
11-
126 ## Context Integration
137
148 Specialized context features for codebase understanding and documentation integration.
159
16-[Browse Context Features →](customize/context/codebase)
10+[Browse Context Features →](/guides/understanding-assistants)
1711
1812 ## Deep Dives
1913
@@ -33,6 +27,12 @@
3327
3428 [Learn Model Roles →](/customize/model-roles)
3529
30+## Deep Dives
31+
32+Detailed technical explanations of Continue's internal workings and advanced configuration options.
33+
34+[Read Deep Dives →](/customization/overview#configuration)
35+
3636 ## Reference
3737
3838 Complete configuration reference and API documentation.
@@ -47,4 +47,4 @@
4747
4848 ---
4949
50-These advanced topics help you get the most out of Continue in complex development environments.
50+These advanced topics help you get the most out of Continue in complex development environments.
No newline at the end of the file
deleted docs/customize/settings.mdx +0 −41
@@ -1,41 +0,0 @@
1----
2-title: "User Settings Page"
3-description: "Reference for Adjusting User-Specific Settings"
4-keywords: [config, settings, configuration, customize, customization, sidebar]
5----
6-
7-The **User Settings page** can be accessed by clicking the gear icon in the header of the Continue sidebar and then selecting the "Settings" tab.
8-
9-![settings](/images/settings-header.png)
10-
11-Which takes you to this page (select the "Settings" tab):
12-
13-![User Settings Page](/images/settings-page.png)
14-
15-Below that, the following settings which are not part of a configuration file are available:
16-
17-- **Show Session Tabs**: If on, displays tabs above the chat as an alternative way to organize and access your sessions. Off by default
18-- **Wrap Codeblocks**: If on, enables text wrapping in code blocks. Off by default
19-- **Show Chat Scrollbar**: If on, enables a scrollbar in the chat window. Off by default
20-- **Text-to-Speech Output**: If on, reads LLM responses aloud with TTS. Off by default
21-- **Enable Session Titles**: If on, generates summary titles for each chat session after the first message, using the current Chat model. On by default
22-- **Format Markdown**: If off, shows responses as raw text. On by default
23-- **Allow Anonymous Telemetry**: If on, allows Continue to send anonymous telemetry. **On** by default
24-- **Enable Indexing**: Enables indexing of the codebase for the @codebase and @code context providers. **On** by default
25-- **Font Size**: Specifies base font size for UI elements
26-- **Multiline Autocompletions**: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto`
27-- **Autocomplete timeout**: Maximum time in milliseconds for autocomplete request/retrieval. Defaults to 150
28-- **Autocomplete debounce**: Minimum time in milliseconds to trigger an autocomplete request after a change. Defaults to 250
29-- **Disable autocomplete in files**: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., `**/*.{txt,md}`
30-
31-## Experimental settings
32-
33-At the bottom of the User Settings page there is an "Experimental Settings" section which contains new or otherwise experimental settings, including:
34-
35-<Warning>
36- **Auto-Accept Agent Edits**: Be very careful with this setting. When turned
37- on, Agent mode's edit tool can make changes to files with no manual review or
38- guaranteed stopping point. If on, diffs generated by the edit tool are
39- automatically accepted and Agent proceeds with the next conversational turn.
40- Off by default.
41-</Warning>
modified docs/customize/telemetry.mdx +1 −1
@@ -25,6 +25,6 @@
2525
2626 ## How to Opt Out
2727
28-You can disable anonymous telemetry by visiting the [User Settings Page](/customize/settings) and toggling "Allow Anonymous Telemetry" off.
28+You can disable anonymous telemetry by toggling "Allow Anonymous Telemetry" off in the user settings.
2929
3030 Alternatively in VS Code, you can disable telemetry through your VS Code settings by unchecking the "Continue: Telemetry Enabled" box (this will override the Settings Page settings). VS Code settings can be accessed with `File` > `Preferences` > `Settings` (or use the keyboard shortcut `ctrl` + `,` on Windows/Linux or `cmd` + `,` on macOS).
modified docs/docs.json +265 −87
@@ -27,6 +27,18 @@
2727 "group": "Features",
2828 "icon": "star",
2929 "pages": [
30+ {
31+ "group": "Agent",
32+ "icon": "robot",
33+ "pages": [
34+ "features/agent/quick-start",
35+ "features/agent/how-it-works",
36+ "features/agent/plan-mode",
37+ "features/agent/model-setup",
38+ "features/agent/how-to-customize",
39+ "features/agent/context-selection"
40+ ]
41+ },
3042 {
3143 "group": "Chat",
3244 "icon": "messages",
@@ -46,7 +58,8 @@
4658 "features/autocomplete/how-it-works",
4759 "features/autocomplete/model-setup",
4860 "features/autocomplete/how-to-customize",
49- "features/autocomplete/context-selection"
61+ "features/autocomplete/context-selection",
62+ "features/autocomplete/next-edit"
5063 ]
5164 },
5265 {
@@ -59,18 +72,6 @@
5972 "features/edit/how-to-customize",
6073 "features/edit/context-selection"
6174 ]
62- },
63- {
64- "group": "Agent",
65- "icon": "robot",
66- "pages": [
67- "features/agent/quick-start",
68- "features/agent/how-it-works",
69- "features/agent/plan-mode",
70- "features/agent/model-setup",
71- "features/agent/how-to-customize",
72- "features/agent/context-selection"
73- ]
7475 }
7576 ]
7677 },
@@ -80,15 +81,15 @@
8081 "pages": [
8182 "customization/overview",
8283 "customization/models",
83- "customization/prompts",
84+ "customization/mcp-tools",
8485 "customization/rules",
85- "customization/mcp-tools"
86+ "customization/prompts"
8687 ]
8788 },
8889 {
8990 "group": "Help",
9091 "icon": "book-open",
91- "pages": ["troubleshooting"]
92+ "pages": ["faqs", "troubleshooting"]
9293 }
9394 ]
9495 },
@@ -108,32 +109,31 @@
108109 "group": "Popular Providers",
109110 "pages": [
110111 "customize/model-providers/top-level/anthropic",
111- "customize/model-providers/top-level/openai",
112112 "customize/model-providers/top-level/azure",
113113 "customize/model-providers/top-level/bedrock",
114- "customize/model-providers/top-level/ollama",
115114 "customize/model-providers/top-level/gemini",
116- "customize/model-providers/top-level/deepseek",
117- "customize/model-providers/top-level/mistral",
118- "customize/model-providers/top-level/xAI",
119- "customize/model-providers/top-level/vertexai",
120- "customize/model-providers/top-level/inception"
115+ "customize/model-providers/top-level/inception",
116+ "customize/model-providers/top-level/lmstudio",
117+ "customize/model-providers/top-level/ollama",
118+ "customize/model-providers/top-level/openrouter",
119+ "customize/model-providers/top-level/openai",
120+ "customize/model-providers/top-level/tetrate_agent_router_service",
121+ "customize/model-providers/top-level/vertexai"
121122 ]
122123 },
123124 {
124125 "group": "More Providers",
125126 "pages": [
127+ "customize/model-providers/more/deepseek",
128+ "customize/model-providers/more/deepinfra",
126129 "customize/model-providers/more/groq",
127- "customize/model-providers/more/together",
128- "customize/model-providers/more/lmstudio",
130+ "customize/model-providers/more/huggingfaceinferenceapi",
129131 "customize/model-providers/more/llamacpp",
130132 "customize/model-providers/more/llamastack",
131- "customize/model-providers/more/openrouter",
132- "customize/model-providers/more/huggingfaceinferenceapi",
133- "customize/model-providers/more/cohere",
133+ "customize/model-providers/more/mistral",
134134 "customize/model-providers/more/nvidia",
135- "customize/model-providers/more/cloudflare",
136- "customize/model-providers/more/deepinfra"
135+ "customize/model-providers/more/together",
136+ "customize/model-providers/more/xAI"
137137 ]
138138 }
139139 ]
@@ -151,36 +151,23 @@
151151 "customize/model-roles/reranking"
152152 ]
153153 },
154- {
155- "group": "Context Providers",
156- "icon": "code",
157- "pages": [
158- "customize/context/codebase",
159- "customize/context/documentation"
160- ]
161- },
154+
162155 {
163156 "group": "Deep Dives",
164157 "icon": "microscope",
165158 "pages": [
166159 "customize/deep-dives/configuration",
167- "customize/settings",
168160 "customize/deep-dives/slash-commands",
169161 "customize/deep-dives/rules",
170162 "customize/deep-dives/prompts",
171163 "customize/deep-dives/autocomplete",
172164 "customize/deep-dives/development-data",
173- "customize/deep-dives/vscode-actions",
174165 "customize/deep-dives/mcp",
166+ "customize/deep-dives/custom-providers",
175167 "customize/deep-dives/model-capabilities"
176168 ]
177169 },
178- {
179- "group": "Telemetry",
180- "icon": "chart-line",
181- "pages": ["customize/telemetry"]
182- },
183- "customize/custom-providers"
170+ "customize/telemetry"
184171 ]
185172 }
186173 ]
@@ -193,13 +180,13 @@
193180 "pages": [
194181 "hub/introduction",
195182 {
196- "group": "Assistants",
183+ "group": "agents",
197184 "icon": "robot",
198185 "pages": [
199- "hub/assistants/intro",
200- "hub/assistants/use-an-assistant",
201- "hub/assistants/create-an-assistant",
202- "hub/assistants/edit-an-assistant"
186+ "hub/agents/intro",
187+ "hub/agents/use-an-agent",
188+ "hub/agents/create-an-agent",
189+ "hub/agents/edit-an-agent"
203190 ]
204191 },
205192 {
@@ -209,8 +196,7 @@
209196 "hub/blocks/intro",
210197 "hub/blocks/use-a-block",
211198 "hub/blocks/block-types",
212- "hub/blocks/create-a-block",
213- "hub/blocks/bundles"
199+ "hub/blocks/create-a-block"
214200 ]
215201 },
216202 {
@@ -243,15 +229,15 @@
243229 "group": "Guides",
244230 "pages": [
245231 "guides/overview",
246- "guides/understanding-assistants",
232+ "guides/understanding-agents",
233+ "guides/codebase-documentation-awareness",
247234 "guides/cli",
235+ "guides/continuous-ai",
248236 "guides/plan-mode-guide",
249237 "guides/ollama-guide",
250- "guides/llama3.1",
251- "guides/set-up-codestral",
238+ "guides/instinct",
252239 "guides/running-continue-without-internet",
253240 "guides/custom-code-rag",
254- "guides/build-your-own-context-provider",
255241 "guides/how-to-self-host-a-model"
256242 ]
257243 }
@@ -265,9 +251,12 @@
265251 "icon": "code",
266252 "pages": [
267253 "reference",
268- "reference/json-reference",
269254 "reference/yaml-migration",
270- "reference/continue-mcp"
255+ "reference/continue-mcp",
256+ "reference/json-reference",
257+ "reference/deprecated-context-providers",
258+ "reference/deprecated-codebase",
259+ "reference/deprecated-docs"
271260 ]
272261 }
273262 ]
@@ -289,6 +278,11 @@
289278 "anchor": "Blog",
290279 "href": "https://continue.dev/blog",
291280 "icon": "newspaper"
281+ },
282+ {
283+ "anchor": "Release Notes",
284+ "href": "https://changelog.continue.dev/",
285+ "icon": "bullhorn"
292286 }
293287 ]
294288 }
@@ -355,14 +349,14 @@
355349 "source": "/hub/secrets",
356350 "destination": "/hub/secrets/secret-types"
357351 },
358- {
359- "source": "/hub/assistants",
360- "destination": "/hub/assistants/intro"
361- },
362352 {
363353 "source": "/hub/blocks",
364354 "destination": "/hub/blocks/intro"
365355 },
356+ {
357+ "source": "/hub/agents/intro",
358+ "destination": "/hub/agents/intro"
359+ },
366360 {
367361 "source": "/customize",
368362 "destination": "/customization/overview"
@@ -383,14 +377,6 @@
383377 "source": "/install/jetbrains",
384378 "destination": "/getting-started/install"
385379 },
386- {
387- "source": "/advanced/deep-dives/settings",
388- "destination": "/customize/settings"
389- },
390- {
391- "source": "/customize/deep-dives/settings",
392- "destination": "/customize/settings"
393- },
394380 {
395381 "source": "/customize/model-types",
396382 "destination": "/customize/model-roles/intro"
@@ -469,19 +455,19 @@
469455 },
470456 {
471457 "source": "/walkthroughs/codebase-embeddings",
472- "destination": "/customize/context/codebase"
458+ "destination": "/reference/deprecated-codebase"
473459 },
474460 {
475461 "source": "/features/codebase-embeddings",
476- "destination": "/customize/context/codebase"
462+ "destination": "/reference/deprecated-codebase"
477463 },
478464 {
479465 "source": "/advanced/deep-dives/codebase",
480- "destination": "/customize/context/codebase"
466+ "destination": "/reference/deprecated-codebase"
481467 },
482468 {
483469 "source": "/advanced/context/codebase",
484- "destination": "/customize/context/codebase"
470+ "destination": "/reference/deprecated-codebase"
485471 },
486472 {
487473 "source": "/walkthroughs/tab-autocomplete",
@@ -545,11 +531,15 @@
545531 },
546532 {
547533 "source": "/walkthroughs/quick-actions",
548- "destination": "/customize/deep-dives/vscode-actions"
534+ "destination": "/customize/overview"
549535 },
550536 {
551537 "source": "/advanced/deep-dives/vscode-actions",
552- "destination": "/customize/deep-dives/vscode-actions"
538+ "destination": "/customize/overview"
539+ },
540+ {
541+ "source": "/customize/deep-dives/vscode-actions",
542+ "destination": "/customize/overview"
553543 },
554544 {
555545 "source": "/changelog",
@@ -569,19 +559,19 @@
569559 },
570560 {
571561 "source": "/customization/context-providers",
572- "destination": "/customize/custom-providers"
562+ "destination": "/customize/deep-dives/custom-providers"
573563 },
574564 {
575565 "source": "/advanced/context-integration/custom-providers",
576- "destination": "/customize/custom-providers"
566+ "destination": "/customize/deep-dives/custom-providers"
577567 },
578568 {
579569 "source": "/advanced/context/custom-providers",
580- "destination": "/customize/custom-providers"
570+ "destination": "/customize/deep-dives/custom-providers"
581571 },
582572 {
583573 "source": "/advanced/custom-providers",
584- "destination": "/customize/custom-providers"
574+ "destination": "/customize/deep-dives/custom-providers"
585575 },
586576 {
587577 "source": "/development-data",
@@ -597,19 +587,19 @@
597587 },
598588 {
599589 "source": "/features/talk-to-your-docs",
600- "destination": "/customize/context/documentation"
590+ "destination": "/reference/deprecated-docs"
601591 },
602592 {
603593 "source": "/advanced/context-integration/documentation",
604- "destination": "/customize/context/documentation"
594+ "destination": "/reference/deprecated-docs"
605595 },
606596 {
607597 "source": "/advanced/deep-dives/docs",
608- "destination": "/customize/context/documentation"
598+ "destination": "/reference/deprecated-docs"
609599 },
610600 {
611601 "source": "/advanced/context/documentation",
612- "destination": "/customize/context/documentation"
602+ "destination": "/reference/deprecated-docs"
613603 },
614604 {
615605 "source": "/reference/Model Providers/anthropicllm",
@@ -1003,17 +993,205 @@
1003993 "source": "/agent/context-selection",
1004994 "destination": "/features/agent/context-selection"
1005995 },
996+ {
997+ "source": "/customize/context/codebase",
998+ "destination": "/guides/codebase-documentation-awareness"
999+ },
1000+ {
1001+ "source": "/customize/context/documentation",
1002+ "destination": "/guides/codebase-documentation-awareness"
1003+ },
10061004 {
10071005 "source": "/customization/overview#codebase-context",
1008- "destination": "/customize/context/codebase"
1006+ "destination": "/guides/codebase-documentation-awareness"
10091007 },
10101008 {
10111009 "source": "/customization/overview#documentation-context",
1012- "destination": "/customize/context/documentation"
1010+ "destination": "/guides/codebase-documentation-awareness"
1011+ },
1012+ {
1013+ "source": "/guides/llama3.1",
1014+ "destination": "/guides/ollama-guide"
1015+ },
1016+ {
1017+ "source": "/guides/set-up-codestral",
1018+ "destination": "/customize/model-providers/top-level/mistral"
1019+ },
1020+ {
1021+ "source": "/guides/build-your-own-context-provider",
1022+ "destination": "/customize/deep-dives/custom-providers"
1023+ },
1024+ {
1025+ "source": "/hub/blocks/bundles",
1026+ "destination": "/hub/blocks/intro"
1027+ },
1028+ {
1029+ "source": "/customize/settings",
1030+ "destination": "/customize/overview"
1031+ },
1032+ {
1033+ "source": "/advanced/deep-dives/settings",
1034+ "destination": "/customize/overview"
1035+ },
1036+ {
1037+ "source": "/customize/deep-dives/settings",
1038+ "destination": "/customize/overview"
1039+ },
1040+ {
1041+ "source": "/customize/custom-providers#@greptile-context-provider",
1042+ "destination": "/reference/deprecated-context-providers"
1043+ },
1044+ {
1045+ "source": "/customize/custom-providers#@commits-context-provider",
1046+ "destination": "/reference/deprecated-context-providers"
1047+ },
1048+ {
1049+ "source": "/customize/custom-providers#@discord-context-provider",
1050+ "destination": "/reference/deprecated-context-providers"
1051+ },
1052+ {
1053+ "source": "/customize/custom-providers#@jira-context-provider",
1054+ "destination": "/reference/deprecated-context-providers"
1055+ },
1056+ {
1057+ "source": "/customize/custom-providers#@gitlab-merge-request-context-provider",
1058+ "destination": "/reference/deprecated-context-providers"
1059+ },
1060+ {
1061+ "source": "/customize/custom-providers#@google-context-provider",
1062+ "destination": "/reference/deprecated-context-providers"
1063+ },
1064+ {
1065+ "source": "/customize/custom-providers#@database-context-provider",
1066+ "destination": "/reference/deprecated-context-providers"
1067+ },
1068+ {
1069+ "source": "/customize/custom-providers#@issue-context-provider",
1070+ "destination": "/reference/deprecated-context-providers"
1071+ },
1072+ {
1073+ "source": "/customize/custom-providers#@url-context-provider",
1074+ "destination": "/reference/deprecated-context-providers"
1075+ },
1076+ {
1077+ "source": "/customize/custom-providers#@search-context-provider",
1078+ "destination": "/reference/deprecated-context-providers"
1079+ },
1080+ {
1081+ "source": "/customize/custom-providers#@web-context-provider",
1082+ "destination": "/reference/deprecated-context-providers"
1083+ },
1084+ {
1085+ "source": "/troubleshooting#faqs",
1086+ "destination": "/faqs"
1087+ },
1088+ {
1089+ "source": "/troubleshooting#networking-issues",
1090+ "destination": "/faqs#networking-issues"
1091+ },
1092+ {
1093+ "source": "/troubleshooting#configure-certificates",
1094+ "destination": "/faqs#configure-certificates"
1095+ },
1096+ {
1097+ "source": "/troubleshooting#vs-code-proxy-settings",
1098+ "destination": "/faqs#vs-code-proxy-settings"
1099+ },
1100+ {
1101+ "source": "/troubleshooting#code-server",
1102+ "destination": "/faqs#code-server"
1103+ },
1104+ {
1105+ "source": "/troubleshooting#changes-to-assistants-not-showing-in-vs-code",
1106+ "destination": "/faqs#changes-to-agents-not-showing-in-vs-code"
1107+ },
1108+ {
1109+ "source": "/troubleshooting#i-installed-continue-but-dont-see-the-sidebar-window",
1110+ "destination": "/faqs#i-installed-continue-but-dont-see-the-sidebar-window"
1111+ },
1112+ {
1113+ "source": "/troubleshooting#im-getting-a-404-error-from-openai",
1114+ "destination": "/faqs#im-getting-a-404-error-from-openai"
1115+ },
1116+ {
1117+ "source": "/troubleshooting#im-getting-a-404-error-from-openrouter",
1118+ "destination": "/faqs#im-getting-a-404-error-from-openrouter"
1119+ },
1120+ {
1121+ "source": "/troubleshooting#indexing-issues",
1122+ "destination": "/faqs#indexing-issues"
1123+ },
1124+ {
1125+ "source": "/troubleshooting#agent-mode-is-unavailable-or-tools-arent-working",
1126+ "destination": "/faqs#agent-mode-is-unavailable-or-tools-arent-working"
1127+ },
1128+ {
1129+ "source": "/troubleshooting#check-if-your-model-has-tool-support",
1130+ "destination": "/faqs#check-if-your-model-has-tool-support"
1131+ },
1132+ {
1133+ "source": "/troubleshooting#tools-not-working",
1134+ "destination": "/faqs#tools-not-working"
1135+ },
1136+ {
1137+ "source": "/troubleshooting#images-not-uploading",
1138+ "destination": "/faqs#images-not-uploading"
1139+ },
1140+ {
1141+ "source": "/troubleshooting#add-capabilities",
1142+ "destination": "/faqs#add-capabilities"
1143+ },
1144+ {
1145+ "source": "/troubleshooting#verify-with-provider",
1146+ "destination": "/faqs#verify-with-provider"
1147+ },
1148+ {
1149+ "source": "/troubleshooting#verifying-current-capabilities",
1150+ "destination": "/faqs#verifying-current-capabilities"
1151+ },
1152+ {
1153+ "source": "/troubleshooting#android-studio-nothing-to-show-in-chat",
1154+ "destination": "/faqs#android-studio-nothing-to-show-in-chat"
1155+ },
1156+ {
1157+ "source": "/troubleshooting#i-received-a-codebase-indexing-disabled-your-linux-system-lacks-required-cpu-features-avx2-fma-notification",
1158+ "destination": "/faqs#i-received-a-codebase-indexing-disabled-your-linux-system-lacks-required-cpu-features-avx2-fma-notification"
1159+ },
1160+ {
1161+ "source": "/troubleshooting#how-do-i-reset-the-state-of-the-extension",
1162+ "destination": "/faqs#how-do-i-reset-the-state-of-the-extension"
1163+ },
1164+ {
1165+ "source": "/troubleshooting#still-having-trouble",
1166+ "destination": "/faqs#still-having-trouble"
10131167 },
10141168 {
10151169 "source": "/customize/model-providers",
10161170 "destination": "/customize/model-providers/overview"
1171+ },
1172+ {
1173+ "source": "/features/edit/next-edit",
1174+ "destination": "/features/autocomplete/next-edit"
1175+ },
1176+ {
1177+ "source": "/hub/assistants/intro",
1178+ "destination": "/hub/agents/intro"
1179+ },
1180+ {
1181+ "source": "/hub/assistants/use-an-assistant",
1182+ "destination": "/hub/agents/use-an-agent"
1183+ },
1184+ {
1185+ "source": "/hub/assistants/create-an-assistant",
1186+ "destination": "/hub/agents/create-an-agent"
1187+ },
1188+ {
1189+ "source": "/hub/assistants/edit-an-assistant",
1190+ "destination": "/hub/agents/edit-an-agent"
1191+ },
1192+ {
1193+ "source": "/guides/understanding-assistants",
1194+ "destination": "/guides/understanding-agents"
10171195 }
10181196 ]
10191197 }
added docs/faqs.mdx +385 −0
@@ -0,0 +1,385 @@
1+---
2+title: "FAQs"
3+description: "Frequently asked questions about Continue"
4+---
5+
6+## Networking Issues
7+
8+### Configure Certificates
9+
10+If you're seeing a `fetch failed` error and your network requires custom certificates, you will need to configure them in your config file. In each of the objects in the `"models"` array, add `requestOptions.caBundlePath` like this:
11+
12+<Tabs>
13+ <Tab title="YAML">
14+ ```yaml
15+ models:
16+ - name: My Model
17+ ...
18+ requestOptions:
19+ caBundlePath: /path/to/cert.pem
20+ ```
21+ </Tab>
22+ <Tab title="JSON">
23+ ```json
24+ {
25+ "models": [
26+ {
27+ "name": "My Model",
28+ "...": "...",
29+ "requestOptions": {
30+ "caBundlePath": "/path/to/cert.pem"
31+ }
32+ }
33+ ]
34+ }
35+ ```
36+ </Tab>
37+</Tabs>
38+
39+You may also set `requestOptions.caBundlePath` to an array of paths to multiple certificates.
40+
41+**_Windows VS Code Users_**: Installing the [win-ca](https://marketplace.visualstudio.com/items?itemName=ukoloff.win-ca) extension should also correct this issue.
42+
43+### VS Code Proxy Settings
44+
45+If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use `cmd/ctrl` + `,` to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy.
46+
47+### code-server
48+
49+Continue can be used in [code-server](https://coder.com/), but if you are running across an error in the logs that includes "This is likely because the editor is not running in a secure context", please see [their documentation on securely exposing code-server](https://coder.com/docs/code-server/latest/guide#expose-code-server).
50+
51+## Changes to agents not showing in VS Code
52+
53+If you've made changes to agents (adding, modifying, or removing them) but the changes aren't appearing in the Continue extension in VS Code, try reloading the VS Code window:
54+
55+1. Open the command palette (`cmd/ctrl` + `shift` + `P`)
56+2. Type "Reload Window"
57+3. Select the reload option
58+
59+This will restart VS Code and reload all extensions, which should make your agent changes visible.
60+
61+## I installed Continue, but don't see the sidebar window
62+
63+By default the Continue window is on the left side of VS Code, but it can be dragged to right side as well, which we recommend in our tutorial. In the situation where you have previously installed Continue and moved it to the right side, it may still be there. You can reveal Continue either by using cmd/ctrl+L or by clicking the button in the top right of VS Code to open the right sidebar.
64+
65+## I'm getting a 404 error from OpenAI
66+
67+If you have entered a valid API key and model, but are still getting a 404 error from OpenAI, this may be because you need to add credits to your billing account. You can do so from the [billing console](https://platform.openai.com/settings/organization/billing/overview). If you just want to check that this is in fact the cause of the error, you can try adding $1 to your account and checking whether the error persists.
68+
69+## I'm getting a 404 error from OpenRouter
70+
71+If you have entered a valid API key and model, but are still getting a 404 error from OpenRouter, this may be because models that do not support function calling will return an error to Continue when a request is sent. Example error: `HTTP 404 Not Found from https://openrouter.ai/api/v1/chat/completions`
72+
73+## Indexing issues
74+
75+If you are having persistent errors with indexing, our recommendation is to rebuild your index from scratch. Note that for large codebases this may take some time.
76+
77+This can be accomplished using the following command: `Continue: Rebuild codebase index`.
78+
79+## Agent mode is unavailable or tools aren't working
80+
81+If Agent mode is grayed out or tools aren't functioning properly, this is likely due to model capability configuration issues.
82+
83+<Info>
84+ Continue uses system message tools as a fallback for models without native tool support, so most models should work with Agent mode automatically.
85+</Info>
86+
87+### Check if your model has tool support
88+
89+1. Not all models support native tool/function calling, but Continue will automatically use system message tools as a fallback
90+2. Try adding `capabilities: ["tool_use"]` to your model config to force tool support
91+3. Verify your provider supports function calling or that system message tools are working correctly
92+
93+### Tools Not Working
94+
95+If tools aren't being called:
96+
97+1. Ensure `tool_use` is in your capabilities
98+2. Check that your API endpoint actually supports function calling
99+3. Some providers may use different function calling formats
100+
101+### Images Not Uploading
102+
103+If you can't upload images:
104+
105+1. Add `image_input` to capabilities
106+2. Ensure your model actually supports vision (e.g., gpt-4-vision, claude-3)
107+3. Check that your provider passes through image data
108+
109+### Add capabilities
110+
111+If Continue's autodetection isn't working correctly, you can manually add capabilities in your `config.yaml`:
112+
113+```yaml
114+models:
115+ - name: my-model
116+ provider: openai
117+ model: gpt-4
118+ capabilities:
119+ - tool_use
120+ - image_input
121+```
122+
123+### Verify with provider
124+
125+Some proxy services (like OpenRouter) or custom deployments may not preserve tool calling capabilities. Check your provider's documentation.
126+
127+### Verifying Current Capabilities
128+
129+To see what capabilities Continue detected for your model:
130+
131+1. Check the mode selector tooltips - they indicate if tools are available
132+2. Try uploading an image - if disabled, the model lacks `image_input`
133+3. Check if Agent mode is available - requires `tool_use`
134+
135+See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for complete configuration details.
136+
137+## Android Studio - "Nothing to show" in Chat
138+
139+This can be fixed by selecting `Actions > Choose Boot runtime for the IDE` then selecting the latest version, and then restarting Android Studio. [See this thread](https://github.com/continuedev/continue/issues/596#issuecomment-1789327178) for details.
140+
141+## I received a "Codebase indexing disabled - Your Linux system lacks required CPU features (AVX2, FMA)" notification
142+
143+We use LanceDB as our vector database for codebase search features. On x64 Linux systems, LanceDB requires specific CPU features (FMA and AVX2) which may not be available on older processors.
144+
145+Most Continue features will work normally, including autocomplete and chat. However, commands that rely on codebase indexing, such as `@codebase`, `@files`, and `@folder`, will be disabled.
146+
147+For more details about this requirement, see the [LanceDB issue #2195](https://github.com/lancedb/lance/issues/2195).
148+
149+## Ollama Issues
150+
151+For a comprehensive guide on setting up and troubleshooting Ollama, see the [Ollama Guide](/guides/ollama-guide).
152+
153+### Unable to connect to local Ollama instance
154+
155+If you're getting "Unable to connect to local Ollama instance" errors:
156+
157+1. **Verify Ollama is running**: Check http://localhost:11434 in your browser - you should see "Ollama is running"
158+2. **Start Ollama properly**: Use `ollama serve` (not just `ollama run model-name`)
159+3. **Check your config**: Ensure your `config.yaml` has the correct setup:
160+
161+```yaml
162+models:
163+ - name: llama3
164+ provider: ollama
165+ model: llama3:latest
166+```
167+
168+### Connection failed to remote Ollama (EHOSTUNREACH/ECONNREFUSED)
169+
170+When connecting to Ollama on another machine:
171+
172+1. **Configure Ollama to listen on all interfaces**:
173+ - Set environment variable: `OLLAMA_HOST=0.0.0.0:11434`
174+ - For systemd: Edit `/etc/systemd/system/ollama.service` and add under `[Service]`:
175+ ```
176+ Environment="OLLAMA_HOST=0.0.0.0:11434"
177+ Environment="OLLAMA_ORIGINS=*"
178+ ```
179+ - Restart Ollama: `sudo systemctl restart ollama`
180+
181+2. **Update your Continue config**:
182+```yaml
183+models:
184+ - name: llama3
185+ provider: ollama
186+ apiBase: http://192.168.1.136:11434 # Use your server's IP
187+ model: llama3:latest
188+```
189+
190+3. **Check firewall settings**: Ensure port 11434 is open on the server
191+
192+### Ollama not working in WSL
193+
194+For WSL users having connection issues:
195+
196+#### Windows 11 22H2+ (Recommended)
197+Create or edit `%UserProfile%\.wslconfig`:
198+```ini
199+[wsl2]
200+networkingMode=mirrored
201+```
202+Then restart WSL: `wsl --shutdown`
203+
204+#### Older Windows/WSL versions
205+In PowerShell (as Administrator):
206+```powershell
207+# Add firewall rules
208+New-NetFireWallRule -DisplayName 'WSL Ollama' -Direction Inbound -LocalPort 11434 -Action Allow -Protocol TCP
209+New-NetFireWallRule -DisplayName 'WSL Ollama' -Direction Outbound -LocalPort 11434 -Action Allow -Protocol TCP
210+
211+# Get WSL IP (run 'ip addr' in WSL to find eth0 IP)
212+# Then add port proxy (replace <WSL_IP> with your actual IP)
213+netsh interface portproxy add v4tov4 listenport=11434 listenaddress=0.0.0.0 connectport=11434 connectaddress=<WSL_IP>
214+```
215+
216+### Docker container can't connect to host Ollama
217+
218+When running Continue or other tools in Docker that need to connect to Ollama on the host:
219+
220+**Windows/Mac**: Use `host.docker.internal`:
221+```yaml
222+models:
223+ - name: llama3
224+ provider: ollama
225+ apiBase: http://host.docker.internal:11434
226+ model: llama3:latest
227+```
228+
229+**Linux**: Use the Docker bridge IP (usually `172.17.0.1`):
230+```yaml
231+models:
232+ - name: llama3
233+ provider: ollama
234+ apiBase: http://172.17.0.1:11434
235+ model: llama3:latest
236+```
237+
238+**Docker run command**: Add host mapping:
239+```bash
240+docker run -d --add-host=host.docker.internal:host-gateway ...
241+```
242+
243+### Parse errors with remote Ollama
244+
245+If you're getting parse errors with remote Ollama:
246+
247+1. **Verify the model is installed on the remote**:
248+ ```bash
249+ OLLAMA_HOST=192.168.1.136:11434 ollama list
250+ ```
251+
252+2. **Install missing models**:
253+ ```bash
254+ OLLAMA_HOST=192.168.1.136:11434 ollama pull llama3
255+ ```
256+
257+3. **Check URL format**: Ensure you're using `http://` not `https://` for local network addresses
258+
259+## Local Agent
260+
261+### Managing Local Secrets and Environment Variables
262+
263+For running Continue completely offline without internet access, see the [Running Continue Without Internet guide](/guides/running-continue-without-internet).
264+
265+Continue supports multiple methods for managing secrets locally, searched in this order:
266+
267+1. **Workspace `.env` files**: Place a `.env` file in your workspace root directory
268+2. **Workspace Continue folder**: Place a `.env` file in `<workspace-root>/.continue/.env`
269+3. **Global `.env` file**: Place a `.env` file in `~/.continue/.env` for user-wide secrets
270+4. **Process environment variables**: Use standard system environment variables
271+
272+#### Creating `.env` files
273+
274+Create a `.env` file in one of these locations:
275+- **Per-workspace**: `<workspace-root>/.env` or `<workspace-root>/.continue/.env`
276+- **Global**: `~/.continue/.env`
277+
278+Example `.env` file:
279+```
280+OPENAI_API_KEY=sk-...
281+ANTHROPIC_API_KEY=sk-ant-...
282+CUSTOM_API_URL=https://api.example.com
283+```
284+
285+#### Using secrets in config.yaml
286+
287+Reference your local secrets using the `secrets` namespace:
288+```yaml
289+models:
290+ - provider: openai
291+ apiKey: ${{ secrets.OPENAI_API_KEY }}
292+```
293+
294+#### Hub-managed secrets
295+
296+For centralized team secret management, use `${{ inputs.SECRET_NAME }}` syntax in your config.yaml and manage them at [https://hub.continue.dev/settings/secrets](https://hub.continue.dev/settings/secrets):
297+```yaml
298+models:
299+ - provider: openai
300+ apiKey: ${{ inputs.OPENAI_API_KEY }}
301+```
302+
303+#### Important notes
304+
305+- **Never commit `.env` files** to version control - add them to `.gitignore`
306+- The `.env` file uses standard dotenv format (KEY=value, no quotes needed)
307+- Secrets are loaded when Continue starts, so restart your IDE after changes
308+- Local `.env` files take precedence over Hub secrets when both exist
309+
310+#### Troubleshooting secrets
311+
312+If your API keys aren't being recognized:
313+1. Check the `.env` file is in the correct location
314+2. Ensure there are no quotes around values in the `.env` file
315+3. Restart your IDE after adding/changing secrets
316+4. Verify the variable name matches exactly (case-sensitive)
317+5. Check that your `.env` file has proper line endings (LF, not CRLF on Windows)
318+
319+### Using Model Addons Locally
320+
321+You can leverage model addons from the Continue Hub in your local agent configurations using the `uses:` syntax. This allows you to reference pre-configured model blocks without duplicating configuration.
322+
323+#### Requirements
324+
325+- You must be logged in to Continue
326+- Internet connection is required (model addons are fetched from the hub)
327+
328+#### Usage
329+
330+In your local `config.yaml`, reference model addons using the format `provider/model-name`:
331+
332+```yaml
333+name: My Local Agent
334+version: 0.0.1
335+schema: v1
336+models:
337+ - uses: ollama/llama3.1-8b
338+ - uses: anthropic/claude-3.5-sonnet
339+ - uses: openai/gpt-4
340+```
341+
342+#### With local configuration
343+
344+You can combine hub model addons with local models:
345+
346+```yaml
347+name: My Local Agent
348+version: 0.0.1
349+schema: v1
350+models:
351+ # Hub model addon
352+ - uses: anthropic/claude-3.5-sonnet
353+
354+ # Local model configuration
355+ - name: Local Ollama
356+ provider: ollama
357+ model: codellama:latest
358+ apiBase: http://localhost:11434
359+```
360+
361+#### Override addon settings
362+
363+You can override specific settings from the model addon:
364+
365+```yaml
366+models:
367+ - uses: ollama/llama3.1-8b
368+ override:
369+ apiBase: http://192.168.1.100:11434 # Use remote Ollama server
370+ roles:
371+ - chat
372+ - autocomplete
373+```
374+
375+This feature allows you to maintain consistent model configurations across teams while still allowing local customization when needed.
376+
377+## How do I reset the state of the extension?
378+
379+Continue stores its data in the `~/.continue` directory (`%USERPROFILE%\.continue` on Windows).
380+
381+If you'd like to perform a clean reset of the extension, including removing all configuration files, indices, etc, you can remove this directory, uninstall, and then reinstall.
382+
383+## Still having trouble?
384+
385+You can also join our Discord community [here](https://discord.gg/vapESyrFmJ) for additional support and GitHub Discussions. Alternatively, you can create a GitHub issue [here](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=), providing details of your problem, and we'll be able to help you out more quickly.
No newline at the end of the file
modified docs/features/agent/how-to-customize.mdx +5 −5
@@ -6,7 +6,7 @@
66
77 ## How to Add Rules Blocks
88
9-Adding Rules can be done in your assistant locally or in the Hub. You can explore Rules on the Continue Hub and refer to the [Rules deep dive](/customize/deep-dives/rules) for more details.
9+Adding Rules can be done in your agent locally or in the Hub. You can explore Rules on the Continue Hub and refer to the [Rules deep dive](/customize/deep-dives/rules) for more details.
1010
1111 ## How to Customize System Messages
1212
@@ -18,14 +18,14 @@
1818 provider: openai
1919 model: gpt-4o
2020 chatOptions:
21- baseSystemMessage: "You are a helpful coding assistant."
22- baseAgentSystemMessage: "You are a systematic coding assistant. Break down problems methodically."
23- basePlanSystemMessage: "You are a planning assistant. Create clear, actionable steps."
21+ baseSystemMessage: "You are a helpful coding agent."
22+ baseAgentSystemMessage: "You are a systematic coding agent. Break down problems methodically."
23+ basePlanSystemMessage: "You are a planning agent. Create clear, actionable steps."
2424 ```
2525
2626 ## How to Add MCP Tools
2727
28-You can add MCP servers to your assistant to give Agent access to more tools. Explore [MCP Servers on the Hub](https://hub.continue.dev) and consult the [MCP guide](/customize/deep-dives/mcp) for more details.
28+You can add MCP servers to your agent to give Agent access to more tools. Explore [MCP Servers on the Hub](https://hub.continue.dev) and consult the [MCP guide](/customize/deep-dives/mcp) for more details.
2929
3030 ## How to Configure Tool Policies
3131
modified docs/features/agent/model-setup.mdx +7 −19
@@ -3,15 +3,12 @@
33 description: "Learn how to set up models for Agent Mode in Continue, including recommended models and configuration options for optimal performance"
44 sidebarTitle: "Model Setup"
55 ---
6+import { ModelRecommendations } from '/snippets/ModelRecommendations.jsx'
67
78 The models you set up for Chat mode will be used with Agent mode if the model supports tool calling. The recommended models and how to set them up can be found [here](/features/chat/model-setup).
89
910 ## How System Message Tools Work
1011
11-<Info>
12- System message tools are experimental and may change in future releases.
13-</Info>
14-
1512 Continue implements an innovative approach called **system message tools** that ensures consistent tool functionality across all models, regardless of their native capabilities. This allows Agent mode to work seamlessly with a wider range of models and providers.
1613
1714 ### How System Message Tools Function
@@ -23,23 +20,14 @@
2320 - **Better reliability** - Models that struggle with native tools often perform better with system message tools
2421 - **Seamless switching** - Change between providers without modifying your workflow
2522
26-### What Models Are Recommended for Agent Mode
27-
28-For the best Agent mode experience, we recommend models with strong reasoning and instruction-following capabilities:
29-
30-**Premium Models:**
23+## Recommended Agent Models
3124
32-- **Claude Sonnet 4** (Anthropic) - Our top recommendation for its exceptional tool use and reasoning
33-- **GPT-4** models (OpenAI) - Excellent native tool support
34-- **DeepSeek** models - Strong performance with competitive pricing
35-
36-**Local Models:**
37-While more limited in capabilities, these models can work with system message tools:
38-
39-- Qwen2.5-Coder 32B - Best local option for Agent mode
40-- Devstral 27B - Good for code-specific tasks
41-- Smaller models (7B-13B) - May struggle with complex tool interactions
25+<ModelRecommendations role="all" />
4226
4327 ### How to Configure Agent Mode
4428
4529 Agent mode automatically determines whether to use native or system message tools based on the model's capabilities. No additional configuration is required - simply select your model and Continue handles the rest.
30+
31+## How to Check Model Compatibility
32+
33+To see which models support specific features like tool use (for Agent mode) and image input, check out our [Model Capabilities guide](/customize/deep-dives/model-capabilities).
No newline at the end of the file
modified docs/features/autocomplete/how-it-works.mdx +7 −0
@@ -25,3 +25,10 @@
2525 - Occasionally discarding low-quality responses, such as those with excessive repetition
2626
2727 You can learn more about how it works in the [Autocomplete deep dive](/customization/models#autocomplete).
28+
29+<Info>
30+ **Looking for AI that predicts your next changes or additions?** Check out
31+ [Next Edit](/features/autocomplete/next-edit), an experimental feature that
32+ proactively suggests code changes before you even start typing, going beyond
33+ traditional autocomplete to anticipate entire code modifications.
34+</Info>
modified docs/features/autocomplete/how-to-customize.mdx +1 −1
@@ -3,6 +3,6 @@
33 description: “Learn how to customize autocomplete behavior in Continue, including user settings, configuration options, and adjustments to improve AI code suggestions in your IDE.”
44 ---
55
6-Continue offers a handful of settings to customize autocomplete behavior. Visit the [User Settings Page](/customize/settings) to manage these settings.
6+Continue offers a handful of settings to customize autocomplete behavior. Visit the User Settings Page (Gear Icon) to manage these settings.
77
88 For a comprehensive guide on all configuration options and their impacts, see the [Autocomplete deep dive](/customize/deep-dives/autocomplete).
modified docs/features/autocomplete/model-setup.mdx +12 −33
@@ -3,48 +3,27 @@
33 description: "Choose the best autocomplete model for Continue, including hosted high-performance options, fast speed/quality tradeoffs, and local privacy-first models."
44 sidebarTitle: "Recommended Autocomplete Models"
55 ---
6+import { ModelRecommendations } from '/snippets/ModelRecommendations.jsx';
67
7-Setting up the right model for autocomplete is crucial for a smooth coding experience. Here are our top recommendations:
8+Setting up the right model for autocomplete is important for a smooth coding experience. Here are our top recommendations:
89
9-## Recommended Models for Autocomplete in Continue
10+## Model Recommendations
1011
11-### Hosted (Best Performance)
12+<ModelRecommendations role="autocomplete" />
1213
13-For the highest quality autocomplete suggestions, we recommend **[Codestral](https://hub.continue.dev/mistral/codestral)** from Mistral.
14+<Info>
15+ For a complete comparison of all models, see our [comprehensive model recommendations](/customization/models#recommended-models).
16+</Info>
1417
15-This model is specifically designed for code completion and offers excellent performance across multiple programming languages.
18+## Next Edit Model
1619
17-**Codestral Quick Setup:**
20+For proactive code prediction that anticipates your next edit, Continue supports specialized [Next Edit](/features/autocomplete/next-edit) models:
1821
19-1. Get your API key from [Mistral AI](https://console.mistral.ai)
20-2. Add [Codestral](https://hub.continue.dev/mistral/codestral) to your assistant on Continue Hub
21-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)
22-4. Click `Reload config` in the assistant selector in the Continue IDE extension
22+**Supported Next Edit model:**
2323
24-### Hosted (Best Speed/Quality Tradeoff)
24+- `mercury-coder-nextedit`: Primary model optimized for next edit prediction
2525
26-For fast, quality autocomplete suggestions, we recommend **[Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small)** from Inception Labs.
27-
28-This model is specifically designed for code completion and is particularly fast because it is a diffusion model.
29-
30-**Mercury Coder Small Quick Setup:**
31-
32-1. Get your API key from [Inception Labs](https://platform.inceptionlabs.ai/)
33-2. Add [Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small) to your assistant on Continue Hub
34-3. Add `INCEPTION_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)
35-4. Click `Reload config` in the assistant selector in the Continue IDE extension
36-
37-### Local (Offline / Privacy First)
38-
39-For a fully local autocomplete experience, we recommend **[Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b)**.
40-
41-This model provides good suggestions while keeping your code completely private.
42-
43-**Quick Setup:**
44-
45-1. Install [Ollama](https://ollama.ai/)
46-2. Add [Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b) to your assistant on Continue Hub
47-3. Click `Reload config` in the assistant selector in the Continue IDE extension
26+Next Edit automatically activates when you have a compatible model configured for autocomplete and the appropriate access permissions.
4827
4928 ## Need Help?
5029
added docs/features/autocomplete/next-edit.mdx +156 −0
@@ -0,0 +1,156 @@
1+---
2+title: "Next Edit"
3+description: "Learn how Continue's Next Edit feature predicts and suggests your next code changes using AI, going beyond traditional autocomplete to anticipate entire code modifications"
4+---
5+
6+<Warning>
7+ Next Edit is currently an experimental feature. It requires
8+ [Instinct](https://hub.continue.dev/continuedev/instinct) or [Mercury Coder
9+ model](https://hub.continue.dev/inceptionlabs/mercury-coder) configured in
10+ your Continue autocomplete settings and is not yet available for JetBrains
11+ use.
12+</Warning>
13+
14+## What is Next Edit?
15+
16+Next Edit is an advanced AI-powered code prediction feature that anticipates what changes you'll make next in your code. Unlike traditional autocomplete that reacts to your typing, Next Edit proactively analyzes your recent edits and coding patterns to suggest entire code modifications before you even start typing.
17+
18+Think of it as having an AI pair programmer that understands your coding flow and suggests the logical next step in your development process.
19+
20+## How Next Edit Works
21+
22+### The Prediction Process
23+
24+1. **Context Analysis**: Captures your current cursor position and recent edit history
25+2. **Pattern Recognition**: Analyzes your coding patterns and the surrounding code context
26+3. **Next Step Prediction**: Uses specialized AI models to predict what you'll likely change next
27+4. **Visual Presentation**: Shows predictions as diff overlays rather than simple text completions
28+5. **Interactive Review**: Lets you accept (Tab) or reject (Esc) the suggested changes
29+6. **Jump to Next Edit Location**: Lets you jump (Tab) to the next edit location or reject (Esc)
30+
31+### Intelligent Triggering
32+
33+Next Edit activates automatically when:
34+
35+- You finish making a code change
36+- The AI detects a logical continuation point
37+- Specialized next-edit models are available
38+- The current context suggests a predictable next step
39+
40+## Next Edit vs Traditional Autocomplete
41+
42+<AccordionGroup>
43+ <Accordion title="Prediction Scope">
44+ **Autocomplete**: Completes the current line or statement you're typing
45+
46+ **Next Edit**: Predicts entire code modifications across multiple lines
47+ </Accordion>
48+
49+ <Accordion title="User Interaction">
50+ **Autocomplete**: Shows ghost text at your cursor position
51+
52+ **Next Edit**: Displays diff overlays showing before/after changes, while also displaying ghost text if the change is purely additive.
53+
54+ </Accordion>
55+
56+ <Accordion title="Timing">
57+ **Autocomplete**: Reactive - responds to what you're currently typing
58+
59+ **Next Edit**: Proactive - anticipates what you'll do next
60+ </Accordion>
61+
62+ <Accordion title="Context Awareness">
63+ **Autocomplete**: Focuses on immediate code completion
64+
65+ **Next Edit**: Analyzes recent edit patterns and broader code context
66+ </Accordion>
67+</AccordionGroup>
68+
69+## How to Use Next Edit
70+
71+### Prerequisites
72+
73+Next Edit requires:
74+
75+- Compatible AI models (Mercury Coder or Instinct)
76+- Continue development team access
77+- VS Code (JetBrains support coming soon)
78+- **API Keys**: Organizations can add API keys to [org secrets](/hub/secrets/secret-types) for team-wide access. Individual users need to provide their own API keys in their [model configuration](/customize/model-providers/overview)
79+
80+<Note>
81+ To use Next Edit, you must have the Instinct or Mercury Coder model configured
82+ in your Continue autocomplete model settings. This model is specifically
83+ designed for next edit predictions. Once it's been loaded, you must reload VS
84+ Code to activate it.
85+ <img
86+ src="/images/features/autocomplete/images/instinct-autocomplete.png"
87+ alt="Next Edit Model Setup"
88+ />
89+</Note>
90+
91+### Using Next Edit Predictions
92+
93+<Steps>
94+ <Step title="Make a Code Change">
95+ Edit your code normally. Next Edit will analyze your change patterns.
96+ </Step>
97+
98+<Step title="Review Predictions">
99+ When Next Edit activates, you'll see a diff overlay showing predicted changes
100+ in an editable region.
101+</Step>
102+
103+<Step title="Accept or Reject">
104+ - **Tab**: Accept the prediction and apply changes - **Esc**: Reject the
105+ prediction and continue coding normally
106+</Step>
107+
108+ <Step title="Continue Coding">
109+ If accepted, your cursor moves to the last changed line. If rejected, your
110+ workflow continues uninterrupted.
111+ </Step>
112+</Steps>
113+
114+## What are the Model Requirements for Next Edit?
115+
116+### Specialized Models
117+
118+Next Edit requires AI models specifically trained for code prediction:
119+
120+- **Mercury Coder**: Primary model optimized for next edit prediction
121+- **Instinct**: The leading open Next Edit model, trained by Continue
122+
123+### Automatic Detection
124+
125+Continue automatically enables Next Edit when:
126+
127+1. Your configured autocomplete model supports next edit capabilities
128+2. You have development team access permissions
129+3. The current code context suggests predictable next steps
130+
131+## Best Practices
132+
133+<CardGroup cols={2}>
134+ <Card title="Trust the Process" icon="robot">
135+ Let Next Edit observe your coding patterns for a few editing sessions before expecting highly accurate predictions.
136+ </Card>
137+
138+<Card title="Review Carefully" icon="magnifying-glass">
139+ Always review suggested changes before accepting, especially for complex logic
140+ modifications.
141+</Card>
142+
143+<Card title="Provide Feedback" icon="message">
144+ Have feedback? We want to hear it. __[Add your thoughts to our feedback
145+ discussions](https://github.com/continuedev/continue/discussions/categories/feedback)__
146+ to help us improve.
147+</Card>
148+
149+ <Card title="Combine with Other Features" icon="puzzle-piece">
150+ Use Next Edit alongside Continue's Chat and Agent modes for comprehensive AI-assisted development.
151+ </Card>
152+</CardGroup>
153+
154+---
155+
156+_Next Edit represents Continue's vision for proactive AI coding assistance that anticipates developer needs rather than just reacting to input. As this feature evolves, it will become a powerful tool for accelerating development workflows and reducing repetitive coding tasks._
modified docs/features/chat/context-selection.mdx +4 −8
@@ -20,17 +20,13 @@
2020
2121 You can include a specific file in your current workspace by typing '@Files' and selecting the file.
2222
23-## How to Include a Specific Folder
23+## Codebase Search
2424
25-You can include a folder in your current workspace by typing '@Folder' and selecting the directory.
26-
27-## How to Use Codebase Search
28-
29-You can automatically include relevant files from your codebase by typing '@Codebase'.
25+For better codebase awareness, see our [guide on making agents aware of codebases and documentation](/guides/codebase-documentation-awareness).
3026
3127 ## How to Include Documentation Sites
3228
33-You can include a documentation site as context by typing '@Docs' and selecting the site.
29+For better documentation awareness, see our [guide on making agents aware of codebases and documentation](/guides/codebase-documentation-awareness).
3430
3531 ## How to Include Terminal Contents
3632
@@ -42,4 +38,4 @@
4238
4339 ## How to Use Other Context Providers
4440
45-You can see a full list of built-in context providers [here](/customize/custom-providers) and learn about how to create your own context provider [here](/guides/build-your-own-context-provider).
41+You can see a full list of built-in context providers [here](/customize/deep-dives/custom-providers).
modified docs/features/chat/how-it-works.mdx +4 −6
@@ -22,10 +22,7 @@
2222
2323 ### How to Add Manual Context
2424
25-- `@Codebase` - Search and include relevant code from your project
26-- `@Docs` - Include documentation context
2725 - `@Files` - Reference specific files
28-- Custom context providers
2926
3027 ## How Response Handling Works
3128
@@ -47,12 +44,13 @@
4744
4845 View the exact prompt sent to the AI model in the [prompt logs](/troubleshooting) for debugging and optimization.
4946
50-### How to Learn More About Context Providers
47+### Context
5148
52-Learn more about how context providers work:
49+Learn more about how you can bring in context:
5350
5451 - [Codebase Context](/customize/context/codebase)
55-- [Documentation Context](/customize/context/documentation)
52+- [Documentation Context](/guides/codebase-documentation-awareness)
53+- [Built-in Context Providers](/customize/deep-dives/custom-providers)
5654
5755 ---
5856
modified docs/features/chat/how-to-customize.mdx +2 −5
@@ -7,8 +7,5 @@
77
88 There are a number of different ways to customize Chat:
99
10-- Add a `rules` block to give the model persistent instructions through the system prompt
11-- Configure `@Codebase`
12-- Configure `@Docs`
13-- [Build your own context provider](/guides/build-your-own-context-provider)
14-- [Create a custom code RAG](/guides/custom-code-rag)
10+- Add [rules](/customization/rules) to give the model persistent instructions through the system prompt
11+- Create [prompts](/customization/prompts) to kickoff workflows with instructions you repeat often
No newline at the end of the file
modified docs/features/chat/model-setup.mdx +14 −97
@@ -1,104 +1,21 @@
1-The model you use for for Chat mode will be
1+---
2+title: "Recommended Models for Chat in Continue"
3+description: "Choose the best chat model for Continue, including hosted high-performance options, fast speed/quality tradeoffs, and local privacy-first models."
4+sidebarTitle: "Recommended Chat Models"
5+---
6+import { ModelRecommendations } from '/snippets/ModelRecommendations.jsx';
7+
8+The model you use for for Chat mode will be:
29
310 - used with Edit mode by default but can be switched
411 - always used with Agent mode if the model supports tool calling
512
6-## What Models Are Recommended for Chat?
13+## Model Recommendations
714
8-Our strong recommendation is to use [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet) from Anthropic.
15+<ModelRecommendations role="chat_edit" />
916
10-Its strong tool calling and reasoning capabilities make it the best model for Agent mode.
17+<Info>
18+ For a comprehensive comparison of all available models by role, see our [model recommendations table](/customization/models#recommended-models).
19+</Info>
1120
12-1. Get your API key from [Anthropic](https://console.anthropic.com/)
13-2. Add [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet) to your assistant on Continue Hub
14-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)
15-4. Click `Reload config` in the assistant selector in the Continue IDE extension
16-
17-### What Other Hosted Models Are Available?
18-
19-These models have varying tool calling and reasoning capabilities.
20-
21-[Kimi K2](https://hub.continue.dev/openrouter/kimi-k2) from Moonshot AI
22-
23-1. Get your API key from [OpenRouter](https://openrouter.ai/settings/keys)
24-2. Add [Kimi K2](https://hub.continue.dev/openrouter/kimi-k2) to your assistant on Continue Hub
25-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)
26-4. Click `Reload config` in the assistant selector in the Continue IDE extension
27-
28-[Qwen Coder 3 480B](https://hub.continue.dev/openrouter/qwen3-coder) from Qwen
29-
30-1. Get your API key from [OpenRouter](https://openrouter.ai/settings/keys)
31-2. Add [Qwen Coder 3 480B](https://hub.continue.dev/openrouter/qwen3-coder) to your assistant on Continue Hub
32-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)
33-4. Click `Reload config` in the assistant selector in the Continue IDE extension
34-
35-[Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) from Google
36-
37-1. Get your API key from [Google AI Studio](https://aistudio.google.com)
38-2. Add [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) to your assistant on Continue Hub
39-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)
40-4. Click `Reload config` in the assistant selector in the Continue IDE extension
41-
42-[o3](https://hub.continue.dev/openai/o3) from OpenAI
43-
44-1. Get your API key from [OpenAI](https://platform.openai.com)
45-2. Add [o3](https://hub.continue.dev/openai/o3) to your assistant on Continue Hub
46-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)
47-4. Click `Reload config` in the assistant selector in the Continue IDE extension
48-
49-[Grok 4](https://hub.continue.dev/xai/grok-4) from xAI
50-
51-1. Get your API key from [xAI](https://console.x.ai/)
52-2. Add [Grok 4](https://hub.continue.dev/xai/grok-4) to your assistant on Continue Hub
53-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)
54-4. Click `Reload config` in the assistant selector in the Continue IDE extension
55-
56-[Devstral Medium](https://hub.continue.dev/mistral/devstral-medium) from Mistral AI
57-
58-1. Get your API key from [Mistral AI](https://console.mistral.ai/)
59-2. Add [Devstral Medium](https://hub.continue.dev/mistral/devstral-medium) to your assistant on Continue Hub
60-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)
61-4. Click `Reload config` in the assistant selector in the Continue IDE extension
62-
63-[DeepSeek-V3](https://hub.continue.dev/togetherai/deepseek-v3) from DeepSeek
64-
65-1. Get your API key from [Together AI](https://api.together.ai)
66-2. Add [DeepSeek-V3](https://hub.continue.dev/togetherai/deepseek-v3) to your assistant on Continue Hub
67-3. Add `TOGETHER_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)
68-4. Click `Reload config` in the assistant selector in the Continue IDE extension
69-
70-### What Local Models Are Available?
71-
72-These models can be run on your computer if you have enough VRAM.
73-
74-Their limited tool calling and reasoning capabilities will make it challenging to use Agent mode.
75-
76-[Qwen2.5-Coder 32B](https://hub.continue.dev/ollama/qwen2.5-coder-32b)
77-
78-1. Add [Qwen2.5-Coder 32B](https://hub.continue.dev/ollama/qwen2.5-coder-32b) to your assistant on Continue Hub
79-2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
80-3. Click `Reload config` in the assistant selector in the Continue IDE extension
81-
82-[Devstral Small 27B](https://hub.continue.dev/ollama/devstral)
83-
84-1. Add [Devstral Small](https://hub.continue.dev/ollama/devstral) to your assistant on Continue Hub
85-2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
86-3. Click `Reload config` in the assistant selector in the Continue IDE extension
87-
88-[Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) from Qwen
89-
90-1. Add [Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) to your assistant on Continue Hub
91-2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
92-3. Click `Reload config` in the assistant selector in the Continue IDE extension
93-
94-[Gemma 3 4B](https://hub.continue.dev/ollama/gemma3-4b) from Google
95-
96-1. Add [Gemma 3 4B](https://hub.continue.dev/ollama/gemma3-4b) to your assistant on Continue Hub
97-2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
98-3. Click `Reload config` in the assistant selector in the Continue IDE extension
99-
100-For more detailed setup instructions, see [here](/getting-started/install#setup-your-first-model).
101-
102-## How to Check Model Compatibility
103-
104-To see which models support specific features like tool use (for Agent mode) and image input, check out our [Model Capabilities guide](/customize/deep-dives/model-capabilities).
21+For model recommendations, please refer to our [Model Recommendations page](/customization/models).
No newline at the end of the file
modified docs/features/chat/quick-start.mdx +0 −2
@@ -33,8 +33,6 @@
3333
3434 Type `@` to include specific context:
3535
36-- `@Codebase` - Search your project for relevant code
37-- `@Docs` - Include documentation
3836 - `@Files` - Reference specific files
3937 - `@Terminal` - Include terminal output
4038
modified docs/features/edit/how-it-works.mdx +4 −0
@@ -13,4 +13,8 @@
1313
1414 If you accept the diff, we remove the previously highlighted lines, and if you reject the diff, we remove the proposed changes.
1515
16+<Info>
17+**Looking for AI that predicts your next edit?** Check out [Next Edit](/features/autocomplete/next-edit), an experimental feature that proactively suggests code changes before you even start typing, going beyond traditional autocomplete to anticipate entire code modifications.
18+</Info>
19+
1620 If you would like to view the exact prompt that is sent to the model during an edit, you can [find it in the prompt logs](/troubleshooting#check-the-logs).
modified docs/features/edit/how-to-customize.mdx +1 −1
@@ -6,7 +6,7 @@
66
77 ## How to Set Active Edit/Apply Model
88
9-You can configure particular models from your Assistant to be used for Edit and Apply requests.
9+You can configure particular models from your Agent to be used for Edit and Apply requests.
1010
1111 1. Click the 3 dots above the main input
1212 2. Click the cube icon to expand the "Models" section
modified docs/features/edit/model-setup.mdx +10 −6
@@ -1,21 +1,25 @@
11 ---
22 title: "How to Set Up Edit Models"
3-sidebarTitle: "Set Up Edit Models"
3+sidebarTitle: "Recommended Edit Models"
44 description: "Learn how to set up and customize models for Edit functionality in Continue."
55 ---
6+import { ModelRecommendations } from '/snippets/ModelRecommendations.jsx';
67
78 The model you set up for Chat mode will be used for Edit mode by default.
89
9-The recommended models and how to set them up can be found [here](/features/chat/model-setup).
10+## Recommendations
11+
12+<ModelRecommendations role="chat_edit" />
13+
14+<Info>
15+ See our [comprehensive model recommendations](/customization/models#recommended-models) for the best models for each role, including Edit and Apply.
16+</Info>
1017
1118 ## How to Set Up an Apply Model
1219
1320 We also recommend setting up an Apply model for the best Edit experience.
1421
15-**Recommended Apply models:**
16-
17-- [Morph v3](https://hub.continue.dev/morphllm/morph-v2)
18-- [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply)
22+For recommended Apply models, please refer to our [Model Recommendations page](/customization/models).
1923
2024 ## How to Determine Model Compatibility
2125
modified docs/features/plan/how-it-works.mdx +1 −2
@@ -85,8 +85,7 @@
8585 - Encourages thorough analysis before suggesting changes
8686
8787 <Info>
88- The system message can be customized per model. See [How to
89- Customize](/features/plan/how-to-customize) for details or see it [directly in
88+ The system message can be customized per model. See it [directly in
9089 the
9190 code](https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts).
9291 </Info>
modified docs/features/plan/quick-start.mdx +1 −1
@@ -11,7 +11,7 @@
1111
1212 You can switch to `Plan` in the mode selector below the chat input box.
1313
14-![How to select plan mode](/images/mode-select-plan.png)
14+![How to select plan mode](/images/plan-mode-selector.png)
1515
1616 <Info>
1717 If Plan is disabled with a `Not Supported` message, the selected model or
modified docs/getting-started/extensions.mdx +2 −2
@@ -1,6 +1,6 @@
11 ---
2-title: "Understanding Assistants"
2+title: "Understanding Agents"
33 description: "Continue offers two ways to configure your AI assistants"
44 ---
55
6-This content has moved to our comprehensive guide: [Understanding Assistants: Hub vs Local Configuration](/guides/understanding-assistants)
6+This content has moved to our comprehensive guide: [Understanding Agents: Hub vs Local Configuration](/guides/understanding-assistants)
modified docs/getting-started/install.mdx +3 −3
@@ -24,7 +24,7 @@
2424 </Step>
2525
2626 <Step title="Sign In">
27-[Sign in to the hub](https://auth.continue.dev/) to get started with your first assistant
27+[Sign in to the hub](https://auth.continue.dev/) to get started with your first agent
2828 </Step>
2929 </Steps>
3030
@@ -54,7 +54,7 @@
5454 </Step>
5555
5656 <Step title="Sign In">
57-[Sign in to the hub](https://auth.continue.dev/) to get started with your first assistant
57+[Sign in to the hub](https://auth.continue.dev/) to get started with your first agent
5858 </Step>
5959 </Steps>
6060
@@ -68,6 +68,6 @@
6868
6969 ## Signing in
7070
71-Click "Get started" to sign in to the hub and start using assistants.
71+Click "Get started" to sign in to the hub and start using agents.
7272
7373 ![Hub Onboarding in the Extension](/images/getting-started/images/hub-onboarding-card-81abd457b6d131c4b0aa89a5a6d647d3.png)
modified docs/getting-started/overview.mdx +2 −2
@@ -57,6 +57,6 @@
5757 </Tab>
5858 </Tabs>
5959
60-## AI Coding Assistants
60+## AI Coding Agents
6161
62-Continue offers flexible AI assistants that enhance your development workflow. You can choose between cloud-managed **Hub Assistants** for easy setup and synchronization, or **Local Assistants** for complete control and privacy. Learn more about [understanding and configuring assistants](/guides/understanding-assistants).
62+Continue offers flexible AI assistants that enhance your development workflow. You can choose between cloud-managed **Hub Agents** for easy setup and synchronization, or **Local Agents** for complete control and privacy. Learn more about [understanding and configuring assistants](/guides/understanding-assistants).
modified docs/getting-started/quick-start.mdx +2 −2
@@ -247,12 +247,12 @@
247247
248248 <Accordion title="Chat & Agent Best Practices">
249249 Discover [effective prompting techniques](/customize/deep-dives/prompts), [hub
250- v. local assistants](/guides/understanding-assistants), and [custom slash
250+ v. local agents](/guides/understanding-agents), and [custom slash
251251 commands](/customize/deep-dives/slash-commands).
252252 </Accordion>
253253
254254 <Accordion title="Enterprise & Teams">
255- Explore [Hub Assistants](/hub/assistants/intro), [organization
255+ Explore [Hub Agents](/hub/agents/intro), [organization
256256 management](/hub/governance/creating-an-org), and [sharing
257257 configurations](/hub/sharing).
258258 </Accordion>
deleted docs/guides/build-your-own-context-provider.mdx +0 −162
@@ -1,162 +0,0 @@
1----
2-title: "How to Build Your Own Context Provider"
3-description: "Learn how to create custom context providers for Continue using HTTP servers, CustomContextProvider API, or VSCode extensions to provide tailored context to your AI assistant"
4----
5-
6-## How to Create an HTTP Context Provider
7-
8-Continue can retrieve context from a custom HTTP server that you create and serve. Add the `@HTTP` context provider to your configuration like this:
9-
10-- YAML
11-- JSON
12-
13-config.yaml
14-
15-```
16-context: provider: http params: url: https://myserver.com/context-provider title: http displayTitle: My Custom Context description: Gets things from my private list options: maxItems: 20
17-```
18-
19-config.json
20-
21-```json
22-{
23- "name": "http",
24- "params": {
25- "url": "https://myserver.com/context-provider",
26- "title": "http",
27- "description": "Custom HTTP Context Provider",
28- "displayTitle": "My Custom Context",
29- "options": { "maxItems": 20 }
30- }
31-}
32-```
33-
34-Then, create a server that responds to requests as are made from [HttpContextProvider.ts](https://github.com/continuedev/continue/blob/main/core/context/providers/HttpContextProvider.ts). See the `hello` endpoint in [context_provider_server.py](https://github.com/continuedev/continue/blob/main/core/context/providers/context_provider_server.py) for an example that uses FastAPI.
35-
36-The `"options"` property can be used to send additional parameters to your endpoint. The full request body has the following shape:
37-
38-```json
39-{ query: string; fullInput: string; options: Record<string, JsonValue>; workspacePath?: string; // Only provided if the server is local.}
40-```
41-
42-<Info>
43- The following methods for creating custom context providers are deprecated. We
44- recommend using HTTP context providers, [MCP
45- Servers](/customize/deep-dives/mcp), and [Prompts](/customize/deep-dives/prompts)
46- where possible.
47-</Info>
48-
49-## How to Use CustomContextProvider
50-
51-Custom context providers can be implemented in a `config.ts` placed in your Continue global directory (`~/.continue` for MacOS, `%USERPROFILE%/.continue` for Windows). You can implement the `CustomContextProvider` interface in your `config.ts`
52-
53-```
54-interface CustomContextProvider { title: string; displayTitle?: string; description?: string; renderInlineAs?: string; type?: ContextProviderType; getContextItems( query: string, extras: ContextProviderExtras, ): Promise<ContextItem[]>; loadSubmenuItems?: ( args: LoadSubmenuItemsArgs, ) => Promise<ContextSubmenuItem[]>;}
55-```
56-
57-As an example, let's say you have a set of internal documents that have been indexed in a vector database. You've set up a simple REST API that allows internal users to query and get back relevant snippets. This context provider will send the query to this server and return the results from the vector database. The return type of `getContextItems` _must_ be an array of objects that have all of the following properties:
58-
59-- `name`: The name of the context item, which will be displayed as a title
60-- `description`: A longer description of the context item
61-- `content`: The actual content of the context item, which will be fed to the LLM as context
62-
63-\~/.continue/config.ts
64-
65-```
66-const RagContextProvider: CustomContextProvider = { title: "rag", displayTitle: "RAG", description: "Retrieve snippets from our vector database of internal documents", getContextItems: async ( query: string, extras: ContextProviderExtras, ): Promise<ContextItem[]> => { const response = await fetch("https://internal_rag_server.com/retrieve", { method: "POST", body: JSON.stringify({ query }), }); const results = await response.json(); return results.map((result) => ({ name: result.title, description: result.title, content: result.contents, })); },};
67-```
68-
69-It can then be added in `config.ts` like so:
70-
71-\~/.continue/config.ts
72-
73-```
74-export function modifyConfig(config: Config): Config { if (!config.contextProviders) { config.contextProviders = []; } config.contextProviders.push(RagContextProvider); return config;}
75-```
76-
77-This is automatically appended to your configuration.
78-
79-### How to Create Custom Context Providers with Submenu or Query
80-
81-There are 3 types of context providers: "normal", "query", and "submenu". The "normal" type is the default, and is what we've seen so far.
82-
83-The **"query"** type is used when you want to display a text box to the user, and then use the contents of that text box to generate the context items. Built-in examples include "search" and "google". This text is what gets passed to the "query" argument in `getContextItems`. To implement a "query" context provider, simply set `"type": "query"` in your custom context provider object.
84-
85-The **"submenu"** type is used when you want to display a list of searchable items in the dropdown. Built-in examples include "issue" and "folder". To implement a "submenu" context provider, set `"type": "submenu"` and implement the `loadSubmenuItems` and `getContextItems` functions. Here is an example that shows a list of all README files in the current workspace:
86-
87-\~/.continue/config.ts
88-
89-```
90-const ReadMeContextProvider: CustomContextProvider = { title: "readme", displayTitle: "README", description: "Reference README.md files in your workspace", type: "submenu", getContextItems: async ( query: string, extras: ContextProviderExtras, ): Promise<ContextItem[]> => { // 'query' is the filepath of the README selected from the dropdown const content = await extras.ide.readFile(query); return [ { name: getFolder(query), description: getFolderAndBasename(query), content, }, ]; }, loadSubmenuItems: async ( args: LoadSubmenuItemsArgs, ): Promise<ContextSubmenuItem[]> => { const { ide } = args; // Filter all workspace files for READMEs const workspaceDirs = await ide.getWorkspaceDirs(); const allFiles = await Promise.all( workspaceDirs.map((dir) => ide.subprocess(`find ${dir} -name "README.md"`), ), ); // 'readmes' now contains an array of file paths for each README.md file found in the workspace, // excluding those in 'node_modules' const readmes = allFiles .flatMap((mds) => mds[0].split("\n")) .filter((file) => file.trim() !== "" && !file.includes("/node_modules/")); // Return the items that will be shown in the dropdown return readmes.map((filepath) => { return { id: filepath, title: getFolder(filepath), description: getFolderAndBasename(filepath), }; }); },};export function modifyConfig(config: Config): Config { if (!config.contextProviders) { config.contextProviders = []; } config.contextProviders.push(ReadMeContextProvider); return config;}function getFolder(path: string): string { return path.split(/[\/\\]/g).slice(-2)[0];}function getFolderAndBasename(path: string): string { return path .split(/[\/\\]/g) .slice(-2) .join("/");}
91-```
92-
93-The flow of information in the above example is as follows:
94-
95-1. The user types `@readme` and selects it from the dropdown, now displaying the submenu where they can search for any item returned by `loadSubmenuItems`.
96-2. The user selects one of the READMEs in the submenu, enters the rest of their input, and presses enter.
97-3. The `id` of the chosen `ContextSubmenuItem` is passed to `getContextItems` as the `query` argument. In this case it is the filepath of the README.
98-4. The `getContextItems` function can then use the `query` to retrieve the full contents of the README and format the content before returning the context item which will be included in the prompt.
99-
100-### How to Import Outside Modules
101-
102-To include outside Node modules in your config.ts, run `npm install <module_name>` from the `~/.continue` directory, and then import them in config.ts.
103-
104-Continue will use [esbuild](https://esbuild.github.io/) to bundle your `config.ts` and any dependencies into a single Javascript file. The exact configuration used can be found [here](https://github.com/continuedev/continue/blob/5c9874400e223bbc9786a8823614a2e501fbdaf7/extensions/vscode/src/ideProtocol.ts#L45-L52).
105-
106-### `CustomContextProvider` Reference
107-
108-- `title`: An identifier for the context provider
109-
110-- `displayTitle` (optional): The title displayed in the dropdown
111-
112-- `description` (optional): The longer description displayed in the dropdown when hovered
113-
114-- `type` (optional): The type of context provider. Options are "normal", "query", and "submenu". Defaults to "normal".
115-
116-- `renderInlineAs` (optional): The string that will be rendered inline at the top of the prompt. If no value is provided, the `displayTitle` will be used. An empty string can be provided to prevent rendering the default `displayTitle`.
117-
118-- `getContextItems`: A function that returns the documents to include in the prompt. It should return a list of `ContextItem`s, and is given access to the following arguments:
119-
120- - `extras.fullInput`: A string representing the user's full input to the text box. This can be used for example to generate an embedding to compare against a set of other embedded documents
121- - `extras.embeddingsProvider`: The embeddings provider has an `embed` function that will convert text (such as `fullInput`) to an embedding
122- - `extras.llm`: The current default LLM, which you can use to make completion requests
123- - `extras.ide`: An instance of the `IDE` class, which lets you gather various sources of information from the IDE, including the contents of the terminal, the list of open files, or any warnings in the currently open file.
124- - `query`: (not currently used) A string representing the query
125-
126-- `loadSubmenuItems` (optional): A function that returns a list of `ContextSubmenuItem`s to display in a submenu. It is given access to an `IDE`, the same that is passed to `getContextItems`. .
127-
128-## How to Use Extension API for VSCode
129-
130-Continue exposes an API for registering context providers from a 3rd party VSCode extension. This is useful if you have a VSCode extension that provides some additional context that you would like to use in Continue. To use this API, add the following to your `package.json`:
131-
132-package.json
133-
134-```json
135-{ "extensionDependencies": ["continue.continue"] }
136-```
137-
138-Or install the Continue Core module from npm:
139-
140-```
141-npm i @continuedev/core
142-```
143-
144-You can add the Continue core module as a dev dependency in your `package.json`:
145-
146-package.json
147-
148-```json
149-{ "devDependencies": { "@continuedev/core": "^0.0.1" } }
150-```
151-
152-Then, you can use the `registerCustomContextProvider` function to register your context provider. Your custom context provider must implement the `IContextProvider` interface. Here is an example:
153-
154-myCustomContextProvider.ts
155-
156-```
157-import * as vscode from "vscode";import { IContextProvider, ContextProviderDescription, ContextProviderExtras, ContextItem, LoadSubmenuItemsArgs, ContextSubmenuItem,} from "@continuedev/core";class MyCustomProvider implements IContextProvider { get description(): ContextProviderDescription { return { title: "Custom", displayTitle: "Custom", description: "my custom context provider", type: "normal", }; } async getContextItems( query: string, extras: ContextProviderExtras, ): Promise<ContextItem[]> { return [ { name: "Custom", description: "Custom description", content: "Custom content", }, ]; } async loadSubmenuItems( args: LoadSubmenuItemsArgs, ): Promise<ContextSubmenuItem[]> { return []; }}// create an instance of your custom providerconst customProvider = new MyCustomProvider();// get Continue extension using vscode APIconst continueExt = vscode.extensions.getExtension("Continue.continue");// get the API from the extensionconst continueApi = continueExt?.exports;// register your custom providercontinueApi?.registerCustomContextProvider(customProvider);
158-```
159-
160-This will register `MyCustomProvider` with Continue!
161-
162-![alt text](/images/guides/images/image-8befb5162b7779402f70ff42bb589edb.png)
modified docs/guides/cli.mdx +2 −2
@@ -4,7 +4,7 @@
44 description: "Learn how to use Continue's command-line interface for context engineering, automated coding tasks, and headless development workflows with customizable models, rules, and tools"
55 ---
66
7-<Warning>Continue CLI (cn) is currently in Alpha</Warning>
7+<Warning>Continue CLI (cn) is currently in Beta</Warning>
88
99 `cn` is an open-source, modular coding agent for the command line.
1010
@@ -91,4 +91,4 @@
9191
9292 Run `cn` with the `--verbose` flag to see more detailed logs. These will be output to `~/.continue/logs/cn.log`.
9393
94-If you have feedback on the alpha, please [share in our Discord](https://discord.com/invite/EfJEfdFnDQ).
94+If you have feedback on the beta, please [share in our Discord](https://discord.com/invite/EfJEfdFnDQ) or [leave feedback in the GitHub discussion](https://github.com/continuedev/continue/discussions/7307).
added docs/guides/codebase-documentation-awareness.mdx +182 −0
@@ -0,0 +1,182 @@
1+---
2+title: How to make your agent aware of codebases and documentation
3+description: Learn how to give your AI agent access to codebases and documentation for more context-aware assistance
4+keywords: [agent, codebase, documentation, MCP, context, RAG, tools]
5+---
6+
7+# How to make your agent aware of codebases and documentation
8+
9+AI coding agents work best when they understand the context of your project. This guide shows you how to give your agent access to codebases and documentation, making it more helpful and accurate.
10+
11+## Make your agent aware of your open codebase
12+
13+When your agent understands your current codebase, it can provide more relevant suggestions and answers.
14+
15+### Let your agent explore the codebase using tools
16+
17+Your agent can use built-in tools to navigate and understand your code:
18+
19+1. **File exploration tools**: The agent can read files, search for patterns, and understand project structure
20+2. **Code search**: Use search to find relevant code snippets
21+3. **Git integration**: Access commit history and understand code evolution
22+
23+### Create rules to help the agent understand your codebase
24+
25+Rules guide your agent's behavior and understanding. Place markdown files in `.continue/rules` in your project to provide context:
26+
27+```markdown
28+# Project Architecture
29+
30+This is a React application with:
31+- Components in `/src/components`
32+- API routes in `/src/api`
33+- State management using Redux in `/src/store`
34+
35+## Coding Standards
36+- Use TypeScript for all new files
37+- Follow the existing naming conventions
38+- Write tests for all new features
39+```
40+
41+<Tip>
42+ Place rules files at different levels of your project hierarchy to scope when they trigger
43+</Tip>
44+
45+Learn more about [rules configuration](/customize/deep-dives/rules).
46+
47+## Make your agent aware of other codebases
48+
49+Sometimes you need your agent to understand code beyond your current project.
50+
51+### Public codebases
52+
53+For open-source projects and public repositories, you have several options:
54+
55+#### Rules with hyperlinks
56+
57+Create rules that point to external codebases:
58+
59+```markdown
60+# External Dependencies
61+
62+Our authentication system is based on:
63+- [Auth.js documentation](https://authjs.dev/)
64+- [Example implementation](https://github.com/nextauthjs/next-auth-example)
65+
66+When implementing auth features, reference these patterns.
67+```
68+
69+#### GitHub and GitLab CLIs
70+
71+Enable `gh` or `glab` CLI access for your agent to interact with repositories.
72+
73+Add rules to guide CLI usage:
74+
75+```markdown
76+# Repository Access
77+
78+You can use the `gh` CLI to:
79+- Search for issues: `gh issue list --repo owner/repo`
80+- View pull requests: `gh pr list --repo owner/repo`
81+- Clone repositories: `gh repo clone owner/repo`
82+```
83+
84+#### DeepWiki MCP
85+
86+[DeepWiki MCP](https://hub.continue.dev/deepwiki/deepwiki-mcp) lets your agent explore any public GitHub repository.
87+
88+Once configured, your agent can explore repositories like:
89+- "Explore the React repository structure"
90+- "Find how authentication is implemented in NextAuth.js"
91+
92+### Internal codebases
93+
94+For private and internal repositories, you need additional setup:
95+
96+#### Custom MCP servers
97+
98+Create an MCP server that has access to your internal repositories.
99+
100+#### Custom code RAG
101+
102+For faster retrieval and lower costs with very large internal codebases, consider implementing a [custom code RAG](/guides/custom-code-rag) system. This is an advanced approach that requires more setup but can provide performance benefits at scale.
103+
104+## Make your agent aware of relevant documentation
105+
106+Documentation provides crucial context for your agent to understand APIs, frameworks, and best practices.
107+
108+### Public documentation
109+
110+#### Rules with documentation links
111+
112+Guide your agent to relevant documentation:
113+
114+```markdown
115+# Documentation Resources
116+
117+For framework-specific questions, refer to:
118+- React: https://react.dev/reference/react
119+- Next.js: https://nextjs.org/docs
120+- Tailwind CSS: https://tailwindcss.com/docs
121+
122+Always cite documentation when explaining concepts.
123+```
124+
125+#### Context7 MCP
126+
127+[Context7 MCP](https://hub.continue.dev/upstash/context7-mcp) enables your agent to search and retrieve information from public documentation:
128+
129+Your agent can then answer questions like:
130+- "How do I use React hooks?"
131+- "What's the syntax for Tailwind CSS animations?"
132+
133+### Internal documentation
134+
135+For private documentation and wikis:
136+
137+#### Rules with internal links
138+
139+Create rules that reference internal resources:
140+
141+```markdown
142+# Internal Documentation
143+
144+Our team documentation is available at:
145+- API Documentation: https://internal.docs/api
146+- Architecture Guide: https://internal.docs/architecture
147+- Deployment Process: https://internal.docs/deployment
148+
149+Always follow our internal standards when suggesting code.
150+```
151+
152+#### Custom MCP servers for docs
153+
154+Create an MCP server that accesses your internal documentation.
155+
156+## Migrating from deprecated context providers
157+
158+If you were previously using the `@Codebase` or `@Docs` context providers, here's how to migrate to the new approach:
159+
160+### Migrating from @Codebase
161+
162+The `@Codebase` context provider has been deprecated. Instead:
163+
164+1. **Use built-in tools**: Your agent can now use file exploration and search tools to understand your codebase
165+2. **Add rules**: Create `.continue/rules` files to provide context about your project structure
166+3. **Use MCP servers**: For external codebases, use DeepWiki MCP or custom MCP servers
167+
168+### Migrating from @Docs
169+
170+The `@Docs` context provider has been deprecated. Instead:
171+
172+1. **Use Context7 MCP**: For public documentation, Context7 MCP provides similar functionality
173+2. **Add documentation links in rules**: Create rules that reference documentation URLs
174+3. **Use custom MCP servers**: For internal documentation, create an MCP server with access to your docs
175+
176+The new approach provides better integration with Continue's Agent features and more intelligent context selection.
177+
178+## Next steps
179+
180+- Learn more about [MCP servers](/reference/continue-mcp)
181+- Explore [rules configuration](/customize/deep-dives/rules)
182+- Set up [custom assistants](/guides/understanding-assistants) with specific knowledge domains
added docs/guides/continuous-ai.mdx +207 −0
@@ -0,0 +1,207 @@
1+---
2+title: "Continuous AI: A Developer's Guide"
3+description: "Learn how to integrate intelligent automation into development workflows, making AI assistance as natural as syntax highlighting. Implement systematic AI workflows that compound productivity gains over time."
4+---
5+
6+Continuous AI is the integration of intelligent automation directly into development workflows, making AI assistance as natural and reliable as syntax highlighting or code completion. Its purpose is to amplify developer intent at every stage of the coding process.
7+
8+Think of it this way: DevOps automated the mechanical aspects of software delivery—building, testing, deploying. Continuous AI automates the intelligence aspects—understanding context, making suggestions, adapting to patterns, and learning from developer feedback.
9+
10+## Why Continuous AI Matters Now
11+
12+The same market forces that made DevOps inevitable are now driving Continuous AI adoption:
13+
14+<CardGroup>
15+ <Card title="Developer Behavior is Shifting" icon="chart-line">
16+ Engineering teams are rapidly adopting AI tools, with many seeing
17+ significant productivity improvements in their workflows.
18+ </Card>
19+
20+<Card title="Economic Pressure" icon="dollar-sign">
21+ AI-assisted coding is contributing measurable increases in developer output,
22+ creating competitive advantages for early adopters.
23+</Card>
24+
25+ <Card title="Tooling Maturity" icon="wrench">
26+ Unlike DevOps, Continuous AI can be implemented incrementally on existing
27+ development stacks without major infrastructure changes.
28+ </Card>
29+</CardGroup>
30+
31+The teams that implement systematic AI workflows first create advantages that compound over time.
32+
33+## The Continuous AI Maturity Model
34+
35+Teams typically progress through three stages when adopting Continuous AI:
36+
37+<Accordion title="Level 1: Manual AI Assistance">
38+You prompt the AI when you remember, and it completes the task. This is great for quick productivity boosts but remains highly manual and inconsistent.
39+
40+**Example**: Using AI to draft a function or suggest a test case only when you think to ask for it.
41+
42+**Continue Implementation**: Using [Chat](/features/chat/quick-start) or [Edit](/features/edit/quick-start) mode for one-off coding tasks.
43+
44+</Accordion>
45+
46+<Accordion title="Level 2: Workflow Automation">
47+AI handles routine tasks with human oversight. This is where teams start seeing compounding gains.
48+
49+**Examples**:
50+
51+- AI adds missing documentation during PR review
52+- Automatic code formatting and style corrections
53+- Generated unit tests for new functions
54+- Updated issue tracking when branches are merged
55+
56+**Continue Implementation**: Using [Continue CLI](/guides/cli) with custom rules and integrations into CI/CD pipelines.
57+
58+</Accordion>
59+
60+<Accordion title="Level 3: Zero-Intervention Workflows">
61+AI autonomously completes processes end-to-end without human input, but only for very specific, low-risk workflows.
62+
63+**Examples**:
64+
65+- AI merges safe dependency updates after automated tests pass
66+- Automatic documentation updates when code changes
67+- Self-healing test suites that fix themselves based on failure patterns
68+
69+**Continue Implementation**: Fully automated [agents](/features/agent/quick-start) with strict permissions and safety guardrails.
70+
71+</Accordion>
72+
73+## Building Your Continuous AI Workflow
74+
75+### Start with Level 1 → Level 2: Pick One Workflow
76+
77+Don't try to automate everything at once. Choose a specific daily friction point:
78+
79+```bash
80+# Example: Automated code review comments
81+git diff | cn -p "review this diff and suggest improvements following our team standards"
82+
83+# Example: Generate missing tests
84+cn -p "create unit tests for the functions in src/auth.js"
85+
86+# Example: Update documentation
87+cn -p "update the README with the new API endpoints from the recent changes"
88+```
89+
90+### Configure Team-Wide Intelligence
91+
92+The most effective Continuous AI is tuned to your codebase, standards, and practices:
93+
94+```yaml config.yaml
95+rules:
96+ - name: code-review
97+ description: "Review code following team standards"
98+ rule: "Review following our TypeScript style guide and security practices"
99+ context:
100+ - "docs/style-guide.md"
101+ - "security-checklist.md"
102+```
103+
104+### Implement Progressive Permissions
105+
106+Use Continue CLI's permission system to gradually expand AI capabilities:
107+
108+```yaml ~/.continue/permissions.yaml
109+permissions:
110+ - allow: "Bash(git*)" # Git commands are safe
111+ - ask: "Write(**/*.ts)" # Ask before modifying TypeScript files
112+ - deny: "Bash(rm*)" # Never allow deletions
113+```
114+
115+### Measure What Matters: Intervention Rate
116+
117+Track how often you need to correct AI output. Lower intervention rates mean higher trust and compounding productivity gains.
118+
119+## Real-World Implementation Patterns
120+
121+<AccordionGroup>
122+ <Accordion title="Pattern 1: The Async Triage Bot">
123+ Imagine setting up an AI agent that checks new GitHub issues every morning and leaves the first helpful response. This lightens the load for maintainers and ensures community members feel heard quickly.
124+ </Accordion>
125+
126+ <Accordion title="Pattern 2: The PR Review Agent">
127+ AI can automatically review new pull requests for security, performance, and style issues. The reviewer still has the final say, but the agent highlights common problems and speeds up the feedback loop.
128+
129+ </Accordion>
130+ <Accordion title="Pattern 3: The Documentation Guardian">
131+ Whenever code changes, AI can scan for mismatches in documentation and suggest updates. This keeps docs current without relying on developers to remember every detail.
132+ </Accordion>
133+</AccordionGroup>
134+## Best Practices for Sustainable Continuous AI
135+
136+<CardGroup>
137+ <Card title="Human-AI Collaboration" icon="handshake">
138+ AI should amplify human intelligence, not replace it. Always validate AI
139+ suggestions rather than blindly accepting them.
140+ </Card>
141+
142+<Card title="Start Small, Scale Thoughtfully" icon="seedling">
143+ Begin with low-risk, high-value automations. Gradually expand as you build
144+ trust and understanding.
145+</Card>
146+
147+<Card title="Customize for Your Context" icon="cog">
148+ Generic AI suggestions are often wrong or irrelevant. Configure AI to
149+ understand your specific patterns and requirements.
150+</Card>
151+
152+ <Card title="Build Safety Guardrails" icon="shield">
153+ Use permission systems, code review processes, and testing to ensure AI
154+ actions are safe and reversible.
155+ </Card>
156+</CardGroup>
157+
158+## Common Pitfalls to Avoid
159+
160+<Warning>
161+ **Over-automation**: Don't automate processes you don't fully understand
162+</Warning>
163+
164+<Warning>
165+ **Ignoring Context**: AI works best when it understands your codebase and team
166+ practices
167+</Warning>
168+
169+<Warning>
170+ **Skipping Safety**: Always implement proper permissions and review processes
171+</Warning>
172+
173+<Warning>
174+ **Vanity Metrics**: Focus on intervention rate and actual time saved, not "AI
175+ suggestions generated"
176+</Warning>
177+
178+## Getting Started Today
179+
180+<Steps>
181+ <Step title="Install Continue CLI">
182+ ```bash npm i -g @continuedev/cli ```
183+ </Step>
184+
185+<Step title="Pick One Workflow">Choose a daily friction point to automate</Step>
186+
187+<Step title="Set Permissions">Configure safe boundaries for AI actions</Step>
188+
189+<Step title="Measure Impact">Track intervention rates and time saved</Step>
190+
191+ <Step title="Iterate and Expand">Gradually add more automated workflows</Step>
192+</Steps>
193+
194+## The Competitive Advantage
195+
196+Teams implementing Continuous AI are coding faster and building institutional intelligence that scales with their organization. While others manually perform routine tasks, your AI handles the repetitive work so your team can focus on innovation and complex problem-solving.
197+
198+## What's Next?
199+
200+As AI capabilities continue to improve and tooling matures, we're moving toward a world where intelligent assistance is as fundamental to development as version control or IDEs. The teams that start building these capabilities now will have refined systems, cultural readiness, and institutional knowledge when Continuous AI becomes the industry standard.
201+
202+Ready to amplify your development workflow with Continuous AI? Start with one simple automation and build from there.
203+
204+<Card title="Want to dive deeper?" icon="rocket">
205+ Check out our guides on [Continue CLI](/guides/cli) and [Understanding
206+ Agents](/guides/understanding-agents).
207+</Card>
modified docs/guides/custom-code-rag.mdx +83 −33
@@ -1,6 +1,7 @@
11 ---
22 title: "How to Build Custom Code RAG"
3-description: "Learn how to build a custom retrieval-augmented generation (RAG) system for code using vector databases like LanceDB, embeddings models like voyage-code-3, and chunking strategies for better code search and context"
3+description: "Build a custom retrieval-augmented generation (RAG) system for faster and more cost-efficient code search across large codebases. This guide is for advanced users who need to index code a single time across all users or include custom logic."
4+keywords: [RAG, vector database, embeddings, code search, MCP]
45 ---
56
67 ## Step 1: How to Choose an Embeddings Model
@@ -61,45 +62,94 @@
6162
6263 In the beginning, you should probably run it by hand. Once you are confident that your custom RAG is providing value and is ready for the long-term, then you can set up a cron job to run it periodically. Because codebases are largely unchanged in short time frames, you won't want to re-index more than once a day. Once per week or month is probably even sufficient.
6364
64-## Step 6: How to Set Up Your Server
65-
66-In order for the Continue extension to access your custom RAG system, you'll need to set up a server. This server is responsible for recieving a query from the extension, querying the vector database, and returning the results in the format expected by Continue.
67-
68-Here is a reference implementation using FastAPI that is capable of handling requests from Continue's "http" context provider.
69-
70-```
71-"""This is an example of a server that can be used with the "http" context provider."""from fastapi import FastAPIfrom pydantic import BaseModelclass ContextProviderInput(BaseModel): query: str fullInput: strapp = FastAPI()@app.post("/retrieve")async def create_item(item: ContextProviderInput): results = [] # TODO: Query your vector database here. # Construct the "context item" format expected by Continue context_items = [] for result in results: context_items.append({ "name": result.filename, "description": result.filename, "content": result.text, }) return context_items
65+## Step 6: How to set up an MCP server
66+
67+To integrate your custom RAG system with Continue, you'll create an MCP (Model Context Protocol) server. MCP provides a standardized way for AI tools to access external resources.
68+
69+### Create your MCP server
70+
71+Here's a reference implementation using Python that queries your vector database:
72+
73+```python
74+"""Custom RAG MCP server for code retrieval"""
75+import asyncio
76+from mcp.server import Server
77+from mcp.server.stdio import stdio_server
78+from mcp.types import Tool, TextContent
79+import lancedb
80+
81+# Initialize your vector database connection
82+db = lancedb.connect("/path/to/your/db")
83+table = db.open_table("code_chunks")
84+
85+app = Server("custom-rag-server")
86+
87+@app.tool()
88+async def search_codebase(query: str, limit: int = 10) -> list[TextContent]:
89+ """
90+ Search the codebase using vector similarity.
91+
92+ Args:
93+ query: The search query
94+ limit: Maximum number of results to return
95+ """
96+ # Query your vector database
97+ results = table.search(query).limit(limit).to_list()
98+
99+ # Format results for Continue
100+ formatted_results = []
101+ for result in results:
102+ formatted_results.append(TextContent(
103+ type="text",
104+ text=f"File: {result['filename']}\n\n{result['text']}"
105+ ))
106+
107+ return formatted_results
108+
109+@app.tool()
110+async def get_file_context(filename: str) -> list[TextContent]:
111+ """
112+ Get all chunks from a specific file.
113+
114+ Args:
115+ filename: The name of the file to retrieve
116+ """
117+ results = table.where(f"filename = '{filename}'").to_list()
118+
119+ return [TextContent(
120+ type="text",
121+ text="\n".join([r['text'] for r in results])
122+ )]
123+
124+if __name__ == "__main__":
125+ stdio_server(app).run()
72126 ```
73127
74-After you've set up your server, you can configure Continue to use it by adding the "http" context provider to your `contextProviders` array in your configuration:
75-
76-- YAML
77-- JSON
78-
79-config.yaml
80-
128+### Configure Continue to use your MCP server
129+
130+Add your MCP server to Continue's configuration:
131+
132+**config.yaml:**
133+```yaml
134+mcpServers:
135+ - name: custom-rag
136+ command: python
137+ args:
138+ - /path/to/your/mcp_server.py
139+ env:
140+ VOYAGE_API_KEY: ${VOYAGE_API_KEY}
81141 ```
82-context:
83- - provider: http
84- params:
85- url: https://myserver.com/retrieve
86- name: http
87- description: Custom HTTP Context Provider
88- displayTitle: My Custom Context
89-```
90-
91-config.json
92142
143+**config.json:**
93144 ```json
94145 {
95- "contextProviders": [
146+ "mcpServers": [
96147 {
97- "name": "http",
98- "params": {
99- "url": "https://myserver.com/retrieve",
100- "title": "http",
101- "description": "Custom HTTP Context Provider",
102- "displayTitle": "My Custom Context"
148+ "name": "custom-rag",
149+ "command": "python",
150+ "args": ["/path/to/your/mcp_server.py"],
151+ "env": {
152+ "VOYAGE_API_KEY": "${VOYAGE_API_KEY}"
103153 }
104154 }
105155 ]
added docs/guides/instinct.mdx +39 −0
@@ -0,0 +1,39 @@
1+---
2+title: "Using Instinct with Ollama in Continue"
3+description: "Learn how to run Instinct, Continue's leading open Next Edit model, on your own hardware with Ollama"
4+---
5+
6+<Warning>
7+ Instinct is a 7 billion parameter model. You should expect slow responses if
8+ running on a laptop. To learn how to inference Instinct on a GPU, see our
9+ [HuggingFace model card](https://huggingface.co/continuedev/instinct).
10+</Warning>
11+
12+We recently released Instinct, a state-of-the-art open Next Edit model. Robustly fine-tuned from Qwen2.5-Coder-7B, Instinct intelligently predicts your next move to keep you in flow. To learn more about the model, check out [our blog post](https://blog.continue.dev).
13+
14+<Frame>
15+ <img src="/images/instinct.gif" />
16+</Frame>
17+
18+### 1. Install Ollama
19+
20+If you haven't already installed Ollama, see our guide [here](./ollama-guide.mdx).
21+
22+### 2. Download Instinct
23+
24+```bash
25+ollama run nate/instinct
26+```
27+
28+### 3. Update your `config.yaml`
29+
30+Open your `config.yaml` and add Instinct to the models section:
31+
32+```yaml
33+# ... rest of config.yaml ...
34+
35+models:
36+ - uses: continuedev/instinct
37+```
38+
39+Alternatively, you can just click to add the block at https://hub.continue.dev/continuedev/instinct.
deleted docs/guides/llama3.1.mdx +0 −222
@@ -1,222 +0,0 @@
1----
2-title: "How to Use Llama 3.1 with Continue"
3-description: "Learn how to set up and use Llama 3.1 models with Continue using Ollama, Groq, Together AI, Replicate, SambaNova, or Cerebras Inference for local and cloud-based development"
4----
5-
6-If you haven't already installed Continue, you can do that [here for VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) or [here for JetBrains](https://plugins.jetbrains.com/plugin/22707-continue). For more general information on customizing Continue, read [our customization docs](/customize/overview).
7-
8-Below we share some of the easiest ways to get up and running, depending on your use-case.
9-
10-## How to Use Llama 3.1 with Ollama
11-
12-Ollama is the fastest way to get up and running with local language models. We recommend trying Llama 3.1 8b, which is impressive for its size and will perform well on most hardware.
13-
14-1. Download Ollama [here](https://ollama.ai/) (it should walk you through the rest of these steps)
15-2. Open a terminal and run `ollama run llama3.1:8b`
16-3. Change your Continue config file like this:
17-
18-- YAML
19-- JSON
20-
21-config.yaml
22-
23-```
24-models:
25- - name: Llama 3.1 8b
26- provider: ollama
27- model: llama3.1-8b
28-```
29-
30-config.json
31-
32-```json
33-{
34- "models": [
35- { "title": "Llama 3.1 8b", "provider": "ollama", "model": "llama3.1-8b" }
36- ]
37-}
38-```
39-
40-## How to Use Llama 3.1 with Groq
41-
42-<Info>
43- Check if your chosen model is still supported by referring to the [model
44- documentation](https://console.groq.com/docs/models). If a model has been
45- deprecated, you may encounter a 404 error when attempting to use it.
46-</Info>
47-
48-Groq provides the fastest available inference for open-source language models, including the entire Llama 3.1 family.
49-
50-1. Obtain an API key [here](https://console.groq.com/keys)
51-2. Update your Continue config file like this:
52-
53-- YAML
54-- JSON
55-
56-config.yaml
57-
58-```
59-models:
60- - name: Llama 3.3 70b Versatile
61- provider: groq
62- model: llama-3.3-70b-versatile
63- apiKey: <YOUR_GROQ_API_KEY>
64-```
65-
66-config.json
67-
68-```json
69-{
70- "models": [
71- {
72- "title": "Llama 3.3 70b Versatile",
73- "provider": "groq",
74- "model": "llama-3.3-70b-versatile",
75- "apiKey": "<YOUR_GROQ_API_KEY>"
76- }
77- ]
78-}
79-```
80-
81-## How to Use Llama 3.1 with Together AI
82-
83-Together AI provides fast and reliable inference of open-source models. You'll be able to run the 405b model with good speed.
84-
85-1. Create an account [here](https://api.together.xyz/signup)
86-2. Copy your API key that appears on the welcome screen
87-3. Update your Continue config file like this:
88-
89-- YAML
90-- JSON
91-
92-config.yaml
93-
94-```
95-models:
96- - name: Llama 3.1 405b
97- provider: together
98- model: llama3.1-405b
99- apiKey: <YOUR_TOGETHER_API_KEY>
100-```
101-
102-config.json
103-
104-```json
105-{
106- "models": [
107- {
108- "title": "Llama 3.1 405b",
109- "provider": "together",
110- "model": "llama3.1-405b",
111- "apiKey": "<YOUR_TOGETHER_API_KEY>"
112- }
113- ]
114-}
115-```
116-
117-## How to Use Llama 3.1 with Replicate
118-
119-Replicate makes it easy to host and run open-source AI with an API.
120-
121-1. Get your Replicate API key [here](https://replicate.ai/)
122-2. Change your Continue config file like this:
123-
124-- YAML
125-- JSON
126-
127-config.yaml
128-
129-```
130-models:
131- - name: Llama 3.1 405b
132- provider: replicate
133- model: llama3.1-405b
134- apiKey: <YOUR_REPLICATE_API_KEY>
135-```
136-
137-config.json
138-
139-```json
140-{
141- "models": [
142- {
143- "title": "Llama 3.1 405b",
144- "provider": "replicate",
145- "model": "llama3.1-405b",
146- "apiKey": "<YOUR_REPLICATE_API_KEY>"
147- }
148- ]
149-}
150-```
151-
152-## How to Use Llama 3.1 with SambaNova
153-
154-SambaNova Cloud provides world record Llama3.1 70B/405B serving.
155-
156-1. Create an account [here](http://cloud.sambanova.ai?utm_source=continue&utm_medium=external&utm_campaign=cloud_signup)
157-2. Copy your API key
158-3. Update your Continue config file like this:
159-
160-- YAML
161-- JSON
162-
163-config.yaml
164-
165-```
166-models:
167- - name: SambaNova Llama 3.1 405B
168- provider: sambanova
169- model: llama3.1-405b
170- apiKey: <YOUR_SAMBA_API_KEY>
171-```
172-
173-config.json
174-
175-```json
176-{
177- "models": [
178- {
179- "title": "SambaNova Llama 3.1 405B",
180- "provider": "sambanova",
181- "model": "llama3.1-405b",
182- "apiKey": "<YOUR_SAMBA_API_KEY>"
183- }
184- ]
185-}
186-```
187-
188-## How to Use Llama 3.1 with Cerebras Inference
189-
190-Cerebras Inference uses specialized silicon to provides fast inference for the Llama3.1 8B/70B.
191-
192-1. Create an account in the portal [here](https://cloud.cerebras.ai/).
193-2. Create and copy the API key for use in Continue.
194-3. Update your Continue config file:
195-
196-- YAML
197-- JSON
198-
199-config.yaml
200-
201-```
202-models:
203- - name: Cerebras Llama 3.1 70B
204- provider: cerebras
205- model: llama3.1-70b
206- apiKey: <YOUR_CEREBRAS_API_KEY>
207-```
208-
209-config.json
210-
211-```json
212-{
213- "models": [
214- {
215- "title": "Cerebras Llama 3.1 70B",
216- "provider": "cerebras",
217- "model": "llama3.1-70b",
218- "apiKey": "<YOUR_CEREBRAS_API_KEY>"
219- }
220- ]
221-}
222-```
modified docs/guides/ollama-guide.mdx +274 −51
@@ -14,7 +14,7 @@
1414
1515 ## How to Install Ollama - Step-by-Step
1616
17-### Step 1: How to Install Ollama
17+### Step 1: Install Ollama
1818
1919 Choose the installation method for your operating system:
2020
@@ -29,110 +29,333 @@
2929 # Download from ollama.ai
3030 ```
3131
32-### Step 2: How to Download Models
32+### Step 2: Start Ollama Service
3333
34-After installing Ollama, download the models you want to use. Here are some popular options:
34+After installation, start the Ollama service:
3535
36+```bash
37+# Check Ollama version - verify it's installed
38+ollama --version
39+
40+# Start Ollama (runs in background)
41+ollama serve
42+
43+# Verify it's running
44+curl http://localhost:11434
45+# Should return "Ollama is running"
3646 ```
37-# Popular models for development
38-ollama pull mistral
39-ollama pull qwen2.5-coder:1.5b-base
40-ollama pull nomic-embed-text:latest
47+
48+### Step 3: Download Models
49+
50+<Warning>
51+ **Important**: Always use `ollama pull` instead of `ollama run` to download
52+ models. The `run` command starts an interactive session which isn't needed for
53+ Continue.
54+</Warning>
55+
56+Download models using the exact tag specified:
57+
58+```bash
59+# Pull models with specific tags
60+ollama pull deepseek-r1:32b # 32B parameter version
61+ollama pull deepseek-r1:latest # Latest/default version
62+ollama pull mistral:latest
63+ollama pull qwen2.5-coder:1.5b
64+
65+# List all downloaded models
66+ollama list
4167 ```
4268
69+**Common Model Tags:**
70+
71+- `:latest` - Default version (used if no tag specified)
72+- `:32b`, `:7b`, `:1.5b` - Parameter count versions
73+- `:instruct`, `:base` - Model variants
74+
75+<Note>
76+ If a model page shows `deepseek-r1:32b` on Ollama's website, you must pull it
77+ with that exact tag. Using just `deepseek-r1` will pull `:latest` which may be
78+ a different size.
79+</Note>
80+
4381 ## How to Configure Ollama with Continue
4482
45-Configure Continue to work with your local Ollama instance:
83+There are multiple ways to configure Ollama models in Continue:
84+
85+### Method 1: Using Hub Model Blocks in Local config.yaml
86+
87+The easiest way is to use [pre-configured model blocks](/reference#local-blocks) from the Continue Hub in your local configuration:
88+
89+```yaml title="~/.continue/agents/My Local Agent.yaml"
90+name: My Local Agent
91+version: 0.0.1
92+schema: v1
93+models:
94+ - uses: ollama/deepseek-r1-32b
95+ - uses: ollama/qwen2.5-coder-7b
96+ - uses: ollama/gpt-oss-20b
97+```
98+
99+<Warning>
100+ **Important**: Hub blocks only provide configuration - you still need to pull
101+ the model locally. The hub block `ollama/deepseek-r1-32b` configures Continue
102+ to use `model: deepseek-r1:32b`, but the actual model must be installed:
103+ ```bash
104+ # Check what the hub block expects (view on hub.continue.dev)
105+ # Then pull that exact model tag locally
106+ ollama pull deepseek-r1:32b # Required for ollama/deepseek-r1-32b hub block
107+ ```
108+ If the model isn't installed, Ollama will return:
109+ `404 model "deepseek-r1:32b" not found, try pulling it first`
110+</Warning>
111+
112+### Method 2: Using Autodetect
113+
114+Continue can automatically detect available Ollama models. You can configure this in your YAML:
115+
116+```yaml title="~/.continue/config.yaml"
117+models:
118+ - name: Autodetect
119+ provider: ollama
120+ model: AUTODETECT
121+ roles:
122+ - chat
123+ - edit
124+ - apply
125+ - rerank
126+ - autocomplete
127+```
128+
129+Or use it through the GUI:
130+
131+1. Click on the model selector dropdown
132+2. Select "Autodetect" option
133+3. Continue will scan for available Ollama models
134+4. Select your desired model from the detected list
135+
136+<Note>
137+ The Autodetect feature scans your local Ollama installation and lists all
138+ available models. When set to `AUTODETECT`, Continue will dynamically populate
139+ the model list based on what's installed locally via `ollama list`. This is
140+ useful for quickly switching between models without manual configuration. For
141+ any roles not covered by the detected models, you may need to manually
142+ configure them.
143+</Note>
144+
145+You can update `apiBase` with the IP address of a remote machine serving Ollama.
146+
147+### Method 3: Manual Configuration
46148
47-### How to Set Up Continue Configuration
149+For custom configurations or models not on the hub:
48150
49151 ```yaml
50152 models:
51- - name: mistral
153+ - name: DeepSeek R1 32B
52154 provider: ollama
155+ model: deepseek-r1:32b # Must match exactly what `ollama list` shows
53156 apiBase: http://localhost:11434
54- model: mistral
55157 roles:
56158 - chat
57159 - edit
58- - apply
160+ capabilities: # Add if not auto-detected
161+ - tool_use
59162 - name: Qwen2.5-Coder 1.5B
60163 provider: ollama
61- apiBase: http://localhost:11434
62- model: qwen2.5-coder:1.5b-base
164+ model: qwen2.5-coder:1.5b
63165 roles:
64166 - autocomplete
65- - name: Nomic Embed
167+```
168+
169+### Model Capabilities and Tool Support
170+
171+Some Ollama models support tools (function calling) which is required for Agent mode. However, not all models that claim tool support work correctly:
172+
173+#### Checking Tool Support
174+
175+```yaml
176+models:
177+ - name: DeepSeek R1
66178 provider: ollama
67- apiBase: http://localhost:11434
68- model: nomic-embed-text:latest
69- roles:
70- - embed
179+ model: deepseek-r1:latest
180+ capabilities:
181+ - tool_use # Add this to enable tools
71182 ```
72183
73-You can update `apiBase` with the IP address of a remote machine serving Ollama.
184+<Warning>
185+ **Known Issue**: Some models like DeepSeek R1 may show "Agent mode is not
186+ supported" or "does not support tools" even with capabilities configured. This
187+ is a known limitation where the model's actual tool support differs from its
188+ advertised capabilities.
189+</Warning>
190+
191+#### If Agent Mode Shows "Not Supported"
192+
193+1. First, add `capabilities: [tool_use]` to your model config
194+2. If you still get errors, the model may not actually support tools despite documentation
195+3. Use a different model known to work with tools (e.g., Llama 3.1, Mistral)
196+
197+See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for more details.
74198
75199 ### How to Configure Advanced Settings
76200
77201 For optimal performance, consider these advanced configuration options:
78202
79-- Memory optimization
80-- GPU acceleration
81-- Custom model parameters
82-- Performance tuning
203+```yaml
204+models:
205+ - name: Optimized DeepSeek
206+ provider: ollama
207+ model: deepseek-r1:32b
208+ contextLength: 8192 # Adjust context window (default varies by model)
209+ completionOptions:
210+ temperature: 0.7 # Controls randomness (0.0-1.0)
211+ top_p: 0.9 # Nucleus sampling threshold
212+ top_k: 40 # Top-k sampling
213+ num_predict: 2048 # Max tokens to generate
214+ # Ollama-specific options (set via environment or modelfile)
215+ # num_gpu: 35 # Number of GPU layers to offload
216+ # num_thread: 8 # CPU threads to use
217+```
218+
219+For GPU acceleration and memory tuning, create an Ollama Modelfile:
220+
221+```
222+# Create custom model with optimizations
223+FROM deepseek-r1:32b
224+PARAMETER num_gpu 35
225+PARAMETER num_thread 8
226+PARAMETER num_ctx 4096
227+```
83228
84229 ## What Are the Best Practices for Ollama
85230
86231 ### How to Choose the Right Model
87232
88-Choose models based on your specific needs:
233+Choose models based on your specific needs (see [recommended models](/customization/models#recommended-models) for more options):
234+
235+1. **Code Generation**:
236+
237+ - `qwen2.5-coder:7b` - Excellent for code completion
238+ - `codellama:13b` - Strong general coding support
239+ - `deepseek-coder:6.7b` - Fast and efficient
240+
241+2. **Chat & Reasoning**:
242+
243+ - `llama3.1:8b` - Latest Llama with tool support
244+ - `mistral:7b` - Fast and versatile
245+ - `deepseek-r1:32b` - Advanced reasoning capabilities
89246
90-1. **Code Generation**: Use CodeLlama or Mistral
91-2. **Chat**: Llama2 or Mistral
92-3. **Specialized Tasks**: Domain-specific models
247+3. **Autocomplete**:
248+
249+ - `qwen2.5-coder:1.5b` - Lightweight and fast
250+ - `starcoder2:3b` - Optimized for code completion
251+
252+4. **Memory Requirements**:
253+ - 1.5B-3B models: ~4GB RAM
254+ - 7B models: ~8GB RAM
255+ - 13B models: ~16GB RAM
256+ - 32B models: ~32GB RAM
93257
94258 ### How to Optimize Performance
95259
96260 To get the best performance from Ollama:
97261
98-- Monitor system resources
99-- Adjust context window size
100-- Use appropriate model sizes
101-- Enable GPU acceleration when available
262+- Monitor system resources with `ollama ps` to see memory usage
263+- Adjust context window size based on available RAM
264+- Use appropriate model sizes for your hardware
265+- Enable GPU acceleration when available (NVIDIA CUDA or AMD ROCm)
266+- Use `ollama logs` to debug performance issues
102267
103268 ## How to Troubleshoot Ollama Issues
104269
105-### What Are Common Issues
270+### Common Configuration Problems
271+
272+#### "404 model not found, try pulling it first"
273+
274+This error occurs when the model isn't installed locally:
275+
276+**Problem**: Using a hub block or config that references a model not yet pulled
277+**Solution**:
278+
279+```bash
280+# Check what models you have
281+ollama list
282+
283+# Pull the exact model version needed
284+ollama pull model-name:tag # e.g., deepseek-r1:32b
285+```
286+
287+#### Model Tag Mismatches
106288
107-Here are solutions to common problems you might encounter:
289+**Problem**: `ollama pull deepseek-r1` installs `:latest` but hub block expects `:32b`
290+**Solution**: Always pull with the exact tag:
108291
109-#### How to Fix Connection Problems
292+```bash
293+# Wrong - pulls :latest
294+ollama pull deepseek-r1
110295
111-- Check Ollama service status
112-- Verify port availability
113-- Review firewall settings
296+# Right - pulls specific version
297+ollama pull deepseek-r1:32b
298+```
299+
300+#### "Agent mode is not supported"
301+
302+**Problem**: Model doesn't support tools/function calling
303+**Solutions**:
304+
305+1. Add `capabilities: [tool_use]` to your model config
306+2. If still not working, the model may not actually support tools
307+3. Switch to a model with confirmed tool support (Llama 3.1, Mistral)
308+
309+#### Using Hub Blocks in Local Config
114310
115-#### How to Resolve Performance Issues
311+**Problem**: Unclear how to use hub models locally
312+**Solution**: Create a local agent file:
116313
117-- Insufficient RAM
118-- Model too large for system
119-- GPU compatibility
314+```yaml
315+# ~/.continue/agents/Local.yaml
316+name: Local Agent
317+version: 0.0.1
318+schema: v1
319+models:
320+ - uses: ollama/model-name
321+```
120322
121-### How to Apply Solutions
323+### How to Fix Connection Problems
122324
123-Try these solutions in order:
325+- Verify Ollama is running: `curl http://localhost:11434`
326+- Check service status: `systemctl status ollama` (Linux)
327+- Ensure port 11434 is not blocked by firewall
328+- For remote connections, set `OLLAMA_HOST=0.0.0.0:11434`
124329
125-1. Restart Ollama service
126-2. Clear model cache
127-3. Update to latest version
128-4. Check system requirements
330+### How to Resolve Performance Issues
331+
332+- Insufficient RAM: Use smaller models (7B instead of 32B)
333+- Model too large: Check available memory with `ollama ps`
334+- GPU issues: Verify CUDA/ROCm installation for GPU acceleration
335+- Slow generation: Adjust `num_gpu` layers in model configuration
336+- Check system diagnostics: `ollama ps` for active models and memory usage
129337
130338 ## What Are Example Workflows with Ollama
131339
132340 ### How to Use Ollama for Code Generation
133341
134-```
135-# Example: Generate a FastAPI endpointdef create_user_endpoint(): # Continue will help generate the implementation pass
342+```python
343+# Example: Generate a FastAPI endpoint
344+from fastapi import FastAPI, HTTPException
345+from pydantic import BaseModel
346+
347+app = FastAPI()
348+
349+class User(BaseModel):
350+ name: str
351+ email: str
352+ age: int
353+
354+@app.post("/users/")
355+async def create_user(user: User):
356+ # Continue will help complete this implementation
357+ # Use Cmd+I (Mac) or Ctrl+I (Windows/Linux) to generate code
358+ pass
136359 ```
137360
138361 ### How to Use Ollama for Code Review
@@ -150,4 +373,4 @@
150373
151374 ---
152375
153-_This guide is based on Ollama v0.1.x and Continue v0.8.x. Please check for updates regularly._
376+_This guide is based on Ollama v0.11.x and Continue v1.1.x. Please check for updates regularly._
modified docs/guides/overview.mdx +7 −4
@@ -6,15 +6,18 @@
66 ## What Model & Setup Guides Are Available
77
88 - [Using Ollama with Continue](/guides/ollama-guide) - Local AI development with Ollama
9-- [Setting up Codestral](/guides/set-up-codestral) - Configure Mistral's Codestral model
109 - [How to Self-Host a Model](/guides/how-to-self-host-a-model) - Self-hosting AI models
1110 - [Running Continue Without Internet](/guides/running-continue-without-internet) - Offline development setup
12-- [Llama 3.1 Setup](/guides/llama3.1) - Getting started with Llama 3.1
11+
12+## Continuous AI
13+
14+- [Continuous AI: A Developer's Guide](/guides/continuous-ai) - Integrating AI into development workflows
15+- [How to Use Continue CLI (cn)](/guides/cli) - Command-line interface for Continue
1316
1417 ## What Advanced Tutorials Are Available
1518
16-- [Build Your Own Context Provider](/guides/build-your-own-context-provider) - Create custom context providers
17-- [Custom Code RAG](/guides/custom-code-rag) - Implement custom retrieval-augmented generation
19+- [Codebase and Documentation Awareness](/guides/codebase-documentation-awareness) - Make your agent aware of codebases and documentation
20+- [Custom Code RAG](/guides/custom-code-rag) - Advanced: Build custom retrieval-augmented generation for large codebases
1821
1922 ## How to Contribute to Guides
2023
modified docs/guides/plan-mode-guide.mdx +0 −4
@@ -113,9 +113,6 @@
113113 | **Highlighted Code** | `cmd/ctrl + L` (VS Code) or `cmd/ctrl + J` (JetBrains) | Component-specific analysis |
114114 | **Active File** | `opt/alt + enter` when sending request | Current file context |
115115 | **@Files** | `@Files package.json tsconfig.json` | Specific file analysis |
116-| **@Folder** | `@Folder src/auth` | Directory-wide planning |
117-| **@Codebase** | `@Codebase` | Comprehensive system analysis |
118-| **@Docs** | `@Docs React Router` | Standards-compliant planning |
119116 | **@Terminal** | `@Terminal` | Debugging with output |
120117 | **@Git Diff** | `@Git Diff` | Change impact analysis |
121118
@@ -275,7 +272,6 @@
275272 **Remember:**
276273
277274 - Choose the right mode for each task
278-- Leverage context providers (@Codebase, @Files, @Docs, etc.) for better planning
279275 - Start broad, then focus your planning sessions for better results
280276 - Transition to Agent mode with clear execution steps
281277
modified docs/guides/running-continue-without-internet.mdx +2 −2
@@ -4,6 +4,6 @@
44 ---
55
66 1. Download the latest .vsix file from the [Open VSX Registry](https://open-vsx.org/extension/Continue/continue) and [install it to VS Code](https://code.visualstudio.com/docs/editor/extension-marketplace#_install-from-a-vsix).
7-2. Open the [User Settings Page](/customize/settings) and turn off "Allow Anonymous Telemetry". This will stop Continue from attempting requests to PostHog for [anonymous telemetry](/customize/telemetry).
8-3. Also in `config.json`, set the default model to a local model. You can find available options [here](/customize/model-providers/overview).
7+2. Turn off "Allow Anonymous Telemetry" in the user settings. This will stop Continue from attempting requests to PostHog for [anonymous telemetry](/customize/telemetry).
8+3. Also in `config.json`, set the default model to a local model. You can available options [here](/customization/models#openai).
99 4. Restart VS Code to ensure that the changes to `config.json` or `config.yaml` take effect.
deleted docs/guides/set-up-codestral.mdx +0 −58
@@ -1,58 +0,0 @@
1----
2-title: "How to Set Up Codestral"
3-description: "Step-by-step guide for configuring Mistral's Codestral model with Continue for both chat and autocomplete functionality using your Mistral AI API key"
4----
5-
6-**Here is a step-by-step guide on how to set up Codestral with Continue using the Mistral AI API:**
7-
8-1. Install the Continue VS Code or JetBrains extension following the instructions [here](/getting-started/install)
9-
10-2. Click on the gear icon in the bottom right corner of the Continue window to open `~/.continue/config.json` (MacOS) / `%userprofile%\.continue\config.json` (Windows)
11-
12-3. Log in and create an API key on Mistral AI's La Plateforme [here](https://console.mistral.ai/codestral). Make sure you get an API key from the "Codestral" page.
13-
14-4. To use Codestral as your model for both `autocomplete` and `chat`, insert your Mistral API key below and add it to your configuration file:
15-
16-- YAML
17-- JSON
18-
19-config.yaml
20-
21-```
22-models:
23- - name: Codestral
24- provider: mistral
25- model: codestral-latest
26- apiKey: <YOUR_CODESTRAL_API_KEY>
27- apiBase: https://codestral.mistral.ai/v1
28- roles:
29- - chat
30- - autocomplete
31-```
32-
33-config.json
34-
35-```json
36-{
37- "models": [
38- {
39- "title": "Codestral",
40- "provider": "mistral",
41- "model": "codestral-latest",
42- "apiKey": "<YOUR_CODESTRAL_API_KEY>",
43- "apiBase": "https://codestral.mistral.ai/v1"
44- }
45- ],
46- "tabAutocompleteModel": [
47- {
48- "title": "Codestral",
49- "provider": "mistral",
50- "model": "codestral-latest",
51- "apiKey": "<YOUR_CODESTRAL_API_KEY>",
52- "apiBase": "https://codestral.mistral.ai/v1"
53- }
54- ]
55-}
56-```
57-
58-5. If you run into any issues or have any questions, please join our Discord and post in the `#help` channel [here](https://discord.gg/EfJEfdFnDQ)
added docs/guides/understanding-agents.mdx +202 −0
@@ -0,0 +1,202 @@
1+---
2+title: "How to Understand Agents: Hub vs Local Configuration"
3+description: "Learn how to choose between cloud-managed Hub agents and local configuration for AI development assistance in Continue, including setup, management, and best practices for each approach"
4+---
5+
6+Every developer has unique needs when it comes to AI assistance. Some prefer the convenience of cloud-managed configurations, while others need the control and privacy of local setups. Continue offers both paths, and this guide will help you choose the right one for your workflow.
7+
8+## What Are the Two Paths to AI Assistance?
9+
10+Continue provides two distinct ways to configure your AI agent:
11+
12+Think of Continue's configuration options like choosing between a managed service and self-hosting. Both get you to the same destination—powerful AI assistance in your IDE—but the journey and control level differ significantly.
13+
14+### How to Access Your Agent Configuration
15+
16+Before we dive into the specifics, let's understand how to access your configuration:
17+
18+1. Open the Continue Chat sidebar by pressing <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains)
19+2. Click the Agent selector above the main chat input
20+3. Hover over an agent and click:
21+ - `new window` icon for Hub agents
22+ - `gear` icon for Local agents
23+
24+![configure an agent](/images/configure-continue.png)
25+
26+## What Are Hub Agents: The Managed Experience
27+
28+Hub Agents represent the "it just works" philosophy. When you [sign in to Continue Hub](https://auth.continue.dev/), you gain access to a curated ecosystem of pre-configured agents that sync seamlessly across all your development environments.
29+
30+### Why Should You Choose Hub Agents?
31+
32+**The Power of Simplicity**
33+
34+- **Instant Setup**: Browse the [agent marketplace](https://hub.continue.dev) and add any agent to your account with a single click
35+- **Web-Based Management**: Configure models, add secrets, and customize settings through an intuitive web interface—no JSON editing required
36+- **Automatic Synchronization**: Make a change on the hub, and it reflects immediately across all your IDE instances
37+- **Team Collaboration**: Share custom agents with your team, ensuring everyone uses the same optimized configurations
38+
39+![nextjs agent](/images/nextjs-assistant.png)
40+
41+### How to Get Started with Hub Agents
42+
43+The journey from zero to AI-powered coding takes just four steps:
44+
45+1. **Select Your Agent**: Click the agent selector in your IDE's Continue panel
46+2. **Explore or Create**: Browse community agents or craft your own specialized helper
47+3. **Secure Your Keys**: Add API keys as [User Secrets](https://hub.continue.dev/settings/secrets) in the hub—they're encrypted and never exposed
48+4. **Sync and Code**: Click "Reload config" to pull your latest settings
49+
50+Pro tip: Hub Agents are perfect for teams. Create a custom agent with your team's coding standards, preferred models, and context sources, then share it with a simple link.
51+
52+### How to Manage Hub Agents
53+
54+All Hub Agent management happens through [the Hub](https://hub.continue.dev). For detailed customization, see our guide on [Editing an Agent](/hub/agents/edit-an-agent).
55+
56+## What Are Local Agents: The Power User's Choice
57+
58+Local Agents put you in the driver's seat. Using a `config.yaml` file, you have complete control over every aspect of your AI agent's behavior, with all configuration stored directly on your machine.
59+
60+### Why Should You Choose Local Agents?
61+
62+**Complete Control and Privacy**
63+
64+- **Your Data, Your Rules**: All configuration stays on your machine—perfect for air-gapped environments or strict data policies
65+- **Version Control Integration**: Check your `config.yaml` into git alongside your code, ensuring reproducible environments
66+- **Offline Capability**: Once configured, no internet connection needed (assuming you're using local models)
67+- **Unlimited Customization**: Access every configuration option, experimental feature, and advanced setting
68+
69+### How to Set Up Local Agents
70+
71+Local configuration lives in a single YAML file in your home directory:
72+
73+**File Locations:**
74+
75+- macOS/Linux: `~/.continue/config.yaml`
76+- Windows: `%USERPROFILE%\.continue\config.yaml`
77+
78+**Quick Access Method:**
79+
80+1. Open the agents dropdown in your IDE
81+2. Click the gear icon next to "Local Agent"
82+3. The `config.yaml` file opens in your editor
83+
84+![local-config-open-steps](/images/local-config-open-steps.png)
85+
86+### The Local Agent Experience
87+
88+When you edit your `config.yaml`, Continue provides intelligent autocomplete for all available options. Save the file, and Continue automatically reloads your configuration—no restart required.
89+
90+The first time you use Continue, it generates a `config.yaml` with sensible defaults. From there, you can customize everything from model selection to context providers, slash commands, and more.
91+
92+For the complete configuration reference, see our [config.yaml documentation](/reference).
93+
94+## How to Make the Right Choice
95+
96+The decision between Hub and Local agents often comes down to your specific needs and constraints. Here's a framework to help you decide:
97+
98+### Choose Hub Agents When You:
99+
100+**Value Convenience Over Control**
101+
102+- Want to start coding with AI assistance in under 60 seconds
103+- Prefer visual interfaces over editing configuration files
104+- Need to switch between multiple machines frequently
105+- Work in a team that needs standardized AI assistance
106+
107+**Need Advanced Collaboration**
108+
109+- Want to share custom agents with teammates
110+- Need centralized API key management
111+- Require quick updates across your entire organization
112+
113+**Are Getting Started**
114+
115+- New to AI-powered development
116+- Want to experiment with different models and configurations
117+- Prefer guided setup experiences
118+
119+### Choose Local Agents When You:
120+
121+**Require Maximum Control**
122+
123+- Need to version control your exact configuration
124+- Want to customize every aspect of the AI behavior
125+- Require reproducible development environments
126+
127+**Have Privacy Requirements**
128+
129+- Work with sensitive code that requires air-gapped environments
130+- Need to ensure all configuration data stays local
131+- Have strict compliance requirements about data storage
132+
133+**Are a Power User**
134+
135+- Comfortable editing YAML/JSON files
136+- Want access to experimental features
137+- Need to integrate with local tools and scripts
138+
139+## How to Use the Hybrid Approach
140+
141+Here's a secret: you don't have to choose just one. Many developers use both approaches:
142+
143+- **Hub Agents** for general development and experimentation
144+- **Local Agents** for production work or client projects with specific requirements
145+
146+You can switch between them seamlessly using the agent selector in your IDE.
147+
148+## Common Patterns and Best Practices
149+
150+### For Hub Agent Users
151+
152+1. **Start with Community Agents**: Before creating your own, explore what others have built
153+2. **Use Secrets Properly**: Never hardcode API keys—always use the User Secrets feature
154+3. **Create Specialized Agents**: Make different agents for different contexts (frontend, backend, DevOps)
155+4. **Share Liberally**: If you create something useful, share it with the community
156+
157+### For Local Agent Users
158+
159+1. **Version Control Your Config**: Treat your `config.yaml` like code—commit it, review changes, and maintain history
160+2. **Use Environment Variables**: For sensitive data, reference environment variables instead of hardcoding values
161+3. **Document Your Setup**: Add comments to your config explaining non-obvious choices
162+4. **Keep a Backup**: Before major changes, save a working copy of your configuration
163+
164+## Troubleshooting and Tips
165+
166+### Hub Agent Issues
167+
168+**Changes Not Reflecting?**
169+
170+- Click "Reload config" in your IDE
171+- Check your internet connection
172+- Ensure you're signed in to the correct account
173+
174+**Agent Not Available?**
175+
176+- Verify it's added to your account on the hub
177+- Check if it requires specific API keys
178+
179+### Local Agent Issues
180+
181+**Config Not Loading?**
182+
183+- Verify file location matches your OS
184+- Check YAML syntax (Continue will show errors)
185+- Ensure file permissions allow reading
186+
187+**Autocomplete Not Working?**
188+
189+- Update to the latest Continue version
190+- Check that you're editing the correct file
191+
192+## Next Steps
193+
194+Now that you understand both configuration approaches, you're ready to dive deeper:
195+
196+- **For Hub Users**: [Create Your First Agent](/hub/agents/create-an-agent)
197+- **For Local Users**: [Explore the Config Reference](/reference)
198+- **For Everyone**: [Discover Available Models](/customize/model-providers/overview)
199+
200+Remember, the best configuration is the one that helps you code more effectively. Start simple, experiment freely, and gradually refine your setup as you discover what works best for your workflow.
201+
202+Happy coding with Continue! 🚀
deleted docs/guides/understanding-assistants.mdx +0 −202
@@ -1,202 +0,0 @@
1----
2-title: "How to Understand Assistants: Hub vs Local Configuration"
3-description: "Learn how to choose between cloud-managed Hub assistants and local configuration for AI development assistance in Continue, including setup, management, and best practices for each approach"
4----
5-
6-Every developer has unique needs when it comes to AI assistance. Some prefer the convenience of cloud-managed configurations, while others need the control and privacy of local setups. Continue offers both paths, and this guide will help you choose the right one for your workflow.
7-
8-## What Are the Two Paths to AI Assistance?
9-
10-Continue provides two distinct ways to configure your AI assistant:
11-
12-Think of Continue's configuration options like choosing between a managed service and self-hosting. Both get you to the same destination—powerful AI assistance in your IDE—but the journey and control level differ significantly.
13-
14-### How to Access Your Assistant Configuration
15-
16-Before we dive into the specifics, let's understand how to access your configuration:
17-
18-1. Open the Continue Chat sidebar by pressing <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains)
19-2. Click the Assistant selector above the main chat input
20-3. Hover over an assistant and click:
21- - `new window` icon for Hub assistants
22- - `gear` icon for Local assistants
23-
24-![configure an assistant](/images/configure-continue.png)
25-
26-## What Are Hub Assistants: The Managed Experience
27-
28-Hub Assistants represent the "it just works" philosophy. When you [sign in to Continue Hub](https://auth.continue.dev/), you gain access to a curated ecosystem of pre-configured assistants that sync seamlessly across all your development environments.
29-
30-### Why Should You Choose Hub Assistants?
31-
32-**The Power of Simplicity**
33-
34-- **Instant Setup**: Browse the [assistant marketplace](https://hub.continue.dev/explore/assistants) and add any assistant to your account with a single click
35-- **Web-Based Management**: Configure models, add secrets, and customize settings through an intuitive web interface—no JSON editing required
36-- **Automatic Synchronization**: Make a change on the hub, and it reflects immediately across all your IDE instances
37-- **Team Collaboration**: Share custom assistants with your team, ensuring everyone uses the same optimized configurations
38-
39-![nextjs assistant](/images/nextjs-assistant.png)
40-
41-### How to Get Started with Hub Assistants
42-
43-The journey from zero to AI-powered coding takes just four steps:
44-
45-1. **Select Your Assistant**: Click the assistant selector in your IDE's Continue panel
46-2. **Explore or Create**: Browse community assistants or craft your own specialized helper
47-3. **Secure Your Keys**: Add API keys as [User Secrets](https://hub.continue.dev/settings/secrets) in the hub—they're encrypted and never exposed
48-4. **Sync and Code**: Click "Reload config" to pull your latest settings
49-
50-Pro tip: Hub Assistants are perfect for teams. Create a custom assistant with your team's coding standards, preferred models, and context sources, then share it with a simple link.
51-
52-### How to Manage Hub Assistants
53-
54-All Hub Assistant management happens through [the Hub](https://hub.continue.dev). For detailed customization, see our guide on [Editing an Assistant](/hub/assistants/edit-an-assistant).
55-
56-## What Are Local Assistants: The Power User's Choice
57-
58-Local Assistants put you in the driver's seat. Using a `config.yaml` file, you have complete control over every aspect of your AI assistant's behavior, with all configuration stored directly on your machine.
59-
60-### Why Should You Choose Local Assistants?
61-
62-**Complete Control and Privacy**
63-
64-- **Your Data, Your Rules**: All configuration stays on your machine—perfect for air-gapped environments or strict data policies
65-- **Version Control Integration**: Check your `config.yaml` into git alongside your code, ensuring reproducible environments
66-- **Offline Capability**: Once configured, no internet connection needed (assuming you're using local models)
67-- **Unlimited Customization**: Access every configuration option, experimental feature, and advanced setting
68-
69-### How to Set Up Local Assistants
70-
71-Local configuration lives in a single YAML file in your home directory:
72-
73-**File Locations:**
74-
75-- macOS/Linux: `~/.continue/config.yaml`
76-- Windows: `%USERPROFILE%\.continue\config.yaml`
77-
78-**Quick Access Method:**
79-
80-1. Open the assistants dropdown in your IDE
81-2. Click the gear icon next to "Local Assistant"
82-3. The `config.yaml` file opens in your editor
83-
84-![local-config-open-steps](/images/local-config-open-steps.png)
85-
86-### The Local Assistant Experience
87-
88-When you edit your `config.yaml`, Continue provides intelligent autocomplete for all available options. Save the file, and Continue automatically reloads your configuration—no restart required.
89-
90-The first time you use Continue, it generates a `config.yaml` with sensible defaults. From there, you can customize everything from model selection to context providers, slash commands, and more.
91-
92-For the complete configuration reference, see our [config.yaml documentation](/reference).
93-
94-## How to Make the Right Choice
95-
96-The decision between Hub and Local assistants often comes down to your specific needs and constraints. Here's a framework to help you decide:
97-
98-### Choose Hub Assistants When You:
99-
100-**Value Convenience Over Control**
101-
102-- Want to start coding with AI assistance in under 60 seconds
103-- Prefer visual interfaces over editing configuration files
104-- Need to switch between multiple machines frequently
105-- Work in a team that needs standardized AI assistance
106-
107-**Need Advanced Collaboration**
108-
109-- Want to share custom assistants with teammates
110-- Need centralized API key management
111-- Require quick updates across your entire organization
112-
113-**Are Getting Started**
114-
115-- New to AI-powered development
116-- Want to experiment with different models and configurations
117-- Prefer guided setup experiences
118-
119-### Choose Local Assistants When You:
120-
121-**Require Maximum Control**
122-
123-- Need to version control your exact configuration
124-- Want to customize every aspect of the AI behavior
125-- Require reproducible development environments
126-
127-**Have Privacy Requirements**
128-
129-- Work with sensitive code that requires air-gapped environments
130-- Need to ensure all configuration data stays local
131-- Have strict compliance requirements about data storage
132-
133-**Are a Power User**
134-
135-- Comfortable editing YAML/JSON files
136-- Want access to experimental features
137-- Need to integrate with local tools and scripts
138-
139-## How to Use the Hybrid Approach
140-
141-Here's a secret: you don't have to choose just one. Many developers use both approaches:
142-
143-- **Hub Assistants** for general development and experimentation
144-- **Local Assistants** for production work or client projects with specific requirements
145-
146-You can switch between them seamlessly using the assistant selector in your IDE.
147-
148-## Common Patterns and Best Practices
149-
150-### For Hub Assistant Users
151-
152-1. **Start with Community Assistants**: Before creating your own, explore what others have built
153-2. **Use Secrets Properly**: Never hardcode API keys—always use the User Secrets feature
154-3. **Create Specialized Assistants**: Make different assistants for different contexts (frontend, backend, DevOps)
155-4. **Share Liberally**: If you create something useful, share it with the community
156-
157-### For Local Assistant Users
158-
159-1. **Version Control Your Config**: Treat your `config.yaml` like code—commit it, review changes, and maintain history
160-2. **Use Environment Variables**: For sensitive data, reference environment variables instead of hardcoding values
161-3. **Document Your Setup**: Add comments to your config explaining non-obvious choices
162-4. **Keep a Backup**: Before major changes, save a working copy of your configuration
163-
164-## Troubleshooting and Tips
165-
166-### Hub Assistant Issues
167-
168-**Changes Not Reflecting?**
169-
170-- Click "Reload config" in your IDE
171-- Check your internet connection
172-- Ensure you're signed in to the correct account
173-
174-**Assistant Not Available?**
175-
176-- Verify it's added to your account on the hub
177-- Check if it requires specific API keys
178-
179-### Local Assistant Issues
180-
181-**Config Not Loading?**
182-
183-- Verify file location matches your OS
184-- Check YAML syntax (Continue will show errors)
185-- Ensure file permissions allow reading
186-
187-**Autocomplete Not Working?**
188-
189-- Update to the latest Continue version
190-- Check that you're editing the correct file
191-
192-## Next Steps
193-
194-Now that you understand both configuration approaches, you're ready to dive deeper:
195-
196-- **For Hub Users**: [Create Your First Assistant](/hub/assistants/create-an-assistant)
197-- **For Local Users**: [Explore the Config Reference](/reference)
198-- **For Everyone**: [Discover Available Models](/customize/model-providers/overview)
199-
200-Remember, the best configuration is the one that helps you code more effectively. Start simple, experiment freely, and gradually refine your setup as you discover what works best for your workflow.
201-
202-Happy coding with Continue! 🚀
added docs/hub/agents/create-an-agent.mdx +34 −0
@@ -0,0 +1,34 @@
1+---
2+title: "How to Create an AI Agent"
3+description: "Learn how to create custom AI coding agents in Continue Hub by remixing existing agents or building new ones from scratch with reusable blocks and YAML configuration."
4+sidebarTitle: "Create an AI Agent"
5+---
6+
7+## How to Create an AI Agent from Scratch
8+
9+To create an agent from scratch, select “New agent” in the top bar.
10+
11+![New agent button](/images/hub/assistants/images/assistant-new-button-16070e2cff9ce25ec9ebfeecb0e2f2b5.png)
12+
13+Choose a name, slug, description, and icon for your agent.
14+
15+The easiest way to create an agent is to click "Create agent" with the default configuration and then add / remove blocks using the sidebar.
16+
17+Alternatively, you can edit the agent YAML directly before clicking "Create agent". Refer to examples of agents on [hub.continue.dev](https://hub.continue.dev) and visit the [YAML Reference](/reference#complete-yaml-config-example) docs for more details.
18+
19+![New agent YAML](/images/hub/assistants/images/assistant-create-yaml-a991e5a81506f1c3ba611a664a50734c.png)
20+
21+## How to Remix an Agent
22+
23+You can also create an agent by remixing an existing one. This is useful if you want to start with a pre-configured agent and make modifications.
24+
25+By clicking the “remix” button, you’ll be taken to the “Create a remix” page.
26+
27+![Remix Agent Button](/images/hub/assistants/images/assistant-remix-button-728ececa73983140eeab42e33cc3903b.png)
28+
29+Once here, you’ll be able to
30+
31+1. add or remove blocks in YAML configuration
32+2. change the name, description, icon, etc.
33+
34+Clicking “Create agent” will make this agent available for use.
added docs/hub/agents/edit-an-agent.mdx +20 −0
@@ -0,0 +1,20 @@
1+---
2+title: "How to Edit an Agent"
3+description: "New versions of an agent can be created and published using the sidebar."
4+---
5+
6+![Remix Agent Button](/images/hub/assistants/images/assistant-create-sidebar-608be49973f2a7723212adeb52dbcafb.png)
7+
8+First, select an agent from the dropdown at the top.
9+
10+While editing an agent, you can explore the hub and click "Add Block" from a block page to add it to your agent.
11+
12+For blocks that require secret values like API keys, you will see a small notification on the block's tile in the sidebar that will indicate if action is needed.
13+
14+To delete a block, click the trash icon.
15+
16+If a block you want to use does not exist yet, you can [create a new block](/hub/blocks/create-a-block).
17+
18+When you are done editing, click "Publish" to publish a new version of the agent.
19+
20+Click "Open VS Code" or "Open JetBrains" to open your IDE for using the agent.
added docs/hub/agents/intro.mdx +8 −0
@@ -0,0 +1,8 @@
1+---
2+title: "Introduction to Agents"
3+description: "Custom AI code agents are configurations of building blocks that enable a coding experience tailored to your specific use cases."
4+---
5+
6+`config.yaml` is a format for defining custom AI code agents. An agent has some top-level properties (e.g. `name`, `version`), but otherwise consists of composable lists of **blocks** such as `models` and `rules`, which are the atomic building blocks of an agent.
7+
8+The `config.yaml` is parsed by the open-source Continue IDE extensions to create custom agent experiences. When you log in to [hub.continue.dev](https://hub.continue.dev/), your agents will automatically be synced with the IDE extensions.
added docs/hub/agents/use-an-agent.mdx +19 −0
@@ -0,0 +1,19 @@
1+---
2+title: "How to Use an Agent"
3+description: "Learn how to add, configure, and use an AI agent in Continue, including setting required inputs and selecting it in your IDE extension."
4+---
5+
6+## Steps to Use an AI Agent in Continue
7+
8+Once you've found the agent you want to use on Continue Hub:
9+
10+1. Click “Add Agent” on its page
11+2. Add any required inputs (e.g. secrets like API keys)
12+3. Select “Save changes” in agent sidebar on the right hand side
13+
14+After saving, open your IDE extension and:
15+
16+- Select the agent from the **agent dropdown** in the Continue extension.
17+- Begin using it for chat, code generation, or other configured capabilities.
18+
19+![Extension Agent Selector](/images/hub/assistants/images/assistant-extension-select.png)

Next files