Merge branch 'main' into per-tab-model-persistence

This commit is contained in:
ferenci84 2025-09-22 14:26:10 +02:00
commit 811391ef41
693 changed files with 59281 additions and 19685 deletions

View file

@ -1,20 +0,0 @@
#!/bin/bash
# Get file path from hook input
FILE_PATH=$(cat | jq -r '.tool_input.file_path // .tool_input.edits[].file_path // empty' | head -n1)
# Function to run lint and typecheck
run_checks() {
local dir=$1
cd "$dir"
npm run lint >&2 && npm run tsc:check >&2
}
# Run checks based on file location
if [[ "$FILE_PATH" == *"/core/"* ]]; then
run_checks core
elif [[ "$FILE_PATH" == *"/gui/"* ]]; then
run_checks gui
elif [[ "$FILE_PATH" == *"/extensions/vscode/"* ]]; then
run_checks extensions/vscode
fi

View file

@ -1,15 +0,0 @@
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/lint-check.sh"
}
]
}
]
}
}

View file

@ -0,0 +1,5 @@
---
globs: "**/*.{ts,tsx}"
---
Avoid using the `any` type wherever possible. Use unknown or find the correct type. The only acceptable place to use any is when typecasting for test mocks, and even then it's better to avoid and provide a proper mock.

View file

@ -0,0 +1,55 @@
name: "Check LLM Changes"
description: "Check if LLM-related files have changed and set environment variable to control API tests"
outputs:
llm_changed:
description: "Whether LLM-related files have changed"
value: ${{ steps.check-changes.outputs.llm_changed }}
ignore_api_tests:
description: "Whether to ignore API tests based on file changes and other conditions"
value: ${{ steps.check-changes.outputs.ignore_api_tests }}
inputs:
is_fork:
description: "Whether this is a fork PR"
required: false
default: "false"
is_dependabot:
description: "Whether this is a dependabot PR"
required: false
default: "false"
runs:
using: "composite"
steps:
- name: Check if LLM-related files changed
id: check-changes
shell: bash
run: |
if [ "${{ github.event_name }}" = "push" ]; then
# For push events, compare against the previous commit
CHANGED_FILES=$(git diff --name-only HEAD~1...HEAD)
else
# For PR events, compare against the base branch
git fetch origin ${{ github.event.pull_request.base.ref }}
CHANGED_FILES=$(git diff --name-only origin/${{ github.event.pull_request.base.ref }}...HEAD)
fi
echo "Changed files:"
echo "$CHANGED_FILES"
# Check if any LLM-related files were changed
LLM_CHANGED=false
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
LLM_CHANGED=true
fi
echo "LLM files changed: $LLM_CHANGED"
echo "llm_changed=$LLM_CHANGED" >> $GITHUB_OUTPUT
# Determine whether to ignore API tests
IGNORE_API_TESTS=false
if [ "${{ inputs.is_fork }}" = "true" ] || [ "${{ inputs.is_dependabot }}" = "true" ] || [ "$LLM_CHANGED" = "false" ]; then
IGNORE_API_TESTS=true
fi
echo "Ignore API tests: $IGNORE_API_TESTS"
echo "ignore_api_tests=$IGNORE_API_TESTS" >> $GITHUB_OUTPUT

View file

@ -107,7 +107,7 @@ runs:
cd binary
npm run build
- name: Start test IDE
- name: Run tests
shell: bash
run: |
cd extensions/intellij
@ -115,21 +115,7 @@ runs:
Xvfb -ac :99 -screen 0 1920x1080x24 &
sleep 10
mkdir -p build/reports
./gradlew runIdeForUiTests &
- name: Wait for JB connection
uses: jtalk/url-health-check-action@v3
with:
url: http://127.0.0.1:8082
max-attempts: 15
retry-delay: 30s
- name: Run tests
shell: bash
run: |
cd extensions/intellij
export DISPLAY=:99.0
./gradlew test
./gradlew test testIntegration
- name: Move video
if: ${{ failure() }}

View file

@ -1,25 +1,25 @@
name: 'Run VS Code E2E Test'
description: 'Run a single VS Code E2E test with all required setup'
name: "Run VS Code E2E Test"
description: "Run a single VS Code E2E test with all required setup"
inputs:
test_file:
description: 'E2E test file to run'
description: "E2E test file to run"
required: true
command:
description: 'Command to run (e2e:ci:run or e2e:ci:run-yaml)'
description: "Command to run (e2e:ci:run or e2e:ci:run-yaml)"
required: true
ssh_key:
description: 'SSH private key for testing'
description: "SSH private key for testing"
required: false
ssh_host:
description: 'SSH host for testing'
description: "SSH host for testing"
required: false
is_fork:
description: 'Whether this is a fork (affects SSH tests)'
description: "Whether this is a fork (affects SSH tests)"
required: false
default: 'false'
default: "false"
runs:
using: 'composite'
using: "composite"
steps:
- uses: actions/setup-node@v4
with:
@ -58,6 +58,7 @@ runs:
cd core
npm ci
cd ../extensions/vscode
npm ci
npm run e2e:ci:download
else
cd core
@ -131,4 +132,4 @@ runs:
uses: actions/upload-artifact@v4
with:
name: e2e-logs-${{ steps.sanitize_filename.outputs.sanitized_test_file || 'unknown' }}-${{ inputs.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }}
path: extensions/vscode/e2e.log
path: extensions/vscode/e2e.log

View file

@ -0,0 +1,170 @@
name: Auto Fix Failed Tests
on:
workflow_run:
workflows: ["PR Checks", "CLI PR Checks"]
types:
- completed
permissions:
contents: write
pull-requests: write
issues: write
actions: read
jobs:
fix-failed-tests:
# Only run if the workflow failed
# DISABLED: Remove 'false && ' on the next line to enable auto-fixing
if: false && github.event.workflow_run.conclusion == 'failure'
runs-on: ubuntu-latest
steps:
- name: Get workflow run details
id: workflow-details
uses: actions/github-script@v8
with:
script: |
const workflowRun = context.payload.workflow_run;
const { data: jobs } = await github.rest.actions.listJobsForWorkflowRun({
owner: context.repo.owner,
repo: context.repo.repo,
run_id: workflowRun.id
});
// Find all failed jobs since we're only monitoring specific test workflows
const failedJobs = jobs.jobs.filter(job => job.conclusion === 'failure');
if (failedJobs.length === 0) {
core.info('No failed jobs found');
return null;
}
core.setOutput('has_failed_tests', 'true');
core.setOutput('workflow_name', workflowRun.name);
core.setOutput('workflow_run_id', workflowRun.id);
core.setOutput('head_branch', workflowRun.head_branch);
core.setOutput('head_sha', workflowRun.head_sha);
core.setOutput('failed_jobs', JSON.stringify(failedJobs.map(j => j.name)));
return failedJobs;
- name: Get job logs for failed tests
if: steps.workflow-details.outputs.has_failed_tests == 'true'
id: get-logs
uses: actions/github-script@v8
with:
script: |
const workflowRunId = ${{ github.event.workflow_run.id }};
const { data: jobs } = await github.rest.actions.listJobsForWorkflowRun({
owner: context.repo.owner,
repo: context.repo.repo,
run_id: workflowRunId
});
let errorLogs = '';
for (const job of jobs.jobs) {
if (job.conclusion === 'failure') {
try {
const { data: logData } = await github.rest.actions.downloadJobLogsForWorkflowRun({
owner: context.repo.owner,
repo: context.repo.repo,
job_id: job.id
});
errorLogs += `\n\n=== Job: ${job.name} ===\n`;
errorLogs += logData;
} catch (error) {
core.warning(`Could not fetch logs for job ${job.name}: ${error.message}`);
}
}
}
// Store logs in environment file for next step
const fs = require('fs');
fs.writeFileSync('/tmp/test_failure_logs.txt', errorLogs);
core.setOutput('has_logs', errorLogs.length > 0 ? 'true' : 'false');
- name: Checkout repository
if: steps.workflow-details.outputs.has_failed_tests == 'true'
uses: actions/checkout@v5
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
ref: ${{ steps.workflow-details.outputs.head_sha }}
- name: Setup Node.js
if: steps.workflow-details.outputs.has_failed_tests == 'true'
uses: actions/setup-node@v5
with:
node-version: "20"
- name: Install Continue CLI globally
if: steps.workflow-details.outputs.has_failed_tests == 'true'
run: npm i -g @continuedev/cli
- name: Start remote session to fix failed tests
if: steps.workflow-details.outputs.has_failed_tests == 'true'
id: remote-session
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
run: |
# Create a detailed prompt for fixing the failed tests
cat > /tmp/fix_tests_prompt.txt << 'PROMPT_EOF'
🔧 **Auto Test Fix Request**
The following tests failed in workflow "${{ steps.workflow-details.outputs.workflow_name }}" (Run ID: ${{ steps.workflow-details.outputs.workflow_run_id }}):
**Failed Jobs:** ${{ steps.workflow-details.outputs.failed_jobs }}
**Branch:** ${{ steps.workflow-details.outputs.head_branch }}
**Commit:** ${{ steps.workflow-details.outputs.head_sha }}
**Your Task:**
1. Analyze the test failure logs and error messages
2. Identify the root cause of the test failures
3. Fix the failing tests by updating the test code or the underlying implementation
4. Ensure all tests pass after your changes
5. Commit your fixes with a descriptive message
**Test Failure Context:**
Please examine the repository structure, run the failing tests locally to understand the errors, and implement appropriate fixes.
Focus on:
- Understanding what the tests are trying to validate
- Identifying why they're failing (code changes, environment issues, test logic errors)
- Making minimal, targeted fixes that address the root cause
- Ensuring the fixes don't break other functionality
Please start by examining the failing tests and their error messages, then proceed with the necessary fixes.
PROMPT_EOF
echo "Starting Continue CLI remote session for test fixes..."
echo "Prompt content:"
cat /tmp/fix_tests_prompt.txt
# Start remote session and capture JSON output
SESSION_OUTPUT=$(cat /tmp/fix_tests_prompt.txt | cn remote -s --branch ${{ steps.workflow-details.outputs.head_branch }})
echo "Raw session output: $SESSION_OUTPUT"
# Extract URL from JSON output
SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty')
if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then
echo "Failed to extract session URL from output: $SESSION_OUTPUT"
exit 1
fi
echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT
echo "✅ Started remote session: $SESSION_URL"
- name: Log session details
if: steps.workflow-details.outputs.has_failed_tests == 'true'
run: |
echo "✅ Successfully started auto-fix session for failed tests"
echo "Workflow: ${{ steps.workflow-details.outputs.workflow_name }}"
echo "Run ID: ${{ steps.workflow-details.outputs.workflow_run_id }}"
echo "Branch: ${{ steps.workflow-details.outputs.head_branch }}"
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
echo "Failed jobs: ${{ steps.workflow-details.outputs.failed_jobs }}"

View file

@ -24,7 +24,7 @@ jobs:
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version: 20
registry-url: "https://registry.npmjs.org"

View file

@ -25,7 +25,7 @@ jobs:
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version: 20
cache: "npm"
@ -59,6 +59,7 @@ jobs:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node-version: [18, 20, 22, 24]
fail-fast: false
runs-on: ${{ matrix.os }}
steps:
@ -66,7 +67,7 @@ jobs:
uses: actions/checkout@v5
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version: ${{ matrix.node-version }}

View file

@ -41,7 +41,7 @@ jobs:
- name: Add PR title guidance comment
if: always() && steps.pr-title-check.outputs.valid == 'false'
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const { data: comments } = await github.rest.issues.listComments({
@ -104,7 +104,7 @@ jobs:
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
cache: "npm"

View file

@ -18,7 +18,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Run Detailed PR Review
uses: continuedev/continue/actions/detailed-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe
uses: continuedev/continue/actions/detailed-review@12e933bf9d13736c5f47728c436445ef4127fd52
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: continuedev

View file

@ -18,7 +18,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Run Continue PR Review Action
uses: continuedev/continue/actions/general-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe
uses: continuedev/continue/actions/general-review@12e933bf9d13736c5f47728c436445ef4127fd52
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "continuedev"

View file

@ -152,7 +152,7 @@ jobs:
# # Setup Node.js
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
@ -370,7 +370,7 @@ jobs:
# 2. Install npm dependencies
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"

View file

@ -44,7 +44,7 @@ jobs:
- name: Determine and apply tier label
if: steps.check-author.outputs.should_label == 'true'
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const pr = context.payload.pull_request;

View file

@ -20,7 +20,7 @@ jobs:
- id: check
working-directory: .
run: |
if [[ "${{ github.event.release.tag_name }}" == v1.0.*-vscode ]]; then
if [[ "${{ github.event.release.tag_name }}" == v1.2.*-vscode ]]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
echo "should_run=false" >> $GITHUB_OUTPUT
@ -70,7 +70,7 @@ jobs:
with:
fetch-depth: 0
- uses: actions/setup-node@v4
- uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"

View file

@ -23,7 +23,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
- uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
@ -44,6 +44,8 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
with:
fetch-depth: 0 # Needed for git diff to work
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Setup core component
@ -52,6 +54,13 @@ jobs:
component: core
include-root: true
- name: Check if LLM-related files changed
id: llm-changes
uses: ./.github/actions/check-llm-changes
with:
is_fork: ${{ github.event.pull_request.head.repo.fork == true }}
is_dependabot: ${{ github.actor == 'dependabot[bot]' }}
- name: Type check and lint
run: |
cd core
@ -66,7 +75,7 @@ jobs:
npm test
npm run vitest
env:
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}
IGNORE_API_KEY_TESTS: ${{ steps.llm-changes.outputs.ignore_api_tests }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
@ -75,6 +84,9 @@ jobs:
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
gui-checks:
runs-on: ubuntu-latest
@ -180,16 +192,25 @@ jobs:
package: ${{ fromJson(needs.get-packages-matrix.outputs.packages) }}
steps:
- uses: actions/checkout@v5
with:
fetch-depth: 0 # Needed for git diff to work
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Check if LLM-related files changed
id: llm-changes
uses: ./.github/actions/check-llm-changes
with:
is_fork: ${{ github.event.pull_request.head.repo.fork == true }}
is_dependabot: ${{ github.actor == 'dependabot[bot]' }}
- name: Test and check ${{ matrix.package }}
run: |
cd packages/${{ matrix.package }}
npm ci
npm test
env:
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}
IGNORE_API_KEY_TESTS: ${{ steps.llm-changes.outputs.ignore_api_tests }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
@ -199,6 +220,8 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
vscode-get-test-file-matrix:
runs-on: ubuntu-latest
@ -206,7 +229,7 @@ jobs:
test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
- uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
@ -324,7 +347,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
- uses: actions/setup-node@v5
with:
node-version: 20

View file

@ -70,7 +70,7 @@ jobs:
with:
fetch-depth: 0
- uses: actions/setup-node@v4
- uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
@ -165,7 +165,7 @@ jobs:
# 4. Create PR with version bump
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"

View file

@ -32,3 +32,5 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}

View file

@ -32,3 +32,5 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}

View file

@ -23,4 +23,7 @@ jobs:
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}

View file

@ -32,3 +32,5 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}

View file

@ -21,15 +21,32 @@ jobs:
- name: Check if comment contains @continuedev
id: check-mention
run: |
if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
# Create a temporary file to safely handle comment body with special characters
cat > /tmp/comment.txt << 'COMMENT_EOF'
${{ github.event.comment.body }}
COMMENT_EOF
if grep -q "@continuedev" /tmp/comment.txt; then
echo "contains_mention=true" >> $GITHUB_OUTPUT
else
echo "contains_mention=false" >> $GITHUB_OUTPUT
fi
- name: Add eyes reaction to comment
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/github-script@v8
with:
script: |
await github.rest.reactions.createForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: ${{ github.event.comment.id }},
content: 'eyes'
});
- name: Checkout PR branch
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
@ -37,7 +54,7 @@ jobs:
- name: Get PR information
if: steps.check-mention.outputs.contains_mention == 'true'
id: pr-info
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const { data: pr } = await github.rest.pulls.get({
@ -57,90 +74,7 @@ jobs:
- name: Setup Node.js
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install Continue CLI globally
if: steps.check-mention.outputs.contains_mention == 'true'
run: npm i -g @continuedev/cli
- name: Start remote session
if: steps.check-mention.outputs.contains_mention == 'true'
id: remote-session
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
run: |
# Create the prompt for remote session
PROMPT="Please help with the following request from @${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}:
${{ github.event.comment.body }}
Please analyze the current PR, understand the request, implement the necessary changes, and commit them to this branch."
# Start remote session and capture JSON output
SESSION_OUTPUT=$(echo "$PROMPT" | cn remote -s --branch ${{ steps.pr-info.outputs.head_ref }})
echo "Raw session output: $SESSION_OUTPUT"
# Extract URL from JSON output
SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty')
if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then
echo "Failed to extract session URL from output: $SESSION_OUTPUT"
exit 1
fi
echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT
echo "✅ Started remote session: $SESSION_URL"
- name: Comment with session URL
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
uses: actions/github-script@v7
with:
script: |
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
> ${{ github.event.comment.body }}`;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: commentBody
});
- name: Log session details
if: steps.check-mention.outputs.contains_mention == 'true'
run: |
echo "✅ Successfully started remote session for comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}"
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
echo "Original comment: ${{ github.event.comment.body }}"
respond-to-review-comment:
# Only run on pull request review comments
if: github.event_name == 'pull_request_review_comment'
runs-on: ubuntu-latest
steps:
- name: Check if comment contains @continuedev
id: check-mention
run: |
if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
echo "contains_mention=true" >> $GITHUB_OUTPUT
else
echo "contains_mention=false" >> $GITHUB_OUTPUT
fi
- name: Checkout PR branch
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/checkout@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
ref: ${{ github.event.pull_request.head.ref }}
- name: Setup Node.js
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version: "20"
@ -156,13 +90,11 @@ jobs:
run: |
# Create a temporary file for the prompt to handle special characters and newlines properly
cat > /tmp/prompt.txt << 'PROMPT_EOF'
Please help with the following code review comment from @${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}:
Please help with the following request from @${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}:
**File:** ${{ github.event.comment.path }}
**Line:** ${{ github.event.comment.line || github.event.comment.original_line || 'N/A' }}
**Comment:** ${{ github.event.comment.body }}
${{ github.event.comment.body }}
Please analyze the specific file and line mentioned, understand the review feedback, implement the necessary changes, and commit them to this branch.
Please analyze the current PR, understand the request, implement the necessary changes, and commit them to this branch.
PROMPT_EOF
# Debug output
@ -171,7 +103,7 @@ jobs:
# Start remote session and capture JSON output
echo "Starting cn with prompt..."
SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --branch ${{ github.event.pull_request.head.ref }})
SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --config continuedev/address-code-review --branch ${{ steps.pr-info.outputs.head_ref }})
echo "Raw session output: $SESSION_OUTPUT"
# Extract URL from JSON output
@ -187,11 +119,165 @@ jobs:
- name: Comment with session URL
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
uses: actions/github-script@v7
uses: actions/github-script@v8
env:
ORIGINAL_COMMENT: ${{ github.event.comment.body }}
with:
script: |
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
> ${{ github.event.comment.body }}`;
const sessionUrl = '${{ steps.remote-session.outputs.session_url }}';
const originalComment = process.env.ORIGINAL_COMMENT;
const commentBody = "I've started [a remote session](" + sessionUrl + ") to help with your request:\n> " + originalComment;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: commentBody
});
- name: Log session details
if: steps.check-mention.outputs.contains_mention == 'true'
run: |
echo "✅ Successfully started remote session for comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}"
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
echo "Original comment:"
cat /tmp/comment.txt
respond-to-review-comment:
# Only run on pull request review comments
if: github.event_name == 'pull_request_review_comment'
runs-on: ubuntu-latest
steps:
- name: Check if comment contains @continuedev
id: check-mention
run: |
# Create a temporary file to safely handle comment body with special characters
cat > /tmp/review_comment.txt << 'COMMENT_EOF'
${{ github.event.comment.body }}
COMMENT_EOF
if grep -q "@continuedev" /tmp/review_comment.txt; then
echo "contains_mention=true" >> $GITHUB_OUTPUT
else
echo "contains_mention=false" >> $GITHUB_OUTPUT
fi
- name: Add eyes reaction to comment
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/github-script@v8
with:
script: |
await github.rest.reactions.createForPullRequestReviewComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: ${{ github.event.comment.id }},
content: 'eyes'
});
- name: Checkout PR branch
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/checkout@v5
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
ref: ${{ github.event.pull_request.head.ref }}
- name: Setup Node.js
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/setup-node@v5
with:
node-version: "20"
- name: Install Continue CLI globally
if: steps.check-mention.outputs.contains_mention == 'true'
run: npm i -g @continuedev/cli
- name: Get review context
if: steps.check-mention.outputs.contains_mention == 'true'
id: review-context
uses: actions/github-script@v8
with:
script: |
let reviewContext = '';
// Check if this comment is a reply to another review comment
if (context.payload.comment.in_reply_to_id) {
try {
const { data: originalComment } = await github.rest.pulls.getReviewComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.in_reply_to_id
});
reviewContext = `**Original review comment by @${originalComment.user.login}:**
${originalComment.body}
**Reply by @${{ github.event.comment.user.login }}:**
${{ github.event.comment.body }}`;
} catch (error) {
console.log('Could not fetch original comment, using current comment only');
reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:**
${{ github.event.comment.body }}`;
}
} else {
reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:**
${{ github.event.comment.body }}`;
}
core.setOutput('context', reviewContext);
- name: Start remote session
if: steps.check-mention.outputs.contains_mention == 'true'
id: remote-session
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
run: |
# Debug: Echo the branch we're starting the session on
echo "Starting remote session on branch: ${{ github.event.pull_request.head.ref }}"
# Create a temporary file for the prompt to handle special characters and newlines properly
cat > /tmp/prompt.txt << 'PROMPT_EOF'
Please help with the following code review discussion from PR #${{ github.event.pull_request.number }}:
**File:** ${{ github.event.comment.path }}
**Line:** ${{ github.event.comment.line || github.event.comment.original_line || 'N/A' }}
${{ steps.review-context.outputs.context }}
Please analyze the specific file and line mentioned, understand the review feedback and any discussion context, implement the necessary changes, and commit them to this branch.
PROMPT_EOF
# Debug output
echo "PROMPT content:"
cat /tmp/prompt.txt
# Start remote session and capture JSON output
echo "Starting cn with prompt..."
SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --config continuedev/address-code-review --branch ${{ github.event.pull_request.head.ref }})
echo "Raw session output: $SESSION_OUTPUT"
# Extract URL from JSON output
SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty')
if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then
echo "Failed to extract session URL from output: $SESSION_OUTPUT"
exit 1
fi
echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT
echo "✅ Started remote session: $SESSION_URL"
- name: Comment with session URL
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
uses: actions/github-script@v8
env:
ORIGINAL_COMMENT: ${{ github.event.comment.body }}
with:
script: |
const sessionUrl = '${{ steps.remote-session.outputs.session_url }}';
const originalComment = process.env.ORIGINAL_COMMENT;
const commentBody = "I've started [a remote session](" + sessionUrl + ") to help with your request:\n> " + originalComment;
const commentParams = {
owner: context.repo.owner,
@ -212,4 +298,5 @@ jobs:
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
echo "File: ${{ github.event.comment.path }}"
echo "Line: ${{ github.event.comment.line }}"
echo "Original comment: ${{ github.event.comment.body }}"
echo "Original comment:"
cat /tmp/review_comment.txt

View file

@ -32,6 +32,10 @@ on:
required: false
VOYAGE_API_KEY:
required: false
RELACE_API_KEY:
required: false
INCEPTION_API_KEY:
required: false
permissions:
contents: write
@ -55,7 +59,7 @@ jobs:
uses: ./.github/actions/setup-packages
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
@ -77,6 +81,8 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
- name: Release
env:

View file

@ -31,7 +31,7 @@ jobs:
path: deja-view
- name: Setup Python
uses: actions/setup-python@v5
uses: actions/setup-python@v6
with:
python-version: "3.11"
@ -190,7 +190,7 @@ jobs:
echo "confidence=$CONFIDENCE" >> $GITHUB_OUTPUT
- name: Comment with analysis
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
let comment = '';
@ -307,7 +307,7 @@ jobs:
- name: Add labels
if: github.event_name == 'issues'
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const labels = [];

View file

@ -40,7 +40,7 @@ jobs:
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version: 20
registry-url: "https://registry.npmjs.org"

View file

@ -10,7 +10,7 @@ jobs:
pull-requests: write
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
- uses: actions/stale@v10
with:
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!"
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."

View file

@ -21,7 +21,7 @@ jobs:
gh auth login --with-token <<< "${{ github.token }}"
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"

View file

@ -23,5 +23,5 @@ CHANGELOG.md
**/CODEOWNERS
core/vendor
coverage
e2e
# e2e
packages/continue-sdk

2
.vscode/launch.json vendored
View file

@ -153,7 +153,7 @@
"${workspaceFolder}/**",
"!**/node_modules/**"
],
"preLaunchTask": "watch-logs",
"preLaunchTask": "cli:build-and-watch-logs",
"cwd": "${workspaceFolder}/extensions/cli"
},
{

View file

@ -43,7 +43,8 @@
"extensions/vscode/e2e/storage": true,
"extensions/vscode/e2e/vsix": true,
"extensions/.continue-debug": true,
"extensions/cli/dist/**": true
"extensions/cli/dist/**": true,
"packages/config-yaml/dist/**": true
// "sync/**": true
},
"editor.formatOnSave": true,

35
.vscode/tasks.json vendored
View file

@ -330,6 +330,26 @@
"cwd": "${workspaceFolder}/extensions/cli"
}
},
{
"label": "cli:build-no-minify",
"type": "shell",
"command": "npm",
"args": ["run", "build:bundle", "--", "--no-minify"],
"group": "build",
"presentation": {
"echo": true,
"reveal": "silent",
"focus": false,
"panel": "shared",
"showReuseMessage": true,
"clear": false,
"close": true
},
"problemMatcher": ["$tsc"],
"options": {
"cwd": "${workspaceFolder}/extensions/cli"
}
},
{
"label": "cli:test",
"type": "npm",
@ -373,6 +393,21 @@
"options": {
"cwd": "${workspaceFolder}/extensions/cli"
}
},
{
"label": "cli:build-and-watch-logs",
"dependsOn": ["cli:build-no-minify", "watch-logs"],
"dependsOrder": "sequence",
"type": "shell",
"command": "echo",
"args": ["Build and watch logs completed"],
"presentation": {
"group": "build-tasks",
"panel": "shared",
"reveal": "silent",
"close": true,
"focus": false
}
}
]
}

View file

@ -176,9 +176,9 @@ See [`intellij/CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the
### Our Git Workflow
We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the
`main` branch titled `v1.1.x-vscode`, which automatically triggers the workflow
`main` branch titled `v1.3.x-vscode`, which automatically triggers the workflow
in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When
a release has been sufficiently tested, we will create a new release titled `v1.0x-vscode`, triggering a similar
a release has been sufficiently tested, we will create a new release titled `v1.2.x-vscode`, triggering a similar
workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code
extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow
is well explained by <http://releaseflow.org>.

View file

@ -35,25 +35,25 @@ Get started in [VS Code](https://marketplace.visualstudio.com/items?itemName=Con
## Agent
[Agent](/features/agent/quick-start) to work on development tasks together with AI
[Agent](https://docs.continue.dev/features/agent/quick-start) to work on development tasks together with AI
![agent](docs/images/agent.gif)
## Chat
[Chat](/features/chat/quick-start) to ask general questions and clarify code sections
[Chat](https://docs.continue.dev/features/chat/quick-start) to ask general questions and clarify code sections
![chat](docs/images/chat.gif)
## Edit
[Edit](/features/edit/quick-start) to modify a code section without leaving your current file
[Edit](https://docs.continue.dev/features/edit/quick-start) to modify a code section without leaving your current file
![edit](docs/images/edit.gif)
## Autocomplete
[Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type
[Autocomplete](https://docs.continue.dev/features/autocomplete/quick-start) to receive inline code suggestions as you type
![autocomplete](docs/images/autocomplete.gif)

View file

@ -73,7 +73,7 @@ runs:
- name: Install Continue CLI
if: env.SKIP_REVIEW != 'true'
shell: bash
run: npm install -g @continuedev/cli@1.4.25
run: npm install -g @continuedev/cli@1.4.30
- name: Build Inline Review Prompt
if: env.SKIP_REVIEW != 'true'
@ -194,6 +194,21 @@ runs:
exit 1
fi
# Validate API key
if [ -z "$CONTINUE_API_KEY" ]; then
echo "Warning: CONTINUE_API_KEY environment variable is not set"
# Create fallback review and continue
cat > inline_review.json << 'EOF'
{
"review_summary": "AI review skipped: CONTINUE_API_KEY not configured.",
"comments": []
}
EOF
echo "SKIP_CLI=true" >> $GITHUB_ENV
else
echo "SKIP_CLI=false" >> $GITHUB_ENV
fi
# Log the prompt for debugging
echo "===== START REVIEW PROMPT ====="
head -n 50 inline_review_prompt.txt
@ -201,23 +216,67 @@ runs:
tail -n 20 inline_review_prompt.txt
echo "===== END REVIEW PROMPT ====="
# Run the CLI and capture JSON output
cn --readonly --format json --org "${{ inputs.continue-org }}" --config "${{ inputs.continue-config }}" -p "$(cat inline_review_prompt.txt)" > inline_review_raw.json
# Log the output for debugging
echo "Initial Continue CLI output:"
cat inline_review_raw.json
# Validate JSON output and use it directly
if ! jq empty inline_review_raw.json 2>/dev/null; then
echo "Error: Invalid JSON output from Continue CLI"
exit 1
# Test Continue CLI availability
if [ "$SKIP_CLI" != "true" ]; then
echo "Testing Continue CLI..."
if ! cn --version; then
echo "Warning: Continue CLI not found or not working"
cat > inline_review.json << 'EOF'
{
"review_summary": "AI review skipped: Continue CLI installation failed.",
"comments": []
}
EOF
echo "SKIP_CLI=true" >> $GITHUB_ENV
else
echo "Continue CLI version: $(cn --version)"
fi
fi
# Run the CLI and capture JSON output with error handling
if [ "$SKIP_CLI" != "true" ]; then
echo "Executing Continue CLI with config: ${{ inputs.continue-org }}/${{ inputs.continue-config }}"
# Write prompt to temp file for better handling
PROMPT_FILE="/tmp/continue-prompt-$.txt"
cp inline_review_prompt.txt "$PROMPT_FILE"
# Use timeout to prevent hanging (240 seconds = 4 minutes)
if ! timeout 240 cn --config "${{ inputs.continue-org }}/${{ inputs.continue-config }}" -p "@$PROMPT_FILE" --allow Bash --format json > inline_review_raw.json 2>cli_error.log; then
echo "Warning: Continue CLI command failed"
echo "CLI error log:"
cat cli_error.log
# Create fallback review
cat > inline_review.json << 'EOF'
{
"review_summary": "AI review failed due to service initialization issues. Please check the Continue API key and configuration.",
"comments": []
}
EOF
echo "Created fallback review due to CLI failure"
else
# Log the output for debugging
echo "Initial Continue CLI output:"
cat inline_review_raw.json
# Validate JSON output and use it directly
if ! jq empty inline_review_raw.json 2>/dev/null; then
echo "Warning: Invalid JSON output from Continue CLI, using fallback"
cat > inline_review.json << 'EOF'
{
"review_summary": "AI review completed but failed to parse output correctly.",
"comments": []
}
EOF
else
# Use the JSON output directly
cp inline_review_raw.json inline_review.json
echo "Review output:"
cat inline_review.json
fi
fi
fi
# Use the JSON output directly
cp inline_review_raw.json inline_review.json
echo "Review output:"
cat inline_review.json
- name: Post Inline Review Comments
if: env.SKIP_REVIEW != 'true'

View file

@ -1,20 +1,20 @@
name: 'Continue PR Review'
description: 'Automated code review for pull requests using Continue CLI'
author: 'Continue Dev, Inc.'
name: "Continue PR Review"
description: "Automated code review for pull requests using Continue CLI"
author: "Continue Dev, Inc."
inputs:
continue-api-key:
description: 'API key for Continue service'
description: "API key for Continue service"
required: true
continue-org:
description: 'Organization for Continue config'
description: "Organization for Continue config"
required: true
continue-config:
description: 'Config path to use (e.g., "myorg/review-bot")'
required: true
runs:
using: 'composite'
using: "composite"
steps:
- name: Checkout Repository
uses: actions/checkout@v4
@ -27,7 +27,7 @@ runs:
run: |
# Check if this action should run based on event type and user permissions
SHOULD_RUN="false"
if [ "${{ github.event_name }}" = "pull_request" ]; then
# Check if PR is a draft
if [ "${{ github.event.pull_request.draft }}" = "true" ]; then
@ -56,7 +56,7 @@ runs:
else
echo "::notice::Skipping review - Unsupported event type: ${{ github.event_name }}"
fi
echo "SHOULD_RUN=$SHOULD_RUN" >> $GITHUB_ENV
- name: Setup Node.js
@ -68,7 +68,7 @@ runs:
- name: Install Continue CLI
if: env.SHOULD_RUN == 'true'
shell: bash
run: npm install -g @continuedev/cli@1.4.25
run: npm install -g @continuedev/cli@1.4.30
- name: Build PR Review Prompt
if: env.SHOULD_RUN == 'true'
@ -157,19 +157,84 @@ runs:
echo "=================================="
echo ""
# Validate API key
if [ -z "$CONTINUE_API_KEY" ]; then
echo "Warning: CONTINUE_API_KEY environment variable is not set"
# Create fallback review and continue
cat > code_review.md << 'EOF'
## Code Review Summary
⚠️ AI review skipped: CONTINUE_API_KEY not configured.
### Configuration Required
- Please set the CONTINUE_API_KEY secret in repository settings
- Verify that the organization and config path are valid
EOF
echo "SKIP_CLI=true" >> $GITHUB_ENV
else
echo "SKIP_CLI=false" >> $GITHUB_ENV
fi
# Validate inputs to prevent command injection
if [[ ! "$CONTINUE_ORG" =~ ^[a-zA-Z0-9_-]+$ ]]; then
echo "Error: Invalid organization name. Must contain only alphanumeric characters, hyphens, and underscores."
exit 1
fi
if [[ ! "$CONTINUE_CONFIG" =~ ^[a-zA-Z0-9_/-]+$ ]]; then
echo "Error: Invalid config path. Must contain only alphanumeric characters, hyphens, underscores, and forward slashes."
exit 1
fi
# Run the CLI with validated config
cn --readonly --org "$CONTINUE_ORG" --config "$CONTINUE_CONFIG" -p "$(cat review_prompt.txt)" > code_review.md
# Test Continue CLI availability
if [ "$SKIP_CLI" != "true" ]; then
echo "Testing Continue CLI..."
if ! cn --version; then
echo "Warning: Continue CLI not found or not working"
cat > code_review.md << 'EOF'
## Code Review Summary
⚠️ AI review skipped: Continue CLI installation failed.
### Troubleshooting
- Check that npm installation succeeded
- Verify @continuedev/cli package is available
EOF
echo "SKIP_CLI=true" >> $GITHUB_ENV
else
echo "Continue CLI version: $(cn --version)"
fi
fi
# Run the CLI with validated config and error handling
if [ "$SKIP_CLI" != "true" ]; then
echo "Executing Continue CLI with config: $CONTINUE_ORG/$CONTINUE_CONFIG"
# Write prompt to temp file for better handling
PROMPT_FILE="/tmp/continue-prompt-$.txt"
cp review_prompt.txt "$PROMPT_FILE"
# Use timeout to prevent hanging (240 seconds = 4 minutes)
if ! timeout 240 cn --config "$CONTINUE_ORG/$CONTINUE_CONFIG" -p "@$PROMPT_FILE" --allow Bash > code_review.md 2>cli_error.log; then
echo "Error: Continue CLI command failed"
echo "CLI error log:"
cat cli_error.log
# Create fallback review
cat > code_review.md << 'EOF'
## Code Review Summary
⚠️ AI review failed due to service initialization issues. Please check the Continue API key and configuration.
### Troubleshooting
- Verify the CONTINUE_API_KEY secret is set correctly
- Check that the organization and config path are valid
- Ensure the Continue service is accessible
EOF
else
echo "Review generated successfully"
fi
fi
- name: Upload Review Results
if: env.SHOULD_RUN == 'true' && always()
@ -229,5 +294,5 @@ runs:
}
branding:
icon: 'code'
color: 'blue'
icon: "code"
color: "blue"

View file

@ -56,6 +56,7 @@
"@continuedev/fetch": "file:../packages/fetch",
"@continuedev/llm-info": "file:../packages/llm-info",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@continuedev/terminal-security": "file:../packages/terminal-security",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -106,6 +107,7 @@
"quick-lru": "^7.0.0",
"replicate": "^0.26.0",
"request": "^2.88.2",
"shell-quote": "^1.8.3",
"socket.io-client": "^4.7.3",
"sqlite": "^5.1.1",
"sqlite3": "^5.1.7",
@ -140,6 +142,7 @@
"@types/pg": "^8.11.6",
"@types/plist": "^3.0.5",
"@types/request": "^2.48.12",
"@types/shell-quote": "^1.7.5",
"@types/tar": "^6.1.13",
"@types/uuid": "^9.0.7",
"@types/win-ca": "^3.5.4",

View file

@ -166,8 +166,13 @@ export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"];
export const CODE_STOP_BLOCK = "[/CODE]";
export const BRACKET_ENDING_CHARS = [")", "]", "}", ";"];
export const PREFIXES_TO_SKIP = ["<COMPLETION>"];
export const LINES_TO_STOP_AT = ["# End of file.", "<STOP EDITING HERE"];
export const LINES_TO_SKIP = ["</START EDITING HERE>"];
export const LINES_TO_STOP_AT = [
"# End of file.",
"<STOP EDITING HERE",
"<|/updated_code|>",
"```",
];
export const LINES_TO_SKIP = ["</START EDITING HERE>", "<|updated_code|>"];
export const LINES_TO_REMOVE_BEFORE_START = [
"<COMPLETION>",
"[CODE]",

View file

@ -19,7 +19,7 @@ import {
getSingletonHighlighter,
Highlighter,
} from "shiki";
import { DiffLine } from "..";
import { DiffChar, DiffLine } from "..";
import { escapeForSVG, kebabOfThemeStr } from "../util/text";
interface CodeRendererOptions {
@ -228,6 +228,7 @@ export class CodeRenderer {
options: ConversionOptions,
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
newDiffChars: DiffChar[],
): Promise<Buffer> {
const strokeWidth = 1;
const highlightedCodeHtml = await this.highlightCode(
@ -236,13 +237,14 @@ export class CodeRenderer {
currLineOffsetFromTop,
newDiffLines,
);
// console.log(highlightedCodeHtml);
const { guts, lineBackgrounds } = this.convertShikiHtmlToSvgGut(
highlightedCodeHtml,
options,
newDiffChars,
);
const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
const borderColor = "#6b6b6b";
const lines = code.split("\n");
const actualHeight = lines.length * options.lineHeight;
@ -256,12 +258,11 @@ export class CodeRenderer {
}
</style>
<g>
<rect x="0" y="0" rx="10" ry="10" width="${options.dimensions.width}" height="${actualHeight}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
<rect x="0" y="0" rx="2" ry="2" width="${options.dimensions.width}" height="${actualHeight}" fill="${backgroundColor}" stroke="${borderColor}" stroke-width="${strokeWidth}" shape-rendering="crispEdges" />
${lineBackgrounds}
${guts}
</g>
</svg>`;
// console.log(svg);
return Buffer.from(svg, "utf8");
}
@ -269,11 +270,56 @@ export class CodeRenderer {
convertShikiHtmlToSvgGut(
shikiHtml: string,
options: ConversionOptions,
diffChars: DiffChar[],
): { guts: string; lineBackgrounds: string } {
const dom = new JSDOM(shikiHtml);
const document = dom.window.document;
const lines = Array.from(document.querySelectorAll(".line"));
const additionSegmentsByLine = new Map<
number,
Array<{ start: number; end: number }>
>();
diffChars.forEach((diff) => {
if (
diff.type !== "new" ||
diff.newLineIndex === undefined ||
diff.newCharIndexInLine === undefined
) {
return;
}
if (diff.char.includes("\n")) {
return;
}
const start = diff.newCharIndexInLine;
const end = start + diff.char.length;
const existing = additionSegmentsByLine.get(diff.newLineIndex) ?? [];
existing.push({ start, end });
additionSegmentsByLine.set(diff.newLineIndex, existing);
});
additionSegmentsByLine.forEach((segments, lineIndex) => {
segments.sort((a, b) => a.start - b.start);
const merged: Array<{ start: number; end: number }> = [];
segments.forEach((segment) => {
if (merged.length === 0) {
merged.push({ ...segment });
return;
}
const last = merged[merged.length - 1];
if (segment.start <= last.end) {
last.end = Math.max(last.end, segment.end);
} else {
merged.push({ ...segment });
}
});
additionSegmentsByLine.set(lineIndex, merged);
});
const svgLines = lines.map((line, index) => {
const spans = Array.from(line.childNodes)
.map((node) => {
@ -309,60 +355,37 @@ export class CodeRenderer {
return `<text x="0" y="${y}" font-family="${options.fontFamily}" font-size="${options.fontSize.toString()}" xml:space="preserve" dominant-baseline="central" shape-rendering="crispEdges">${spans}</text>`;
});
const estimatedCharWidth = options.fontSize * 0.6;
const additionFill = "rgba(40, 167, 69, 0.25)";
const lineBackgrounds = lines
.map((line, index) => {
const classes = line?.getAttribute("class") || "";
const bgColor = classes.includes("highlighted")
? this.editorLineHighlight
: classes.includes("diff add")
? "rgba(255, 255, 0, 0.2)"
: this.editorBackground;
const y = index * options.lineHeight;
const isFirst = index === 0;
const isLast = index === lines.length - 1;
const isSingleLine = isFirst && isLast;
const radius = 10;
const segments = additionSegmentsByLine.get(index) ?? [];
const backgrounds: string[] = [];
// Handle single line case (both first and last)
if (isSingleLine) {
return `<path d="M ${radius} ${y}
L ${options.dimensions.width - radius} ${y}
Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
L ${options.dimensions.width} ${y + options.lineHeight - radius}
Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width - radius} ${y + options.lineHeight}
L ${radius} ${y + options.lineHeight}
Q ${0} ${y + options.lineHeight} ${0} ${y + options.lineHeight - radius}
L ${0} ${y + radius}
Q ${0} ${y} ${radius} ${y}
Z"
fill="${bgColor}" />`;
if (classes.includes("highlighted")) {
backgrounds.push(
`<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${this.editorLineHighlight}" shape-rendering="crispEdges" />`,
);
}
// SVG notes:
// By default SVGs have anti-aliasing on.
// This is undesirable in our case because pixel-perfect alignment of these rectangles will introduce thin gaps.
// Turning it off with 'shape-rendering="crispEdges"' solves the issue.
return isFirst
? `<path d="M ${0} ${y + options.lineHeight}
L ${0} ${y + radius}
Q ${0} ${y} ${radius} ${y}
L ${options.dimensions.width - radius} ${y}
Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
L ${options.dimensions.width} ${y + options.lineHeight}
Z"
fill="${bgColor}" />`
: isLast
? `<path d="M ${0} ${y}
L ${0} ${y + options.lineHeight - radius}
Q ${0} ${y + options.lineHeight} ${radius} ${y + options.lineHeight}
L ${options.dimensions.width - radius} ${y + options.lineHeight}
Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width} ${y + options.lineHeight - 10}
L ${options.dimensions.width} ${y}
Z"
fill="${bgColor}" />`
: `<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`;
segments.forEach(({ start, end }) => {
const widthInChars = Math.max(end - start, 0);
if (widthInChars <= 0) {
return;
}
const x = start * estimatedCharWidth;
const segmentWidth = widthInChars * estimatedCharWidth;
backgrounds.push(
`<rect x="${x}" y="${y}" width="${segmentWidth}" height="${options.lineHeight}" fill="${additionFill}" shape-rendering="crispEdges" />`,
);
});
return backgrounds.join("\n");
})
.filter((bg) => bg.length > 0)
.join("\n");
return {
@ -394,6 +417,7 @@ export class CodeRenderer {
options: ConversionOptions,
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
newDiffChars: DiffChar[],
): Promise<DataUri> {
switch (options.imageType) {
// case "png":
@ -413,6 +437,7 @@ export class CodeRenderer {
options,
currLineOffsetFromTop,
newDiffLines,
newDiffChars,
);
return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
}

View file

@ -0,0 +1,15 @@
import { RuleWithSource, SlashCommandWithSource } from "../..";
export function convertRuleBlockToSlashCommand(
rule: RuleWithSource,
): SlashCommandWithSource {
return {
name:
rule.name ||
(rule.rule.length > 20 ? rule.rule.substring(0, 20) + "..." : rule.rule),
description: rule.description ?? "",
prompt: rule.rule,
source: "invokable-rule",
promptFile: rule.ruleFile,
};
}

View file

@ -0,0 +1,93 @@
import { describe, expect, it } from "vitest";
import { RuleWithSource } from "../..";
import { convertRuleBlockToSlashCommand } from "./ruleBlockSlashCommand";
describe("convertRuleBlockToSlashCommand", () => {
it("should convert a rule with all properties to a slash command", () => {
const rule: RuleWithSource = {
name: "Code Review",
rule: "Review this code for best practices",
description: "Performs a code review",
source: "rules-block",
ruleFile: "/path/to/rules.yaml",
invokable: true,
};
const result = convertRuleBlockToSlashCommand(rule);
expect(result).toEqual({
name: "Code Review",
description: "Performs a code review",
prompt: "Review this code for best practices",
source: "invokable-rule",
promptFile: "/path/to/rules.yaml",
});
});
it("should handle a rule without name", () => {
const rule: RuleWithSource = {
rule: "Review this code",
source: "rules-block",
invokable: true,
};
const result = convertRuleBlockToSlashCommand(rule);
expect(result.name).toBe("Review this code");
expect(result.prompt).toBe("Review this code");
});
it("should truncate long rule text when used as name", () => {
const rule: RuleWithSource = {
rule: "This is a very long rule text that should be truncated",
source: "rules-block",
invokable: true,
};
const result = convertRuleBlockToSlashCommand(rule);
expect(result.name).toBe("This is a very long ...");
expect(result.prompt).toBe(
"This is a very long rule text that should be truncated",
);
});
it("should handle a rule without description", () => {
const rule: RuleWithSource = {
name: "Test Rule",
rule: "Test rule content",
source: "rules-block",
invokable: true,
};
const result = convertRuleBlockToSlashCommand(rule);
expect(result.description).toBe("");
});
it("should use rule text as the prompt", () => {
const rule: RuleWithSource = {
name: "Explain Code",
rule: "Explain what this code does in simple terms",
source: "rules-block",
invokable: true,
};
const result = convertRuleBlockToSlashCommand(rule);
expect(result.prompt).toBe("Explain what this code does in simple terms");
});
it("should always set source to 'invokable-rule'", () => {
const rule: RuleWithSource = {
name: "Test",
rule: "Test",
source: "default-chat",
invokable: true,
};
const result = convertRuleBlockToSlashCommand(rule);
expect(result.source).toBe("invokable-rule");
});
});

View file

@ -59,27 +59,17 @@ export class ConfigHandler {
constructor(
private readonly ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private llmLogger: ILLMLogger,
sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
initialSessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
) {
this.ide = ide;
this.ideSettingsPromise = ideSettingsPromise;
this.controlPlaneClient = new ControlPlaneClient(
sessionInfoPromise,
ideSettingsPromise,
this.ide.getIdeInfo(),
initialSessionInfoPromise,
this.ide,
);
// This profile manager will always be available
this.globalLocalProfileManager = new ProfileLifecycleManager(
new LocalProfileLoader(
ide,
ideSettingsPromise,
this.controlPlaneClient,
this.llmLogger,
),
new LocalProfileLoader(ide, this.controlPlaneClient, this.llmLogger),
this.ide,
);
@ -97,6 +87,7 @@ export class ConfigHandler {
}
private workspaceDirs: string[] | null = null;
async getWorkspaceId() {
if (!this.workspaceDirs) {
this.workspaceDirs = await this.ide.getWorkspaceDirs();
@ -113,6 +104,13 @@ export class ConfigHandler {
const signal = this.cascadeAbortController.signal;
this.workspaceDirs = null; // forces workspace dirs reload
// Always update globalLocalProfileManager before recreating all the loaders
// during every cascadeInit so it holds the most recent controlPlaneClient.
this.globalLocalProfileManager = new ProfileLifecycleManager(
new LocalProfileLoader(this.ide, this.controlPlaneClient, this.llmLogger),
this.ide,
);
try {
const { orgs, errors } = await this.getOrgs();
@ -202,6 +200,8 @@ export class ConfigHandler {
message: `Error loading Continue Hub assistants${e instanceof Error ? ":\n" + e.message : ""}`,
});
}
} else {
PolicySingleton.getInstance().policy = null;
}
// Load local org if not signed in or hub orgs fail
try {
@ -246,7 +246,6 @@ export class ConfigHandler {
versionSlug: assistant.configResult.config?.version ?? "latest",
controlPlaneClient: this.controlPlaneClient,
ide: this.ide,
ideSettingsPromise: this.ideSettingsPromise,
llmLogger: this.llmLogger,
rawYaml: assistant.rawYaml,
orgScopeId: orgScopeId,
@ -367,7 +366,6 @@ export class ConfigHandler {
const profiles = [...assistantFiles, ...agentFiles].map((assistant) => {
return new LocalProfileLoader(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.llmLogger,
assistant,
@ -392,7 +390,6 @@ export class ConfigHandler {
// Ide settings change: refresh session and cascade refresh from the top
async updateIdeSettings(ideSettings: IdeSettings) {
this.ideSettingsPromise = Promise.resolve(ideSettings);
this.abortCascade();
await this.cascadeInit("IDE settings update");
}
@ -430,8 +427,7 @@ export class ConfigHandler {
if (reload) {
this.controlPlaneClient = new ControlPlaneClient(
Promise.resolve(sessionInfo),
this.ideSettingsPromise,
this.ide.getIdeInfo(),
this.ide,
);
this.abortCascade();
await this.cascadeInit("Control plane session info update");

View file

@ -1,32 +1,32 @@
import { IDE } from "..";
import { joinPathsToUri } from "../util/uri";
const DEFAULT_ASSISTANT_FILE = `# This is an example assistant configuration file
# It is used to define custom AI assistants within Continue
# Each assistant file can be accessed by selecting it from the assistant dropdown
const DEFAULT_ASSISTANT_FILE = `# This is an example agent configuration file
# It is used to define custom AI agents within Continue
# Each agent file can be accessed by selecting it from the agent dropdown
# To learn more, see the full assistant reference: https://docs.continue.dev/reference
# To learn more, see the full config.yaml reference: https://docs.continue.dev/reference
name: Example Assistant
name: Example Agent
version: 1.0.0
schema: v1
# Models define which AI models this assistant can use
# Models define which AI models this agent can use
# https://docs.continue.dev/customization/models
models:
- name: my gpt-5
provider: openai
model: gpt-5
apiKey: YOUR_API_KEY_HERE
apiKey: YOUR_OPENAI_API_KEY_HERE
- uses: ollama/qwen2.5-coder-7b
- uses: anthropic/claude-4-sonnet
with:
ANTHROPIC_API_KEY: \${{ secrets.ANTHROPIC_API_KEY }}
# Context providers define what information the assistant can access
context:
- provider: code
- provider: docs
- provider: diff
- provider: terminal
- provider: problems
- provider: folder
- provider: codebase
# MCP Servers the agent can use
# https://docs.continue.dev/customization/mcp-tools
mcpServers:
- uses: anthropic/memory-mcp
`;
export async function createNewAssistantFile(
@ -42,7 +42,7 @@ export async function createNewAssistantFile(
const baseDirUri = joinPathsToUri(
workspaceDirs[0],
assistantPath ?? ".continue/assistants",
assistantPath ?? ".continue/agents",
);
// Find the first available filename
@ -50,10 +50,7 @@ export async function createNewAssistantFile(
let assistantFileUri: string;
do {
const suffix = counter === 0 ? "" : `-${counter}`;
assistantFileUri = joinPathsToUri(
baseDirUri,
`new-assistant${suffix}.yaml`,
);
assistantFileUri = joinPathsToUri(baseDirUri, `new-agent${suffix}.yaml`);
counter++;
} while (await ide.fileExists(assistantFileUri));

View file

@ -57,6 +57,7 @@ import {
} from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
import { PolicySingleton } from "../control-plane/PolicySingleton";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import { getBaseToolDefinitions } from "../tools";
import { resolveRelativePathInDir } from "../util/ideUtils";
@ -214,8 +215,8 @@ function applyRequestOptionsToModels(
// Prepare models
for (const model of models) {
model.requestOptions = {
...model.requestOptions,
...config.requestOptions,
...model.requestOptions,
};
if (roles !== undefined) {
model.roles = model.roles ?? roles;
@ -544,16 +545,23 @@ async function intermediateToFinalConfig({
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
mcpManager.setConnections(
(config.experimental?.modelContextProtocolServers ?? []).map(
(server, index) => ({
id: `continue-mcp-server-${index + 1}`,
name: `MCP Server`,
...server,
}),
),
false,
);
const orgPolicy = PolicySingleton.getInstance().policy;
if (orgPolicy?.policy?.allowMcpServers === false) {
await mcpManager.shutdown();
} else {
mcpManager.setConnections(
(config.experimental?.modelContextProtocolServers ?? []).map(
(server, index) => ({
id: `continue-mcp-server-${index + 1}`,
name: `MCP Server`,
...server,
requestOptions: config.requestOptions,
}),
),
false,
);
}
// Handle experimental modelRole config values for apply and edit
const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;

View file

@ -1,7 +1,7 @@
import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js";
import { ContinueConfig, IDE, ILLMLogger } from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import { getPrimaryConfigFilePath } from "../../util/paths.js";
@ -15,7 +15,6 @@ export default class LocalProfileLoader implements IProfileLoader {
constructor(
private ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private controlPlaneClient: ControlPlaneClient,
private llmLogger: ILLMLogger,
private overrideAssistantFile?:
@ -57,7 +56,6 @@ export default class LocalProfileLoader implements IProfileLoader {
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
const result = await doLoadConfig({
ide: this.ide,
ideSettingsPromise: this.ideSettingsPromise,
controlPlaneClient: this.controlPlaneClient,
llmLogger: this.llmLogger,
profileId: this.description.id,

View file

@ -2,7 +2,7 @@ import { AssistantUnrolled, ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js";
import { ContinueConfig, IDE, ILLMLogger } from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import doLoadConfig from "./doLoadConfig.js";
@ -28,7 +28,6 @@ export default class PlatformProfileLoader implements IProfileLoader {
private readonly versionSlug: string;
private readonly controlPlaneClient: ControlPlaneClient;
private readonly ide: IDE;
private ideSettingsPromise: Promise<IdeSettings>;
private llmLogger: ILLMLogger;
readonly description: ProfileDescription;
private readonly orgScopeId: string | null;
@ -41,7 +40,6 @@ export default class PlatformProfileLoader implements IProfileLoader {
versionSlug,
controlPlaneClient,
ide,
ideSettingsPromise,
llmLogger,
description,
orgScopeId,
@ -53,7 +51,6 @@ export default class PlatformProfileLoader implements IProfileLoader {
versionSlug: string;
controlPlaneClient: ControlPlaneClient;
ide: IDE;
ideSettingsPromise: Promise<IdeSettings>;
llmLogger: ILLMLogger;
description: ProfileDescription;
orgScopeId: string | null;
@ -65,7 +62,6 @@ export default class PlatformProfileLoader implements IProfileLoader {
this.versionSlug = versionSlug;
this.controlPlaneClient = controlPlaneClient;
this.ide = ide;
this.ideSettingsPromise = ideSettingsPromise;
this.llmLogger = llmLogger;
this.description = description;
this.orgScopeId = orgScopeId;
@ -79,7 +75,6 @@ export default class PlatformProfileLoader implements IProfileLoader {
versionSlug,
controlPlaneClient,
ide,
ideSettingsPromise,
llmLogger,
rawYaml,
orgScopeId,
@ -91,12 +86,11 @@ export default class PlatformProfileLoader implements IProfileLoader {
versionSlug: string;
controlPlaneClient: ControlPlaneClient;
ide: IDE;
ideSettingsPromise: Promise<IdeSettings>;
llmLogger: ILLMLogger;
rawYaml: string;
orgScopeId: string | null;
}): Promise<PlatformProfileLoader> {
const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise);
const controlPlaneEnv = await getControlPlaneEnv(ide.getIdeSettings());
const description: ProfileDescription = {
id: `${ownerSlug}/${packageSlug}`,
@ -121,7 +115,6 @@ export default class PlatformProfileLoader implements IProfileLoader {
versionSlug,
controlPlaneClient,
ide,
ideSettingsPromise,
llmLogger,
description,
orgScopeId,
@ -139,7 +132,6 @@ export default class PlatformProfileLoader implements IProfileLoader {
const results = await doLoadConfig({
ide: this.ide,
ideSettingsPromise: this.ideSettingsPromise,
controlPlaneClient: this.controlPlaneClient,
llmLogger: this.llmLogger,
overrideConfigYaml: this.configResult.config,

View file

@ -11,7 +11,6 @@ import {
import {
ContinueConfig,
IDE,
IdeSettings,
ILLMLogger,
RuleWithSource,
SerializedContinueConfig,
@ -70,7 +69,6 @@ async function loadRules(ide: IDE) {
}
export default async function doLoadConfig(options: {
ide: IDE;
ideSettingsPromise: Promise<IdeSettings>;
controlPlaneClient: ControlPlaneClient;
llmLogger: ILLMLogger;
overrideConfigJson?: SerializedContinueConfig;
@ -82,7 +80,6 @@ export default async function doLoadConfig(options: {
}): Promise<ConfigResult<ContinueConfig>> {
const {
ide,
ideSettingsPromise,
controlPlaneClient,
llmLogger,
overrideConfigJson,
@ -95,7 +92,7 @@ export default async function doLoadConfig(options: {
const ideInfo = await ide.getIdeInfo();
const uniqueId = await ide.getUniqueId();
const ideSettings = await ideSettingsPromise;
const ideSettings = await ide.getIdeSettings();
const workOsAccessToken = await controlPlaneClient.getAccessToken();
const isSignedIn = await controlPlaneClient.isSignedIn();
@ -190,7 +187,6 @@ export default async function doLoadConfig(options: {
const mcpManager = MCPManagerSingleton.getInstance();
const mcpServerStatuses = mcpManager.getStatuses();
// Slightly hacky just need connection's client to make slash command for now
const serializableStatuses = mcpServerStatuses.map((server) => {
const { client, ...rest } = server;
return rest;
@ -332,12 +328,14 @@ export default async function doLoadConfig(options: {
}
}
if (
PolicySingleton.getInstance().policy?.policy?.allowAnonymousTelemetry ===
false
) {
// Org policies
const policy = PolicySingleton.getInstance().policy?.policy;
if (policy?.allowAnonymousTelemetry === false) {
newConfig.allowAnonymousTelemetry = false;
}
if (policy?.allowCodebaseIndexing === false) {
newConfig.disableIndexing = true;
}
// Setup telemetry only after (and if) we know it is enabled
await Telemetry.setup(
@ -372,7 +370,7 @@ export default async function doLoadConfig(options: {
const useOnPremProxy =
controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl;
const env = await getControlPlaneEnv(ideSettingsPromise);
const env = await getControlPlaneEnv(Promise.resolve(ideSettings));
let controlPlaneProxyUrl: string = useOnPremProxy
? controlPlane?.proxyUrl
: env.DEFAULT_CONTROL_PLANE_PROXY_URL;

View file

@ -1061,6 +1061,7 @@ declare global {
filepath?: string;
fileContent?: string;
originalFileContent?: string;
autoFormattingDiff?: string;
}
export interface RangeInFileWithContents {

View file

@ -4,6 +4,7 @@ import {
ConfigResult,
ConfigValidationError,
isAssistantUnrolledNonNullable,
mergeConfigYamlRequestOptions,
mergeUnrolledAssistants,
ModelRole,
PackageIdentifier,
@ -24,7 +25,9 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
import { convertRuleBlockToSlashCommand } from "../../commands/slash/ruleBlockSlashCommand";
import { getControlPlaneEnvSync } from "../../control-plane/env";
import { PolicySingleton } from "../../control-plane/PolicySingleton";
import { getBaseToolDefinitions } from "../../tools";
import { getCleanUriPath } from "../../util/uri";
import { loadConfigContextProviders } from "../loadContextProviders";
@ -32,10 +35,7 @@ import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks";
import { LocalPlatformClient } from "./LocalPlatformClient";
import { llmsFromModelConfig } from "./models";
import {
convertYamlMcpToContinueMcp,
convertYamlRuleToContinueRule,
} from "./yamlToContinueConfig";
import { convertYamlRuleToContinueRule } from "./yamlToContinueConfig";
async function loadConfigYaml(options: {
overrideConfigYaml: AssistantUnrolled | undefined;
@ -153,16 +153,15 @@ async function loadConfigYaml(options: {
};
}
async function configYamlToContinueConfig(options: {
export async function configYamlToContinueConfig(options: {
config: AssistantUnrolled;
ide: IDE;
ideSettings: IdeSettings;
ideInfo: IdeInfo;
uniqueId: string;
llmLogger: ILLMLogger;
workOsAccessToken: string | undefined;
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
let { config, ide, ideSettings, ideInfo, uniqueId, llmLogger } = options;
let { config, ide, ideInfo, uniqueId, llmLogger } = options;
const localErrors: ConfigValidationError[] = [];
@ -190,6 +189,7 @@ async function configYamlToContinueConfig(options: {
summarize: null,
},
rules: [],
requestOptions: { ...config.requestOptions },
};
// Right now, if there are any missing packages in the config, then we will just throw an error
@ -207,10 +207,30 @@ async function configYamlToContinueConfig(options: {
}
for (const rule of config.rules ?? []) {
continueConfig.rules.push(convertYamlRuleToContinueRule(rule));
const convertedRule = convertYamlRuleToContinueRule(rule);
continueConfig.rules.push(convertedRule);
// Convert invokable rules to slash commands
if (convertedRule.invokable) {
try {
const slashCommand = convertRuleBlockToSlashCommand(convertedRule);
continueConfig.slashCommands?.push(slashCommand);
} catch (e) {
localErrors.push({
message: `Error converting invokable rule ${convertedRule.name} to slash command: ${e instanceof Error ? e.message : e}`,
fatal: false,
});
}
}
}
continueConfig.data = config.data;
continueConfig.data = config.data?.map((d) => ({
...d,
requestOptions: mergeConfigYamlRequestOptions(
d.requestOptions,
continueConfig.requestOptions,
),
}));
continueConfig.docs = config.docs?.map((doc) => ({
title: doc.name,
startUrl: doc.startUrl,
@ -234,12 +254,6 @@ async function configYamlToContinueConfig(options: {
});
});
continueConfig.experimental = {
modelContextProtocolServers: config.mcpServers?.map(
convertYamlMcpToContinueMcp,
),
};
// Prompt files -
try {
const promptFiles = await getAllPromptFiles(ide, undefined, true);
@ -291,9 +305,7 @@ async function configYamlToContinueConfig(options: {
try {
const llms = await llmsFromModelConfig({
model,
ide,
uniqueId,
ideSettings,
llmLogger,
config: continueConfig,
});
@ -378,21 +390,31 @@ async function configYamlToContinueConfig(options: {
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
mcpManager.setConnections(
(config.mcpServers ?? []).map((server) => ({
id: server.name,
name: server.name,
sourceFile: server.sourceFile,
transport: {
type: "stdio",
args: [],
...(server as any), // TODO: fix the types on mcpServers in config-yaml
},
timeout: server.connectionTimeout,
})),
false,
{ ide },
);
const orgPolicy = PolicySingleton.getInstance().policy;
if (orgPolicy?.policy?.allowMcpServers === false) {
await mcpManager.shutdown();
} else {
mcpManager.setConnections(
(config.mcpServers ?? []).map((server) => ({
id: server.name,
name: server.name,
sourceFile: server.sourceFile,
transport: {
type: "stdio",
args: [],
requestOptions: mergeConfigYamlRequestOptions(
server.requestOptions,
config.requestOptions,
),
...(server as any), // TODO: fix the types on mcpServers in config-yaml
},
timeout: server.connectionTimeout,
})),
false,
{ ide },
);
}
return { config: continueConfig, errors: localErrors };
}
@ -443,7 +465,6 @@ export async function loadContinueConfigFromYaml(options: {
await configYamlToContinueConfig({
config: configYamlResult.config,
ide,
ideSettings,
ideInfo,
uniqueId,
llmLogger,

View file

@ -1,12 +1,9 @@
import { ModelConfig } from "@continuedev/config-yaml";
import {
ContinueConfig,
IDE,
IdeSettings,
ILLMLogger,
LLMOptions,
} from "../..";
mergeConfigYamlRequestOptions,
ModelConfig,
} from "@continuedev/config-yaml";
import { ContinueConfig, ILLMLogger, LLMOptions } from "../..";
import { BaseLLM } from "../../llm";
import { LLMClasses } from "../../llm/llms";
@ -29,14 +26,12 @@ function getModelClass(
async function modelConfigToBaseLLM({
model,
uniqueId,
ideSettings,
llmLogger,
config,
isFromAutoDetect,
}: {
model: ModelConfig;
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
config: ContinueConfig;
isFromAutoDetect?: boolean;
@ -49,6 +44,11 @@ async function modelConfigToBaseLLM({
const { capabilities, ...rest } = model;
const mergedRequestOptions = mergeConfigYamlRequestOptions(
rest.requestOptions,
config.requestOptions,
);
let options: LLMOptions = {
...rest,
contextLength: model.defaultCompletionOptions?.contextLength,
@ -74,6 +74,7 @@ async function modelConfigToBaseLLM({
},
autocompleteOptions: model.autocompleteOptions,
isFromAutoDetect,
requestOptions: mergedRequestOptions,
};
// Model capabilities - need to be undefined if not found
@ -154,17 +155,13 @@ async function modelConfigToBaseLLM({
async function autodetectModels({
llm,
model,
ide,
uniqueId,
ideSettings,
llmLogger,
config,
}: {
llm: BaseLLM;
model: ModelConfig;
ide: IDE;
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
@ -183,7 +180,6 @@ async function autodetectModels({
name: modelName,
},
uniqueId,
ideSettings,
llmLogger,
config,
isFromAutoDetect: true,
@ -199,23 +195,18 @@ async function autodetectModels({
export async function llmsFromModelConfig({
model,
ide,
uniqueId,
ideSettings,
llmLogger,
config,
}: {
model: ModelConfig;
ide: IDE;
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
const baseLlm = await modelConfigToBaseLLM({
model,
uniqueId,
ideSettings,
llmLogger,
config,
});
@ -227,9 +218,7 @@ export async function llmsFromModelConfig({
const models = await autodetectModels({
llm: baseLlm,
model,
ide,
uniqueId,
ideSettings,
llmLogger,
config,
});

View file

@ -0,0 +1,355 @@
import { ModelConfig } from "@continuedev/config-yaml";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { ContinueConfig, ILLMLogger } from "../..";
import { llmsFromModelConfig } from "./models";
// Mock the LLM classes
vi.mock("../../llm/llms", () => ({
LLMClasses: [
class MockOpenAI {
static providerName = "openai";
static defaultOptions = {
completionOptions: {
maxTokens: 2048,
},
};
constructor(options: any) {
Object.assign(this, options);
}
async listModels() {
return ["gpt-4", "gpt-3.5-turbo"];
}
},
class MockAnthropic {
static providerName = "anthropic";
static defaultOptions = {
completionOptions: {
maxTokens: 4096,
},
};
constructor(options: any) {
Object.assign(this, options);
}
async listModels() {
return ["claude-3-5-sonnet-20241022", "claude-3-haiku-20240307"];
}
},
],
}));
describe("llmsFromModelConfig requestOptions merging", () => {
let mockLLMLogger: ILLMLogger;
let mockConfig: ContinueConfig;
beforeEach(() => {
mockLLMLogger = { log: vi.fn() } as any;
mockConfig = {
requestOptions: {
timeout: 30000,
headers: {
"User-Agent": "Continue/1.0.0",
},
proxy: "global-proxy",
},
contextProviders: [],
mcpServerStatuses: [],
rules: [],
selectedModelByRole: {
apply: null,
autocomplete: null,
chat: null,
edit: null,
embed: null,
rerank: null,
summarize: null,
},
modelsByRole: {
apply: [],
autocomplete: [],
chat: [],
edit: [],
embed: [],
rerank: [],
summarize: [],
},
slashCommands: [],
tools: [],
allowAnonymousTelemetry: false,
} as ContinueConfig;
vi.clearAllMocks();
});
it("should merge model requestOptions with config requestOptions", async () => {
const model: ModelConfig = {
name: "test-openai",
provider: "openai",
model: "gpt-4",
requestOptions: {
timeout: 60000,
headers: {
Authorization: "Bearer token123",
},
proxy: "model-proxy",
},
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: mockConfig,
});
expect(result).toHaveLength(1);
const llm = result[0];
// The LLM should have merged requestOptions
expect(llm.requestOptions).toEqual({
timeout: 60000, // model-specific takes precedence
headers: {
"User-Agent": "Continue/1.0.0", // from global request options
Authorization: "Bearer token123", // from model
},
proxy: "model-proxy", // model-specific takes precedence
});
});
it("should use config requestOptions when model has no requestOptions", async () => {
const model: ModelConfig = {
name: "test-openai",
provider: "openai",
model: "gpt-4",
// no requestOptions
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: mockConfig,
});
expect(result).toHaveLength(1);
const llm = result[0];
// The LLM should have config requestOptions
expect(llm.requestOptions).toEqual(mockConfig.requestOptions);
});
it("should use model requestOptions when config has no requestOptions", async () => {
const model: ModelConfig = {
name: "test-openai",
provider: "openai",
model: "gpt-4",
requestOptions: {
timeout: 45000,
headers: {
"API-Key": "secret",
},
},
};
const configWithoutOptions = { ...mockConfig };
delete configWithoutOptions.requestOptions;
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: configWithoutOptions,
});
expect(result).toHaveLength(1);
const llm = result[0];
// The LLM should have model requestOptions
expect(llm.requestOptions).toEqual(model.requestOptions);
});
it("should handle empty headers correctly in merge", async () => {
const model: ModelConfig = {
name: "test-openai",
provider: "openai",
model: "gpt-4",
requestOptions: {
timeout: 60000,
headers: {},
},
};
const configWithEmptyHeaders = {
...mockConfig,
requestOptions: {
...mockConfig.requestOptions!,
headers: {},
},
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: configWithEmptyHeaders,
});
expect(result).toHaveLength(1);
const llm = result[0];
// When headers merge to empty object, they should be undefined
expect(llm.requestOptions).toEqual({
timeout: 60000,
proxy: "global-proxy",
headers: undefined,
});
});
it("should handle autodetect models with merged requestOptions", async () => {
const model: ModelConfig = {
name: "autodetect-openai",
provider: "openai",
model: "AUTODETECT",
requestOptions: {
timeout: 120000,
headers: {
"X-Custom": "autodetect",
},
},
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: mockConfig,
});
// Should return multiple models from listModels()
expect(result.length).toBeGreaterThan(0);
// Each detected model should have the merged requestOptions
result.forEach((llm) => {
expect(llm.requestOptions).toEqual({
timeout: 120000, // model-specific takes precedence
headers: {
"User-Agent": "Continue/1.0.0", // from global request options
"X-Custom": "autodetect", // from model
},
proxy: "global-proxy", // from global request options
});
});
});
it("should handle unknown provider gracefully", async () => {
const model: ModelConfig = {
name: "unknown-provider",
provider: "unknown",
model: "unknown-model",
requestOptions: {
timeout: 60000,
},
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: mockConfig,
});
// Should return empty array for unknown provider
expect(result).toHaveLength(0);
});
it("should preserve other model properties while merging requestOptions", async () => {
const model: ModelConfig = {
name: "test-anthropic",
provider: "anthropic",
model: "claude-3-5-sonnet-20241022",
roles: ["chat", "summarize"],
capabilities: ["tool_use", "image_input"],
defaultCompletionOptions: {
temperature: 0.7,
maxTokens: 1000,
},
requestOptions: {
timeout: 90000,
},
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: mockConfig,
});
expect(result).toHaveLength(1);
const llm = result[0];
// Should preserve model properties
expect(llm.title).toBe("test-anthropic");
expect(llm.completionOptions?.temperature).toBe(0.7);
expect(llm.completionOptions?.maxTokens).toBe(1000);
expect(llm.capabilities?.tools).toBe(true);
expect(llm.capabilities?.uploadImage).toBe(true);
// Should have merged requestOptions
expect(llm.requestOptions).toEqual({
timeout: 90000,
headers: {
"User-Agent": "Continue/1.0.0",
},
proxy: "global-proxy",
});
});
it("should handle complex header merging scenarios", async () => {
const model: ModelConfig = {
name: "complex-headers",
provider: "openai",
model: "gpt-4",
requestOptions: {
headers: {
Authorization: "Bearer model-token",
Accept: "application/json", // Should override config Accept
"X-Model-Specific": "true",
},
},
};
const configWithMoreHeaders = {
...mockConfig,
requestOptions: {
...mockConfig.requestOptions!,
headers: {
...mockConfig.requestOptions!.headers,
Accept: "text/plain", // Should be overridden by model
"Cache-Control": "no-cache",
},
},
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: configWithMoreHeaders,
});
expect(result).toHaveLength(1);
const llm = result[0];
expect(llm.requestOptions?.headers).toEqual({
"User-Agent": "Continue/1.0.0", // from global request options
"Cache-Control": "no-cache", // from global request options
Authorization: "Bearer model-token", // from model
Accept: "application/json", // from model (overrides config)
"X-Model-Specific": "true", // from model
});
});
});

View file

@ -13,8 +13,10 @@ export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
rule: rule.rule,
globs: rule.globs,
name: rule.name,
description: rule.description,
ruleFile: rule.sourceFile,
alwaysApply: rule.alwaysApply,
invokable: rule.invokable ?? false,
};
}
}

View file

@ -1,6 +1,4 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import {
SSEClientTransport,
SseError,
@ -8,7 +6,8 @@ import {
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { Agent as HttpsAgent } from "https";
import {
IDE,
MCPConnectionStatus,
@ -53,6 +52,7 @@ class MCPConnection {
public status: MCPConnectionStatus = "not-connected";
public isProtectedResource = false;
public errors: string[] = [];
public infos: string[] = [];
public prompts: MCPPrompt[] = [];
public tools: MCPTool[] = [];
public resources: MCPResource[] = [];
@ -94,6 +94,7 @@ class MCPConnection {
return {
...this.options,
errors: this.errors,
infos: this.infos,
prompts: this.prompts,
resources: this.resources,
resourceTemplates: this.resourceTemplates,
@ -123,6 +124,7 @@ class MCPConnection {
this.resources = [];
this.resourceTemplates = [];
this.errors = [];
this.infos = [];
this.stdioOutput = { stdout: "", stderr: "" };
this.abortController.abort();
@ -281,6 +283,16 @@ class MCPConnection {
if (msg.includes("spawn") && msg.includes("enoent")) {
const command = msg.split(" ")[1];
errorMessage += `Error: command "${command}" not found. To use this MCP server, install the ${command} CLI.`;
if (["uv", "uvx"].includes(command)) {
this.infos.push(
'Please install uv by following the installation guide: <a href="https://docs.astral.sh/uv/getting-started/installation/">https://docs.astral.sh/uv/getting-started/installation/</a>',
);
}
if (["node", "npx"].includes(command)) {
this.infos.push(
'Please install npx by following the installation guide: <a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm">https://docs.npmjs.com/downloading-and-installing-node-js-and-npm</a>',
);
}
} else {
errorMessage += "Error: " + error.message;
}
@ -393,6 +405,11 @@ class MCPConnection {
case "websocket":
return new WebSocketClientTransport(new URL(options.transport.url));
case "sse":
const sseAgent =
options.transport.requestOptions?.verifySsl === false
? new HttpsAgent({ rejectUnauthorized: false })
: undefined;
return new SSEClientTransport(new URL(options.transport.url), {
eventSourceInit: {
fetch: (input, init) =>
@ -404,17 +421,27 @@ class MCPConnection {
| Record<string, string>
| undefined),
},
...(sseAgent && { agent: sseAgent }),
}),
},
requestInit: { headers: options.transport.requestOptions?.headers },
requestInit: {
headers: options.transport.requestOptions?.headers,
...(sseAgent && { agent: sseAgent }),
},
});
case "streamable-http":
return new StreamableHTTPClientTransport(
new URL(options.transport.url),
{
requestInit: { headers: options.transport.requestOptions?.headers },
const { url, requestOptions } = options.transport;
const streamableAgent =
requestOptions?.verifySsl === false
? new HttpsAgent({ rejectUnauthorized: false })
: undefined;
return new StreamableHTTPClientTransport(new URL(url), {
requestInit: {
headers: requestOptions?.headers,
...(streamableAgent && { agent: streamableAgent }),
},
);
});
default:
throw new Error(
`Unsupported transport type: ${(options.transport as any).type}`,

View file

@ -142,6 +142,7 @@ describe("MCPConnection", () => {
expect(status).toEqual({
...options,
errors: [],
infos: [],
isProtectedResource: false,
prompts: [],
resources: [],

View file

@ -48,6 +48,21 @@ export class MCPManagerSingleton {
this.connections.delete(id);
}
async shutdown() {
if (this.connections.size > 0) {
await Promise.allSettled(
Array.from(this.connections.entries()).map(([id, connection]) => {
try {
connection.abortController.abort();
void connection.client.close();
} finally {
this.connections.delete(id);
}
}),
);
}
}
setConnections(
servers: MCPOptions[],
forceRefresh: boolean,

View file

@ -16,7 +16,7 @@ class CodeContextProvider extends BaseContextProvider {
displayTitle: "Code",
description: "Type to search",
type: "submenu",
dependsOnIndexing: true,
dependsOnIndexing: ["chunk", "codeSnippets"],
};
async getContextItems(

View file

@ -13,7 +13,7 @@ class CodebaseContextProvider extends BaseContextProvider {
description: "Automatically find relevant files",
type: "normal",
renderInlineAs: "",
dependsOnIndexing: true,
dependsOnIndexing: ["embeddings", "fullTextSearch", "chunk"],
};
async getContextItems(

View file

@ -19,7 +19,7 @@ class FolderContextProvider extends BaseContextProvider {
displayTitle: "Folder",
description: "Type to search",
type: "submenu",
dependsOnIndexing: true,
dependsOnIndexing: ["embeddings", "fullTextSearch", "chunk"],
};
async getContextItems(

View file

@ -28,11 +28,9 @@ async function getContextProviderExtras(
): Promise<ContextProviderExtras> {
setUpTestDir();
const ide = new FileSystemIde(TEST_DIR);
const ideSettingsPromise = ide.getIdeSettings();
const llmLogger = new LLMLogger();
const configHandler = new ConfigHandler(
ide,
ideSettingsPromise,
llmLogger,
Promise.resolve(undefined),
);

View file

@ -11,10 +11,19 @@ import {
import fetch, { RequestInit, Response } from "node-fetch";
import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
import { IdeInfo, IdeSettings, ModelDescription } from "../index.js";
import {
IDE,
ModelDescription,
Session,
BaseSessionMetadata,
} from "../index.js";
import { Logger } from "../util/Logger.js";
import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js";
import {
ControlPlaneSessionInfo,
HubSessionInfo,
isOnPremSession,
} from "./AuthTypes.js";
import { getControlPlaneEnv } from "./env.js";
export interface PolicyResponse {
@ -41,11 +50,15 @@ export interface FreeTrialStatus {
export const TRIAL_PROXY_URL =
"https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
export interface RemoteSessionMetadata extends BaseSessionMetadata {
isRemote: true;
remoteId: string;
}
export class ControlPlaneClient {
constructor(
readonly sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
private readonly ideSettingsPromise: Promise<IdeSettings>,
private readonly ideInfoPromise: Promise<IdeInfo>,
private readonly ide: IDE,
) {}
async resolveFQSNs(
@ -90,9 +103,9 @@ export class ControlPlaneClient {
throw new Error("No access token");
}
const env = await getControlPlaneEnv(this.ideSettingsPromise);
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
const url = new URL(path, env.CONTROL_PLANE_URL).toString();
const ideInfo = await this.ideInfoPromise;
const ideInfo = await this.ide.getIdeInfo();
const resp = await fetch(url, {
...init,
@ -304,4 +317,127 @@ export class ControlPlaneClient {
return null;
}
}
/**
* Check if remote sessions should be enabled based on feature flags
* Requires: PostHog feature flag AND @continue.dev email
*/
public async shouldEnableRemoteSessions(): Promise<boolean> {
// Check if user is signed in
if (!(await this.isSignedIn())) {
return false;
}
// Check if user has @continue.dev email
try {
const sessionInfo = await this.sessionInfoPromise;
if (isOnPremSession(sessionInfo) || !sessionInfo) {
return false;
}
const hubSession = sessionInfo as HubSessionInfo;
const email = hubSession.account?.id;
return email ? email.includes("@continue.dev") : false;
} catch (e) {
Logger.error(e, {
context: "control_plane_check_remote_sessions_enabled",
});
return false;
}
}
/**
* Get current user's session info
*/
public async getSessionInfo(): Promise<ControlPlaneSessionInfo | undefined> {
return await this.sessionInfoPromise;
}
/**
* Fetch remote agents/sessions from the control plane
* Currently restricted to @continue.dev emails for internal use
*/
public async listRemoteSessions(): Promise<RemoteSessionMetadata[]> {
if (!(await this.isSignedIn())) {
return [];
}
try {
// Note: This endpoint is currently restricted to internal @continue.dev users
// In the future, this may be expanded to support broader remote session access
const resp = await this.requestAndHandleError("agents/devboxes", {
method: "GET",
});
const agents = (await resp.json()) as any[];
return agents.map(
(agent: any): RemoteSessionMetadata => ({
sessionId: `remote-${agent.id}`,
title: agent.name || "Remote Agent",
dateCreated: new Date(agent.create_time_ms).toISOString(),
workspaceDirectory: "",
isRemote: true,
remoteId: agent.id,
}),
);
} catch (e) {
// Log error but don't throw - remote sessions are optional
Logger.error(e, {
context: "control_plane_list_remote_sessions",
});
return [];
}
}
public async loadRemoteSession(remoteId: string): Promise<Session> {
if (!(await this.isSignedIn())) {
throw new Error("Not signed in to load remote session");
}
try {
// First get the tunnel URL for the remote agent
const tunnelResp = await this.requestAndHandleError(
`agents/devboxes/${remoteId}/tunnel`,
{
method: "POST",
},
);
const tunnelData = (await tunnelResp.json()) as { url?: string };
const tunnelUrl = tunnelData.url;
if (!tunnelUrl) {
throw new Error(`Failed to get tunnel URL for agent ${remoteId}`);
}
// Now fetch the session state from the remote agent's /state endpoint
const stateResponse = await fetch(`${tunnelUrl}/state`);
if (!stateResponse.ok) {
throw new Error(
`Failed to fetch state from remote agent: ${stateResponse.statusText}`,
);
}
const remoteState = (await stateResponse.json()) as { session?: Session };
// The remote state contains a session property with the full session data
if (!remoteState.session) {
throw new Error(
"Remote agent returned invalid state - no session found",
);
}
return remoteState.session;
} catch (e) {
Logger.error(e, {
context: "control_plane_load_remote_session",
remoteId,
});
throw new Error(
`Failed to load remote session: ${e instanceof Error ? e.message : "Unknown error"}`,
);
}
}
}

View file

@ -17,6 +17,7 @@ import { DataLogger } from "./data/log";
import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { countTokens } from "./llm/countTokens";
import Lemonade from "./llm/llms/Lemonade";
import Ollama from "./llm/llms/Ollama";
import { EditAggregator } from "./nextEdit/context/aggregateEdits";
import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
@ -29,8 +30,9 @@ import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
import { Telemetry } from "./util/posthog";
import {
isProcessBackgrounded,
killTerminalProcess,
markProcessAsBackgrounded,
} from "./util/processTerminalBackgroundStates";
} from "./util/processTerminalStates";
import { getSymbolsForManyFiles } from "./util/treeSitter";
import { TTS } from "./util/tts";
@ -138,7 +140,7 @@ export class Core {
const ideInfoPromise = messenger.request("getIdeInfo", undefined);
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
const sessionInfoPromise = messenger.request(
const initialSessionInfoPromise = messenger.request(
"getControlPlaneSessionInfo",
{
silent: true,
@ -148,9 +150,8 @@ export class Core {
this.configHandler = new ConfigHandler(
this.ide,
ideSettingsPromise,
this.llmLogger,
sessionInfoPromise,
initialSessionInfoPromise,
);
this.docsService = DocsService.createSingleton(
@ -175,6 +176,13 @@ export class Core {
}
};
this.codeBaseIndexer = new CodebaseIndexer(
this.configHandler,
this.ide,
this.messenger,
this.globalContext.get("indexingPaused"),
);
this.configHandler.onConfigUpdate((result) => {
void (async () => {
const serializedResult =
@ -187,6 +195,12 @@ export class Core {
selectedOrgId: this.configHandler.currentOrg?.id ?? null,
});
if (await this.codeBaseIndexer.wasAnyOneIndexAdded()) {
await this.codeBaseIndexer.refreshCodebaseIndex(
await this.ide.getWorkspaceDirs(),
);
}
// update additional submenu context providers registered via VSCode API
const additionalProviders =
this.configHandler.getAdditionalSubmenuContextProviders();
@ -198,13 +212,6 @@ export class Core {
})();
});
this.codeBaseIndexer = new CodebaseIndexer(
this.configHandler,
this.ide,
this.messenger,
this.globalContext.get("indexingPaused"),
);
// Dev Data Logger
const dataLogger = DataLogger.getInstance();
dataLogger.core = this;
@ -225,6 +232,17 @@ export class Core {
return;
}
// Check for disableIndexing to prevent race condition
const { config } = await this.configHandler.loadConfig();
if (!config || config.disableIndexing) {
void this.messenger.request("indexProgress", {
progress: 0,
desc: "Indexing is disabled",
status: "disabled",
});
return;
}
void this.codeBaseIndexer.refreshCodebaseIndex(dirs);
});
});
@ -307,8 +325,27 @@ export class Core {
});
// History
on("history/list", (msg) => {
return historyManager.list(msg.data);
on("history/list", async (msg) => {
const localSessions = historyManager.list(msg.data);
// Check if remote sessions should be enabled based on feature flags
const shouldFetchRemote =
await this.configHandler.controlPlaneClient.shouldEnableRemoteSessions();
// Get remote sessions from control plane if feature is enabled
const remoteSessions = shouldFetchRemote
? await this.configHandler.controlPlaneClient.listRemoteSessions()
: [];
// Combine and sort by date (most recent first)
const allSessions = [...localSessions, ...remoteSessions].sort(
(a, b) =>
new Date(b.dateCreated).getTime() - new Date(a.dateCreated).getTime(),
);
// Apply limit if specified
const limit = msg.data?.limit ?? 100;
return allSessions.slice(0, limit);
});
on("history/delete", (msg) => {
@ -319,6 +356,12 @@ export class Core {
return historyManager.load(msg.data.id);
});
on("history/loadRemote", async (msg) => {
return this.configHandler.controlPlaneClient.loadRemoteSession(
msg.data.remoteId,
);
});
on("history/save", (msg) => {
historyManager.save(msg.data);
});
@ -668,6 +711,8 @@ export class Core {
return queue.dequeueProcessed() || null;
});
// NOTE: This is not used unless prefetch is used.
// At this point this is not used because I opted to rely on the model to return multiple diffs than to use prefetching.
on("nextEdit/queue/processOne", async (msg) => {
console.log("nextEdit/queue/processOne");
const { ctx, recentlyVisitedRanges, recentlyEditedRanges } = msg.data;
@ -720,20 +765,13 @@ export class Core {
data.fileUri ?? "current-file-stream",
); // not super important since currently cancelling apply will cancel all streams it's one file at a time
return streamDiffLines({
highlighted: data.highlighted,
prefix: data.prefix,
suffix: data.suffix,
return streamDiffLines(
data,
llm,
// rules included for edit, NOT apply
rulesToInclude: data.includeRulesInSystemMessage
? config.rules
: undefined,
input: data.input,
language: data.language,
overridePrompt: undefined,
abortController,
});
undefined,
data.includeRulesInSystemMessage ? config.rules : undefined,
);
});
on("cancelApply", async (msg) => {
@ -1007,6 +1045,37 @@ export class Core {
this.handleToolCall(toolCall),
);
on(
"tools/evaluatePolicy",
async ({ data: { toolName, basePolicy, args } }) => {
const { config } = await this.configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
const tool = config.tools.find((t) => t.function.name === toolName);
if (!tool) {
// Tool not found, return base policy
return { policy: basePolicy };
}
// Extract display value for specific tools
let displayValue: string | undefined;
if (toolName === "runTerminalCommand" && args.command) {
displayValue = args.command as string;
}
// If tool has evaluateToolCallPolicy function, use it
if (tool.evaluateToolCallPolicy) {
const evaluatedPolicy = tool.evaluateToolCallPolicy(basePolicy, args);
return { policy: evaluatedPolicy, displayValue };
}
// Otherwise return base policy unchanged
return { policy: basePolicy, displayValue };
},
);
on("isItemTooBig", async ({ data: { item } }) => {
return this.isItemTooBig(item);
});
@ -1024,6 +1093,10 @@ export class Core {
},
);
on("process/killTerminalProcess", async ({ data: { toolCallId } }) => {
await killTerminalProcess(toolCallId);
});
on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
const isValid = setMdmLicenseKey(licenseKey);
return isValid;
@ -1220,6 +1293,9 @@ export class Core {
if (msg.data.title === "Ollama") {
const models = await new Ollama({ model: "" }).listModels();
return models;
} else if (msg.data.title === "Lemonade") {
const models = await new Lemonade({ model: "" }).listModels();
return models;
} else {
return undefined;
}
@ -1305,6 +1381,8 @@ export class Core {
selectedCode,
reranker: config.selectedModelByRole.rerank,
fetch: (url, init) =>
// Important note: context providers fetch uses global request options not LLM request options
// Because LLM calls are handled separately
fetchwithRequestOptions(url, init, config.requestOptions),
isInAgentMode: msg.data.isInAgentMode,
});

View file

@ -1 +1,3 @@
export const EDIT_MODE_STREAM_ID = "edit-mode";
export const APPLY_UNIQUE_TOKEN = "<|!@#IS_APPLY!@#|>";

View file

@ -1,7 +1,14 @@
import { ChatMessage, ILLM, Prediction, PromptLog } from "..";
import {
ChatMessage,
ILLM,
Prediction,
PromptLog,
type StreamDiffLinesType,
} from "..";
import { DEFAULT_MAX_TOKENS } from "../llm/constants";
import { countTokens } from "../llm/countTokens";
import { renderChatMessage } from "../util/messageContent";
import { APPLY_UNIQUE_TOKEN } from "./constants.js";
const INFINITE_STREAM_SAFETY = 0.9;
@ -17,6 +24,7 @@ const RECURSIVE_PROMPT = `Continue EXACTLY where you left`;
export async function* recursiveStream(
llm: ILLM,
abortController: AbortController,
type: StreamDiffLinesType,
prompt: ChatMessage[] | string,
prediction: Prediction | undefined,
currentBuffer = "",
@ -28,8 +36,11 @@ export async function* recursiveStream(
let buffer = currentBuffer;
// let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries
const injectApplyToken = type === "apply" && shouldInjectApplyToken(llm);
if (typeof prompt === "string") {
const generator = llm.streamComplete(prompt, abortController.signal, {
const finalPrompt = injectApplyToken ? prompt + APPLY_UNIQUE_TOKEN : prompt;
const generator = llm.streamComplete(finalPrompt, abortController.signal, {
raw: true,
prediction: undefined,
reasoning: false,
@ -62,7 +73,11 @@ export async function* recursiveStream(
}
}
} else {
const generator = llm.streamChat(prompt, abortController.signal, {
const promptMessages = injectApplyToken
? appendTokenToLastMessage(prompt, APPLY_UNIQUE_TOKEN)
: prompt;
const generator = llm.streamChat(promptMessages, abortController.signal, {
raw: true,
prediction: undefined,
reasoning: false,
@ -104,3 +119,36 @@ export async function* recursiveStream(
}
}
}
function shouldInjectApplyToken(llm: ILLM): boolean {
const model = llm.model?.toLowerCase() ?? "";
return (
llm.underlyingProviderName === "inception" && model.includes("mercury")
);
}
function appendTokenToLastMessage(
messages: ChatMessage[],
token: string,
): ChatMessage[] {
if (messages.length === 0) {
return messages;
}
const lastMessage = messages[messages.length - 1];
if (typeof lastMessage.content !== "string") {
return messages;
}
if (lastMessage.content.endsWith(token)) {
return messages;
}
const updatedMessages = [...messages];
updatedMessages[updatedMessages.length - 1] = {
...lastMessage,
content: lastMessage.content + token,
};
return updatedMessages;
}

View file

@ -1,618 +0,0 @@
import { findSearchMatch, SearchMatchResult } from "./findSearchMatch";
/**
* Helper function to perform a replacement using the match result
* This simulates what the actual replacement tool would do
*/
function performReplacement(
fileContent: string,
match: SearchMatchResult,
replacement: string,
): string {
return (
fileContent.substring(0, match.startIndex) +
replacement +
fileContent.substring(match.endIndex)
);
}
/**
* Helper function to test a specific strategy by crafting inputs that
* will fail all previous strategies
*/
function testSpecificStrategy(
fileContent: string,
searchContent: string,
expectedStrategy: string,
): SearchMatchResult | null {
const result = findSearchMatch(fileContent, searchContent);
if (result && result.strategyName !== expectedStrategy) {
throw new Error(
`Expected strategy ${expectedStrategy} but got ${result.strategyName}`,
);
}
return result;
}
/**
* Helper function to verify that a match result correctly identifies
* the intended content and replacement works properly
*/
function verifyMatchAndReplacement(
fileContent: string,
searchContent: string,
expectedMatchedText: string,
replacementText: string,
expectedResult: string,
): void {
const match = findSearchMatch(fileContent, searchContent);
if (!match) {
throw new Error("No match found");
}
// Verify the match captures the expected text
const actualMatchedText = fileContent.substring(
match.startIndex,
match.endIndex,
);
expect(actualMatchedText).toBe(expectedMatchedText);
// Verify replacement works correctly
const result = performReplacement(fileContent, match, replacementText);
expect(result).toBe(expectedResult);
}
describe("Strategy-specific tests", () => {
describe("exactMatch strategy", () => {
it("should handle exact match at various positions", () => {
const testCases = [
{
name: "at start",
fileContent: "abc def ghi",
searchContent: "abc",
expectedStart: 0,
expectedEnd: 3,
},
{
name: "in middle",
fileContent: "abc def ghi",
searchContent: "def",
expectedStart: 4,
expectedEnd: 7,
},
{
name: "at end",
fileContent: "abc def ghi",
searchContent: "ghi",
expectedStart: 8,
expectedEnd: 11,
},
{
name: "entire content",
fileContent: "abc def ghi",
searchContent: "abc def ghi",
expectedStart: 0,
expectedEnd: 11,
},
];
testCases.forEach(
({ name, fileContent, searchContent, expectedStart, expectedEnd }) => {
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(expectedStart);
expect(result!.endIndex).toBe(expectedEnd);
// Verify the matched content
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
},
);
});
it("should handle multiline exact matches", () => {
const fileContent = `line1
line2
line3
line4`;
const searchContent = `line2
line3`;
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(6); // After "line1\n"
expect(result!.endIndex).toBe(17); // End of "line3"
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
});
it("should handle content with special characters", () => {
const fileContent = `const regex = /[a-z]+/gi;
const str = "Hello, World!";
const result = str.match(regex);`;
const searchContent = `const str = "Hello, World!";`;
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
});
it("should verify replacement works correctly for exact matches", () => {
verifyMatchAndReplacement(
"const a = 1;\nconst b = 2;\nconst c = 3;",
"const b = 2;",
"const b = 2;",
"const b = 42;",
"const a = 1;\nconst b = 42;\nconst c = 3;",
);
});
it("should handle Windows-style line endings", () => {
const fileContent = "line1\r\nline2\r\nline3";
const searchContent = "line2";
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(7); // After "line1\r\n"
expect(result!.endIndex).toBe(12); // End of "line2"
});
it("should handle mixed line endings", () => {
const fileContent = "line1\nline2\r\nline3\rline4";
const searchContent = "line2\r\nline3";
const result = testSpecificStrategy(
fileContent,
searchContent,
"exactMatch",
);
expect(result).not.toBeNull();
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
});
});
describe("trimmedMatch strategy", () => {
it("should match when only whitespace differs at edges", () => {
const testCases = [
{
name: "leading spaces",
fileContent: "abc\n def\nghi",
searchContent: " def",
trimmedSearch: "def",
},
{
name: "trailing spaces",
fileContent: "abc\ndef \nghi",
searchContent: "def ",
trimmedSearch: "def",
},
{
name: "both leading and trailing",
fileContent: "abc\n def \nghi",
searchContent: " def ",
trimmedSearch: "def",
},
{
name: "tabs and spaces",
fileContent: "abc\n\t def \t\nghi",
searchContent: "\t def \t",
trimmedSearch: "def",
},
];
testCases.forEach(
({ name, fileContent, searchContent, trimmedSearch }) => {
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
// For cases where exact match exists, it should be preferred
if (fileContent.indexOf(searchContent) !== -1) {
expect(result!.strategyName).toBe("exactMatch");
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(searchContent);
} else {
expect(result!.strategyName).toBe("trimmedMatch");
// The match should find the trimmed content with surrounding whitespace
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toContain(trimmedSearch);
}
},
);
});
it("should handle multiline content with edge whitespace", () => {
const fileContent = `function test() {
const x = 1;
const y = 2;
}`;
const searchContent = ` const x = 1;
const y = 2; `;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
// Since there's no exact match (trailing spaces don't exist), trimmedMatch should be used
expect(result!.strategyName).toBe("trimmedMatch");
});
it("should verify replacement with trimmed matches", () => {
const fileContent = "start\n targetContent \nend";
const searchContent = " targetContent ";
const replacement = "newContent";
const match = findSearchMatch(fileContent, searchContent);
expect(match).not.toBeNull();
expect(match!.strategyName).toBe("trimmedMatch");
const result = performReplacement(fileContent, match!, replacement);
expect(result).toBe("start\nnewContent\nend");
});
it("should handle edge case with only whitespace", () => {
const fileContent = " \n \n ";
const searchContent = " \n ";
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
// Should find exact match since the content matches exactly
expect(result!.strategyName).toBe("exactMatch");
});
});
describe("whitespaceIgnoredMatch strategy", () => {
it("should match content with different indentation", () => {
const fileContent = `function test() {
const x = 1;
if (x > 0) {
return true;
}
}`;
const searchContent = `const x=1;
if(x>0){
return true;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the match covers the intended code block
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toContain("const x = 1");
expect(matchedContent).toContain("return true");
});
it("should handle complex whitespace variations", () => {
const testCases = [
{
name: "spaces vs tabs",
fileContent: "if\t(\tcondition\t)\t{\n\treturn\ttrue;\n}",
searchContent: "if (condition) { return true; }",
},
{
name: "multiple spaces collapsed",
fileContent: "const result = calculate( x , y );",
searchContent: "const result=calculate(x,y);",
},
{
name: "newlines removed",
fileContent: "function\ntest\n(\n)\n{\nreturn\n1\n;\n}",
searchContent: "function test(){return 1;}",
},
];
testCases.forEach(({ name, fileContent, searchContent }) => {
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the entire content is matched
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent.replace(/\s/g, "")).toBe(
searchContent.replace(/\s/g, ""),
);
});
});
it("should handle partial matches with whitespace differences", () => {
const fileContent = `class Example {
constructor(name) {
this.name = name;
this.items = [];
}
addItem(item) {
this.items.push(item);
}
}`;
const searchContent = `constructor(name){this.name=name;this.items=[];}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// The match should cover the constructor method
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toContain("constructor");
expect(matchedContent).toContain("this.items = []");
});
it("should verify replacement with whitespace-ignored matches", () => {
const fileContent = `function calculate ( a , b ) {
return a + b ;
}`;
const searchContent = `function calculate(a,b){return a+b;}`;
const replacement = `function calculate(x, y) {
return x + y;
}`;
const match = findSearchMatch(fileContent, searchContent);
expect(match).not.toBeNull();
expect(match!.strategyName).toBe("whitespaceIgnoredMatch");
const result = performReplacement(fileContent, match!, replacement);
expect(result).toBe(replacement);
});
it("should handle edge cases with empty content after whitespace removal", () => {
const fileContent = " \n\t\r\n ";
const searchContent = " \n ";
const result = findSearchMatch(fileContent, searchContent);
// Since search content doesn't exist in file but trims to empty, should return emptySearch
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("emptySearch");
});
it("should match correctly when multiple potential matches exist", () => {
const fileContent = `const a=1;
const a = 1 ;
const a = 1;`;
const searchContent = "const a = 1;";
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
// Should find the exact match first (third occurrence)
expect(result!.strategyName).toBe("exactMatch");
expect(result!.startIndex).toBe(33); // After first two lines
});
});
describe("Empty search content", () => {
it("should always return position 0 for empty search", () => {
const testCases = [
{ fileContent: "some content" },
{ fileContent: "" },
{ fileContent: "line1\nline2\nline3" },
{ fileContent: " spaces " },
];
testCases.forEach(({ fileContent }) => {
const result = findSearchMatch(fileContent, "");
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
});
it("should treat whitespace-only search as empty", () => {
const searchVariants = [" ", "\n\n", "\t\t", " \n\t "];
searchVariants.forEach((searchContent) => {
const result = findSearchMatch("test content", searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
});
});
describe("Strategy precedence", () => {
it("should always prefer exact match over other strategies", () => {
const fileContent = `exact match
exact match with spaces
exactmatch`;
// This should find exact match even though fuzzy would also work
const result = findSearchMatch(fileContent, "exact match");
expect(result!.strategyName).toBe("exactMatch");
expect(result!.startIndex).toBe(0);
});
it("should prefer trimmed match over whitespace-ignored", () => {
const fileContent = " content ";
const searchContent = " content ";
// Should find exact match
const result = findSearchMatch(fileContent, searchContent);
expect(result!.strategyName).toBe("exactMatch");
});
it("should prefer whitespace-ignored over fuzzy", () => {
const fileContent = "const x = 1;";
const searchContent = "const x=1;";
// Should use whitespace-ignored, not fuzzy
const result = findSearchMatch(fileContent, searchContent);
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
});
});
describe("Replacement verification tests", () => {
it("should correctly replace content found by each strategy", () => {
const testCases = [
{
name: "exact match replacement",
fileContent: "const a = 1;\nconst b = 2;\nconst c = 3;",
searchContent: "const b = 2;",
replacement: "const b = 42;",
expectedResult: "const a = 1;\nconst b = 42;\nconst c = 3;",
expectedStrategy: "exactMatch",
},
{
name: "trimmed match replacement",
fileContent: "start\n target \nend",
searchContent: " target ",
replacement: "replaced",
expectedResult: "start\nreplaced\nend",
expectedStrategy: "trimmedMatch",
},
{
name: "whitespace-ignored replacement",
fileContent: "if ( x > 0 ) { return true; }",
searchContent: "if(x>0){return true;}",
replacement: "if (x > 0) { return false; }",
expectedResult: "if (x > 0) { return false; }",
expectedStrategy: "whitespaceIgnoredMatch",
},
];
testCases.forEach(
({
name,
fileContent,
searchContent,
replacement,
expectedResult,
expectedStrategy,
}) => {
const match = findSearchMatch(fileContent, searchContent);
expect(match).not.toBeNull();
expect(match!.strategyName).toBe(expectedStrategy);
const result = performReplacement(fileContent, match!, replacement);
expect(result).toBe(expectedResult);
},
);
});
it("should handle edge cases in replacement", () => {
// Empty replacement
verifyMatchAndReplacement(
"before target after",
"target",
"target",
"",
"before after",
);
// Replacement longer than original
verifyMatchAndReplacement(
"short",
"short",
"short",
"much longer replacement",
"much longer replacement",
);
// Multiline replacement
verifyMatchAndReplacement(
"single line",
"single",
"single",
"multi\nline\nreplacement",
"multi\nline\nreplacement line",
);
});
});
describe("Performance and edge cases", () => {
it("should handle very long content efficiently", () => {
const longContent = "x".repeat(10000) + "target" + "y".repeat(10000);
const result = findSearchMatch(longContent, "target");
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(10000);
expect(result!.endIndex).toBe(10006);
});
it("should handle unicode and special characters", () => {
const testCases = [
{
fileContent: "const emoji = '🚀🌟🎉';",
searchContent: "🚀🌟🎉",
},
{
fileContent: "const chinese = '你好世界';",
searchContent: "你好世界",
},
{
fileContent: "const regex = /\\d+/g;",
searchContent: "/\\d+/g",
},
];
testCases.forEach(({ fileContent, searchContent }) => {
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toContain(searchContent);
});
});
it("should handle null bytes and control characters", () => {
const fileContent = "before\x00null\x01byte\x02after";
const searchContent = "\x00null\x01byte\x02";
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("exactMatch");
});
});
});

View file

@ -1,587 +0,0 @@
import { findSearchMatch } from "./findSearchMatch";
describe("Exact matches", () => {
it("should find exact match at the beginning of file", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `function hello() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: fileContent.length,
strategyName: "exactMatch",
});
});
it("should find exact match in the middle of file", () => {
const fileContent = `const a = 1;
function hello() {
console.log("world");
}
const b = 2;`;
const searchContent = `function hello() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 13, // After "const a = 1;\n"
endIndex: 13 + searchContent.length,
strategyName: "exactMatch",
});
});
it("should find exact match at the end of file", () => {
const fileContent = `const a = 1;
function hello() {
console.log("world");
}`;
const searchContent = `function hello() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 13, // After "const a = 1;\n"
endIndex: fileContent.length,
strategyName: "exactMatch",
});
});
it("should find exact match with single line", () => {
const fileContent = `const a = 1;
const b = 2;
const c = 3;`;
const searchContent = `const b = 2;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 13, // After "const a = 1;\n"
endIndex: 13 + searchContent.length,
strategyName: "exactMatch",
});
});
it("should find exact match with whitespace preserved", () => {
const fileContent = `function test() {
const x = 1;
const y = 2;
}`;
const searchContent = ` const x = 1;
const y = 2;`;
const result = findSearchMatch(fileContent, searchContent);
// The actual indexOf result is 18, not 17
expect(result).toEqual({
startIndex: 18,
endIndex: 18 + searchContent.length,
strategyName: "exactMatch",
});
});
});
describe("Trimmed matches", () => {
it("should find trimmed match when exact match fails due to leading newlines", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `\n\nfunction hello() {
console.log("world");
}\n\n`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: fileContent.length, // Uses trimmed length
strategyName: "trimmedMatch",
});
});
it("should find trimmed match when exact match fails due to trailing newlines", () => {
const fileContent = `const a = 1;
function hello() {
return "world";
}
const b = 2;`;
const searchContent = `\nfunction hello() {
return "world";
}\n`;
const result = findSearchMatch(fileContent, searchContent);
// The function finds the exact match first (at index 12), not the trimmed match
expect(result).toEqual({
startIndex: 12,
endIndex: 12 + searchContent.length,
strategyName: "exactMatch",
});
});
it("should find trimmed match for single line with extra whitespace", () => {
const fileContent = `const a = 1;
const b = 2;
const c = 3;`;
const searchContent = `\n const b = 2; \n`;
const result = findSearchMatch(fileContent, searchContent);
const trimmedSearchContent = searchContent.trim();
const expectedStart = fileContent.indexOf(trimmedSearchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + trimmedSearchContent.length,
strategyName: "trimmedMatch",
});
});
});
describe("Empty search content", () => {
it("should match at beginning for empty search content", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = "";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should match at beginning for whitespace-only search content", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = "\n\n \t \n";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should match at beginning for empty file and empty search", () => {
const fileContent = "";
const searchContent = "";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
});
describe("Edge cases", () => {
it("should handle empty file with non-empty search", () => {
const fileContent = "";
const searchContent = "function hello() {}";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should handle very large content", () => {
const repeatedLine = "const x = 1;\n";
const fileContent =
repeatedLine.repeat(1000) +
"const target = 2;\n" +
repeatedLine.repeat(1000);
const searchContent = "const target = 2;";
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = repeatedLine.length * 1000;
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
strategyName: "exactMatch",
});
});
it("should handle special characters and symbols", () => {
const fileContent = `const regex = /[a-zA-Z]+/g;
const symbols = !@#$%^&*();
const unicode = "🚀 Hello 世界";`;
const searchContent = `const symbols = !@#$%^&*();`;
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = fileContent.indexOf(searchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
strategyName: "exactMatch",
});
});
it("should prefer exact match over trimmed match", () => {
const fileContent = `function test() {
const x = 1;
}
function test() {
const x = 1;
}`;
const searchContent = `function test() {
const x = 1;
}`;
const result = findSearchMatch(fileContent, searchContent);
// Should find the first exact match, not a trimmed version
expect(result).toEqual({
startIndex: 0,
endIndex: searchContent.length,
strategyName: "exactMatch",
});
});
it("should handle multiple occurrences and return first match", () => {
const fileContent = `const a = 1;
const b = 2;
const a = 1;`;
const searchContent = `const a = 1;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: searchContent.length,
strategyName: "exactMatch",
});
});
});
describe("Whitespace-ignored matches", () => {
it("should match code with different indentation", () => {
const fileContent = `function example() {
const x = 1;
const y = 2;
return x + y;
}`;
const searchContent = `const x=1;
const y=2;
return x+y;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(20); // After "function example() {\n"
expect(result!.endIndex).toBe(72); // End of " return x + y;"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content contains the original whitespace
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
const x = 1;
const y = 2;
return x + y;`);
});
it("should match single line with different spacing", () => {
const fileContent = `const a = 1;
const b = 2;
const c = 3;`;
const searchContent = `const b=2;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(12); // After "const a = 1;"
expect(result!.endIndex).toBe(32); // End of "const b = 2;"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content preserves original spacing
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
const b = 2;`);
});
it("should match with tabs vs spaces", () => {
const fileContent = `function test() {
\tif (condition) {
\t\treturn true;
\t}
}`;
const searchContent = `if (condition) {
return true;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(17); // After "function test() {"
expect(result!.endIndex).toBe(53); // End of "\t}"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content preserves original tabs
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
\tif (condition) {
\t\treturn true;
\t}`);
});
it("should match complex whitespace patterns", () => {
const fileContent = `const obj = {
key1 : 'value1',
key2 : 'value2',
key3 : 'value3'
};`;
const searchContent = `key1:'value1',
key2:'value2',
key3:'value3'`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(13); // After "const obj = {"
expect(result!.endIndex).toBe(83); // End of " key3 : 'value3'"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content preserves original formatting
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
key1 : 'value1',
key2 : 'value2',
key3 : 'value3'`);
});
it("should handle newlines and mixed whitespace", () => {
const fileContent = `function calc() {
let result = 0;
result += 5;
return result;
}`;
const searchContent = `let result=0;result+=5;return result;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(17); // After "function calc() {\n\n"
expect(result!.endIndex).toBe(78); // End of " return result;"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content includes all original whitespace
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
let result = 0;
result += 5;
return result;`);
});
it("should prefer exact match over whitespace-ignored match", () => {
const fileContent = `const x=1;
const x = 1;`;
const searchContent = `const x=1;`;
const result = findSearchMatch(fileContent, searchContent);
// Should find the exact match first (at index 0), not the whitespace-ignored match
expect(result).toEqual({
startIndex: 0,
endIndex: 10,
strategyName: "exactMatch",
});
});
it("should handle empty content after whitespace removal", () => {
const fileContent = `function test() {
return 1;
}`;
const searchContent = `\n\n \t \n`;
const result = findSearchMatch(fileContent, searchContent);
// Should match at beginning for empty/whitespace-only content
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should handle complex code blocks with different formatting", () => {
const fileContent = `class Example {
constructor(name) {
this.name = name;
this.value = 0;
}
getValue() {
return this.value;
}
}`;
const searchContent = `constructor(name){
this.name=name;
this.value=0;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(15); // After "class Example {"
expect(result!.endIndex).toBe(95); // End of " }"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content preserves original formatting
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
constructor(name) {
this.name = name;
this.value = 0;
}`);
});
it("should return null when no close match exists", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `this has nothing to do with the other option`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should handle multiple potential matches and return first", () => {
const fileContent = `const a=1;
const a = 1;
const a = 1;`;
const searchContent = `const a=1;`;
const result = findSearchMatch(fileContent, searchContent);
// Should find the first exact match
expect(result).toEqual({
startIndex: 0,
endIndex: 10,
strategyName: "exactMatch",
});
});
});
describe("Real-world scenarios", () => {
it("should match typical function replacement", () => {
const fileContent = `class Calculator {
constructor() {
this.result = 0;
}
reset() {
this.result = 0;
return this;
}
add(value) {
this.result += value;
return this;
}
}`;
const searchContent = ` reset() {
this.result = 0;
return this;
}`;
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = fileContent.indexOf(searchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
strategyName: "exactMatch",
});
});
it("should match import statement", () => {
const fileContent = `import React from 'react';
import { useState, useEffect } from 'react';
import './App.css';
function App() {
return <div>Hello World</div>;
}`;
const searchContent = `import { useState, useEffect } from 'react';`;
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = fileContent.indexOf(searchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
strategyName: "exactMatch",
});
});
it("should match comment block", () => {
const fileContent = `/**
* This is a comment
* that spans multiple lines
*/
function test() {
// Single line comment
return true;
}`;
const searchContent = `/**
* This is a comment
* that spans multiple lines
*/`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: searchContent.length,
strategyName: "exactMatch",
});
});
});

View file

@ -1,203 +0,0 @@
/**
* Represents a basic match result with start and end character positions
*/
interface BasicMatchResult {
/** The starting character index of the match in the file content */
startIndex: number;
/** The ending character index of the match in the file content */
endIndex: number;
}
/**
* Represents a match result with start and end character positions
*/
export interface SearchMatchResult extends BasicMatchResult {
/** The name of the strategy that successfully matched */
strategyName: string;
}
/**
* Strategy function type for finding matches
*/
type MatchStrategy = (
fileContent: string,
searchContent: string,
) => BasicMatchResult | null;
/**
* Exact string matching strategy
*/
function exactMatch(
fileContent: string,
searchContent: string,
): BasicMatchResult | null {
const exactIndex = fileContent.indexOf(searchContent);
if (exactIndex !== -1) {
return {
startIndex: exactIndex,
endIndex: exactIndex + searchContent.length,
};
}
return null;
}
/**
* Trimmed content matching strategy
* Finds content where the search content (when trimmed) matches content in the file,
* and returns the span that includes the file content's whitespace
*/
function trimmedMatch(
fileContent: string,
searchContent: string,
): BasicMatchResult | null {
const trimmedSearchContent = searchContent.trim();
// Don't apply if search content has no leading/trailing whitespace to trim
if (trimmedSearchContent === searchContent) {
return null;
}
// Don't match if trimmed content is empty
if (trimmedSearchContent === "") {
return null;
}
// Look for the trimmed content in the file
const trimmedContentIndex = fileContent.indexOf(trimmedSearchContent);
if (trimmedContentIndex === -1) {
return null;
}
// Find the boundaries that include surrounding whitespace (but not newlines)
// Look backwards for horizontal whitespace (spaces and tabs)
let startIndex = trimmedContentIndex;
while (startIndex > 0 && /[ \t]/.test(fileContent[startIndex - 1])) {
startIndex--;
}
// Look forwards for horizontal whitespace (spaces and tabs)
let endIndex = trimmedContentIndex + trimmedSearchContent.length;
while (endIndex < fileContent.length && /[ \t]/.test(fileContent[endIndex])) {
endIndex++;
}
return {
startIndex,
endIndex,
};
}
/**
* Whitespace-ignored matching strategy
* Removes all whitespace from both content and search, then finds the match
*/
function whitespaceIgnoredMatch(
fileContent: string,
searchContent: string,
): BasicMatchResult | null {
// Remove all whitespace (spaces, tabs, newlines, etc.)
const strippedFileContent = fileContent.replace(/\s/g, "");
const strippedSearchContent = searchContent.replace(/\s/g, "");
if (strippedSearchContent === "") {
return null; // Empty search after stripping whitespace
}
const strippedIndex = strippedFileContent.indexOf(strippedSearchContent);
if (strippedIndex === -1) {
return null;
}
// Map the stripped position back to the original file content
let originalStartIndex = 0;
let strippedCharCount = 0;
// Find the original position by counting non-whitespace characters
for (let i = 0; i < fileContent.length; i++) {
if (strippedCharCount === strippedIndex) {
originalStartIndex = i;
break;
}
if (!/\s/.test(fileContent[i])) {
strippedCharCount++;
}
}
// Find the end position by counting the length of the search content
let originalEndIndex = originalStartIndex;
let matchedChars = 0;
for (
let i = originalStartIndex;
i < fileContent.length && matchedChars < strippedSearchContent.length;
i++
) {
if (!/\s/.test(fileContent[i])) {
matchedChars++;
}
originalEndIndex = i + 1;
}
return {
startIndex: originalStartIndex,
endIndex: originalEndIndex,
};
}
/**
* Ordered list of matching strategies to try with their names
*/
const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [
{ strategy: exactMatch, name: "exactMatch" },
{ strategy: trimmedMatch, name: "trimmedMatch" },
{ strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" },
];
/**
* Find the exact match position for search content in file content.
* Uses multiple matching strategies in order of preference.
*
* Matching Strategy:
* 1. If search content is empty, matches at the beginning of file (position 0)
* 2. Try each matching strategy in order until one succeeds
*
* @param fileContent - The complete content of the file to search in
* @param searchContent - The content to search for
* @param config - Configuration options for matching behavior
* @returns Match result with character positions, or null if no match found
*/
export function findSearchMatch(
fileContent: string,
searchContent: string,
): SearchMatchResult | null {
// Handle truly empty search content
if (searchContent === "") {
return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
}
// Handle whitespace-only search content that trims to empty
const trimmedSearchContent = searchContent.trim();
if (trimmedSearchContent === "") {
// Check if the whitespace-only search content has an exact match first
const exactIndex = fileContent.indexOf(searchContent);
if (exactIndex !== -1) {
return {
startIndex: exactIndex,
endIndex: exactIndex + searchContent.length,
strategyName: "exactMatch",
};
}
// If no exact match for whitespace-only content, treat as empty search
return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
}
// Try each matching strategy in order
for (const { strategy, name } of matchingStrategies) {
const result = strategy(fileContent, searchContent);
if (result !== null) {
return { ...result, strategyName: name };
}
}
return null;
}

View file

@ -1,390 +0,0 @@
import {
parseAllSearchReplaceBlocks,
parseSearchReplaceBlock,
} from "./parseSearchReplaceBlock";
describe("parseSearchReplaceBlock", () => {
describe("Complete blocks", () => {
it("should parse a complete basic search/replace block", () => {
const content = `------- SEARCH
reset() {
this.result = 0;
return this;
}
=======
// Resets the calculator result to 0 and returns the instance for method chaining
reset() {
this.result = 0;
return this;
}
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
expect(result.searchContent).toBe(`reset() {
this.result = 0;
return this;
}`);
expect(result.replaceContent)
.toBe(`// Resets the calculator result to 0 and returns the instance for method chaining
reset() {
this.result = 0;
return this;
}`);
expect(result.error).toBeUndefined();
});
it("should handle different marker lengths", () => {
const content = `------- SEARCH
old content
=========
new content
+++++++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
expect(result.searchContent).toBe("old content");
expect(result.replaceContent).toBe("new content");
});
it("should handle empty search content", () => {
const content = `------- SEARCH
=======
new content
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
expect(result.searchContent).toBe("");
expect(result.replaceContent).toBe("new content");
});
it("should handle empty replace content (deletion)", () => {
const content = `------- SEARCH
old content to delete
=======
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
expect(result.searchContent).toBe("old content to delete");
expect(result.replaceContent).toBe("");
});
it("should handle both empty search and replace content", () => {
const content = `------- SEARCH
=======
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
expect(result.searchContent).toBe("");
expect(result.replaceContent).toBe("");
});
});
describe("Incomplete blocks", () => {
it("should handle incomplete search block", () => {
const content = `------- SEARCH
some content`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(false);
expect(result.searchContent).toBe("some content");
expect(result.replaceContent).toBe("");
expect(result.error).toBeUndefined();
});
it("should handle incomplete replace block", () => {
const content = `------- SEARCH
old content
=======
new content`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(false);
expect(result.searchContent).toBe("old content");
expect(result.replaceContent).toBe("new content");
expect(result.error).toBeUndefined();
});
});
describe("Error cases", () => {
it("should error on search end without start", () => {
const content = `=======
some content
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(false);
expect(result.error).toBe(
"Found search block end marker without matching start marker",
);
});
it("should error on replace end without replace start", () => {
const content = `+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(false);
expect(result.error).toBe(
"Found replace block end marker without matching replace start marker",
);
});
});
describe("Regex pattern validation", () => {
it("should match various search start patterns", () => {
const patterns = ["--- SEARCH", "------- SEARCH", "------------- SEARCH"];
patterns.forEach((pattern) => {
const content = `${pattern}
content
=======
replacement
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
});
});
it("should match various search end patterns", () => {
const patterns = ["===", "=======", "=============="];
patterns.forEach((pattern) => {
const content = `------- SEARCH
content
${pattern}
replacement
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
});
});
it("should match various replace end patterns", () => {
const patterns = [
"+++ REPLACE",
"+++++++ REPLACE",
"+++++++++++ REPLACE",
];
patterns.forEach((pattern) => {
const content = `------- SEARCH
content
=======
replacement
${pattern}`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
});
});
it("should not match invalid patterns", () => {
const invalidPatterns = [
"-- SEARCH", // Too few dashes
"SEARCH", // No markers
"== SEARCH", // Wrong markers
"=== REPLACE", // Wrong end marker
"++++ SEARCH", // Wrong markers for search
];
invalidPatterns.forEach((pattern) => {
const content = `${pattern}
content`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(false);
expect(result.searchContent).toBe(""); // Should not enter search mode
});
});
});
});
describe("parseAllSearchReplaceBlocks", () => {
it("should parse multiple complete blocks", () => {
const content = `------- SEARCH
old code 1
=======
new code 1
+++++++ REPLACE
------- SEARCH
old code 2
=======
new code 2
+++++++ REPLACE`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(2);
expect(blocks[0].searchContent).toBe("old code 1");
expect(blocks[0].replaceContent).toBe("new code 1");
expect(blocks[1].searchContent).toBe("old code 2");
expect(blocks[1].replaceContent).toBe("new code 2");
});
it("should handle blocks with different content", () => {
const content = `------- SEARCH
function old() {
return 1;
}
=======
function new() {
return 2;
}
+++++++ REPLACE
------- SEARCH
const x = 'old';
=======
const x = 'new';
+++++++ REPLACE`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(2);
expect(blocks[0].searchContent).toBe(`function old() {
return 1;
}`);
expect(blocks[0].replaceContent).toBe(`function new() {
return 2;
}`);
expect(blocks[1].searchContent).toBe(`const x = 'old';`);
expect(blocks[1].replaceContent).toBe(`const x = 'new';`);
});
it("should handle deletion blocks (empty replace content)", () => {
const content = `------- SEARCH
code to keep
=======
modified code
+++++++ REPLACE
------- SEARCH
code to delete
=======
+++++++ REPLACE`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(2);
expect(blocks[0].searchContent).toBe("code to keep");
expect(blocks[0].replaceContent).toBe("modified code");
expect(blocks[1].searchContent).toBe("code to delete");
expect(blocks[1].replaceContent).toBe(""); // Deletion
});
it("should handle insertion blocks (empty search content)", () => {
const content = `------- SEARCH
existing code
=======
modified existing code
+++++++ REPLACE
------- SEARCH
=======
new code to insert
+++++++ REPLACE`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(2);
expect(blocks[0].searchContent).toBe("existing code");
expect(blocks[0].replaceContent).toBe("modified existing code");
expect(blocks[1].searchContent).toBe(""); // Insertion
expect(blocks[1].replaceContent).toBe("new code to insert");
});
it("should skip incomplete blocks", () => {
const content = `------- SEARCH
incomplete block
------- SEARCH
complete block
=======
replacement
+++++++ REPLACE`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(1);
expect(blocks[0].searchContent).toBe("complete block");
expect(blocks[0].replaceContent).toBe("replacement");
});
it("should handle single block", () => {
const content = `------- SEARCH
single block
=======
replacement
+++++++ REPLACE`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(1);
expect(blocks[0].searchContent).toBe("single block");
expect(blocks[0].replaceContent).toBe("replacement");
});
it("should return empty array when no complete blocks found", () => {
const content = `------- SEARCH
incomplete
=======
missing replace marker`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(0);
});
it("should handle blocks with extra content between them", () => {
const content = `Some other content here
------- SEARCH
block 1
=======
replacement 1
+++++++ REPLACE
More content in between
------- SEARCH
block 2
=======
replacement 2
+++++++ REPLACE
Trailing content`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(2);
expect(blocks[0].searchContent).toBe("block 1");
expect(blocks[0].replaceContent).toBe("replacement 1");
expect(blocks[1].searchContent).toBe("block 2");
expect(blocks[1].replaceContent).toBe("replacement 2");
});
it("should throw error for malformed blocks", () => {
const content = `------- SEARCH
content
+++++++ REPLACE`; // Missing =======
expect(() => parseAllSearchReplaceBlocks(content)).toThrow(
"Found replace block end marker without matching replace start marker",
);
});
});

View file

@ -1,147 +0,0 @@
// Search and replace block markers using flexible regex patterns
const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH$/;
const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/;
const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE$/;
export interface SearchReplaceBlockResult {
/** Whether a complete search/replace block has been parsed */
isComplete: boolean;
/** The content to search for in the file */
searchContent?: string;
/** The content to replace the search content with */
replaceContent?: string;
/** Error message if parsing failed */
error?: string;
}
/**
* Parses a search and replace block from content.
*
* Expected format:
* ------- SEARCH
* [content to find]
* =======
* [content to replace with]
* +++++++ REPLACE
*
* @param content - The content to parse
* @returns ParseResult with completion status and extracted content
*/
export function parseSearchReplaceBlock(
content: string,
): SearchReplaceBlockResult {
const lines = content.split("\n");
let currentSearchContent = "";
let currentReplaceContent = "";
let inSearch = false;
let inReplace = false;
for (const line of lines) {
if (SEARCH_BLOCK_START_REGEX.test(line)) {
inSearch = true;
inReplace = false;
currentSearchContent = "";
currentReplaceContent = "";
continue;
}
if (SEARCH_BLOCK_END_REGEX.test(line)) {
if (!inSearch) {
return {
isComplete: false,
error: "Found search block end marker without matching start marker",
};
}
inSearch = false;
inReplace = true;
continue;
}
if (REPLACE_BLOCK_END_REGEX.test(line)) {
if (!inReplace) {
return {
isComplete: false,
error:
"Found replace block end marker without matching replace start marker",
};
}
// Complete block found
return {
isComplete: true,
searchContent: currentSearchContent.trim(),
replaceContent: currentReplaceContent.trim(),
};
}
// Accumulate content
if (inSearch) {
currentSearchContent += line + "\n";
} else if (inReplace) {
currentReplaceContent += line + "\n";
}
}
// Block is not yet complete
return {
isComplete: false,
searchContent: currentSearchContent.trim(),
replaceContent: currentReplaceContent.trim(),
};
}
/**
* Parses all complete search and replace blocks from content.
*
* @param content - The content containing multiple search/replace blocks
* @returns Array of complete search/replace blocks found
* @throws Error if any malformed blocks are encountered
*/
export function parseAllSearchReplaceBlocks(
content: string,
): SearchReplaceBlockResult[] {
const blocks: SearchReplaceBlockResult[] = [];
const lines = content.split("\n");
let currentBlockLines: string[] = [];
let inBlock = false;
for (const line of lines) {
if (SEARCH_BLOCK_START_REGEX.test(line)) {
// Start of new block
if (inBlock && currentBlockLines.length > 0) {
// Process previous incomplete block if any
const blockContent = currentBlockLines.join("\n");
const result = parseSearchReplaceBlock(blockContent);
if (result.isComplete) {
blocks.push(result);
} else if (result.error) {
// Fail fast on any parsing error
throw new Error(result.error);
}
// If incomplete but no error, it's just a partial block - continue processing
}
currentBlockLines = [line];
inBlock = true;
} else if (inBlock) {
currentBlockLines.push(line);
// Check if this line completes the current block
if (REPLACE_BLOCK_END_REGEX.test(line)) {
const blockContent = currentBlockLines.join("\n");
const result = parseSearchReplaceBlock(blockContent);
if (result.isComplete) {
blocks.push(result);
} else if (result.error) {
// Fail fast on any parsing error
throw new Error(result.error);
}
currentBlockLines = [];
inBlock = false;
}
}
}
return blocks;
}

View file

@ -4,6 +4,7 @@ import {
ILLM,
Prediction,
RuleWithSource,
StreamDiffLinesPayload,
ToolResultChatMessage,
UserChatMessage,
} from "../";
@ -20,6 +21,7 @@ import { streamDiff } from "../diff/streamDiff";
import { streamLines } from "../diff/util";
import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
import { gptEditPrompt } from "../llm/templates/edit";
import { defaultApplyPrompt } from "../llm/templates/edit/gpt";
import { findLast } from "../util/findLast";
import { Telemetry } from "../util/posthog";
import { recursiveStream } from "./recursiveStream";
@ -42,6 +44,20 @@ function constructEditPrompt(
});
}
function constructApplyPrompt(
originalCode: string,
newCode: string,
llm: ILLM,
) {
const template = llm.promptTemplates?.apply ?? defaultApplyPrompt;
const rendered = llm.renderPromptTemplate(template, [], {
original_code: originalCode,
new_code: newCode,
});
return rendered;
}
export async function* addIndentation(
diffLineGenerator: AsyncGenerator<DiffLine>,
indentation: string,
@ -58,27 +74,15 @@ function modelIsInept(model: string): boolean {
return !(model.includes("gpt") || model.includes("claude"));
}
export async function* streamDiffLines({
prefix,
highlighted,
suffix,
llm,
abortController,
input,
language,
overridePrompt,
rulesToInclude,
}: {
prefix: string;
highlighted: string;
suffix: string;
llm: ILLM;
abortController: AbortController;
input: string;
language: string | undefined;
overridePrompt: ChatMessage[] | undefined;
rulesToInclude: RuleWithSource[] | undefined;
}): AsyncGenerator<DiffLine> {
export async function* streamDiffLines(
options: StreamDiffLinesPayload,
llm: ILLM,
abortController: AbortController,
overridePrompt: ChatMessage[] | undefined,
rulesToInclude: RuleWithSource[] | undefined,
): AsyncGenerator<DiffLine> {
const { type, prefix, highlighted, suffix, input, language } = options;
void Telemetry.capture(
"inlineEdit",
{
@ -104,27 +108,30 @@ export async function* streamDiffLines({
// For apply can be overridden with simply apply prompt
let prompt =
overridePrompt ??
constructEditPrompt(prefix, highlighted, suffix, llm, input, language);
(type === "apply"
? constructApplyPrompt(oldLines.join("\n"), options.newCode, llm)
: constructEditPrompt(prefix, highlighted, suffix, llm, input, language));
// Rules can be included with edit prompt
// If any rules are present this will result in using chat instead of legacy completion
const systemMessage = rulesToInclude
? getSystemMessageWithRules({
availableRules: rulesToInclude,
userMessage:
typeof prompt === "string"
? ({
role: "user",
content: prompt,
} as UserChatMessage)
: (findLast(
prompt,
(msg) => msg.role === "user" || msg.role === "tool",
) as UserChatMessage | ToolResultChatMessage | undefined),
baseSystemMessage: undefined,
contextItems: [],
}).systemMessage
: undefined;
const systemMessage =
rulesToInclude || llm.baseChatSystemMessage
? getSystemMessageWithRules({
availableRules: rulesToInclude ?? [],
userMessage:
typeof prompt === "string"
? ({
role: "user",
content: prompt,
} as UserChatMessage)
: (findLast(
prompt,
(msg) => msg.role === "user" || msg.role === "tool",
) as UserChatMessage | ToolResultChatMessage | undefined),
baseSystemMessage: llm.baseChatSystemMessage,
contextItems: [],
}).systemMessage
: undefined;
if (systemMessage) {
if (typeof prompt === "string") {
@ -158,7 +165,13 @@ export async function* streamDiffLines({
content: highlighted,
};
const completion = recursiveStream(llm, abortController, prompt, prediction);
const completion = recursiveStream(
llm,
abortController,
type,
prompt,
prediction,
);
let lines = streamLines(completion);

40
core/index.d.ts vendored
View file

@ -173,6 +173,11 @@ export interface ModelInstaller {
}
export type ContextProviderType = "normal" | "query" | "submenu";
export type ContextIndexingType =
| "chunk"
| "embeddings"
| "fullTextSearch"
| "codeSnippets";
export interface ContextProviderDescription {
title: ContextProviderName;
@ -180,7 +185,7 @@ export interface ContextProviderDescription {
description: string;
renderInlineAs?: string;
type: ContextProviderType;
dependsOnIndexing?: boolean;
dependsOnIndexing?: ContextIndexingType[];
}
export type FetchFunction = (url: string | URL, init?: any) => Promise<any>;
@ -267,7 +272,7 @@ export interface Session {
history: ChatHistoryItem[];
}
export interface SessionMetadata {
export interface BaseSessionMetadata {
sessionId: string;
title: string;
dateCreated: string;
@ -1070,11 +1075,6 @@ export interface ToolExtras {
codeBaseIndexer?: CodebaseIndexer;
}
export type ToolPolicy =
| "allowedWithPermission"
| "allowedWithoutPermission"
| "disabled";
export interface Tool {
type: "function";
function: {
@ -1099,6 +1099,11 @@ export interface Tool {
exampleArgs?: Array<[string, string | number]>;
};
defaultToolPolicy?: ToolPolicy;
toolCallIcon?: string;
evaluateToolCallPolicy?: (
basePolicy: ToolPolicy,
parsedArgs: Record<string, unknown>,
) => ToolPolicy;
}
interface ToolChoice {
@ -1277,6 +1282,7 @@ export interface MCPOptions {
transport: TransportOptions;
faviconUrl?: string;
timeout?: number;
requestOptions?: RequestOptions;
}
export type MCPConnectionStatus =
@ -1329,6 +1335,7 @@ export interface MCPTool {
export interface MCPServerStatus extends MCPOptions {
status: MCPConnectionStatus;
errors: string[];
infos: string[];
isProtectedResource: boolean;
prompts: MCPPrompt[];
@ -1383,9 +1390,12 @@ export interface ApplyState {
fileContent?: string;
originalFileContent?: string;
toolCallId?: string;
autoFormattingDiff?: string;
}
export interface StreamDiffLinesPayload {
export type StreamDiffLinesType = "edit" | "apply";
interface StreamDiffLinesOptionsBase {
type: StreamDiffLinesType;
prefix: string;
highlighted: string;
suffix: string;
@ -1396,6 +1406,19 @@ export interface StreamDiffLinesPayload {
fileUri?: string;
}
interface StreamDiffLinesOptionsEdit extends StreamDiffLinesOptionsBase {
type: "edit";
}
interface StreamDiffLinesOptionsApply extends StreamDiffLinesOptionsBase {
type: "apply";
newCode: string;
}
type StreamDiffLinesPayload =
| StreamDiffLinesOptionsApply
| StreamDiffLinesOptionsEdit;
export interface HighlightedCodePayload {
rangeInFileWithContents: RangeInFileWithContents;
prompt?: string;
@ -1803,6 +1826,7 @@ export interface RuleWithSource {
description?: string;
ruleFile?: string;
alwaysApply?: boolean;
invokable?: boolean;
}
export interface CompleteOnboardingPayload {
mode: OnboardingModes;

View file

@ -21,6 +21,7 @@ import CodebaseContextProvider from "../context/providers/CodebaseContextProvide
import { ContinueConfig } from "../index.js";
import { localPathToUri } from "../util/pathToUri.js";
import { CodebaseIndexer } from "./CodebaseIndexer.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
import { CodebaseIndex } from "./types.js";
@ -675,5 +676,154 @@ describe("CodebaseIndexer", () => {
]);
});
});
describe("getIndexesToBuild", () => {
let indexer: CodebaseIndexer;
let mockConfig: any;
let mockEmbeddingsModel: any;
let mockIdeSettings: any;
beforeEach(async () => {
indexer = new CodebaseIndexer(
testConfigHandler,
testIde,
mockMessenger as any,
false,
);
mockEmbeddingsModel = {
maxEmbeddingChunkSize: 1000,
model: "test-model",
provider: "test-provider",
};
mockIdeSettings = {
remoteConfigServerUrl: "http://test.com",
userToken: "test-token",
};
mockConfig = {
selectedModelByRole: {
embed: mockEmbeddingsModel,
},
contextProviders: [],
};
jest
.spyOn(testIde, "getIdeSettings")
.mockResolvedValue(mockIdeSettings);
});
afterEach(() => {
jest.clearAllMocks();
});
test("should create specific indexTypes for the requested context providers", async () => {
mockConfig.contextProviders = [
{
description: {
dependsOnIndexing: ["chunk", "codeSnippets"],
},
},
];
jest.spyOn(testConfigHandler, "loadConfig").mockResolvedValue({
config: mockConfig,
errors: [],
configLoadInterrupted: false,
});
const indexes = (await (
indexer as any
).getIndexesToBuild()) as CodebaseIndex[];
expect(indexes).toHaveLength(2);
expect(indexes[0].artifactId).toBe("chunks");
expect(indexes[1].artifactId).toBe("codeSnippets");
});
test("should handle duplicate contexts", async () => {
mockConfig.contextProviders = [
{
description: {
dependsOnIndexing: ["codeSnippets"],
},
},
{
description: {
dependsOnIndexing: ["codeSnippets"],
},
},
];
jest.spyOn(testConfigHandler, "loadConfig").mockResolvedValue({
config: mockConfig,
errors: [],
configLoadInterrupted: false,
});
const indexes = await (indexer as any).getIndexesToBuild();
expect(indexes).toHaveLength(1);
expect(indexes[0].artifactId).toBe("codeSnippets");
});
});
});
describe("wasAnyOneIndexAdded", () => {
let testIndexer: TestCodebaseIndexer;
let mockGetIndexesToBuild: jest.MockedFunction<any>;
beforeEach(() => {
testIndexer = new TestCodebaseIndexer(
testConfigHandler,
testIde,
mockMessenger as any,
false,
);
// Mock getIndexesToBuild to control what indexes should be built
mockGetIndexesToBuild = jest
.spyOn(testIndexer as any, "getIndexesToBuild")
.mockResolvedValue([]);
jest
.spyOn(testIndexer, "refreshCodebaseIndex")
.mockImplementation(async () => {});
});
afterEach(() => {
jest.clearAllMocks();
});
test("should return true when indexes to build differ from built indexes", async () => {
const mockIndex1 = new TestCodebaseIndex();
const mockIndex2 = new FullTextSearchCodebaseIndex();
mockGetIndexesToBuild.mockResolvedValue([mockIndex1]);
(testIndexer as any).builtIndexes = [mockIndex2];
const result = await testIndexer.wasAnyOneIndexAdded();
expect(result).toBe(true);
});
test("should return true when there are more indexes to build than built indexes", async () => {
const mockIndex1 = new TestCodebaseIndex();
const mockIndex2 = new FullTextSearchCodebaseIndex();
mockGetIndexesToBuild.mockResolvedValue([mockIndex1, mockIndex2]);
(testIndexer as any).builtIndexes = [mockIndex1];
const result = await testIndexer.wasAnyOneIndexAdded();
expect(result).toBe(true);
});
test("should return false when there are fewer indexes to build than built indexes", async () => {
const mockIndex1 = new TestCodebaseIndex();
const mockIndex2 = new FullTextSearchCodebaseIndex();
mockGetIndexesToBuild.mockResolvedValue([mockIndex1]);
(testIndexer as any).builtIndexes = [mockIndex1, mockIndex2];
const result = await testIndexer.wasAnyOneIndexAdded();
expect(result).toBe(false);
});
});
});

View file

@ -2,6 +2,7 @@ import * as fs from "fs/promises";
import { ConfigHandler } from "../config/ConfigHandler.js";
import {
ContextIndexingType,
ContinueConfig,
IDE,
IndexingProgressUpdate,
@ -58,6 +59,7 @@ export class CodebaseIndexer {
private indexingCancellationController: AbortController;
private codebaseIndexingState: IndexingProgressUpdate;
private readonly pauseToken: PauseToken;
private builtIndexes: CodebaseIndex[] = [];
private getUserFriendlyIndexName(artifactId: string): string {
if (artifactId === FullTextSearchCodebaseIndex.artifactId)
@ -166,28 +168,46 @@ export class CodebaseIndexer {
return [];
}
const indexes: CodebaseIndex[] = [
new ChunkCodebaseIndex(
this.ide.readFile.bind(this.ide),
continueServerClient,
embeddingsModel.maxEmbeddingChunkSize,
), // Chunking must come first
];
const lanceDbIndex = await LanceDbIndex.create(
embeddingsModel,
this.ide.readFile.bind(this.ide),
const indexTypesToBuild = new Set( // use set to remove duplicates
config.contextProviders
.map((provider) => provider.description.dependsOnIndexing)
.filter((indexType) => Array.isArray(indexType)) // remove undefined indexTypes
.flat(),
);
if (lanceDbIndex) {
indexes.push(lanceDbIndex);
const indexTypeToIndexerMapping: Record<
ContextIndexingType,
() => Promise<CodebaseIndex | null>
> = {
chunk: async () =>
new ChunkCodebaseIndex(
this.ide.readFile.bind(this.ide),
continueServerClient,
embeddingsModel.maxEmbeddingChunkSize,
),
codeSnippets: async () => new CodeSnippetsCodebaseIndex(this.ide),
fullTextSearch: async () => new FullTextSearchCodebaseIndex(),
embeddings: async () => {
const lanceDbIndex = await LanceDbIndex.create(
embeddingsModel,
this.ide.readFile.bind(this.ide),
);
return lanceDbIndex;
},
};
const indexes: CodebaseIndex[] = [];
// not parallelizing to avoid race conditions in sqlite
for (const indexType of indexTypesToBuild) {
if (indexType && indexType in indexTypeToIndexerMapping) {
const index = await indexTypeToIndexerMapping[indexType]();
if (index) {
indexes.push(index);
}
}
}
indexes.push(
new FullTextSearchCodebaseIndex(),
new CodeSnippetsCodebaseIndex(this.ide),
);
this.builtIndexes = indexes;
return indexes;
}
@ -694,6 +714,15 @@ export class CodebaseIndexer {
}
}
public async wasAnyOneIndexAdded() {
const indexes = await this.getIndexesToBuild();
return !indexes.every((index) =>
this.builtIndexes.some(
(builtIndex) => builtIndex.artifactId === index.artifactId,
),
);
}
public async refreshCodebaseIndex(paths: string[]) {
if (!this.indexingCancellationController.signal.aborted) {
this.indexingCancellationController.abort();

View file

@ -272,7 +272,7 @@ export default class DocsService {
id: doc.startUrl,
isReindexing: false,
title: doc.title,
debugInfo: `max depth: ${doc.maxDepth}`,
debugInfo: `max depth: ${doc.maxDepth ?? "unlimited"}`,
icon: doc.faviconUrl,
url: doc.startUrl,
};
@ -468,7 +468,7 @@ export default class DocsService {
embeddingsProviderId: provider.embeddingId,
isReindexing: forceReindex && indexExists,
title: siteIndexingConfig.title,
debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`,
debugInfo: `max depth: ${siteIndexingConfig.maxDepth ?? "unlimited"}`,
icon: siteIndexingConfig.faviconUrl,
url: siteIndexingConfig.startUrl,
};

View file

@ -155,9 +155,27 @@ describe("DocsCrawler", () => {
test(
`Default crawler common site: ${url}`,
async () => {
const { pages, crawler } = await runCrawl(url);
expect(pages.length).toBeGreaterThanOrEqual(1);
expect(crawler).toEqual("default");
// Retry logic to handle flaky network requests to TRIAL_PROXY_URL
let lastError;
const maxRetries = 3;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const { pages, crawler } = await runCrawl(url);
expect(pages.length).toBeGreaterThanOrEqual(1);
expect(crawler).toEqual("default");
return; // Test passed, exit retry loop
} catch (error) {
lastError = error;
if (attempt === maxRetries) {
throw error; // Final attempt failed, throw the error
}
// Wait before retrying (exponential backoff)
await new Promise((resolve) =>
setTimeout(resolve, 1000 * attempt),
);
}
}
},
TIMEOUT_MS,
);

View file

@ -203,6 +203,13 @@ export const DEFAULT_IGNORE_DIRS = [
...ADDITIONAL_INDEXING_IGNORE_DIRS,
];
export const DEFAULT_IGNORES = [
...DEFAULT_IGNORE_FILETYPES,
...DEFAULT_IGNORE_DIRS,
];
export const defaultIgnoresGlob = `!{${DEFAULT_IGNORES.join(",")}}`;
// Create ignore instances
export const defaultSecurityIgnoreFile = ignore().add(
DEFAULT_SECURITY_IGNORE_FILETYPES,

View file

@ -1,4 +1,9 @@
import { ChatMessage, ModelCapability, TemplateType } from "../index.js";
import {
ChatMessage,
ModelCapability,
ModelDescription,
TemplateType,
} from "../index.js";
import { NEXT_EDIT_MODELS } from "./constants.js";
import {
@ -40,6 +45,7 @@ import {
const PROVIDER_HANDLES_TEMPLATING: string[] = [
"lmstudio",
"lemonade",
"openai",
"nvidia",
"ollama",
@ -62,6 +68,7 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [
const PROVIDER_SUPPORTS_IMAGES: string[] = [
"openai",
"ollama",
"lemonade",
"cohere",
"gemini",
"msty",
@ -80,26 +87,24 @@ const PROVIDER_SUPPORTS_IMAGES: string[] = [
"watsonx",
];
const MODEL_SUPPORTS_IMAGES: string[] = [
"llava",
"gpt-4-turbo",
"gpt-4o",
"gpt-4o-mini",
"gpt-4-vision",
"claude-3",
"c4ai-aya-vision-8b",
"c4ai-aya-vision-32b",
"gemini-ultra",
"gemini-1.5-pro",
"gemini-1.5-flash",
"sonnet",
"opus",
"haiku",
"pixtral",
"llama3.2",
"llama-3.2",
"llama4",
"granite-vision",
const MODEL_SUPPORTS_IMAGES: RegExp[] = [
/llava/,
/gpt-4-turbo/,
/gpt-4o/,
/gpt-4o-mini/,
/claude-3/,
/gemini-ultra/,
/gemini-1\.5-pro/,
/gemini-1\.5-flash/,
/sonnet/,
/opus/,
/haiku/,
/pixtral/,
/llama-?3\.2/,
/llama-?4/, // might use something like /llama-?(?:[4-9](?:\.\d+)?|\d{2,}(?:\.\d+)?)/ for forward compat, if needed
/\bgemma-?3(?!n)/, // gemma3 supports vision, but gemma3n doesn't!
/\b(pali|med)gemma/,
/qwen(.*)vl/,
];
function modelSupportsImages(
@ -115,10 +120,14 @@ function modelSupportsImages(
return false;
}
const lower = model.toLowerCase();
const lowerModel = model.toLowerCase();
const lowerTitle = title?.toLowerCase() ?? "";
if (
lowerModel.includes("vision") ||
lowerTitle.includes("vision") ||
MODEL_SUPPORTS_IMAGES.some(
(modelName) => lower.includes(modelName) || title?.includes(modelName),
(modelrx) => modelrx.test(lowerModel) || modelrx.test(lowerTitle),
)
) {
return true;
@ -126,6 +135,26 @@ function modelSupportsImages(
return false;
}
function modelSupportsReasoning(
model: ModelDescription | null | undefined,
): boolean {
if (!model) {
return false;
}
if ("anthropic" === model.underlyingProviderName) {
return true;
}
if (model.model.includes("deepseek-r")) {
return true;
}
if (model.completionOptions?.reasoning) {
// Reasoning support is forced at the config level. Model might not necessarily support it though!
return true;
}
return false;
}
const PARALLEL_PROVIDERS: string[] = [
"anthropic",
"bedrock",
@ -421,4 +450,5 @@ export {
llmCanGenerateInParallel,
modelSupportsImages,
modelSupportsNextEdit,
modelSupportsReasoning,
};

View file

@ -85,7 +85,7 @@ function encodingForModel(modelName: string): Encoding {
function countImageTokens(content: MessagePart): number {
if (content.type === "imageUrl") {
return 85;
return 1024;
}
throw new Error("Non-image content type");
}

View file

@ -95,10 +95,31 @@ describe("BaseLLM", () => {
test("should return true when modelSupportsImages returns true", () => {
baseLLM.model = "gpt-4-vision";
expect(baseLLM.supportsImages()).toBe(true);
baseLLM.model = "fancy-vision-model";
expect(baseLLM.supportsImages()).toBe(true);
baseLLM.model = "gemma3:4b";
expect(baseLLM.supportsImages()).toBe(true);
baseLLM.model = "google/gemma-3-270m";
expect(baseLLM.supportsImages()).toBe(true);
baseLLM.model = "foo/paligemma-custom-100";
expect(baseLLM.supportsImages()).toBe(true);
baseLLM.model = "foo/medgemma_4b_it_16Q";
expect(baseLLM.supportsImages()).toBe(true);
baseLLM.model = "qwen2.5vl";
expect(baseLLM.supportsImages()).toBe(true);
});
test("should return false when modelSupportsImages returns false", () => {
expect(baseLLM.supportsImages()).toBe(false);
baseLLM.model = "gemma3n";
expect(baseLLM.supportsImages()).toBe(false);
});
});

View file

@ -30,6 +30,7 @@ import {
TemplateType,
Usage,
} from "../index.js";
import { isLemonadeInstalled } from "../util/lemonadeHelper.js";
import { Logger } from "../util/Logger.js";
import mergeJson from "../util/merge.js";
import { renderChatMessage } from "../util/messageContent.js";
@ -370,8 +371,17 @@ export abstract class BaseLLM implements ILLM {
},
});
if (error !== undefined) {
if (error === "cancel" || error.name === "AbortError") {
if (typeof error === "undefined") {
interaction?.logItem({
kind: "success",
promptTokens,
generatedTokens,
thinkingTokens,
usage,
});
return "success";
} else {
if (error === "cancel" || error?.name?.includes("AbortError")) {
interaction?.logItem({
kind: "cancel",
promptTokens,
@ -393,15 +403,6 @@ export abstract class BaseLLM implements ILLM {
});
return "error";
}
} else {
interaction?.logItem({
kind: "success",
promptTokens,
generatedTokens,
thinkingTokens,
usage,
});
return "success";
}
}
@ -503,6 +504,24 @@ export abstract class BaseLLM implements ILLM {
: "Unable to connect to local Ollama instance. Ollama may not be installed or may not running.";
throw new Error(message);
}
if (
e.code === "ECONNREFUSED" &&
e.message.includes("http://localhost:8000")
) {
const isInstalled = await isLemonadeInstalled();
let message: string;
if (process.platform === "linux") {
// On Linux, isLemonadeInstalled checks if it's running (via health endpoint)
message =
"Unable to connect to local Lemonade instance. Please ensure Lemonade is running. Visit http://lemonade-server.ai for setup instructions.";
} else {
// On Windows, we can check if it's installed
message = isInstalled
? "Unable to connect to local Lemonade instance. Lemonade server may not be running."
: "Unable to connect to local Lemonade instance. Lemonade may not be installed or may not be running.";
}
throw new Error(message);
}
}
throw e;
}
@ -537,18 +556,14 @@ export abstract class BaseLLM implements ILLM {
}
private _formatChatMessage(msg: ChatMessage): string {
let contentToShow = "";
if (msg.role === "tool") {
contentToShow = msg.content;
} else if (msg.role === "assistant" && msg.toolCalls?.length) {
contentToShow = msg.toolCalls
let contentToShow = renderChatMessage(msg);
if (msg.role === "assistant" && msg.toolCalls?.length) {
contentToShow += msg.toolCalls
?.map(
(toolCall) =>
`${toolCall.function?.name}(${toolCall.function?.arguments})`,
)
.join("\n");
} else if ("content" in msg) {
contentToShow = renderChatMessage(msg);
}
return `<${msg.role}>\n${contentToShow}\n\n`;
@ -615,6 +630,7 @@ export abstract class BaseLLM implements ILLM {
kind: "chunk",
chunk: formattedContent,
});
completion += formattedContent;
yield content;
}
@ -630,6 +646,7 @@ export abstract class BaseLLM implements ILLM {
kind: "chunk",
chunk,
});
completion += chunk;
yield chunk;
}
@ -1039,6 +1056,10 @@ export abstract class BaseLLM implements ILLM {
const msg = fromChatResponse(response);
yield msg;
completion = this._formatChatMessage(msg);
interaction?.logItem({
kind: "message",
message: msg,
});
} else {
// Stream true
const stream = this.openaiAdapter.chatCompletionStream(

View file

@ -68,6 +68,17 @@ class Anthropic extends BaseLLM {
return finalOptions;
}
private buildTextPart(text: string, addCaching: boolean) {
const part: any = {
type: "text",
text,
};
if (addCaching) {
part.cache_control = { type: "ephemeral" };
}
return part;
}
private convertMessage(message: ChatMessage, addCaching: boolean): any {
if (message.role === "tool") {
return {
@ -81,14 +92,30 @@ class Anthropic extends BaseLLM {
],
};
} else if (message.role === "assistant" && message.toolCalls) {
return {
role: "assistant",
content: message.toolCalls.map((toolCall) => ({
const parts: any[] = [];
if (message.content) {
if (typeof message.content === "string") {
parts.push(this.buildTextPart(message.content, addCaching));
} else if (message.content.length > 0) {
const textContent = message.content.filter((p) => p.type === "text");
const textParts = textContent.map((part, idx) => {
const cache = idx === textContent.length - 1 && addCaching;
return this.buildTextPart(part.text, cache);
});
parts.push(...textParts);
}
}
parts.push(
...message.toolCalls.map((toolCall) => ({
type: "tool_use",
id: toolCall.id,
name: toolCall.function?.name,
input: safeParseToolCallArgs(toolCall),
})),
);
return {
role: "assistant",
content: parts,
};
} else if (message.role === "thinking" && !message.redactedThinking) {
return {
@ -154,9 +181,7 @@ class Anthropic extends BaseLLM {
public convertMessages(msgs: ChatMessage[]): any[] {
// should be public for use within VertexAI
const filteredmessages = msgs.filter(
(m) => m.role !== "system" && !!m.content,
);
const filteredmessages = msgs.filter((m) => m.role !== "system");
const lastTwoUserMsgIndices = filteredmessages
.map((msg, index) => (msg.role === "user" ? index : -1))
.filter((index) => index !== -1)

View file

@ -532,7 +532,7 @@ describe("Bedrock", () => {
);
});
it("should add cache points for prompt caching when needed", () => {
it("should add cache points when cacheBehavior.cacheConversation is enabled", () => {
// Create a test instance with caching behavior enabled
const bedrockWithCaching = new TestBedrock({
apiKey: "test-key",
@ -576,5 +576,95 @@ describe("Bedrock", () => {
const userMessageText = converted[0].content?.[0].text;
expect(userMessageText).toMatch(/First message.+/);
});
it("should add cache points when completionOptions.promptCaching is enabled", () => {
// Create a test instance with prompt caching enabled via completionOptions
const bedrockWithPromptCaching = new TestBedrock({
apiKey: "test-key",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
region: "us-east-1",
});
// Set completionOptions.promptCaching (without cacheBehavior)
bedrockWithPromptCaching.completionOptions = {
...bedrockWithPromptCaching.completionOptions,
promptCaching: true,
};
const messages: ChatMessage[] = [
{ role: "user", content: "First message" } as UserChatMessage,
{ role: "assistant", content: "First response" },
{ role: "user", content: "Second message" } as UserChatMessage,
];
const availableTools = new Set<string>();
const converted = bedrockWithPromptCaching["_convertMessages"](
messages,
availableTools,
);
// The last two user messages should have cache points
expect(converted.length).toBe(3);
expect(converted[0].role).toBe("user");
expect(converted[0].content?.some((block) => block.cachePoint)).toBe(
true,
);
expect(converted[1].role).toBe("assistant");
expect(converted[2].role).toBe("user");
expect(converted[2].content?.some((block) => block.cachePoint)).toBe(
true,
);
// Verify that text content includes a cache ID suffix
const userMessageText = converted[0].content?.[0].text;
expect(userMessageText).toMatch(/First message.+/);
});
it("should not add cache points when both caching options are disabled", () => {
// Create a test instance with no caching enabled
const bedrockNoCaching = new TestBedrock({
apiKey: "test-key",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
region: "us-east-1",
});
// Explicitly set no caching
bedrockNoCaching.cacheBehavior = {
cacheConversation: false,
cacheSystemMessage: false,
};
bedrockNoCaching.completionOptions = {
...bedrockNoCaching.completionOptions,
promptCaching: false,
};
const messages: ChatMessage[] = [
{ role: "user", content: "First message" } as UserChatMessage,
{ role: "assistant", content: "First response" },
{ role: "user", content: "Second message" } as UserChatMessage,
];
const availableTools = new Set<string>();
const converted = bedrockNoCaching["_convertMessages"](
messages,
availableTools,
);
// No cache points should be added
expect(converted.length).toBe(3);
expect(converted[0].role).toBe("user");
expect(converted[0].content?.some((block) => block.cachePoint)).toBe(
false,
);
expect(converted[1].role).toBe("assistant");
expect(converted[2].role).toBe("user");
expect(converted[2].content?.some((block) => block.cachePoint)).toBe(
false,
);
// Verify that text content doesn't include a cache ID suffix
const userMessageText = converted[0].content?.[0].text;
expect(userMessageText).toBe("First message");
});
});
});

View file

@ -513,7 +513,10 @@ class Bedrock extends BaseLLM {
// The second-to-last because it retrieves potentially already cached contents,
// The last one because we want it cached for later retrieval.
// See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
if (this.cacheBehavior?.cacheConversation) {
if (
this.cacheBehavior?.cacheConversation ||
this.completionOptions.promptCaching
) {
this._addCachingToLastTwoUserMessages(converted);
}

View file

@ -2,6 +2,7 @@ import { streamSse } from "@continuedev/fetch";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import { ChatCompletionCreateParams } from "@continuedev/openai-adapters";
import { APPLY_UNIQUE_TOKEN } from "../../edit/constants.js";
import { UNIQUE_TOKEN } from "../../nextEdit/constants.js";
import OpenAI from "./OpenAI.js";
@ -96,40 +97,21 @@ class Inception extends OpenAI {
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
if (this.isNextEdit(messages)) {
messages = this.removeNextEditToken(messages);
// Use edit/completions endpoint.
const endpoint = new URL("edit/completions", this.apiBase);
const resp = await this.fetch(endpoint, {
method: "POST",
body: JSON.stringify({
model: options.model,
messages: messages,
max_tokens: options.maxTokens,
temperature: options.temperature,
top_p: options.topP,
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
stop: options.stop,
stream: true,
}),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
messages = this.removeToken(messages, UNIQUE_TOKEN);
yield* this.streamSpecialEndpoint(
"edit/completions",
messages,
signal,
});
for await (const chunk of streamSse(resp)) {
if (chunk.choices?.[0]?.delta?.content) {
yield {
role: "assistant",
content: chunk.choices[0].delta.content,
};
}
}
options,
);
} else if (this.isApply(messages)) {
messages = this.removeToken(messages, APPLY_UNIQUE_TOKEN);
yield* this.streamSpecialEndpoint(
"apply/completions",
messages,
signal,
options,
);
} else {
// Use regular chat/completions endpoint - call parent OpenAI implementation.
yield* super._streamChat(messages, signal, options);
@ -145,23 +127,68 @@ class Inception extends OpenAI {
);
}
private removeNextEditToken(messages: ChatMessage[]): ChatMessage[] {
private isApply(messages: ChatMessage[]): boolean {
return messages.some(
(message) =>
typeof message.content === "string" &&
message.content.endsWith(APPLY_UNIQUE_TOKEN),
);
}
private removeToken(messages: ChatMessage[], token: string): ChatMessage[] {
const lastMessage = messages[messages.length - 1];
if (
typeof lastMessage?.content === "string" &&
lastMessage.content.endsWith(UNIQUE_TOKEN)
lastMessage.content.endsWith(token)
) {
const cleanedMessages = [...messages];
cleanedMessages[cleanedMessages.length - 1] = {
...lastMessage,
content: lastMessage.content.slice(0, -UNIQUE_TOKEN.length),
content: lastMessage.content.slice(0, -token.length),
};
return cleanedMessages;
}
return messages;
}
private async *streamSpecialEndpoint(
path: string,
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const endpoint = new URL(path, this.apiBase);
const resp = await this.fetch(endpoint, {
method: "POST",
body: JSON.stringify({
model: options.model,
messages,
max_tokens: options.maxTokens,
temperature: options.temperature,
top_p: options.topP,
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
stop: options.stop,
stream: true,
}),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
signal,
});
for await (const chunk of streamSse(resp)) {
const content = chunk.choices?.[0]?.delta?.content;
if (content) {
yield { role: "assistant", content };
}
}
}
}
export default Inception;

12
core/llm/llms/Lemonade.ts Normal file
View file

@ -0,0 +1,12 @@
import { LLMOptions } from "../../index.js";
import OpenAI from "./OpenAI.js";
class Lemonade extends OpenAI {
static providerName = "lemonade";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "http://localhost:8000/api/v1/",
};
}
export default Lemonade;

View file

@ -87,6 +87,7 @@ interface OllamaChatOptions extends OllamaBaseOptions {
tools?: OllamaTool[]; // the tools of the chat, this can be used to keep a tool memory
// Not supported yet - tools: tools for the model to use if supported. Requires stream to be set to false
// And correspondingly, tool calls in OllamaChatMessage
think?: boolean; // if true the model will be prompted to think about the response before generating it
}
type OllamaBaseResponse = {
@ -146,11 +147,10 @@ class Ollama extends BaseLLM implements ModelInstaller {
private static modelsBeingInstalledMutex = new Mutex();
private fimSupported: boolean = false;
constructor(options: LLMOptions) {
super(options);
if (options.isFromAutoDetect) {
if (options.model === "AUTODETECT") {
return;
}
const headers: Record<string, string> = {
@ -269,6 +269,11 @@ class Ollama extends BaseLLM implements ModelInstaller {
return this.modelMap[this.model] ?? this.model;
}
get contextLength() {
const DEFAULT_OLLAMA_CONTEXT_LENGTH = 8192; // twice of https://github.com/ollama/ollama/blob/29ddfc2cab7f5a83a96c3133094f67b22e4f27d1/envconfig/config.go#L185
return this._contextLength ?? DEFAULT_OLLAMA_CONTEXT_LENGTH;
}
private _getModelFileParams(
options: CompletionOptions,
): OllamaModelFileParams {
@ -393,6 +398,7 @@ class Ollama extends BaseLLM implements ModelInstaller {
model: this._getModel(),
messages: ollamaMessages,
options: this._getModelFileParams(options),
think: options.reasoning,
keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
stream: options.stream,
// format: options.format, // Not currently in base completion options

View file

@ -174,7 +174,7 @@ class OpenAI extends BaseLLM {
protected _getHeaders() {
return {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
...(this.apiKey && { Authorization: `Bearer ${this.apiKey}` }),
"api-key": this.apiKey ?? "", // For Azure
};
}

View file

@ -7,16 +7,23 @@ class Scaleway extends OpenAI {
static providerName = "scaleway";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.scaleway.ai/v1/",
model: "qwen2.5-coder-32b-instruct",
model: "qwen3-coder-30b-a3b-instruct",
useLegacyCompletionsEndpoint: false,
};
private static MODEL_IDS: { [name: string]: string } = {
"llama3.1-8b": "llama-3.1-8b-instruct",
"llama3.3-70b": "llama-3.3-70b-instruct",
"pixtral-12b": "pixtral-12b-2409",
"mistral-small3.1": "mistral-small-3.1-24b-instruct-2503",
"mistral-small3.2": "mistral-small-3.2-24b-instruct-2506",
"devstral-small": "devstral-small-2505",
"deepseek-r1-distill-llama-70b": "deepseek-r1-distill-llama-70b",
"qwen2.5-coder-32b": "qwen2.5-coder-32b-instruct",
"qwen3-coder-30b-a3b": "qwen3-coder-30b-a3b-instruct",
"qwen3-235b-a22b": "qwen3-235b-a22b-instruct-2507",
"gemma-3-27b": "gemma-3-27b-it",
"gpt-oss-120b": "gpt-oss-120b",
};
protected _convertModelName(model: string) {

18
core/llm/llms/TARS.ts Normal file
View file

@ -0,0 +1,18 @@
import { LLMOptions } from "../../index.js";
import { osModelsEditPrompt } from "../templates/edit.js";
import OpenAI from "./OpenAI.js";
class TARS extends OpenAI {
static providerName = "tars";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.router.tetrate.ai/v1",
model: "gpt-5-mini",
promptTemplates: {
edit: osModelsEditPrompt,
},
useLegacyCompletionsEndpoint: false,
};
}
export default TARS;

View file

@ -33,6 +33,7 @@ import Kindo from "./Kindo";
import LlamaCpp from "./LlamaCpp";
import Llamafile from "./Llamafile";
import LlamaStack from "./LlamaStack";
import Lemonade from "./Lemonade";
import LMStudio from "./LMStudio";
import Mistral from "./Mistral";
import MockLLM from "./Mock";
@ -53,6 +54,7 @@ import SambaNova from "./SambaNova";
import Scaleway from "./Scaleway";
import SiliconFlow from "./SiliconFlow";
import ContinueProxy from "./stubs/ContinueProxy";
import TARS from "./TARS";
import TestLLM from "./Test";
import TextGenWebUI from "./TextGenWebUI";
import Together from "./Together";
@ -81,6 +83,7 @@ export const LLMClasses = [
LlamaCpp,
OpenAI,
OVHcloud,
Lemonade,
LMStudio,
Mistral,
Bedrock,
@ -116,6 +119,7 @@ export const LLMClasses = [
Inception,
Voyage,
LlamaStack,
TARS,
];
export async function llmFromDescription(

View file

@ -95,7 +95,7 @@ export async function* llmStreamChat(
...init,
signal: abortController.signal,
},
config.requestOptions,
model.requestOptions,
),
completionOptions,
abortController,

View file

@ -71,3 +71,10 @@ export const gptEditPrompt: PromptTemplateFunction = (history, otherData) => {
return paragraphs.join("\n\n");
};
export const defaultApplyPrompt: PromptTemplateFunction = (
history,
otherData,
) => {
return `${otherData.original_code}\n\nThe following code was suggested as an edit:\n\`\`\`\n${otherData.new_code}\n\`\`\`\nPlease apply it to the previous code.`;
};

View file

@ -374,9 +374,8 @@ export function isRecommendedAgentModel(modelName: string): boolean {
[/o[134]/],
[/deepseek/, /r1|reasoner/],
[/gemini/, /2\.5/, /pro/],
[/gpt/, /4/],
[/gpt-5/],
[/claude/, /sonnet/, /3\.5|3\.7|3-5|3-7|-4/],
[/claude/, /sonnet/, /3\.7|3-7|-4/],
[/claude/, /opus/, /-4/],
];
for (const combo of recs) {

View file

@ -13,6 +13,10 @@ export enum EditableRegionStrategy {
Static = "static",
}
/**
* This was an attempt to find next edit locations deterministically.
* I was intending to use this in tandem with the prefetching logic, but we are not using it anymore.
*/
export async function getNextEditableRegion(
strategy: EditableRegionStrategy,
ctx: any,

View file

@ -7,6 +7,14 @@ export interface ProcessedItem {
outcome: NextEditOutcome; // Result from the model
}
/**
* Keeps a queue of the broken down diffs from a changed editable range, as determined in core/nextEdit/diff.ts
*/
/**
* 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.
* I originally intended this to be a separate data structure to handle prefetching next edit outcomes from the model in the background.
* Due to subpar results, lack of satisfactory next edit location suggestion algorithms and token cost/latency issues, I scratched the idea.
*/
export class PrefetchQueue {
private static instance: PrefetchQueue | null = null;

View file

@ -19,14 +19,13 @@ import { HelperVars } from "../autocomplete/util/HelperVars.js";
import { AutocompleteInput } from "../autocomplete/util/types.js";
import { isSecurityConcern } from "../indexing/ignore.js";
import { modelSupportsNextEdit } from "../llm/autodetect.js";
import { countTokens } from "../llm/countTokens.js";
import { localPathOrUriToPath } from "../util/pathToUri.js";
import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js";
import { NextEditLoggingService } from "./NextEditLoggingService.js";
import { PrefetchQueue } from "./NextEditPrefetchQueue.js";
import { NextEditProviderFactory } from "./NextEditProviderFactory.js";
import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js";
import { BaseNextEditModelProvider } from "./providers/BaseNextEditProvider.js";
import {
ModelSpecificContext,
NextEditOutcome,
@ -45,6 +44,14 @@ const ERRORS_TO_IGNORE = [
"operation was aborted",
];
/**
* This is the next edit analogue to autocomplete's CompletionProvider.
* You will see a lot of similar if not identical methods to CompletionProvider methods.
* All logic used to live inside this class, but that became untenable quickly.
* I moved a lot of the model-specific logic (prompt building, pre/post processing, etc.) to the BaseNextEditProvider and the children inheriting from it.
* Keeping this class around might be a good idea because it handles lots of delicate logic such as abort signals, chains, logging, etc.
* There being a singleton also gives a lot of guarantees about the state of the next edit state machine.
*/
export class NextEditProvider {
private static instance: NextEditProvider | null = null;
@ -62,10 +69,9 @@ export class NextEditProvider {
private currentEditChainId: string | null = null;
private previousRequest: AutocompleteInput | null = null;
private previousCompletions: NextEditOutcome[] = [];
// private nextEditableRegionsInTheCurrentChain: RangeInFile[] = [];
// Model-specific provider instance.
private modelProvider: BaseNextEditProvider | null = null;
private modelProvider: BaseNextEditModelProvider | null = null;
private constructor(
private readonly configHandler: ConfigHandler,
@ -223,14 +229,14 @@ export class NextEditProvider {
this.currentEditChainId = null;
this.previousCompletions = [];
// TODO: this should be cleaned up in the prefetch queue.
// this.nextEditableRegionsInTheCurrentChain = [];
if (this.previousRequest) {
const fileContent = (
await this.ide.readFile(this.previousRequest.filepath)
).toString();
const ast = await getAst(this.previousRequest.filepath, fileContent);
if (ast) {
DocumentHistoryTracker.getInstance().push(
localPathOrUriToPath(this.previousRequest.filepath),
@ -253,6 +259,9 @@ export class NextEditProvider {
return this.previousCompletions.length === 1;
}
/**
* This is the main entry point to this class.
*/
public async provideInlineCompletionItems(
input: AutocompleteInput,
token: AbortSignal | undefined,
@ -370,6 +379,8 @@ export class NextEditProvider {
throw new Error("Model provider not initialized");
}
// NOTE: getAllSnippetsWithoutRace doesn't seem to incur much performance penalties when compared to getAllSnippets.
// Use getAllSnippets if snippet gathering becomes noticably slow.
const [snippetPayload, workspaceDirs] = await Promise.all([
getAllSnippetsWithoutRace({
helper,
@ -445,6 +456,9 @@ export class NextEditProvider {
}
// Send prompts to LLM (using only user prompt for fine-tuned models).
// prompts[1] extracts the user prompt from the system-user prompt pair.
// NOTE: Stream is currently set to false, but this should ideally be a per-model flag.
// Mercury Coder currently does not support streaming.
const msg: ChatMessage = await llm.chat([prompts[1]], token, {
stream: false,
});
@ -484,7 +498,7 @@ export class NextEditProvider {
}
if (outcome) {
// Handle NextEditProvider-specific state
// Handle NextEditProvider-specific state.
this.previousCompletions.push(outcome);
// Mark as displayed for JetBrains
@ -494,97 +508,6 @@ export class NextEditProvider {
return outcome;
}
private _calculateOptimalEditableRegion(
helper: HelperVars,
heuristic: "fourChars" | "tokenizer" = "tokenizer",
): {
editableRegionStartLine: number;
editableRegionEndLine: number;
} {
const cursorLine = helper.pos.line;
const fileLines = helper.fileLines;
const MAX_TOKENS = 512;
// Initialize with cursor line.
let editableRegionStartLine = cursorLine;
let editableRegionEndLine = cursorLine;
// Get initial content and token count.
let currentContent = fileLines[cursorLine];
let totalTokens =
heuristic === "tokenizer"
? countTokens(currentContent, helper.modelName)
: Math.ceil(currentContent.length / 4);
// Expand outward alternating between adding lines above and below.
let addingAbove = true;
while (totalTokens < MAX_TOKENS) {
let addedLine = false;
if (addingAbove) {
// Try to add a line above.
if (editableRegionStartLine > 0) {
editableRegionStartLine--;
const lineContent = fileLines[editableRegionStartLine];
const lineTokens =
heuristic === "tokenizer"
? countTokens(lineContent, helper.modelName)
: Math.ceil(lineContent.length / 4);
totalTokens += lineTokens;
addedLine = true;
}
} else {
// Try to add a line below.
if (editableRegionEndLine < fileLines.length - 1) {
editableRegionEndLine++;
const lineContent = fileLines[editableRegionEndLine];
const lineTokens =
heuristic === "tokenizer"
? countTokens(lineContent, helper.modelName)
: Math.ceil(lineContent.length / 4);
totalTokens += lineTokens;
addedLine = true;
}
}
// If we can't add in the current direction, try the other.
if (!addedLine) {
// If we're already at both file boundaries, we're done.
if (
editableRegionStartLine === 0 &&
editableRegionEndLine === fileLines.length - 1
) {
break;
}
// If we couldn't add in one direction, force the next attempt in the other direction.
addingAbove = !addingAbove;
continue;
}
// If we exceeded the token limit, revert the last addition.
if (totalTokens > MAX_TOKENS) {
if (addingAbove) {
editableRegionStartLine++;
} else {
editableRegionEndLine--;
}
break;
}
// Alternate between adding above and below for balanced context.
addingAbove = !addingAbove;
}
return {
editableRegionStartLine,
editableRegionEndLine,
};
}
private async _markDisplayedIfJetBrains(
completionId: string,
outcome: NextEditOutcome,
@ -595,6 +518,12 @@ export class NextEditProvider {
}
}
/**
* This is a wrapper around provideInlineCompletionItems.
* This is invoked when we call the model in the background using prefetch.
* 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.
* You will see that calls to this method is made from NextEditPrefetchQueue.proecss(), which is wrapped in `if (!this.usingFullFileDiff)`.
*/
public async provideInlineCompletionItemsWithChain(
ctx: {
completionId: string;

View file

@ -1,259 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
import { HelperVars } from "../autocomplete/util/HelperVars.js";
import { ConfigHandler } from "../config/ConfigHandler.js";
import { IDE, ILLM } from "../index.js";
import { NextEditProvider } from "./NextEditProvider.js";
// Mock the countTokens function
vi.mock("../llm/countTokens.js", () => ({
countTokens: (text: string) => {
// Simple mock that counts 1 token per character for predictable tests
return text.length;
},
}));
// Create a helper function to set up the test context
function createMockHelper(
fileContents: string,
cursorLine: number,
): HelperVars {
const fileLines = fileContents.split("\n");
return {
fileLines,
fileContents,
pos: { line: cursorLine, character: 0 },
modelName: "gpt-4",
lang: { name: "typescript" },
filepath: "test/file.ts",
workspaceUris: ["test/workspace"],
options: {},
input: { completionId: "test-completion-id" },
} as unknown as HelperVars;
}
// TODO: Add more tests for other methods.
describe("_calculateOptimalEditableRegion", () => {
let nextEditProvider: NextEditProvider;
let mockConfigHandler: ConfigHandler;
let mockIde: IDE;
let mockGetLlm: () => Promise<ILLM | undefined>;
let mockOnError: (e: any) => void;
let mockGetDefinitionsFromLsp: GetLspDefinitionsFunction;
beforeEach(() => {
// Create comprehensive mocks for all dependencies
mockConfigHandler = {
loadConfig: vi.fn().mockResolvedValue({ config: {} }),
} as unknown as ConfigHandler;
mockIde = {
readFile: vi.fn().mockResolvedValue(""),
getWorkspaceDirs: vi.fn().mockResolvedValue([]),
getRepoName: vi.fn().mockResolvedValue("test-repo"),
getUniqueId: vi.fn().mockResolvedValue("test-id"),
getIdeInfo: vi.fn().mockResolvedValue({ ideType: "vscode" }),
onDidChangeActiveTextEditor: vi.fn().mockImplementation((callback) => {
// Return a disposable object that does nothing when disposed
return {
dispose: () => {},
};
}),
} as unknown as IDE;
mockGetLlm = vi.fn().mockResolvedValue({
model: "gpt-4",
providerName: "openai",
underlyingProviderName: "openai",
completionOptions: {},
chat: vi.fn(),
});
mockOnError = vi.fn();
mockGetDefinitionsFromLsp = vi.fn();
// Initialize NextEditProvider with mocked dependencies
nextEditProvider = NextEditProvider.initialize(
mockConfigHandler,
mockIde,
mockGetLlm,
mockOnError,
mockGetDefinitionsFromLsp,
"default",
);
// Expose the private method for testing
// This is a bit of a hack, but necessary for testing private methods
(nextEditProvider as any)._calculateOptimalEditableRegion = (
NextEditProvider.prototype as any
)._calculateOptimalEditableRegion.bind(nextEditProvider);
});
// Test cases remain the same as before...
it("should include only the cursor line when it already exceeds token limit", () => {
// Create a mock helper with a very long cursor line (>500 characters)
const longLine = "X".repeat(600);
const helper = createMockHelper(longLine, 0);
//@ts-ignore
const result = nextEditProvider._calculateOptimalEditableRegion(
helper,
"tokenizer",
);
expect(result.editableRegionStartLine).toBe(0);
expect(result.editableRegionEndLine).toBe(0);
});
it("should expand symmetrically when possible", () => {
// Create content with identical lines and cursor in the middle
const lines = Array(11).fill("A".repeat(40)).join("\n"); // 11 lines of 40 chars each
const helper = createMockHelper(lines, 5); // Cursor in the middle (line 5)
//@ts-ignore
const result = nextEditProvider._calculateOptimalEditableRegion(
helper,
"tokenizer",
);
// Should expand 5 lines in each direction (total 11 lines) for symmetry
expect(result.editableRegionStartLine).toBe(0);
expect(result.editableRegionEndLine).toBe(10);
});
it("should expand asymmetrically when hitting a file boundary", () => {
// Create content with cursor near the top
const lines = Array(20).fill("B".repeat(20)).join("\n"); // 20 lines of 20 chars each
const helper = createMockHelper(lines, 1); // Cursor near the top (line 1)
//@ts-ignore
const result = nextEditProvider._calculateOptimalEditableRegion(
helper,
"tokenizer",
);
// Should include more lines below since it can't expand much above
expect(result.editableRegionStartLine).toBe(0);
// Should include many more lines below to reach token limit
expect(result.editableRegionEndLine).toBeGreaterThan(10);
});
it("should handle files with varying line lengths", () => {
// Create content with varying line lengths
const fileContents = [
"Short line", // 10 chars
"A".repeat(100), // 100 chars
"Medium length line here", // 24 chars
"B".repeat(200), // 200 chars
"Another typical line of code", // 28 chars
].join("\n");
const helper = createMockHelper(fileContents, 2); // Cursor on the medium line
//@ts-ignore
const result = nextEditProvider._calculateOptimalEditableRegion(
helper,
"tokenizer",
);
// Should include all lines since total tokens < 500
expect(result.editableRegionStartLine).toBe(0);
expect(result.editableRegionEndLine).toBe(4);
});
it("should respect the token limit and not include too many lines", () => {
// Create content with many small lines (10 chars each)
const lines = Array(600).fill("C".repeat(10)).join("\n");
const helper = createMockHelper(lines, 300); // Cursor in the middle
//@ts-ignore
const result = nextEditProvider._calculateOptimalEditableRegion(
helper,
"tokenizer",
);
// Each line is 10 chars = 10 tokens per line with our mock.
// So with 500 token limit, we should get 50 lines total.
// 25 above, 25 below, +1 current
const totalLines =
result.editableRegionEndLine - result.editableRegionStartLine + 1;
expect(totalLines).toBe(51); // Not more than 51 lines (25 above, 25 below, +1 for current line)
});
it("should use character approximation when using fourChars heuristic", () => {
// In this test, we're setting up a situation where tiktoken and fourChars would give different results
// Creating 5 lines, each 100 characters
const lines = Array(10).fill("D".repeat(100)).join("\n");
const helper = createMockHelper(lines, 2); // Cursor in the middle
// Mock for tiktoken counting (1 char = 1 token)
//@ts-ignore
const tokenizerResult = nextEditProvider._calculateOptimalEditableRegion(
helper,
"tokenizer",
);
// Mock for fourChars counting (1 token = 4 chars)
// This should include more lines since each line is counted as 25 tokens instead of 100
//@ts-ignore
const fourCharsResult = nextEditProvider._calculateOptimalEditableRegion(
helper,
"fourChars",
);
// The fourChars approach should include more lines since it estimates fewer tokens per line
expect(
fourCharsResult.editableRegionEndLine -
fourCharsResult.editableRegionStartLine,
).toBeGreaterThan(
tokenizerResult.editableRegionEndLine -
tokenizerResult.editableRegionStartLine,
);
});
it("should include the entire file if it's within token limit", () => {
// Create a small file
const smallFile = "Small file\nwith just\na few lines\nof text";
const helper = createMockHelper(smallFile, 1);
//@ts-ignore
const result = nextEditProvider._calculateOptimalEditableRegion(
helper,
"tokenizer",
);
// Should include all lines
expect(result.editableRegionStartLine).toBe(0);
expect(result.editableRegionEndLine).toBe(3);
});
it("should prioritize balanced context when token limit allows", () => {
// Create content with alternating long and short lines
const fileContents = [
"Short", // 5 chars
"E".repeat(80), // 80 chars
"Also short", // 10 chars
"F".repeat(80), // 80 chars
"Another short one", // 17 chars
"G".repeat(80), // 80 chars
"Final short line", // 16 chars
].join("\n");
const helper = createMockHelper(fileContents, 3); // Cursor on the long line (index 3)
//@ts-ignore
const result = nextEditProvider._calculateOptimalEditableRegion(
helper,
"tokenizer",
);
// Should try to include equal number of lines above and below cursor
const linesAbove = result.editableRegionStartLine;
const linesBelow =
helper.fileLines.length - 1 - result.editableRegionEndLine;
// Difference between lines above and below should be minimal
expect(Math.abs(linesAbove - linesBelow)).toBeLessThanOrEqual(1);
});
});

View file

@ -1,10 +1,10 @@
import { NEXT_EDIT_MODELS } from "../llm/constants.js";
import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js";
import { BaseNextEditModelProvider } from "./providers/BaseNextEditProvider.js";
import { InstinctProvider } from "./providers/InstinctNextEditProvider.js";
import { MercuryCoderProvider } from "./providers/MercuryCoderNextEditProvider.js";
export class NextEditProviderFactory {
static createProvider(modelName: string): BaseNextEditProvider {
static createProvider(modelName: string): BaseNextEditModelProvider {
if (modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER)) {
return new MercuryCoderProvider();
} else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) {

View file

@ -19,7 +19,12 @@ import {
} from "../types.js";
import { isWhitespaceOnlyDeletion } from "../utils.js";
export abstract class BaseNextEditProvider {
/**
* This class is used as an abstract base class for model-specific providers.
* This and its children are responsible for pre/post processing of prompts and outcomes.
* Different next edit models have very different requirements.
*/
export abstract class BaseNextEditModelProvider {
protected readonly modelName: string;
constructor(modelName: string) {

View file

@ -11,9 +11,9 @@ import {
PromptTemplateRenderer,
} from "../templating/NextEditPromptEngine.js";
import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js";
import { BaseNextEditProvider } from "./BaseNextEditProvider.js";
import { BaseNextEditModelProvider } from "./BaseNextEditProvider.js";
export class InstinctProvider extends BaseNextEditProvider {
export class InstinctProvider extends BaseNextEditModelProvider {
private templateRenderer: PromptTemplateRenderer;
constructor() {

View file

@ -11,9 +11,9 @@ import {
PromptTemplateRenderer,
} from "../templating/NextEditPromptEngine.js";
import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js";
import { BaseNextEditProvider } from "./BaseNextEditProvider.js";
import { BaseNextEditModelProvider } from "./BaseNextEditProvider.js";
export class MercuryCoderProvider extends BaseNextEditProvider {
export class MercuryCoderProvider extends BaseNextEditModelProvider {
private templateRenderer: PromptTemplateRenderer;
constructor() {

101
core/package-lock.json generated
View file

@ -17,6 +17,7 @@
"@continuedev/fetch": "file:../packages/fetch",
"@continuedev/llm-info": "file:../packages/llm-info",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@continuedev/terminal-security": "file:../packages/terminal-security",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -67,6 +68,7 @@
"quick-lru": "^7.0.0",
"replicate": "^0.26.0",
"request": "^2.88.2",
"shell-quote": "^1.8.3",
"socket.io-client": "^4.7.3",
"sqlite": "^5.1.1",
"sqlite3": "^5.1.7",
@ -101,6 +103,7 @@
"@types/pg": "^8.11.6",
"@types/plist": "^3.0.5",
"@types/request": "^2.48.12",
"@types/shell-quote": "^1.7.5",
"@types/tar": "^6.1.13",
"@types/uuid": "^9.0.7",
"@types/win-ca": "^3.5.4",
@ -149,10 +152,10 @@
},
"../packages/config-yaml": {
"name": "@continuedev/config-yaml",
"version": "1.0.96",
"version": "1.14.0",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "file:../config-types",
"@continuedev/config-types": "^1.0.14",
"yaml": "^2.6.1",
"zod": "^3.24.2"
},
@ -176,17 +179,22 @@
},
"../packages/fetch": {
"name": "@continuedev/fetch",
"version": "1.0.16",
"version": "1.1.0",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "file:../config-types",
"@continuedev/config-types": "^1.0.14",
"follow-redirects": "^1.15.6",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.5",
"node-fetch": "^3.3.2"
},
"devDependencies": {
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^9.2.6",
"@semantic-release/npm": "^10.0.6",
"@types/follow-redirects": "^1.14.4",
"semantic-release": "^21.1.2",
"typescript": "^5.0.0",
"vitest": "^3.2.0"
}
@ -196,20 +204,25 @@
"version": "1.0.9",
"license": "Apache-2.0",
"devDependencies": {
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^9.2.6",
"@semantic-release/npm": "^10.0.6",
"@types/node": "^22.15.29",
"semantic-release": "^21.1.2",
"typescript": "^5.5.2"
}
},
"../packages/openai-adapters": {
"name": "@continuedev/openai-adapters",
"version": "1.5.1",
"version": "1.14.0",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.842.0",
"@aws-sdk/credential-providers": "^3.840.0",
"@continuedev/config-types": "^1.0.14",
"@continuedev/config-yaml": "^1.8.0",
"@continuedev/fetch": "^1.0.16",
"@continuedev/config-yaml": "^1.14.0",
"@continuedev/fetch": "^1.1.0",
"dotenv": "^16.5.0",
"google-auth-library": "^10.1.0",
"json-schema": "^0.4.0",
@ -236,6 +249,20 @@
"vitest": "^3.2.4"
}
},
"../packages/terminal-security": {
"name": "@continuedev/terminal-security",
"version": "1.0.0",
"license": "Apache-2.0",
"dependencies": {
"shell-quote": "^1.8.1"
},
"devDependencies": {
"@types/node": "^20.11.19",
"@types/shell-quote": "^1.7.5",
"typescript": "^5.5.2",
"vitest": "^3.2.4"
}
},
"node_modules/@75lb/deep-merge": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.2.tgz",
@ -2955,6 +2982,10 @@
"resolved": "../packages/openai-adapters",
"link": true
},
"node_modules/@continuedev/terminal-security": {
"resolved": "../packages/terminal-security",
"link": true
},
"node_modules/@dabh/diagnostics": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.3.tgz",
@ -6892,6 +6923,13 @@
"node": ">= 0.12"
}
},
"node_modules/@types/shell-quote": {
"version": "1.7.5",
"resolved": "https://registry.npmjs.org/@types/shell-quote/-/shell-quote-1.7.5.tgz",
"integrity": "sha512-+UE8GAGRPbJVQDdxi16dgadcBfQ+KG2vgZhV1+3A1XmHbmwcdwhCUwIdy+d3pAGrbvgRoVSjeI9vOWyq376Yzw==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/shimmer": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@types/shimmer/-/shimmer-1.2.0.tgz",
@ -7875,13 +7913,13 @@
"integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw=="
},
"node_modules/axios": {
"version": "1.8.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.8.2.tgz",
"integrity": "sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==",
"version": "1.12.0",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.12.0.tgz",
"integrity": "sha512-oXTDccv8PcfjZmPGlWsPSwtOJCZ/b6W5jAMCNcfwJbCzDckwG0jrYJFaWH1yvivfCXjVzV/SPDEhMB3Q+DSurg==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",
"form-data": "^4.0.4",
"proxy-from-env": "^1.1.0"
}
},
@ -9894,14 +9932,15 @@
}
},
"node_modules/es-set-tostringtag": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.3.tgz",
"integrity": "sha512-3T8uNMC3OQTHkFUsFq8r/BwAXLHvU/9O9mE0fBc/MY5iq/8H7ncvO947LmYA6ldWw9Uh8Yhf25zu6n7nML5QWQ==",
"peer": true,
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
"license": "MIT",
"dependencies": {
"get-intrinsic": "^1.2.4",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.6",
"has-tostringtag": "^1.0.2",
"hasown": "^2.0.1"
"hasown": "^2.0.2"
},
"engines": {
"node": ">= 0.4"
@ -11298,12 +11337,15 @@
}
},
"node_modules/form-data": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.1.tgz",
"integrity": "sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==",
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
"integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"es-set-tostringtag": "^2.1.0",
"hasown": "^2.0.2",
"mime-types": "^2.1.12"
},
"engines": {
@ -11952,7 +11994,6 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
"peer": true,
"dependencies": {
"has-symbols": "^1.0.3"
},
@ -17459,6 +17500,18 @@
"node": ">=8"
}
},
"node_modules/shell-quote": {
"version": "1.8.3",
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz",
"integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/shiki": {
"version": "3.7.0",
"resolved": "https://registry.npmjs.org/shiki/-/shiki-3.7.0.tgz",
@ -19311,9 +19364,9 @@
}
},
"node_modules/vite": {
"version": "6.3.5",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.3.5.tgz",
"integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==",
"version": "6.3.6",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.3.6.tgz",
"integrity": "sha512-0msEVHJEScQbhkbVTb/4iHZdJ6SXp/AvxL2sjwYQFfBqleHtnCqv1J3sa9zbWz/6kW1m9Tfzn92vW+kZ1WV6QA==",
"dev": true,
"license": "MIT",
"dependencies": {

Some files were not shown because too many files have changed in this diff Show more