Merge remote-tracking branch 'upstream/main'
This commit is contained in:
commit
f63baddc7b
915 changed files with 108936 additions and 13399 deletions
|
|
@ -52,7 +52,7 @@ Retrieve the following sites per these providers, and consider these notes on ho
|
|||
// TODO: add info for openai, ollama, etc
|
||||
|
||||
For any other providers, search the web for "latest [provider] models" and find the most relevant model information using your best judgement.
|
||||
Generally, ignore models that do not support text output. These models will be used in a coding assistant client that only supports text/image input and text/output, so extraneous capabilities can be ignored.
|
||||
Generally, ignore models that do not support text output. These models will be used in a coding agent client that only supports text/image input and text/output, so extraneous capabilities can be ignored.
|
||||
Sometimes, "Experimental", "Preview", or similar versions of models are available. The latest-date version of each should have its own information maintained.
|
||||
|
||||
3. UPDATE THE INFORMATION
|
||||
|
|
|
|||
4
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
4
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
|
|
@ -29,7 +29,7 @@ body:
|
|||
- **Continue version**: v0.9.4
|
||||
- **IDE version**: VSCode 1.85.1
|
||||
- Model: Claude Sonnet 3.5
|
||||
- Assistant configuration
|
||||
- Agent configuration
|
||||
value: |
|
||||
- OS:
|
||||
- Continue version:
|
||||
|
|
@ -39,7 +39,7 @@ body:
|
|||
```yaml
|
||||
|
||||
```
|
||||
OR link to assistant in Continue hub:
|
||||
OR link to agent in Continue hub:
|
||||
render: Markdown
|
||||
validations:
|
||||
required: false
|
||||
|
|
|
|||
55
.github/actions/check-llm-changes/action.yml
vendored
Normal file
55
.github/actions/check-llm-changes/action.yml
vendored
Normal 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
|
||||
20
.github/actions/run-jetbrains-tests/action.yml
vendored
20
.github/actions/run-jetbrains-tests/action.yml
vendored
|
|
@ -44,6 +44,7 @@ runs:
|
|||
- name: Setup FFmpeg
|
||||
uses: AnimMouse/setup-ffmpeg@v1
|
||||
with:
|
||||
version: 7.1
|
||||
token: ${{ inputs.github-token }}
|
||||
|
||||
- name: Setup Gradle
|
||||
|
|
@ -93,6 +94,13 @@ runs:
|
|||
path: binary/node_modules
|
||||
key: ${{ runner.os }}-binary-node-modules-${{ hashFiles('binary/package-lock.json') }}
|
||||
|
||||
- name: Install binary dependencies
|
||||
if: steps.binary-cache.outputs.cache-hit != 'true'
|
||||
shell: bash
|
||||
run: |
|
||||
cd binary
|
||||
npm ci
|
||||
|
||||
- name: Build the binaries
|
||||
shell: bash
|
||||
run: |
|
||||
|
|
@ -128,14 +136,22 @@ runs:
|
|||
shell: bash
|
||||
run: |
|
||||
cd extensions/intellij
|
||||
mv video build/reports
|
||||
if [ -d "video" ]; then
|
||||
mv video build/reports
|
||||
else
|
||||
echo "No video directory found to move"
|
||||
fi
|
||||
|
||||
- name: Copy logs
|
||||
if: ${{ failure() }}
|
||||
shell: bash
|
||||
run: |
|
||||
cd extensions/intellij
|
||||
mv build/idea-sandbox/system/log/ build/reports
|
||||
if [ -d "build/idea-sandbox/system/log/" ]; then
|
||||
mv build/idea-sandbox/system/log/ build/reports
|
||||
else
|
||||
echo "No log directory found to copy"
|
||||
fi
|
||||
|
||||
- name: Save fails report
|
||||
if: ${{ failure() }}
|
||||
|
|
|
|||
19
.github/actions/track-rerun/action.yml
vendored
Normal file
19
.github/actions/track-rerun/action.yml
vendored
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
name: Track Workflow Rerun
|
||||
description: Track when GitHub Actions workflows are rerun (attempt > 1)
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
# Eventually we can start logging this to monitor codebase health (e.g. to Slack, PostHog, etc.)
|
||||
- name: Track workflow rerun
|
||||
if: github.run_attempt > 1
|
||||
shell: bash
|
||||
run: |
|
||||
echo "🔄 Workflow rerun detected - Attempt #${{ github.run_attempt }}"
|
||||
echo "📊 Workflow: ${{ github.workflow }}"
|
||||
echo "🔀 PR: ${{ github.event.pull_request.number || 'N/A' }}"
|
||||
echo "📝 Commit: ${{ github.sha }}"
|
||||
echo "👤 Actor: ${{ github.actor }}"
|
||||
echo "⏰ Timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
echo ""
|
||||
echo "::notice title=Workflow Rerun Detected::This is attempt #${{ github.run_attempt }} of workflow '${{ github.workflow }}'"
|
||||
115
.github/workflows/beta-release.yml
vendored
Normal file
115
.github/workflows/beta-release.yml
vendored
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
name: Beta Release
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# Run every day at 9am UTC
|
||||
- cron: "0 9 * * *"
|
||||
workflow_dispatch:
|
||||
# Allow manual triggering
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
beta-release:
|
||||
name: Beta Release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
always-auth: true
|
||||
|
||||
- name: Setup packages
|
||||
uses: ./.github/actions/setup-packages
|
||||
|
||||
- name: Setup core component
|
||||
uses: ./.github/actions/setup-component
|
||||
with:
|
||||
component: core
|
||||
include-root: true
|
||||
|
||||
- name: Build core
|
||||
run: |
|
||||
cd core
|
||||
npm run build
|
||||
|
||||
- name: Install CLI dependencies
|
||||
working-directory: extensions/cli
|
||||
run: npm ci
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
- name: Get current version
|
||||
id: get_version
|
||||
working-directory: extensions/cli
|
||||
run: |
|
||||
# Get the latest version from package.json or npm registry
|
||||
CURRENT_VERSION=$(node -p "require('./package.json').version")
|
||||
if [[ "$CURRENT_VERSION" == "0.0.0-dev" ]]; then
|
||||
# If it's dev version, get latest from npm registry
|
||||
LATEST_VERSION=$(npm view @continuedev/cli version --silent 2>/dev/null || echo "0.0.0")
|
||||
echo "Using latest npm version: $LATEST_VERSION"
|
||||
CURRENT_VERSION=$LATEST_VERSION
|
||||
fi
|
||||
|
||||
# Create beta version with current date
|
||||
DATE_SUFFIX=$(date -u +%Y%m%d)
|
||||
BETA_VERSION="${CURRENT_VERSION}-beta.${DATE_SUFFIX}"
|
||||
|
||||
# Check if this version already exists on npm
|
||||
if npm view @continuedev/cli@$BETA_VERSION version --silent >/dev/null 2>&1; then
|
||||
echo "Version $BETA_VERSION already exists, adding timestamp"
|
||||
# Add hour and minute to make it unique
|
||||
TIMESTAMP_SUFFIX=$(date -u +%Y%m%d.%H%M)
|
||||
BETA_VERSION="${CURRENT_VERSION}-beta.${TIMESTAMP_SUFFIX}"
|
||||
echo "Using timestamped version: $BETA_VERSION"
|
||||
fi
|
||||
|
||||
echo "current_version=$CURRENT_VERSION" >> $GITHUB_OUTPUT
|
||||
echo "beta_version=$BETA_VERSION" >> $GITHUB_OUTPUT
|
||||
echo "date_suffix=$DATE_SUFFIX" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Update package.json for beta
|
||||
working-directory: extensions/cli
|
||||
run: |
|
||||
# Update version in package.json
|
||||
npm version ${{ steps.get_version.outputs.beta_version }} --no-git-tag-version
|
||||
|
||||
- name: Build
|
||||
working-directory: extensions/cli
|
||||
run: npm run build
|
||||
|
||||
- name: Publish beta to npm
|
||||
working-directory: extensions/cli
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
npm publish --tag beta
|
||||
echo "Published beta version: ${{ steps.get_version.outputs.beta_version }}"
|
||||
|
||||
- name: Create beta release on GitHub
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
|
||||
run: |
|
||||
# Create a git tag for the beta
|
||||
git config --local user.email "action@github.com"
|
||||
git config --local user.name "GitHub Action"
|
||||
git tag "v${{ steps.get_version.outputs.beta_version }}"
|
||||
git push origin "v${{ steps.get_version.outputs.beta_version }}"
|
||||
|
||||
# Create GitHub release
|
||||
gh release create "v${{ steps.get_version.outputs.beta_version }}" \
|
||||
--title "Beta Release v${{ steps.get_version.outputs.beta_version }}" \
|
||||
--notes "Daily beta release for testing. This version will be promoted to stable after 7 days if no critical issues are found." \
|
||||
--prerelease
|
||||
2
.github/workflows/cla.yaml
vendored
2
.github/workflows/cla.yaml
vendored
|
|
@ -27,5 +27,5 @@ jobs:
|
|||
path-to-document: "https://github.com/continuedev/continue/blob/main/CLA.md"
|
||||
branch: cla-signatures
|
||||
# Bots and CLAs signed outside of GitHub
|
||||
allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline
|
||||
allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline,agent@continue.dev
|
||||
signed-commit-message: "CLA signed in $pullRequestNo"
|
||||
|
|
|
|||
136
.github/workflows/cli-pr-checks.yml
vendored
Normal file
136
.github/workflows/cli-pr-checks.yml
vendored
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
name: CLI PR Checks
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
track-rerun:
|
||||
runs-on: ubuntu-latest
|
||||
if: github.run_attempt > 1
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- name: Track workflow rerun
|
||||
uses: ./.github/actions/track-rerun
|
||||
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: "npm"
|
||||
cache-dependency-path: extensions/cli/package-lock.json
|
||||
|
||||
- name: Setup packages
|
||||
uses: ./.github/actions/setup-packages
|
||||
- name: Setup core component
|
||||
uses: ./.github/actions/setup-component
|
||||
with:
|
||||
component: core
|
||||
include-root: true
|
||||
|
||||
- name: Build core
|
||||
run: |
|
||||
cd core
|
||||
npm run build
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd extensions/cli
|
||||
npm ci --include=optional
|
||||
|
||||
- name: Run linting
|
||||
run: |
|
||||
cd extensions/cli
|
||||
npm run lint
|
||||
|
||||
test:
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, windows-latest, macos-latest]
|
||||
node-version: [18, 20, 22, 24]
|
||||
fail-fast: false
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Setup Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
|
||||
- name: Cache CLI node_modules
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: extensions/cli/node_modules
|
||||
key: ${{ runner.os }}-node${{ matrix.node-version }}-cli-modules-${{ hashFiles('extensions/cli/package-lock.json') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-node${{ matrix.node-version }}-cli-modules-
|
||||
|
||||
- name: Setup packages
|
||||
uses: ./.github/actions/setup-packages
|
||||
- name: Setup core component
|
||||
uses: ./.github/actions/setup-component
|
||||
with:
|
||||
component: core
|
||||
include-root: true
|
||||
|
||||
- name: Build core
|
||||
run: |
|
||||
cd core
|
||||
npm run build
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd extensions/cli
|
||||
npm ci --include=optional
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
cd extensions/cli
|
||||
npm run build
|
||||
|
||||
- name: Run smoke tests
|
||||
run: |
|
||||
cd extensions/cli
|
||||
npm run test:smoke
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
cd extensions/cli
|
||||
npm test
|
||||
|
||||
# e2e tests are failing on Windows specifically - likely due to stdout flush issues
|
||||
- name: Run e2e tests
|
||||
if: matrix.os != 'windows-latest'
|
||||
run: |
|
||||
cd extensions/cli
|
||||
npm run test:e2e
|
||||
|
||||
# GitHub does not have a way of requiring that all checks pass (you must manually select each job)
|
||||
# This action at least lets us manage the list of required tests via source control
|
||||
# so that creators of new jobs can add them to this list
|
||||
require-all-checks-to-pass-cli:
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- lint
|
||||
- test
|
||||
|
||||
steps:
|
||||
- name: Decide whether the needed jobs succeeded or failed
|
||||
uses: re-actors/alls-green@release/v1
|
||||
with:
|
||||
jobs: ${{ toJSON(needs) }}
|
||||
4
.github/workflows/compliance.yaml
vendored
4
.github/workflows/compliance.yaml
vendored
|
|
@ -36,12 +36,12 @@ jobs:
|
|||
else
|
||||
echo "❌ PR title does not follow conventional commit format"
|
||||
echo "valid=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
# Don't exit with failure - just mark as invalid for comment
|
||||
fi
|
||||
|
||||
- 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({
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ jobs:
|
|||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Run Detailed PR Review
|
||||
uses: continuedev/continue/actions/detailed-review@23d9260536372acf4eb57a41e6ab62bc5869b070
|
||||
uses: continuedev/continue/actions/detailed-review@80c679747b7c7b2624d15db31ff5bdadc9681c65
|
||||
with:
|
||||
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
|
||||
continue-org: continuedev
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ jobs:
|
|||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Run Continue PR Review Action
|
||||
uses: continuedev/continue/actions/general-review@23d9260536372acf4eb57a41e6ab62bc5869b070
|
||||
uses: continuedev/continue/actions/general-review@80c679747b7c7b2624d15db31ff5bdadc9681c65
|
||||
with:
|
||||
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
|
||||
continue-org: "continuedev"
|
||||
|
|
|
|||
32
.github/workflows/docs.yml
vendored
32
.github/workflows/docs.yml
vendored
|
|
@ -1,32 +0,0 @@
|
|||
name: Docs Check
|
||||
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'docs2/**'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'docs2/**'
|
||||
|
||||
jobs:
|
||||
check-broken-links:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '18'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: docs2/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: ./docs2
|
||||
run: npm ci
|
||||
|
||||
- name: Check for broken links
|
||||
working-directory: ./docs2
|
||||
run: npx mintlify broken-links
|
||||
18
.github/workflows/jetbrains-release.yaml
vendored
18
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -120,7 +120,7 @@ jobs:
|
|||
|
||||
# # Set up Java environment for the next steps
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: zulu
|
||||
java-version: 17
|
||||
|
|
@ -189,6 +189,8 @@ jobs:
|
|||
cd ../../gui
|
||||
npm ci
|
||||
npm run build
|
||||
env:
|
||||
NODE_OPTIONS: "--max-old-space-size=8192"
|
||||
|
||||
# Run prepackage.js script
|
||||
- name: Run prepackage script
|
||||
|
|
@ -255,6 +257,7 @@ jobs:
|
|||
# Publish the plugin to JetBrains Marketplace
|
||||
- name: Publish EAP Plugin
|
||||
if: github.event_name == 'release' || (github.event.inputs.eap_channel == 'true' && github.event.inputs.build_only != 'true')
|
||||
continue-on-error: true
|
||||
env:
|
||||
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
|
||||
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
|
||||
|
|
@ -265,6 +268,7 @@ jobs:
|
|||
|
||||
- name: Publish Stable Plugin
|
||||
if: github.event_name == 'release' || (github.event.inputs.stable_channel == 'true' && github.event.inputs.build_only != 'true')
|
||||
continue-on-error: true
|
||||
env:
|
||||
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
|
||||
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
|
||||
|
|
@ -433,7 +437,7 @@ jobs:
|
|||
|
||||
# Set up Java environment for the next steps
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: zulu
|
||||
java-version: 17
|
||||
|
|
@ -456,12 +460,6 @@ jobs:
|
|||
name: tests-result
|
||||
path: ${{ github.workspace }}/extensions/intellij/build/reports/tests
|
||||
|
||||
# Upload the Kover report to CodeCov
|
||||
# - name: Upload Code Coverage Report
|
||||
# uses: codecov/codecov-action@v4
|
||||
# with:
|
||||
# files: ${{ github.workspace }}/build/reports/kover/report.xml
|
||||
|
||||
# Run Qodana inspections and provide report
|
||||
inspectCode:
|
||||
if: false
|
||||
|
|
@ -486,7 +484,7 @@ jobs:
|
|||
|
||||
# Set up Java environment for the next steps
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: zulu
|
||||
java-version: 17
|
||||
|
|
@ -517,7 +515,7 @@ jobs:
|
|||
|
||||
# Set up Java environment for the next steps
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: zulu
|
||||
java-version: 17
|
||||
|
|
|
|||
2
.github/workflows/label-merged-prs.yml
vendored
2
.github/workflows/label-merged-prs.yml
vendored
|
|
@ -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;
|
||||
|
|
|
|||
16
.github/workflows/main-build.yaml
vendored
16
.github/workflows/main-build.yaml
vendored
|
|
@ -24,17 +24,19 @@ jobs:
|
|||
|
||||
- name: Get merged PR number
|
||||
id: get-pr
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
# Get the commit message of the merge commit
|
||||
COMMIT_MSG=$(git log --format=%B -n 1 HEAD)
|
||||
echo "Commit message: $COMMIT_MSG"
|
||||
# Get PR number for the current commit using GitHub API
|
||||
COMMIT_SHA=$(git rev-parse HEAD)
|
||||
echo "Getting PR for commit: $COMMIT_SHA"
|
||||
|
||||
# Extract PR number from merge commit message (format: "Merge pull request #123 from...")
|
||||
PR_NUMBER=$(echo "$COMMIT_MSG" | grep -o "Merge pull request #[0-9]*" | grep -o "[0-9]*" || echo "6723")
|
||||
PR_NUMBER=$(curl -s -H "Authorization: token $GH_TOKEN" \
|
||||
"https://api.github.com/repos/${{ github.repository }}/commits/$COMMIT_SHA/pulls" \
|
||||
| jq -r '.[0].number // empty')
|
||||
|
||||
if [ -z "$PR_NUMBER" ]; then
|
||||
echo "❌ Could not extract PR number from commit message. This might not be a PR merge."
|
||||
echo "Commit message was: $COMMIT_MSG"
|
||||
echo "❌ Could not find PR for commit $COMMIT_SHA"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
|
|
|||
4
.github/workflows/main.yaml
vendored
4
.github/workflows/main.yaml
vendored
|
|
@ -9,7 +9,7 @@ on:
|
|||
publish_build:
|
||||
description: "Whether or not to publish the built extension to the VS Code marketplace"
|
||||
required: true
|
||||
default: false
|
||||
default: "false"
|
||||
|
||||
jobs:
|
||||
check_release_name:
|
||||
|
|
@ -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
|
||||
|
|
|
|||
30
.github/workflows/pr-checks.yaml
vendored
30
.github/workflows/pr-checks.yaml
vendored
|
|
@ -11,6 +11,14 @@ on:
|
|||
- main
|
||||
|
||||
jobs:
|
||||
track-rerun:
|
||||
runs-on: ubuntu-latest
|
||||
if: github.run_attempt > 1
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- name: Track workflow rerun
|
||||
uses: ./.github/actions/track-rerun
|
||||
|
||||
prettier-check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
|
@ -36,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
|
||||
|
|
@ -44,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
|
||||
|
|
@ -58,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 }}
|
||||
|
|
@ -172,16 +189,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 }}
|
||||
|
|
|
|||
4
.github/workflows/preview.yaml
vendored
4
.github/workflows/preview.yaml
vendored
|
|
@ -9,7 +9,7 @@ on:
|
|||
publish_build:
|
||||
description: "Whether or not to publish the built extension to the VS Code marketplace"
|
||||
required: true
|
||||
default: false
|
||||
default: "false"
|
||||
|
||||
jobs:
|
||||
check_release_name:
|
||||
|
|
@ -20,7 +20,7 @@ jobs:
|
|||
- id: check
|
||||
working-directory: .
|
||||
run: |
|
||||
if [[ "${{ github.event.release.tag_name }}" == v1.1.*-vscode ]]; then
|
||||
if [[ "${{ github.event.release.tag_name }}" == v1.3.*-vscode ]]; then
|
||||
echo "should_run=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "should_run=false" >> $GITHUB_OUTPUT
|
||||
|
|
|
|||
277
.github/workflows/respond-to-cubic.yaml
vendored
Normal file
277
.github/workflows/respond-to-cubic.yaml
vendored
Normal file
|
|
@ -0,0 +1,277 @@
|
|||
name: Respond to @continuedev Comments
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_review_comment:
|
||||
types: [created]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
respond-to-comment:
|
||||
# Only run on pull request comments
|
||||
if: github.event_name == 'issue_comment' && github.event.issue.pull_request
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Check if comment contains @continuedev
|
||||
id: check-mention
|
||||
run: |
|
||||
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: Add eyes reaction to comment
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
await github.rest.reactions.createForIssueComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: ${{ github.event.comment.id }},
|
||||
content: 'eyes'
|
||||
});
|
||||
|
||||
- name: Checkout PR branch
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Get PR information
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
id: pr-info
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const { data: pr } = await github.rest.pulls.get({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
pull_number: context.issue.number
|
||||
});
|
||||
|
||||
core.setOutput('head_ref', pr.head.ref);
|
||||
core.setOutput('head_sha', pr.head.sha);
|
||||
return pr;
|
||||
|
||||
- name: Checkout PR branch
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
run: |
|
||||
git checkout ${{ steps.pr-info.outputs.head_ref }}
|
||||
|
||||
- name: Setup Node.js
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/setup-node@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@v8
|
||||
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: 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@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: Get review context
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
id: review-context
|
||||
uses: actions/github-script@v7
|
||||
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 --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
|
||||
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 commentParams = {
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
pull_number: ${{ github.event.pull_request.number }},
|
||||
body: commentBody,
|
||||
commit_id: '${{ github.event.pull_request.head.sha }}',
|
||||
path: '${{ github.event.comment.path }}',
|
||||
in_reply_to: ${{ github.event.comment.id }}
|
||||
};
|
||||
|
||||
await github.rest.pulls.createReviewComment(commentParams);
|
||||
|
||||
- name: Log session details
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
run: |
|
||||
echo "✅ Successfully started remote session for review comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}"
|
||||
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
|
||||
echo "File: ${{ github.event.comment.path }}"
|
||||
echo "Line: ${{ github.event.comment.line }}"
|
||||
echo "Original comment: ${{ github.event.comment.body }}"
|
||||
3
.github/workflows/reusable-release.yml
vendored
3
.github/workflows/reusable-release.yml
vendored
|
|
@ -51,6 +51,9 @@ jobs:
|
|||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup packages
|
||||
uses: ./.github/actions/setup-packages
|
||||
|
||||
- name: Use Node.js from .nvmrc
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
|
|
|
|||
4
.github/workflows/similar-issues.yml
vendored
4
.github/workflows/similar-issues.yml
vendored
|
|
@ -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 = [];
|
||||
|
|
|
|||
222
.github/workflows/stable-release.yml
vendored
Normal file
222
.github/workflows/stable-release.yml
vendored
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
name: Stable Release
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# Run every Monday at 10am UTC (1 hour after beta release)
|
||||
- cron: "0 10 * * 1"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release_type:
|
||||
description: "Release type"
|
||||
required: true
|
||||
type: choice
|
||||
options:
|
||||
- "promote-beta"
|
||||
- "direct-stable"
|
||||
default: "promote-beta"
|
||||
beta_version:
|
||||
description: "Specific beta version to promote (required if release_type is 'promote-beta')"
|
||||
required: false
|
||||
type: string
|
||||
stable_version:
|
||||
description: "Version for direct stable release (e.g., 1.2.3) - required if release_type is 'direct-stable'"
|
||||
required: false
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
stable-release:
|
||||
name: Stable Release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
always-auth: true
|
||||
|
||||
- name: Validate inputs
|
||||
run: |
|
||||
RELEASE_TYPE="${{ inputs.release_type || 'promote-beta' }}"
|
||||
echo "Release type: $RELEASE_TYPE"
|
||||
|
||||
if [[ "$RELEASE_TYPE" == "direct-stable" ]]; then
|
||||
if [[ -z "${{ inputs.stable_version }}" ]]; then
|
||||
echo "Error: stable_version is required for direct-stable release type"
|
||||
exit 1
|
||||
fi
|
||||
echo "Direct stable release version: ${{ inputs.stable_version }}"
|
||||
elif [[ "$RELEASE_TYPE" == "promote-beta" ]]; then
|
||||
echo "Beta promotion release (beta_version: ${{ inputs.beta_version }})"
|
||||
else
|
||||
echo "Error: Invalid release type: $RELEASE_TYPE"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Find beta version to promote
|
||||
if: ${{ (inputs.release_type || 'promote-beta') == 'promote-beta' }}
|
||||
id: find_beta
|
||||
working-directory: extensions/cli
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
if [[ -n "${{ inputs.beta_version }}" ]]; then
|
||||
# Manual input provided
|
||||
BETA_VERSION="${{ inputs.beta_version }}"
|
||||
echo "Using manually specified beta version: $BETA_VERSION"
|
||||
else
|
||||
# Find beta version that's at least 7 days old
|
||||
SEVEN_DAYS_AGO=$(date -u -d '7 days ago' +%Y%m%d)
|
||||
echo "Looking for beta versions from $SEVEN_DAYS_AGO or earlier"
|
||||
|
||||
# Get all beta versions from npm
|
||||
BETA_VERSIONS=$(npm view @continuedev/cli versions --json | jq -r '.[] | select(contains("-beta."))' | sort -V)
|
||||
|
||||
CANDIDATE_VERSION=""
|
||||
for version in $BETA_VERSIONS; do
|
||||
# Extract date from beta version (format: x.y.z-beta.YYYYMMDD)
|
||||
if [[ $version =~ -beta\.([0-9]{8}) ]]; then
|
||||
BETA_DATE="${BASH_REMATCH[1]}"
|
||||
if [[ $BETA_DATE -le $SEVEN_DAYS_AGO ]]; then
|
||||
CANDIDATE_VERSION=$version
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ -z "$CANDIDATE_VERSION" ]]; then
|
||||
echo "No beta version found that is at least 7 days old"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
BETA_VERSION=$CANDIDATE_VERSION
|
||||
echo "Selected beta version for promotion: $BETA_VERSION"
|
||||
fi
|
||||
|
||||
# Extract base version (remove -beta.YYYYMMDD suffix)
|
||||
STABLE_VERSION=$(echo "$BETA_VERSION" | sed 's/-beta\.[0-9]\{8\}//')
|
||||
|
||||
echo "beta_version=$BETA_VERSION" >> $GITHUB_OUTPUT
|
||||
echo "stable_version=$STABLE_VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Set version for direct stable release
|
||||
if: ${{ inputs.release_type == 'direct-stable' }}
|
||||
id: direct_stable
|
||||
run: |
|
||||
echo "stable_version=${{ inputs.stable_version }}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Download and verify beta package
|
||||
if: ${{ (inputs.release_type || 'promote-beta') == 'promote-beta' }}
|
||||
working-directory: extensions/cli
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
# Download the specific beta version
|
||||
npm pack @continuedev/cli@${{ steps.find_beta.outputs.beta_version }}
|
||||
|
||||
# Extract and verify the package
|
||||
PACKAGE_FILE=$(ls continuedev-cli-*.tgz)
|
||||
tar -xzf "$PACKAGE_FILE"
|
||||
|
||||
echo "Beta package contents verified"
|
||||
ls -la package/
|
||||
|
||||
- name: Prepare package for beta promotion
|
||||
if: ${{ (inputs.release_type || 'promote-beta') == 'promote-beta' }}
|
||||
working-directory: extensions/cli
|
||||
run: |
|
||||
# Copy the beta package contents
|
||||
cp -r package/* .
|
||||
|
||||
# Update version to stable (remove beta suffix)
|
||||
npm version ${{ steps.find_beta.outputs.stable_version }} --no-git-tag-version
|
||||
|
||||
- name: Setup packages (for direct stable release)
|
||||
if: ${{ inputs.release_type == 'direct-stable' }}
|
||||
uses: ./.github/actions/setup-packages
|
||||
|
||||
- name: Setup core component (for direct stable release)
|
||||
if: ${{ inputs.release_type == 'direct-stable' }}
|
||||
uses: ./.github/actions/setup-component
|
||||
with:
|
||||
component: core
|
||||
include-root: true
|
||||
|
||||
- name: Build core
|
||||
run: |
|
||||
cd core
|
||||
npm run build
|
||||
|
||||
- name: Prepare package for direct stable release
|
||||
if: ${{ inputs.release_type == 'direct-stable' }}
|
||||
working-directory: extensions/cli
|
||||
run: |
|
||||
# Install dependencies for direct build
|
||||
npm ci
|
||||
|
||||
# Update version to the specified stable version
|
||||
npm version ${{ inputs.stable_version }} --no-git-tag-version
|
||||
|
||||
- name: Build (verification step)
|
||||
working-directory: extensions/cli
|
||||
run: npm run build
|
||||
|
||||
- name: Run tests (verification step)
|
||||
working-directory: extensions/cli
|
||||
run: npm test
|
||||
|
||||
- name: Set final version
|
||||
id: final_version
|
||||
run: |
|
||||
if [[ "${{ inputs.release_type || 'promote-beta' }}" == "direct-stable" ]]; then
|
||||
STABLE_VERSION="${{ steps.direct_stable.outputs.stable_version }}"
|
||||
RELEASE_NOTES="Direct stable release from main branch. Version $STABLE_VERSION built and published directly from the latest main branch."
|
||||
else
|
||||
STABLE_VERSION="${{ steps.find_beta.outputs.stable_version }}"
|
||||
RELEASE_NOTES="Stable release promoted from tested beta version ${{ steps.find_beta.outputs.beta_version }}. This version has been thoroughly tested in beta for at least 7 days."
|
||||
fi
|
||||
echo "stable_version=$STABLE_VERSION" >> $GITHUB_OUTPUT
|
||||
echo "release_notes=$RELEASE_NOTES" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Publish stable to npm
|
||||
working-directory: extensions/cli
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
npm publish --tag latest
|
||||
echo "Published stable version: ${{ steps.final_version.outputs.stable_version }}"
|
||||
|
||||
- name: Create stable release on GitHub
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
|
||||
run: |
|
||||
# Create a git tag for the stable release
|
||||
git config --local user.email "action@github.com"
|
||||
git config --local user.name "GitHub Action"
|
||||
git tag "v${{ steps.final_version.outputs.stable_version }}"
|
||||
git push origin "v${{ steps.final_version.outputs.stable_version }}"
|
||||
|
||||
# Create GitHub release
|
||||
gh release create "v${{ steps.final_version.outputs.stable_version }}" \
|
||||
--title "Stable Release v${{ steps.final_version.outputs.stable_version }}" \
|
||||
--notes "${{ steps.final_version.outputs.release_notes }}" \
|
||||
--latest
|
||||
|
||||
- name: Update GitHub release notes for beta promotion
|
||||
if: ${{ (inputs.release_type || 'promote-beta') == 'promote-beta' }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
|
||||
run: |
|
||||
# Mark the original beta release as superseded
|
||||
gh release edit "v${{ steps.find_beta.outputs.beta_version }}" \
|
||||
--notes "This beta version has been promoted to stable as v${{ steps.final_version.outputs.stable_version }}."
|
||||
|
|
@ -14,7 +14,7 @@ jobs:
|
|||
- name: Checkout sources
|
||||
uses: actions/checkout@v5
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 17
|
||||
|
|
|
|||
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -158,6 +158,7 @@ extensions/intellij/.idea/**
|
|||
**/.idea/shelf/
|
||||
**/.idea/inspectionProfiles/Project_Default.xml
|
||||
**/.idea/php.xml
|
||||
**/.idea/kotlinc.xml
|
||||
|
||||
|
||||
extensions/intellij/bin
|
||||
|
|
@ -170,4 +171,5 @@ extensions/.continue-debug/
|
|||
|
||||
.continuerules
|
||||
**/.continue/assistants/
|
||||
**/.continue/agents/
|
||||
keys
|
||||
6
.idea/kotlinc.xml
generated
6
.idea/kotlinc.xml
generated
|
|
@ -1,6 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="KotlinJpsPluginSettings">
|
||||
<option name="version" value="1.8.0" />
|
||||
</component>
|
||||
</project>
|
||||
|
|
@ -23,5 +23,5 @@ CHANGELOG.md
|
|||
**/CODEOWNERS
|
||||
core/vendor
|
||||
coverage
|
||||
e2e
|
||||
# e2e
|
||||
packages/continue-sdk
|
||||
43
.vscode/launch.json
vendored
43
.vscode/launch.json
vendored
|
|
@ -131,6 +131,49 @@
|
|||
"env": {
|
||||
"NODE_OPTIONS": "--experimental-vm-modules"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Debug CLI",
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/extensions/cli/src/index.ts",
|
||||
"args": [],
|
||||
"env": {
|
||||
"NODE_ENV": "development"
|
||||
// "CONTINUE_API_BASE": "http://localhost:3001/",
|
||||
// "WORKOS_CLIENT_ID": "client_01J0FW6XCPMJMQ3CG51RB4HBZQ",
|
||||
// "HUB_URL": "http://localhost:3000"
|
||||
},
|
||||
"console": "integratedTerminal",
|
||||
"internalConsoleOptions": "neverOpen",
|
||||
"skipFiles": ["<node_internals>/**"],
|
||||
"runtimeArgs": ["--loader", "ts-node/esm"],
|
||||
"sourceMaps": true,
|
||||
"resolveSourceMapLocations": [
|
||||
"${workspaceFolder}/**",
|
||||
"!**/node_modules/**"
|
||||
],
|
||||
"preLaunchTask": "watch-logs",
|
||||
"cwd": "${workspaceFolder}/extensions/cli"
|
||||
},
|
||||
{
|
||||
"name": "Debug CLI Tests",
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/extensions/cli/node_modules/.bin/vitest",
|
||||
"args": ["--run", "--no-cache"],
|
||||
"env": {
|
||||
"NODE_ENV": "test"
|
||||
},
|
||||
"console": "integratedTerminal",
|
||||
"internalConsoleOptions": "neverOpen",
|
||||
"skipFiles": ["<node_internals>/**"],
|
||||
"sourceMaps": true,
|
||||
"resolveSourceMapLocations": [
|
||||
"${workspaceFolder}/**",
|
||||
"!**/node_modules/**"
|
||||
],
|
||||
"cwd": "${workspaceFolder}/extensions/cli"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
3
.vscode/settings.json
vendored
3
.vscode/settings.json
vendored
|
|
@ -42,7 +42,8 @@
|
|||
"extensions/vscode/e2e/_output": true,
|
||||
"extensions/vscode/e2e/storage": true,
|
||||
"extensions/vscode/e2e/vsix": true,
|
||||
"extensions/.continue-debug": true
|
||||
"extensions/.continue-debug": true,
|
||||
"extensions/cli/dist/**": true
|
||||
// "sync/**": true
|
||||
},
|
||||
"editor.formatOnSave": true,
|
||||
|
|
|
|||
62
.vscode/tasks.json
vendored
62
.vscode/tasks.json
vendored
|
|
@ -311,6 +311,68 @@
|
|||
"close": true,
|
||||
"focus": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"label": "cli:build",
|
||||
"type": "npm",
|
||||
"script": "build",
|
||||
"group": "build",
|
||||
"presentation": {
|
||||
"echo": true,
|
||||
"reveal": "silent",
|
||||
"focus": false,
|
||||
"panel": "shared",
|
||||
"showReuseMessage": true,
|
||||
"clear": false
|
||||
},
|
||||
"problemMatcher": ["$tsc"],
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}/extensions/cli"
|
||||
}
|
||||
},
|
||||
{
|
||||
"label": "cli:test",
|
||||
"type": "npm",
|
||||
"script": "test",
|
||||
"group": "test",
|
||||
"presentation": {
|
||||
"echo": true,
|
||||
"reveal": "always",
|
||||
"focus": false,
|
||||
"panel": "shared",
|
||||
"showReuseMessage": true,
|
||||
"clear": false
|
||||
},
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}/extensions/cli"
|
||||
}
|
||||
},
|
||||
{
|
||||
"label": "watch-logs",
|
||||
"type": "shell",
|
||||
"command": "npm run watch:logs",
|
||||
"isBackground": true,
|
||||
"problemMatcher": {
|
||||
"pattern": {
|
||||
"regexp": "^$",
|
||||
"file": 1,
|
||||
"location": 2,
|
||||
"message": 3
|
||||
},
|
||||
"background": {
|
||||
"activeOnStart": true,
|
||||
"beginsPattern": "^.*$",
|
||||
"endsPattern": "^.*$"
|
||||
}
|
||||
},
|
||||
"presentation": {
|
||||
"reveal": "always",
|
||||
"panel": "new",
|
||||
"focus": false
|
||||
},
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}/extensions/cli"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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>.
|
||||
|
|
@ -288,4 +288,4 @@ We require all contributors to accept the CLA and have made it as easy as commen
|
|||
I have read the CLA Document and I hereby sign the CLA
|
||||
```
|
||||
|
||||
3. The CLA‑Assistant bot records your signature in the repo and marks the status check as passed.
|
||||
3. The CLA-Assistant bot records your signature in the repo and marks the status check as passed.
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||

|
||||
|
||||
## 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
|
||||
|
||||

|
||||
|
||||
## 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
|
||||
|
||||

|
||||
|
||||
## 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
|
||||
|
||||

|
||||
|
||||
|
|
|
|||
|
|
@ -219,7 +219,7 @@ We recommend using a specific commit SHA for stability and predictability:
|
|||
Example:
|
||||
|
||||
```yaml
|
||||
uses: continuedev/continue/actions/general-review@17fe39cc4f1760838ce4428aad0a984af13f8266
|
||||
uses: continuedev/continue/actions/general-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
|
|
|||
|
|
@ -29,12 +29,17 @@ runs:
|
|||
SHOULD_RUN="false"
|
||||
|
||||
if [ "${{ github.event_name }}" = "pull_request" ]; then
|
||||
# Check PR author association
|
||||
AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}"
|
||||
if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then
|
||||
SHOULD_RUN="true"
|
||||
# Check if PR is a draft
|
||||
if [ "${{ github.event.pull_request.draft }}" = "true" ]; then
|
||||
echo "::notice::Skipping review - PR is a draft"
|
||||
else
|
||||
echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)"
|
||||
# Check PR author association
|
||||
AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}"
|
||||
if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then
|
||||
SHOULD_RUN="true"
|
||||
else
|
||||
echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)"
|
||||
fi
|
||||
fi
|
||||
elif [ "${{ github.event_name }}" = "issue_comment" ]; then
|
||||
# Check if it's a PR comment with the trigger phrase
|
||||
|
|
@ -68,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'
|
||||
|
|
@ -189,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
|
||||
|
|
@ -196,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'
|
||||
|
|
@ -268,7 +332,23 @@ runs:
|
|||
console.log('Invalid comments:', JSON.stringify(invalidComments, null, 2));
|
||||
}
|
||||
|
||||
const comments = validComments.map(comment => ({
|
||||
// Deduplicate comments based on path + position + body
|
||||
const uniqueComments = [];
|
||||
const seen = new Set();
|
||||
|
||||
for (const comment of validComments) {
|
||||
const key = `${comment.path}:${comment.position}:${comment.body}`;
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
uniqueComments.push(comment);
|
||||
}
|
||||
}
|
||||
|
||||
if (uniqueComments.length < validComments.length) {
|
||||
console.log(`Filtered out ${validComments.length - uniqueComments.length} duplicate comments (same path + position + body)`);
|
||||
}
|
||||
|
||||
const comments = uniqueComments.map(comment => ({
|
||||
path: comment.path,
|
||||
position: comment.position,
|
||||
body: comment.body
|
||||
|
|
@ -283,12 +363,19 @@ runs:
|
|||
// Create the review
|
||||
if (comments.length > 0) {
|
||||
try {
|
||||
let reviewBody = `${reviewData.review_summary || 'AI Code Review'}\n\n---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`;
|
||||
|
||||
// Add triggered by note if from comment
|
||||
if (context.eventName === 'issue_comment') {
|
||||
reviewBody = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${reviewBody}`;
|
||||
}
|
||||
|
||||
await github.rest.pulls.createReview({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
pull_number: prNumber,
|
||||
commit_id: commitSha,
|
||||
body: `${reviewData.review_summary || 'AI Code Review'}\n\n---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`,
|
||||
body: reviewBody,
|
||||
event: 'COMMENT',
|
||||
comments: comments
|
||||
});
|
||||
|
|
@ -310,22 +397,19 @@ runs:
|
|||
}
|
||||
} else {
|
||||
// No inline comments, just post the summary
|
||||
let summaryBody = `## AI Code Review\n\n${reviewData.review_summary}\n\n*No specific line comments generated.*\n\n` +
|
||||
`---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`;
|
||||
|
||||
// Add triggered by note if from comment
|
||||
if (context.eventName === 'issue_comment') {
|
||||
summaryBody = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${summaryBody}`;
|
||||
}
|
||||
|
||||
await github.rest.issues.createComment({
|
||||
issue_number: prNumber,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: `## AI Code Review\n\n${reviewData.review_summary}\n\n*No specific line comments generated.*\n\n` +
|
||||
`---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`
|
||||
});
|
||||
}
|
||||
|
||||
// Add triggered by note if from comment
|
||||
if (context.eventName === 'issue_comment') {
|
||||
await github.rest.issues.createComment({
|
||||
issue_number: prNumber,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: `*Inline review triggered by @${context.payload.comment.user.login}*`
|
||||
body: summaryBody
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -29,12 +29,17 @@ runs:
|
|||
SHOULD_RUN="false"
|
||||
|
||||
if [ "${{ github.event_name }}" = "pull_request" ]; then
|
||||
# Check PR author association
|
||||
AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}"
|
||||
if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then
|
||||
SHOULD_RUN="true"
|
||||
# Check if PR is a draft
|
||||
if [ "${{ github.event.pull_request.draft }}" = "true" ]; then
|
||||
echo "::notice::Skipping review - PR is a draft"
|
||||
else
|
||||
echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)"
|
||||
# Check PR author association
|
||||
AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}"
|
||||
if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then
|
||||
SHOULD_RUN="true"
|
||||
else
|
||||
echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)"
|
||||
fi
|
||||
fi
|
||||
elif [ "${{ github.event_name }}" = "issue_comment" ]; then
|
||||
# Check if it's a PR comment with the trigger phrase
|
||||
|
|
@ -63,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'
|
||||
|
|
@ -152,6 +157,24 @@ 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."
|
||||
|
|
@ -163,8 +186,55 @@ runs:
|
|||
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()
|
||||
|
|
|
|||
191
binary/package-lock.json
generated
191
binary/package-lock.json
generated
|
|
@ -40,7 +40,7 @@
|
|||
"pkg": "^5.8.1",
|
||||
"rimraf": "^5.0.7",
|
||||
"ts-jest": "^29.1.4",
|
||||
"typescript": "^5.3.3"
|
||||
"typescript": "^5.6.3"
|
||||
}
|
||||
},
|
||||
"../core": {
|
||||
|
|
@ -59,7 +59,11 @@
|
|||
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.1.1",
|
||||
"@typescript-eslint/eslint-plugin": "^7.8.0",
|
||||
"@sentry/cli": "^2.50.2",
|
||||
"@sentry/core": "^9.43.0",
|
||||
"@sentry/esbuild-plugin": "^4.0.2",
|
||||
"@sentry/node": "^9.43.0",
|
||||
"@sentry/vite-plugin": "^4.0.2",
|
||||
"@xenova/transformers": "2.14.0",
|
||||
"adf-to-md": "^1.1.0",
|
||||
"async-mutex": "^0.5.0",
|
||||
|
|
@ -78,7 +82,7 @@
|
|||
"http-proxy-agent": "^7.0.1",
|
||||
"https-proxy-agent": "^7.0.3",
|
||||
"iconv-lite": "^0.6.3",
|
||||
"ignore": "^5.3.1",
|
||||
"ignore": "^7.0.5",
|
||||
"is-localhost-ip": "^2.0.0",
|
||||
"jinja-js": "0.1.8",
|
||||
"js-tiktoken": "^1.0.8",
|
||||
|
|
@ -91,7 +95,7 @@
|
|||
"node-html-markdown": "^1.3.0",
|
||||
"ollama": "^0.4.6",
|
||||
"onnxruntime-node": "1.14.0",
|
||||
"openai": "^4.104.0",
|
||||
"openai": "^5.13.1",
|
||||
"p-limit": "^6.1.0",
|
||||
"partial-json": "^0.1.7",
|
||||
"pg": "^8.11.3",
|
||||
|
|
@ -102,6 +106,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",
|
||||
|
|
@ -136,9 +141,12 @@
|
|||
"@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",
|
||||
"@typescript-eslint/eslint-plugin": "^8.40.0",
|
||||
"@typescript-eslint/parser": "^8.40.0",
|
||||
"cross-env": "^7.0.3",
|
||||
"esbuild": "0.17.19",
|
||||
"eslint": "^8",
|
||||
|
|
@ -2890,6 +2898,19 @@
|
|||
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/call-bind-apply-helpers": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
|
||||
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"function-bind": "^1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/callsites": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
|
||||
|
|
@ -3363,6 +3384,20 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/dunder-proto": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.1",
|
||||
"es-errors": "^1.3.0",
|
||||
"gopd": "^1.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/eastasianwidth": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",
|
||||
|
|
@ -3411,6 +3446,51 @@
|
|||
"is-arrayish": "^0.2.1"
|
||||
}
|
||||
},
|
||||
"node_modules/es-define-property": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
|
||||
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/es-errors": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
|
||||
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/es-object-atoms": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
|
||||
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/es-set-tostringtag": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
|
||||
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"get-intrinsic": "^1.2.6",
|
||||
"has-tostringtag": "^1.0.2",
|
||||
"hasown": "^2.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/esbuild": {
|
||||
"version": "0.19.11",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.11.tgz",
|
||||
|
|
@ -3690,12 +3770,15 @@
|
|||
}
|
||||
},
|
||||
"node_modules/form-data": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
|
||||
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
|
||||
"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": {
|
||||
|
|
@ -3768,7 +3851,6 @@
|
|||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
|
||||
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
|
||||
"dev": true,
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
|
|
@ -3791,6 +3873,30 @@
|
|||
"node": "6.* || 8.* || >= 10.*"
|
||||
}
|
||||
},
|
||||
"node_modules/get-intrinsic": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
||||
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.2",
|
||||
"es-define-property": "^1.0.1",
|
||||
"es-errors": "^1.3.0",
|
||||
"es-object-atoms": "^1.1.1",
|
||||
"function-bind": "^1.1.2",
|
||||
"get-proto": "^1.0.1",
|
||||
"gopd": "^1.2.0",
|
||||
"has-symbols": "^1.1.0",
|
||||
"hasown": "^2.0.2",
|
||||
"math-intrinsics": "^1.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/get-package-type": {
|
||||
"version": "0.1.0",
|
||||
"resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz",
|
||||
|
|
@ -3800,6 +3906,19 @@
|
|||
"node": ">=8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/get-proto": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
|
||||
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"dunder-proto": "^1.0.1",
|
||||
"es-object-atoms": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/get-stream": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz",
|
||||
|
|
@ -3881,6 +4000,18 @@
|
|||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/gopd": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
|
||||
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/graceful-fs": {
|
||||
"version": "4.2.11",
|
||||
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
|
||||
|
|
@ -3904,11 +4035,37 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/has-symbols": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
|
||||
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/has-tostringtag": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
|
||||
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"has-symbols": "^1.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/hasown": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
|
||||
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"function-bind": "^1.1.2"
|
||||
},
|
||||
|
|
@ -5179,6 +5336,15 @@
|
|||
"tmpl": "1.0.5"
|
||||
}
|
||||
},
|
||||
"node_modules/math-intrinsics": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/merge-stream": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
|
||||
|
|
@ -6758,10 +6924,11 @@
|
|||
}
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.4.5",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz",
|
||||
"integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==",
|
||||
"version": "5.9.2",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.2.tgz",
|
||||
"integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@
|
|||
"pkg": "^5.8.1",
|
||||
"rimraf": "^5.0.7",
|
||||
"ts-jest": "^29.1.4",
|
||||
"typescript": "^5.3.3"
|
||||
"typescript": "^5.6.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@octokit/rest": "^20.0.2",
|
||||
|
|
|
|||
|
|
@ -6,12 +6,13 @@ import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
|
|||
import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js";
|
||||
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
|
||||
|
||||
import { isSecurityConcern } from "../indexing/ignore.js";
|
||||
import { BracketMatchingService } from "./filtering/BracketMatchingService.js";
|
||||
import { CompletionStreamer } from "./generation/CompletionStreamer.js";
|
||||
import { postprocessCompletion } from "./postprocessing/index.js";
|
||||
import { shouldPrefilter } from "./prefiltering/index.js";
|
||||
import { renderPromptWithTokenLimit } from "./templating/index.js";
|
||||
import { getAllSnippetsWithoutRace } from "./snippets/index.js";
|
||||
import { renderPromptWithTokenLimit } from "./templating/index.js";
|
||||
import { GetLspDefinitionsFunction } from "./types.js";
|
||||
import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js";
|
||||
import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js";
|
||||
|
|
@ -150,6 +151,10 @@ export class CompletionProvider {
|
|||
return undefined;
|
||||
}
|
||||
|
||||
if (isSecurityConcern(input.filepath)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const options = await this._getAutocompleteOptions(llm);
|
||||
|
||||
// Debounce
|
||||
|
|
@ -210,12 +215,6 @@ export class CompletionProvider {
|
|||
const multiline =
|
||||
!helper.options.transform || shouldCompleteMultiline(helper);
|
||||
|
||||
const rawGeneration = await llm.complete(
|
||||
prompt,
|
||||
token,
|
||||
completionOptions,
|
||||
);
|
||||
|
||||
const completionStream =
|
||||
this.completionStreamer.streamCompletionWithFilters(
|
||||
token,
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { IDE } from "../..";
|
|||
import {
|
||||
getGlobalContinueIgArray,
|
||||
getWorkspaceContinueIgArray,
|
||||
} from "../../indexing/ignore";
|
||||
} from "../../indexing/continueignore";
|
||||
import { getConfigJsonPath } from "../../util/paths";
|
||||
import { findUriInDirs } from "../../util/uri";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
|
|
|||
|
|
@ -1,11 +1,8 @@
|
|||
import ignore from "ignore";
|
||||
|
||||
import type { FileType, IDE, SlashCommand } from "../../..";
|
||||
import {
|
||||
DEFAULT_IGNORE,
|
||||
getGlobalContinueIgArray,
|
||||
gitIgArrayFromFile,
|
||||
} from "../../../indexing/ignore";
|
||||
import { getGlobalContinueIgArray } from "../../../indexing/continueignore";
|
||||
import { DEFAULT_IGNORE, gitIgArrayFromFile } from "../../../indexing/ignore";
|
||||
import { renderChatMessage } from "../../../util/messageContent";
|
||||
import {
|
||||
findUriInDirs,
|
||||
|
|
|
|||
|
|
@ -21,7 +21,6 @@ import { PolicySingleton } from "../control-plane/PolicySingleton.js";
|
|||
import { Logger } from "../util/Logger.js";
|
||||
import { Telemetry } from "../util/posthog.js";
|
||||
import {
|
||||
ASSISTANTS,
|
||||
getAllDotContinueDefinitionFiles,
|
||||
LoadAssistantFilesOptions,
|
||||
} from "./loadLocalAssistants.js";
|
||||
|
|
@ -203,6 +202,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 {
|
||||
|
|
@ -339,7 +340,7 @@ export class ConfigHandler {
|
|||
|
||||
async getLocalProfiles(options: LoadAssistantFilesOptions) {
|
||||
/**
|
||||
* Users can define as many local assistants as they want in a `.continue/assistants` folder
|
||||
* Users can define as many local agents as they want in a `.continue/agents` (or previous .continue/assistants) folder
|
||||
*/
|
||||
|
||||
// Local customization disabled for on-premise deployments
|
||||
|
|
@ -358,9 +359,14 @@ export class ConfigHandler {
|
|||
const assistantFiles = await getAllDotContinueDefinitionFiles(
|
||||
this.ide,
|
||||
options,
|
||||
ASSISTANTS,
|
||||
"assistants",
|
||||
);
|
||||
const profiles = assistantFiles.map((assistant) => {
|
||||
const agentFiles = await getAllDotContinueDefinitionFiles(
|
||||
this.ide,
|
||||
options,
|
||||
"agents",
|
||||
);
|
||||
const profiles = [...assistantFiles, ...agentFiles].map((assistant) => {
|
||||
return new LocalProfileLoader(
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
|
|
|
|||
62
core/config/createNewAssistantFile.ts
Normal file
62
core/config/createNewAssistantFile.ts
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
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
|
||||
|
||||
# To learn more, see the full assistant reference: https://docs.continue.dev/reference
|
||||
|
||||
name: Example Assistant
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
|
||||
# Models define which AI models this assistant can use
|
||||
models:
|
||||
- name: my gpt-5
|
||||
provider: openai
|
||||
model: gpt-5
|
||||
apiKey: YOUR_API_KEY_HERE
|
||||
|
||||
# Context providers define what information the assistant can access
|
||||
context:
|
||||
- provider: code
|
||||
- provider: docs
|
||||
- provider: diff
|
||||
- provider: terminal
|
||||
- provider: problems
|
||||
- provider: folder
|
||||
- provider: codebase
|
||||
`;
|
||||
|
||||
export async function createNewAssistantFile(
|
||||
ide: IDE,
|
||||
assistantPath: string | undefined,
|
||||
): Promise<void> {
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
if (workspaceDirs.length === 0) {
|
||||
throw new Error(
|
||||
"No workspace directories found. Make sure you've opened a folder in your IDE.",
|
||||
);
|
||||
}
|
||||
|
||||
const baseDirUri = joinPathsToUri(
|
||||
workspaceDirs[0],
|
||||
assistantPath ?? ".continue/assistants",
|
||||
);
|
||||
|
||||
// Find the first available filename
|
||||
let counter = 0;
|
||||
let assistantFileUri: string;
|
||||
do {
|
||||
const suffix = counter === 0 ? "" : `-${counter}`;
|
||||
assistantFileUri = joinPathsToUri(
|
||||
baseDirUri,
|
||||
`new-assistant${suffix}.yaml`,
|
||||
);
|
||||
counter++;
|
||||
} while (await ide.fileExists(assistantFileUri));
|
||||
|
||||
await ide.writeFile(assistantFileUri, DEFAULT_ASSISTANT_FILE);
|
||||
await ide.openFile(assistantFileUri);
|
||||
}
|
||||
|
|
@ -1,37 +1,8 @@
|
|||
import { ConfigYaml } from "@continuedev/config-yaml";
|
||||
|
||||
export const defaultContextProvidersVsCode: NonNullable<
|
||||
ConfigYaml["context"]
|
||||
>[number][] = [
|
||||
{ provider: "code" },
|
||||
{ provider: "docs" },
|
||||
{ provider: "diff" },
|
||||
{ provider: "terminal" },
|
||||
{ provider: "problems" },
|
||||
{ provider: "folder" },
|
||||
{ provider: "codebase" },
|
||||
];
|
||||
|
||||
export const defaultContextProvidersJetBrains: NonNullable<
|
||||
ConfigYaml["context"]
|
||||
>[number][] = [
|
||||
{ provider: "diff" },
|
||||
{ provider: "folder" },
|
||||
{ provider: "codebase" },
|
||||
];
|
||||
|
||||
export const defaultConfig: ConfigYaml = {
|
||||
name: "Local Assistant",
|
||||
name: "Local Agent",
|
||||
version: "1.0.0",
|
||||
schema: "v1",
|
||||
models: [],
|
||||
context: defaultContextProvidersVsCode,
|
||||
};
|
||||
|
||||
export const defaultConfigJetBrains: ConfigYaml = {
|
||||
name: "Local Assistant",
|
||||
version: "1.0.0",
|
||||
schema: "v1",
|
||||
models: [],
|
||||
context: defaultContextProvidersJetBrains,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -19,7 +19,6 @@ import {
|
|||
ContinueRcJson,
|
||||
CustomContextProvider,
|
||||
EmbeddingsProviderDescription,
|
||||
IContextProvider,
|
||||
IDE,
|
||||
IdeInfo,
|
||||
IdeSettings,
|
||||
|
|
@ -36,10 +35,6 @@ import { getLegacyBuiltInSlashCommandFromDescription } from "../commands/slash/b
|
|||
import { convertCustomCommandToSlashCommand } from "../commands/slash/customSlashCommand";
|
||||
import { slashCommandFromPromptFile } from "../commands/slash/promptFileSlashCommand";
|
||||
import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
|
||||
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
|
||||
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
|
||||
import FileContextProvider from "../context/providers/FileContextProvider";
|
||||
import { contextProviderClassFromName } from "../context/providers/index";
|
||||
import { useHub } from "../control-plane/env";
|
||||
import { BaseLLM } from "../llm";
|
||||
import { LLMClasses, llmFromDescription } from "../llm/llms";
|
||||
|
|
@ -62,9 +57,12 @@ import {
|
|||
} from "../util/paths";
|
||||
import { localPathToUri } from "../util/pathToUri";
|
||||
|
||||
import { getToolsForIde } from "../tools";
|
||||
import { PolicySingleton } from "../control-plane/PolicySingleton";
|
||||
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
|
||||
import { getBaseToolDefinitions } from "../tools";
|
||||
import { resolveRelativePathInDir } from "../util/ideUtils";
|
||||
import { getWorkspaceRcConfigs } from "./json/loadRcConfigs";
|
||||
import { loadConfigContextProviders } from "./loadContextProviders";
|
||||
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
|
||||
import {
|
||||
getModelByRole,
|
||||
|
|
@ -229,7 +227,7 @@ function applyRequestOptionsToModels(
|
|||
export function isContextProviderWithParams(
|
||||
contextProvider: CustomContextProvider | ContextProviderWithParams,
|
||||
): contextProvider is ContextProviderWithParams {
|
||||
return (contextProvider as ContextProviderWithParams).name !== undefined;
|
||||
return "name" in contextProvider && !!contextProvider.name;
|
||||
}
|
||||
|
||||
/** Only difference between intermediate and final configs is the `models` array */
|
||||
|
|
@ -285,6 +283,7 @@ async function intermediateToFinalConfig({
|
|||
...desc,
|
||||
model: modelName,
|
||||
title: modelName,
|
||||
isFromAutoDetect: true,
|
||||
},
|
||||
ide.readFile.bind(ide),
|
||||
getUriFromPath,
|
||||
|
|
@ -322,6 +321,7 @@ async function intermediateToFinalConfig({
|
|||
...desc.options,
|
||||
model: modelName,
|
||||
logger: llmLogger,
|
||||
isFromAutoDetect: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
|
@ -386,50 +386,25 @@ async function intermediateToFinalConfig({
|
|||
|
||||
applyRequestOptionsToModels(tabAutocompleteModels, config);
|
||||
|
||||
// These context providers are always included, regardless of what, if anything,
|
||||
// the user has configured in config.json
|
||||
// Load context providers
|
||||
const { providers: contextProviders, errors: contextErrors } =
|
||||
loadConfigContextProviders(
|
||||
config.contextProviders
|
||||
?.filter((cp) => isContextProviderWithParams(cp))
|
||||
.map((cp) => ({
|
||||
provider: (cp as ContextProviderWithParams).name,
|
||||
params: (cp as ContextProviderWithParams).params,
|
||||
})),
|
||||
!!config.docs?.length,
|
||||
ideInfo.ideType,
|
||||
);
|
||||
|
||||
const codebaseContextParams =
|
||||
(
|
||||
(config.contextProviders || [])
|
||||
.filter(isContextProviderWithParams)
|
||||
.find((cp) => cp.name === "codebase") as
|
||||
| ContextProviderWithParams
|
||||
| undefined
|
||||
)?.params || {};
|
||||
|
||||
const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})];
|
||||
|
||||
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
|
||||
({ description: { title } }) => title,
|
||||
);
|
||||
|
||||
// Context providers
|
||||
const contextProviders: IContextProvider[] = DEFAULT_CONTEXT_PROVIDERS;
|
||||
|
||||
for (const provider of config.contextProviders || []) {
|
||||
if (isContextProviderWithParams(provider)) {
|
||||
const cls = contextProviderClassFromName(provider.name) as any;
|
||||
if (!cls) {
|
||||
if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(provider.name)) {
|
||||
console.warn(`Unknown context provider ${provider.name}`);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
const instance: IContextProvider = new cls(provider.params);
|
||||
|
||||
// Handle continue-proxy
|
||||
if (instance.description.title === "continue-proxy") {
|
||||
(instance as ContinueProxyContextProvider).workOsAccessToken =
|
||||
workOsAccessToken;
|
||||
}
|
||||
|
||||
contextProviders.push(instance);
|
||||
} else {
|
||||
contextProviders.push(new CustomContextProviderClass(provider));
|
||||
for (const cp of config.contextProviders ?? []) {
|
||||
if (!isContextProviderWithParams(cp)) {
|
||||
contextProviders.push(new CustomContextProviderClass(cp));
|
||||
}
|
||||
}
|
||||
errors.push(...contextErrors);
|
||||
|
||||
// Embeddings Provider
|
||||
function getEmbeddingsILLM(
|
||||
|
|
@ -526,7 +501,7 @@ async function intermediateToFinalConfig({
|
|||
const continueConfig: ContinueConfig = {
|
||||
...config,
|
||||
contextProviders,
|
||||
tools: await getToolsForIde(ide),
|
||||
tools: getBaseToolDefinitions(),
|
||||
mcpServerStatuses: [],
|
||||
slashCommands: [],
|
||||
modelsByRole: {
|
||||
|
|
@ -570,16 +545,21 @@ 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,
|
||||
}),
|
||||
),
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
// Handle experimental modelRole config values for apply and edit
|
||||
const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;
|
||||
|
|
@ -654,6 +634,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
|
|||
apiKeyLocation: llm.apiKeyLocation,
|
||||
envSecretLocations: llm.envSecretLocations,
|
||||
sourceFile: llm.sourceFile,
|
||||
isFromAutoDetect: llm.isFromAutoDetect,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
95
core/config/loadContextProviders.ts
Normal file
95
core/config/loadContextProviders.ts
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
import {
|
||||
AssistantUnrolledNonNullable,
|
||||
ConfigValidationError,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { IContextProvider, IdeType } from "..";
|
||||
import { contextProviderClassFromName } from "../context/providers";
|
||||
import CurrentFileContextProvider from "../context/providers/CurrentFileContextProvider";
|
||||
import DiffContextProvider from "../context/providers/DiffContextProvider";
|
||||
import DocsContextProvider from "../context/providers/DocsContextProvider";
|
||||
import FileContextProvider from "../context/providers/FileContextProvider";
|
||||
import ProblemsContextProvider from "../context/providers/ProblemsContextProvider";
|
||||
import RulesContextProvider from "../context/providers/RulesContextProvider";
|
||||
import TerminalContextProvider from "../context/providers/TerminalContextProvider";
|
||||
|
||||
/*
|
||||
Loads context providers based on configuration
|
||||
- default providers will always be loaded, using config params if present
|
||||
- other providers will be loaded if configured
|
||||
|
||||
NOTE the MCPContextProvider is added in doLoadConfig if any resources are present
|
||||
*/
|
||||
export function loadConfigContextProviders(
|
||||
configContext: AssistantUnrolledNonNullable["context"],
|
||||
hasDocs: boolean,
|
||||
ideType: IdeType,
|
||||
): {
|
||||
providers: IContextProvider[];
|
||||
errors: ConfigValidationError[];
|
||||
} {
|
||||
const providers: IContextProvider[] = [];
|
||||
const errors: ConfigValidationError[] = [];
|
||||
|
||||
const defaultProviders: IContextProvider[] = [
|
||||
new FileContextProvider({}),
|
||||
new CurrentFileContextProvider({}),
|
||||
new DiffContextProvider({}),
|
||||
new TerminalContextProvider({}),
|
||||
new ProblemsContextProvider({}),
|
||||
new RulesContextProvider({}),
|
||||
];
|
||||
|
||||
// Add from config
|
||||
if (configContext) {
|
||||
for (const config of configContext) {
|
||||
const cls = contextProviderClassFromName(config.provider) as any;
|
||||
if (
|
||||
!cls &&
|
||||
!defaultProviders.find((p) => p.description.title === config.provider)
|
||||
) {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Unknown context provider ${config.provider}`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
providers.push(
|
||||
new cls({
|
||||
name: config.name,
|
||||
...config.params,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Add from defaults if not found in config
|
||||
for (const defaultProvider of defaultProviders) {
|
||||
if (
|
||||
!providers.find(
|
||||
(p) => p.description.title === defaultProvider.description.title,
|
||||
)
|
||||
) {
|
||||
providers.push(defaultProvider);
|
||||
}
|
||||
}
|
||||
|
||||
if (hasDocs && !providers?.some((cp) => cp.description.title === "docs")) {
|
||||
providers.push(new DocsContextProvider({}));
|
||||
}
|
||||
|
||||
// @problems and @terminal are not supported in jetbrains
|
||||
const filteredProviders = providers.filter((pv) => {
|
||||
if (ideType === "jetbrains") {
|
||||
return (
|
||||
pv.description.title !== TerminalContextProvider.description.title &&
|
||||
pv.description.title !== ProblemsContextProvider.description.title
|
||||
);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
return {
|
||||
providers: filteredProviders,
|
||||
errors,
|
||||
};
|
||||
}
|
||||
590
core/config/loadContextProviders.vitest.ts
Normal file
590
core/config/loadContextProviders.vitest.ts
Normal file
|
|
@ -0,0 +1,590 @@
|
|||
import { beforeEach, describe, expect, it, MockedFunction, vi } from "vitest";
|
||||
import { contextProviderClassFromName } from "../context/providers";
|
||||
import CurrentFileContextProvider from "../context/providers/CurrentFileContextProvider";
|
||||
import DiffContextProvider from "../context/providers/DiffContextProvider";
|
||||
import FileContextProvider from "../context/providers/FileContextProvider";
|
||||
import ProblemsContextProvider from "../context/providers/ProblemsContextProvider";
|
||||
import RulesContextProvider from "../context/providers/RulesContextProvider";
|
||||
import TerminalContextProvider from "../context/providers/TerminalContextProvider";
|
||||
import { loadConfigContextProviders } from "./loadContextProviders";
|
||||
|
||||
// Mock the contextProviderClassFromName function
|
||||
vi.mock("../context/providers", () => ({
|
||||
contextProviderClassFromName: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock all provider classes
|
||||
vi.mock("../context/providers/CurrentFileContextProvider", () => ({
|
||||
default: vi.fn().mockImplementation((options) => ({
|
||||
description: { title: "current-file" },
|
||||
options,
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("../context/providers/DiffContextProvider", () => ({
|
||||
default: vi.fn().mockImplementation((options) => ({
|
||||
description: { title: "diff" },
|
||||
options,
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("../context/providers/FileContextProvider", () => ({
|
||||
default: vi.fn().mockImplementation((options) => ({
|
||||
description: { title: "file" },
|
||||
options,
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("../context/providers/ProblemsContextProvider", () => {
|
||||
const MockProblemsContextProvider = vi.fn().mockImplementation((options) => ({
|
||||
description: { title: "problems" },
|
||||
options,
|
||||
}));
|
||||
(MockProblemsContextProvider as any).description = { title: "problems" };
|
||||
return { default: MockProblemsContextProvider };
|
||||
});
|
||||
|
||||
vi.mock("../context/providers/RulesContextProvider", () => ({
|
||||
default: vi.fn().mockImplementation((options) => ({
|
||||
description: { title: "rules" },
|
||||
options,
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("../context/providers/TerminalContextProvider", () => {
|
||||
const MockTerminalContextProvider = vi.fn().mockImplementation((options) => ({
|
||||
description: { title: "terminal" },
|
||||
options,
|
||||
}));
|
||||
(MockTerminalContextProvider as any).description = { title: "terminal" };
|
||||
return { default: MockTerminalContextProvider };
|
||||
});
|
||||
|
||||
const mockedContextProviderClassFromName =
|
||||
contextProviderClassFromName as MockedFunction<
|
||||
typeof contextProviderClassFromName
|
||||
>;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("loadConfigContextProviders", () => {
|
||||
describe("with empty or undefined config", () => {
|
||||
it("should return only default providers when config is undefined", () => {
|
||||
const result = loadConfigContextProviders(undefined, false, "vscode");
|
||||
|
||||
expect(result.errors).toEqual([]);
|
||||
expect(result.providers).toHaveLength(6);
|
||||
|
||||
// Verify all default providers are included
|
||||
const providerTitles = result.providers.map((p) => p.description.title);
|
||||
expect(providerTitles).toEqual(
|
||||
expect.arrayContaining([
|
||||
"file",
|
||||
"current-file",
|
||||
"diff",
|
||||
"terminal",
|
||||
"problems",
|
||||
"rules",
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("should return only default providers when config is empty array", () => {
|
||||
const result = loadConfigContextProviders([], false, "vscode");
|
||||
|
||||
expect(result.errors).toEqual([]);
|
||||
expect(result.providers).toHaveLength(6);
|
||||
|
||||
const providerTitles = result.providers.map((p) => p.description.title);
|
||||
expect(providerTitles).toEqual(
|
||||
expect.arrayContaining([
|
||||
"file",
|
||||
"current-file",
|
||||
"diff",
|
||||
"terminal",
|
||||
"problems",
|
||||
"rules",
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("should exclude problems and terminal in jetbrains", () => {
|
||||
const result = loadConfigContextProviders([], false, "jetbrains");
|
||||
|
||||
expect(result.errors).toEqual([]);
|
||||
expect(result.providers).toHaveLength(4);
|
||||
|
||||
const providerTitles = result.providers.map((p) => p.description.title);
|
||||
expect(providerTitles).toEqual(
|
||||
expect.arrayContaining(["file", "current-file", "diff", "rules"]),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("should return default + docs when has docs is true", () => {
|
||||
const result = loadConfigContextProviders([], true, "vscode");
|
||||
|
||||
expect(result.errors).toEqual([]);
|
||||
expect(result.providers).toHaveLength(7);
|
||||
|
||||
const providerTitles = result.providers.map((p) => p.description.title);
|
||||
expect(providerTitles).toEqual(
|
||||
expect.arrayContaining([
|
||||
"file",
|
||||
"current-file",
|
||||
"diff",
|
||||
"terminal",
|
||||
"problems",
|
||||
"rules",
|
||||
"docs",
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("with valid config", () => {
|
||||
it("should load providers from config with correct parameters", () => {
|
||||
const mockProvider = vi.fn().mockImplementation((options) => ({
|
||||
description: { title: "custom-provider" },
|
||||
options,
|
||||
})) as any;
|
||||
|
||||
mockedContextProviderClassFromName.mockReturnValue(mockProvider);
|
||||
|
||||
const config = [
|
||||
{
|
||||
provider: "custom-provider",
|
||||
name: "my-custom-provider",
|
||||
params: {
|
||||
apiKey: "test-key",
|
||||
baseUrl: "https://api.example.com",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const result = loadConfigContextProviders(config, false, "vscode");
|
||||
|
||||
expect(result.errors).toEqual([]);
|
||||
expect(mockedContextProviderClassFromName).toHaveBeenCalledWith(
|
||||
"custom-provider",
|
||||
);
|
||||
expect(mockProvider).toHaveBeenCalledWith({
|
||||
name: "my-custom-provider",
|
||||
apiKey: "test-key",
|
||||
baseUrl: "https://api.example.com",
|
||||
});
|
||||
|
||||
// Should have custom provider + all defaults
|
||||
expect(result.providers).toHaveLength(7);
|
||||
|
||||
const customProvider = result.providers.find(
|
||||
(p) => p.description.title === "custom-provider",
|
||||
);
|
||||
expect(customProvider).toBeDefined();
|
||||
expect((customProvider as any)?.options).toEqual({
|
||||
name: "my-custom-provider",
|
||||
apiKey: "test-key",
|
||||
baseUrl: "https://api.example.com",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle multiple providers in config", () => {
|
||||
const mockProvider1 = vi.fn().mockImplementation((options) => ({
|
||||
description: { title: "provider-1" },
|
||||
options,
|
||||
})) as any;
|
||||
|
||||
const mockProvider2 = vi.fn().mockImplementation((options) => ({
|
||||
description: { title: "provider-2" },
|
||||
options,
|
||||
})) as any;
|
||||
|
||||
mockedContextProviderClassFromName
|
||||
.mockReturnValueOnce(mockProvider1)
|
||||
.mockReturnValueOnce(mockProvider2);
|
||||
|
||||
const config = [
|
||||
{
|
||||
provider: "provider-1",
|
||||
name: "first-provider",
|
||||
params: { setting1: "value1" },
|
||||
},
|
||||
{
|
||||
provider: "provider-2",
|
||||
name: "second-provider",
|
||||
params: { setting2: "value2" },
|
||||
},
|
||||
];
|
||||
|
||||
const result = loadConfigContextProviders(config, false, "vscode");
|
||||
|
||||
expect(result.errors).toEqual([]);
|
||||
expect(result.providers).toHaveLength(8); // 2 custom + 6 defaults
|
||||
|
||||
expect(mockProvider1).toHaveBeenCalledWith({
|
||||
name: "first-provider",
|
||||
setting1: "value1",
|
||||
});
|
||||
|
||||
expect(mockProvider2).toHaveBeenCalledWith({
|
||||
name: "second-provider",
|
||||
setting2: "value2",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle config with empty params", () => {
|
||||
const mockProvider = vi.fn().mockImplementation((options) => ({
|
||||
description: { title: "no-params-provider" },
|
||||
options,
|
||||
})) as any;
|
||||
|
||||
mockedContextProviderClassFromName.mockReturnValue(mockProvider);
|
||||
|
||||
const config = [
|
||||
{
|
||||
provider: "no-params-provider",
|
||||
name: "simple-provider",
|
||||
params: {},
|
||||
},
|
||||
];
|
||||
|
||||
const result = loadConfigContextProviders(config, false, "vscode");
|
||||
|
||||
expect(result.errors).toEqual([]);
|
||||
expect(mockProvider).toHaveBeenCalledWith({
|
||||
name: "simple-provider",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle config without params property", () => {
|
||||
const mockProvider = vi.fn().mockImplementation((options) => ({
|
||||
description: { title: "provider-without-params" },
|
||||
options,
|
||||
})) as any;
|
||||
|
||||
mockedContextProviderClassFromName.mockReturnValue(mockProvider);
|
||||
|
||||
const config = [
|
||||
{
|
||||
provider: "provider-without-params",
|
||||
name: "minimal-provider",
|
||||
} as any, // Cast to bypass type checking for test
|
||||
];
|
||||
|
||||
const result = loadConfigContextProviders(config, false, "vscode");
|
||||
|
||||
expect(result.errors).toEqual([]);
|
||||
expect(mockProvider).toHaveBeenCalledWith({
|
||||
name: "minimal-provider",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("error handling", () => {
|
||||
it("should add error for unknown provider", () => {
|
||||
mockedContextProviderClassFromName.mockReturnValue(undefined);
|
||||
|
||||
const config = [
|
||||
{
|
||||
provider: "unknown-provider",
|
||||
name: "test-provider",
|
||||
params: {},
|
||||
},
|
||||
];
|
||||
|
||||
const result = loadConfigContextProviders(config, false, "vscode");
|
||||
|
||||
expect(result.errors).toEqual([
|
||||
{
|
||||
fatal: false,
|
||||
message: "Unknown context provider unknown-provider",
|
||||
},
|
||||
]);
|
||||
|
||||
// Should still have default providers
|
||||
expect(result.providers).toHaveLength(6);
|
||||
expect(mockedContextProviderClassFromName).toHaveBeenCalledWith(
|
||||
"unknown-provider",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle multiple unknown providers", () => {
|
||||
mockedContextProviderClassFromName.mockReturnValue(undefined);
|
||||
|
||||
const config = [
|
||||
{
|
||||
provider: "unknown-1",
|
||||
name: "test-1",
|
||||
params: {},
|
||||
},
|
||||
{
|
||||
provider: "unknown-2",
|
||||
name: "test-2",
|
||||
params: {},
|
||||
},
|
||||
];
|
||||
|
||||
const result = loadConfigContextProviders(config, false, "vscode");
|
||||
|
||||
expect(result.errors).toEqual([
|
||||
{
|
||||
fatal: false,
|
||||
message: "Unknown context provider unknown-1",
|
||||
},
|
||||
{
|
||||
fatal: false,
|
||||
message: "Unknown context provider unknown-2",
|
||||
},
|
||||
]);
|
||||
|
||||
expect(result.providers).toHaveLength(6); // Only defaults
|
||||
});
|
||||
|
||||
it("should handle mix of valid and invalid providers", () => {
|
||||
const mockValidProvider = vi.fn().mockImplementation((options) => ({
|
||||
description: { title: "valid-provider" },
|
||||
options,
|
||||
})) as any;
|
||||
|
||||
mockedContextProviderClassFromName
|
||||
.mockReturnValueOnce(mockValidProvider)
|
||||
.mockReturnValueOnce(undefined);
|
||||
|
||||
const config = [
|
||||
{
|
||||
provider: "valid-provider",
|
||||
name: "valid",
|
||||
params: { key: "value" },
|
||||
},
|
||||
{
|
||||
provider: "invalid-provider",
|
||||
name: "invalid",
|
||||
params: {},
|
||||
},
|
||||
];
|
||||
|
||||
const result = loadConfigContextProviders(config, false, "vscode");
|
||||
|
||||
expect(result.errors).toEqual([
|
||||
{
|
||||
fatal: false,
|
||||
message: "Unknown context provider invalid-provider",
|
||||
},
|
||||
]);
|
||||
|
||||
// Should have valid provider + defaults
|
||||
expect(result.providers).toHaveLength(7);
|
||||
expect(mockValidProvider).toHaveBeenCalledWith({
|
||||
name: "valid",
|
||||
key: "value",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("default provider merging", () => {
|
||||
it("should not duplicate providers when config matches defaults", () => {
|
||||
// Mock FileContextProvider to be returned by contextProviderClassFromName
|
||||
mockedContextProviderClassFromName.mockReturnValue(FileContextProvider);
|
||||
|
||||
const config = [
|
||||
{
|
||||
provider: "file",
|
||||
name: "custom-file-provider",
|
||||
params: { maxFiles: 100 },
|
||||
},
|
||||
];
|
||||
|
||||
const result = loadConfigContextProviders(config, false, "vscode");
|
||||
|
||||
expect(result.errors).toEqual([]);
|
||||
|
||||
// Should have configured file provider + other defaults (not duplicate file)
|
||||
expect(result.providers).toHaveLength(6);
|
||||
|
||||
const fileProviders = result.providers.filter(
|
||||
(p) => p.description.title === "file",
|
||||
);
|
||||
expect(fileProviders).toHaveLength(1);
|
||||
|
||||
// The configured one should be used (with custom params)
|
||||
expect(FileContextProvider).toHaveBeenCalledWith({
|
||||
name: "custom-file-provider",
|
||||
maxFiles: 100,
|
||||
});
|
||||
});
|
||||
|
||||
it("should add default providers not present in config", () => {
|
||||
const mockCustomProvider = vi.fn().mockImplementation((options) => ({
|
||||
description: { title: "custom-only" },
|
||||
options,
|
||||
})) as any;
|
||||
|
||||
mockedContextProviderClassFromName.mockReturnValue(mockCustomProvider);
|
||||
|
||||
const config = [
|
||||
{
|
||||
provider: "custom-only",
|
||||
name: "custom",
|
||||
params: {},
|
||||
},
|
||||
];
|
||||
|
||||
const result = loadConfigContextProviders(config, false, "vscode");
|
||||
|
||||
expect(result.errors).toEqual([]);
|
||||
expect(result.providers).toHaveLength(7); // 1 custom + 6 defaults
|
||||
|
||||
// All defaults should be present
|
||||
const providerTitles = result.providers.map((p) => p.description.title);
|
||||
expect(providerTitles).toEqual(
|
||||
expect.arrayContaining([
|
||||
"custom-only",
|
||||
"file",
|
||||
"current-file",
|
||||
"diff",
|
||||
"terminal",
|
||||
"problems",
|
||||
"rules",
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("should preserve order with configured providers first", () => {
|
||||
const mockProvider = vi.fn().mockImplementation((options) => ({
|
||||
description: { title: "custom-provider" },
|
||||
options,
|
||||
})) as any;
|
||||
|
||||
mockedContextProviderClassFromName.mockReturnValue(mockProvider);
|
||||
|
||||
const config = [
|
||||
{
|
||||
provider: "custom-provider",
|
||||
name: "custom",
|
||||
params: {},
|
||||
},
|
||||
];
|
||||
|
||||
const result = loadConfigContextProviders(config, false, "vscode");
|
||||
|
||||
expect(result.providers[0].description.title).toBe("custom-provider");
|
||||
|
||||
// Rest should be defaults in their original order
|
||||
const defaultTitles = result.providers
|
||||
.slice(1)
|
||||
.map((p) => p.description.title);
|
||||
expect(defaultTitles).toEqual([
|
||||
"file",
|
||||
"current-file",
|
||||
"diff",
|
||||
"terminal",
|
||||
"problems",
|
||||
"rules",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("edge cases", () => {
|
||||
it("should handle provider constructor throwing error", () => {
|
||||
const mockProvider = vi.fn().mockImplementation(() => {
|
||||
throw new Error("Provider construction failed");
|
||||
}) as any;
|
||||
|
||||
mockedContextProviderClassFromName.mockReturnValue(mockProvider);
|
||||
|
||||
const config = [
|
||||
{
|
||||
provider: "failing-provider",
|
||||
name: "failing",
|
||||
params: {},
|
||||
},
|
||||
];
|
||||
|
||||
expect(() => loadConfigContextProviders(config, false, "vscode")).toThrow(
|
||||
"Provider construction failed",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle null provider class", () => {
|
||||
mockedContextProviderClassFromName.mockReturnValue(undefined);
|
||||
|
||||
const config = [
|
||||
{
|
||||
provider: "null-provider",
|
||||
name: "null",
|
||||
params: {},
|
||||
},
|
||||
];
|
||||
|
||||
const result = loadConfigContextProviders(config, false, "vscode");
|
||||
|
||||
expect(result.errors).toEqual([
|
||||
{
|
||||
fatal: false,
|
||||
message: "Unknown context provider null-provider",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle provider with same title as default but different implementation", () => {
|
||||
// Mock a provider with same title as a default
|
||||
const mockFileProvider = vi.fn().mockImplementation((options) => ({
|
||||
description: { title: "file" }, // Same title as FileContextProvider
|
||||
options,
|
||||
customProperty: "custom-implementation",
|
||||
})) as any;
|
||||
|
||||
mockedContextProviderClassFromName.mockReturnValue(mockFileProvider);
|
||||
|
||||
const config = [
|
||||
{
|
||||
provider: "custom-file",
|
||||
name: "my-file-provider",
|
||||
params: { customParam: "value" },
|
||||
},
|
||||
];
|
||||
|
||||
const result = loadConfigContextProviders(config, false, "vscode");
|
||||
|
||||
expect(result.errors).toEqual([]);
|
||||
|
||||
// Should not duplicate - custom implementation should be used
|
||||
const fileProviders = result.providers.filter(
|
||||
(p) => p.description.title === "file",
|
||||
);
|
||||
expect(fileProviders).toHaveLength(1);
|
||||
|
||||
const fileProvider = fileProviders[0] as any;
|
||||
expect(fileProvider.customProperty).toBe("custom-implementation");
|
||||
expect(fileProvider.options).toEqual({
|
||||
name: "my-file-provider",
|
||||
customParam: "value",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("provider instantiation", () => {
|
||||
it("should call default provider constructors with empty options", () => {
|
||||
loadConfigContextProviders([], false, "vscode");
|
||||
|
||||
expect(FileContextProvider).toHaveBeenCalledWith({});
|
||||
expect(CurrentFileContextProvider).toHaveBeenCalledWith({});
|
||||
expect(DiffContextProvider).toHaveBeenCalledWith({});
|
||||
expect(TerminalContextProvider).toHaveBeenCalledWith({});
|
||||
expect(ProblemsContextProvider).toHaveBeenCalledWith({});
|
||||
expect(RulesContextProvider).toHaveBeenCalledWith({});
|
||||
});
|
||||
|
||||
it("should call provider constructors exactly once per provider", () => {
|
||||
loadConfigContextProviders([], false, "vscode");
|
||||
|
||||
expect(FileContextProvider).toHaveBeenCalledTimes(1);
|
||||
expect(CurrentFileContextProvider).toHaveBeenCalledTimes(1);
|
||||
expect(DiffContextProvider).toHaveBeenCalledTimes(1);
|
||||
expect(TerminalContextProvider).toHaveBeenCalledTimes(1);
|
||||
expect(ProblemsContextProvider).toHaveBeenCalledTimes(1);
|
||||
expect(RulesContextProvider).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
|
@ -10,16 +10,16 @@ import { getGlobalFolderWithName } from "../util/paths";
|
|||
import { localPathToUri } from "../util/pathToUri";
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
|
||||
export const ASSISTANTS = "assistants";
|
||||
export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`;
|
||||
|
||||
export function isLocalDefinitionFile(uri: string): boolean {
|
||||
if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const normalizedUri = URI.normalize(uri);
|
||||
return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`);
|
||||
return (
|
||||
normalizedUri.includes(`/.continue/agents/`) ||
|
||||
normalizedUri.includes(`/.continue/assistants/`)
|
||||
);
|
||||
}
|
||||
|
||||
async function getDefinitionFilesInDir(
|
||||
|
|
@ -35,7 +35,11 @@ async function getDefinitionFilesInDir(
|
|||
}
|
||||
|
||||
const overrideDefaultIgnores = ignore()
|
||||
.add(DEFAULT_IGNORE_FILETYPES.filter((t) => t !== "config.yaml"))
|
||||
.add(
|
||||
DEFAULT_IGNORE_FILETYPES.filter(
|
||||
(t) => t !== "config.yaml" && t !== "config.yml",
|
||||
),
|
||||
)
|
||||
.add(DEFAULT_IGNORE_DIRS);
|
||||
|
||||
const uris = await walkDir(dir, ide, {
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import {
|
|||
getAllDotContinueDefinitionFiles,
|
||||
LoadAssistantFilesOptions,
|
||||
} from "./loadLocalAssistants";
|
||||
describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
|
||||
describe("ASSISTANTS getAllDotContinueDefinitionFiles with fileExtType option", () => {
|
||||
beforeEach(() => {
|
||||
setUpTestDir();
|
||||
walkDirCache.invalidate();
|
||||
|
|
@ -18,6 +18,8 @@ describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
|
|||
[".continue/assistants/assistant2.yml", "yaml content 2"],
|
||||
[".continue/assistants/assistant3.md", "markdown content 1"],
|
||||
[".continue/assistants/assistant4.txt", "txt content"],
|
||||
[".continue/assistants/config.yaml", "txt content"],
|
||||
[".continue/assistants/config.yml", "txt content"],
|
||||
]);
|
||||
});
|
||||
|
||||
|
|
@ -38,9 +40,14 @@ describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
|
|||
options,
|
||||
"assistants",
|
||||
);
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result).toHaveLength(4);
|
||||
expect(result.map((f) => f.path.split("/").pop())).toEqual(
|
||||
expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
|
||||
expect.arrayContaining([
|
||||
"assistant1.yaml",
|
||||
"assistant2.yml",
|
||||
"config.yaml",
|
||||
"config.yml",
|
||||
]),
|
||||
);
|
||||
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
|
||||
"assistant3.md",
|
||||
|
|
@ -69,6 +76,12 @@ describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
|
|||
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
|
||||
"assistant2.yml",
|
||||
);
|
||||
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
|
||||
"config.yml",
|
||||
);
|
||||
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
|
||||
"config.yaml",
|
||||
);
|
||||
});
|
||||
|
||||
it("should return all supported files when fileExtType is not specified", async () => {
|
||||
|
|
@ -83,11 +96,13 @@ describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
|
|||
options,
|
||||
"assistants",
|
||||
);
|
||||
expect(result).toHaveLength(3);
|
||||
expect(result).toHaveLength(5);
|
||||
expect(result.map((f) => f.path.split("/").pop())).toEqual(
|
||||
expect.arrayContaining([
|
||||
"assistant1.yaml",
|
||||
"assistant2.yml",
|
||||
"config.yml",
|
||||
"config.yaml",
|
||||
"assistant3.md",
|
||||
]),
|
||||
);
|
||||
|
|
@ -124,9 +139,14 @@ describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
|
|||
workspaceOnOptions,
|
||||
"assistants",
|
||||
);
|
||||
expect(workspaceResult).toHaveLength(2);
|
||||
expect(workspaceResult).toHaveLength(4);
|
||||
expect(workspaceResult.map((f) => f.path.split("/").pop())).toEqual(
|
||||
expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
|
||||
expect.arrayContaining([
|
||||
"assistant1.yaml",
|
||||
"assistant2.yml",
|
||||
"config.yaml",
|
||||
"config.yml",
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -187,7 +207,7 @@ describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
|
|||
options,
|
||||
"assistants",
|
||||
);
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result).toHaveLength(4);
|
||||
const yamlFile = result.find((f) => f.path.includes("assistant1.yaml"));
|
||||
expect(yamlFile?.content).toBe("yaml content 1");
|
||||
});
|
||||
|
|
@ -212,9 +232,14 @@ describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
|
|||
"assistants",
|
||||
);
|
||||
// Should only get lowercase extensions (current implementation)
|
||||
expect(yamlResult).toHaveLength(2);
|
||||
expect(yamlResult).toHaveLength(4);
|
||||
expect(yamlResult.map((f) => f.path.split("/").pop())).toEqual(
|
||||
expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
|
||||
expect.arrayContaining([
|
||||
"assistant1.yaml",
|
||||
"assistant2.yml",
|
||||
"config.yaml",
|
||||
"config.yml",
|
||||
]),
|
||||
);
|
||||
expect(yamlResult.map((f) => f.path.split("/").pop())).not.toContain(
|
||||
"assistant5.YAML",
|
||||
|
|
@ -240,3 +265,232 @@ describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
|
|||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("AGENTS getAllDotContinueDefinitionFiles with fileExtType option", () => {
|
||||
beforeEach(() => {
|
||||
setUpTestDir();
|
||||
walkDirCache.invalidate();
|
||||
|
||||
// Add test files to the test directory
|
||||
addToTestDir([
|
||||
".continue/agents/",
|
||||
[".continue/agents/agent1.yaml", "yaml content 1"],
|
||||
[".continue/agents/agent2.yml", "yaml content 2"],
|
||||
[".continue/agents/agent3.md", "markdown content 1"],
|
||||
[".continue/agents/agent4.txt", "txt content"],
|
||||
]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
tearDownTestDir();
|
||||
walkDirCache.invalidate();
|
||||
});
|
||||
|
||||
it("should return only YAML files when fileExtType is 'yaml'", async () => {
|
||||
const options: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false, // Only test workspace for simplicity
|
||||
includeWorkspace: true,
|
||||
fileExtType: "yaml",
|
||||
};
|
||||
|
||||
const result = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
options,
|
||||
"agents",
|
||||
);
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result.map((f) => f.path.split("/").pop())).toEqual(
|
||||
expect.arrayContaining(["agent1.yaml", "agent2.yml"]),
|
||||
);
|
||||
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
|
||||
"agent3.md",
|
||||
);
|
||||
});
|
||||
|
||||
it("should return only Markdown files when fileExtType is 'markdown'", async () => {
|
||||
const options: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
fileExtType: "markdown",
|
||||
};
|
||||
|
||||
const result = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
options,
|
||||
"agents",
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result.map((f) => f.path.split("/").pop())).toEqual(["agent3.md"]);
|
||||
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
|
||||
"agent1.yaml",
|
||||
);
|
||||
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
|
||||
"agent2.yml",
|
||||
);
|
||||
});
|
||||
|
||||
it("should return all supported files when fileExtType is not specified", async () => {
|
||||
const options: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
// fileExtType not specified
|
||||
};
|
||||
|
||||
const result = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
options,
|
||||
"agents",
|
||||
);
|
||||
expect(result).toHaveLength(3);
|
||||
expect(result.map((f) => f.path.split("/").pop())).toEqual(
|
||||
expect.arrayContaining(["agent1.yaml", "agent2.yml", "agent3.md"]),
|
||||
);
|
||||
// Should not include .txt files
|
||||
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
|
||||
"agent4.txt",
|
||||
);
|
||||
});
|
||||
|
||||
it("should respect includeWorkspace option with fileExtType", async () => {
|
||||
// Test with includeWorkspace: false
|
||||
const workspaceOffOptions: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false,
|
||||
includeWorkspace: false,
|
||||
fileExtType: "yaml",
|
||||
};
|
||||
|
||||
const noWorkspaceResult = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
workspaceOffOptions,
|
||||
"agents",
|
||||
);
|
||||
expect(noWorkspaceResult).toHaveLength(0);
|
||||
|
||||
// Test with includeWorkspace: true
|
||||
const workspaceOnOptions: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
fileExtType: "yaml",
|
||||
};
|
||||
|
||||
const workspaceResult = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
workspaceOnOptions,
|
||||
"agents",
|
||||
);
|
||||
expect(workspaceResult).toHaveLength(2);
|
||||
expect(workspaceResult.map((f) => f.path.split("/").pop())).toEqual(
|
||||
expect.arrayContaining(["agent1.yaml", "agent2.yml"]),
|
||||
);
|
||||
});
|
||||
|
||||
it("should return empty array when no files match the specified extension type", async () => {
|
||||
// Create a test directory with only non-matching files
|
||||
tearDownTestDir();
|
||||
walkDirCache.invalidate();
|
||||
setUpTestDir();
|
||||
addToTestDir([
|
||||
".continue/agents/",
|
||||
[".continue/agents/nonmatch1.txt", "txt content"],
|
||||
[".continue/agents/nonmatch2.json", "json content"],
|
||||
]);
|
||||
|
||||
const options: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
|
||||
fileExtType: "yaml",
|
||||
};
|
||||
|
||||
const result = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
options,
|
||||
"agents",
|
||||
);
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("should handle directories that don't exist", async () => {
|
||||
// Create a clean test directory without the agents folder
|
||||
tearDownTestDir();
|
||||
setUpTestDir();
|
||||
|
||||
const options: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
fileExtType: "yaml",
|
||||
};
|
||||
|
||||
const result = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
options,
|
||||
"agents",
|
||||
);
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("should return correct file content", async () => {
|
||||
const options: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
fileExtType: "yaml",
|
||||
};
|
||||
|
||||
const result = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
options,
|
||||
"agents",
|
||||
);
|
||||
expect(result).toHaveLength(2);
|
||||
const yamlFile = result.find((f) => f.path.includes("agent1.yaml"));
|
||||
expect(yamlFile?.content).toBe("yaml content 1");
|
||||
});
|
||||
|
||||
it("should filter by file extension case sensitively", async () => {
|
||||
// Add files with uppercase extensions
|
||||
addToTestDir([
|
||||
[".continue/agents/agent5.YAML", "uppercase yaml"],
|
||||
[".continue/agents/agent6.YML", "uppercase yml"],
|
||||
[".continue/agents/agent7.MD", "uppercase md"],
|
||||
]);
|
||||
|
||||
const yamlOptions: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
fileExtType: "yaml",
|
||||
};
|
||||
|
||||
const yamlResult = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
yamlOptions,
|
||||
"agents",
|
||||
);
|
||||
// Should only get lowercase extensions (current implementation)
|
||||
expect(yamlResult).toHaveLength(2);
|
||||
expect(yamlResult.map((f) => f.path.split("/").pop())).toEqual(
|
||||
expect.arrayContaining(["agent1.yaml", "agent2.yml"]),
|
||||
);
|
||||
expect(yamlResult.map((f) => f.path.split("/").pop())).not.toContain(
|
||||
"agent5.YAML",
|
||||
);
|
||||
|
||||
const markdownOptions: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
fileExtType: "markdown",
|
||||
};
|
||||
|
||||
const markdownResult = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
markdownOptions,
|
||||
"agents",
|
||||
);
|
||||
expect(markdownResult).toHaveLength(1);
|
||||
expect(markdownResult.map((f) => f.path.split("/").pop())).toEqual([
|
||||
"agent3.md",
|
||||
]);
|
||||
expect(markdownResult.map((f) => f.path.split("/").pop())).not.toContain(
|
||||
"agent7.MD",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ export default class LocalProfileLoader implements IProfileLoader {
|
|||
iconUrl: "",
|
||||
title: overrideAssistantFile?.path
|
||||
? getUriPathBasename(overrideAssistantFile.path)
|
||||
: "Local Assistant",
|
||||
: "Local Agent",
|
||||
errors: undefined,
|
||||
uri:
|
||||
overrideAssistantFile?.path ??
|
||||
|
|
@ -48,7 +48,7 @@ export default class LocalProfileLoader implements IProfileLoader {
|
|||
);
|
||||
this.description.title = parsedAssistant.name;
|
||||
} catch (e) {
|
||||
console.error("Failed to parse assistant file: ", e);
|
||||
console.error("Failed to parse agent file: ", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,9 +20,8 @@ import {
|
|||
} from "../../";
|
||||
import { stringifyMcpPrompt } from "../../commands/slash/mcpSlashCommand";
|
||||
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
|
||||
import CurrentFileContextProvider from "../../context/providers/CurrentFileContextProvider";
|
||||
import ContinueProxyContextProvider from "../../context/providers/ContinueProxyContextProvider";
|
||||
import MCPContextProvider from "../../context/providers/MCPContextProvider";
|
||||
import RulesContextProvider from "../../context/providers/RulesContextProvider";
|
||||
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { getControlPlaneEnv } from "../../control-plane/env.js";
|
||||
|
|
@ -98,6 +97,7 @@ export default async function doLoadConfig(options: {
|
|||
const uniqueId = await ide.getUniqueId();
|
||||
const ideSettings = await ideSettingsPromise;
|
||||
const workOsAccessToken = await controlPlaneClient.getAccessToken();
|
||||
const isSignedIn = await controlPlaneClient.isSignedIn();
|
||||
|
||||
// Migrations for old config files
|
||||
// Removes
|
||||
|
|
@ -157,17 +157,13 @@ export default async function doLoadConfig(options: {
|
|||
const { rules, errors: rulesErrors } = await loadRules(ide);
|
||||
errors.push(...rulesErrors);
|
||||
newConfig.rules.unshift(...rules);
|
||||
newConfig.contextProviders.push(new RulesContextProvider({}));
|
||||
|
||||
// Add current file as context if setting is enabled
|
||||
if (
|
||||
newConfig.experimental?.useCurrentFileAsContext === true &&
|
||||
!newConfig.contextProviders.find(
|
||||
(c) =>
|
||||
c.description.title === CurrentFileContextProvider.description.title,
|
||||
)
|
||||
) {
|
||||
newConfig.contextProviders.push(new CurrentFileContextProvider({}));
|
||||
const proxyContextProvider = newConfig.contextProviders?.find(
|
||||
(cp) => cp.description.title === "continue-proxy",
|
||||
);
|
||||
if (proxyContextProvider) {
|
||||
(proxyContextProvider as ContinueProxyContextProvider).workOsAccessToken =
|
||||
workOsAccessToken;
|
||||
}
|
||||
|
||||
// Show deprecation warnings for providers
|
||||
|
|
@ -285,6 +281,9 @@ export default async function doLoadConfig(options: {
|
|||
rules: newConfig.rules,
|
||||
enableExperimentalTools:
|
||||
newConfig.experimental?.enableExperimentalTools ?? false,
|
||||
isSignedIn,
|
||||
isRemote: await ide.isWorkspaceRemote(),
|
||||
modelName: newConfig.selectedModelByRole.chat?.model,
|
||||
}),
|
||||
);
|
||||
|
||||
|
|
@ -333,12 +332,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(
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ export const sharedConfigSchema = z
|
|||
displayRawMarkdown: z.boolean(),
|
||||
showChatScrollbar: z.boolean(),
|
||||
autoAcceptEditToolDiffs: z.boolean(),
|
||||
continueAfterToolRejection: z.boolean(),
|
||||
|
||||
// `tabAutocompleteOptions` in `ContinueConfig`
|
||||
useAutocompleteCache: z.boolean(),
|
||||
|
|
@ -158,6 +159,11 @@ export function modifyAnyConfigWithSharedConfig<
|
|||
configCopy.ui.showSessionTabs = sharedConfig.showSessionTabs;
|
||||
}
|
||||
|
||||
if (sharedConfig.continueAfterToolRejection !== undefined) {
|
||||
configCopy.ui.continueAfterToolRejection =
|
||||
sharedConfig.continueAfterToolRejection;
|
||||
}
|
||||
|
||||
configCopy.experimental = {
|
||||
...configCopy.experimental,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,31 +0,0 @@
|
|||
import { ModelDescription } from "../index.d";
|
||||
|
||||
/**
|
||||
* Determines if system message tools should be auto-enabled for the given model.
|
||||
* This is used to automatically enable system message tools for certain provider/model combinations
|
||||
* where we have a strong preference, taking priority over user manual settings.
|
||||
*
|
||||
* System message tools are an alternative to native tool calling where tool definitions and calls
|
||||
* are embedded in the system message as text rather than using the provider's native tool calling API.
|
||||
* This can be beneficial for providers/models that don't support native tool calling or have
|
||||
* poor tool calling performance.
|
||||
*
|
||||
* Current auto-enable rules:
|
||||
* - OpenRouter provider: true for all models except those containing "claude" (since Claude models
|
||||
* generally have good native tool calling support)
|
||||
* - All other providers: undefined (no auto-preference, use manual setting)
|
||||
*
|
||||
* @param model The model description to check
|
||||
* @returns true to force enable, false to force disable, undefined for no auto-preference
|
||||
*/
|
||||
export function shouldAutoEnableSystemMessageTools(
|
||||
model: ModelDescription,
|
||||
): boolean | undefined {
|
||||
// Auto-enable for OpenRouter, but exclude Claude models which have good native tool calling
|
||||
if (model.provider === "openrouter") {
|
||||
return !model.model.toLowerCase().includes("claude");
|
||||
}
|
||||
|
||||
// No auto-preference for all other providers - use manual setting
|
||||
return undefined;
|
||||
}
|
||||
|
|
@ -1,85 +0,0 @@
|
|||
import { describe, expect, test } from "vitest";
|
||||
import { ModelDescription } from "../index.d";
|
||||
import { shouldAutoEnableSystemMessageTools } from "./shouldAutoEnableSystemMessageTools";
|
||||
|
||||
describe("shouldAutoEnableSystemMessageTools", () => {
|
||||
const createModel = (provider: string, model: string): ModelDescription => ({
|
||||
title: "Test Model",
|
||||
provider,
|
||||
underlyingProviderName: provider,
|
||||
model,
|
||||
});
|
||||
|
||||
test("should return true for OpenRouter models that don't contain 'claude'", () => {
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(createModel("openrouter", "gpt-4o")),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "llama-3.3-70b-instruct"),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "qwen/qwen-2.5-72b-instruct"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("should return false for OpenRouter Claude models", () => {
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "anthropic/claude-3-sonnet"),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "anthropic/claude-3.5-sonnet"),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "claude-3-haiku"),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("should return undefined for all other providers", () => {
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(createModel("openai", "gpt-4o")),
|
||||
).toBe(undefined);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("anthropic", "claude-3.5-sonnet"),
|
||||
),
|
||||
).toBe(undefined);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("groq", "llama-3.3-70b-versatile"),
|
||||
),
|
||||
).toBe(undefined);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("together", "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo"),
|
||||
),
|
||||
).toBe(undefined);
|
||||
});
|
||||
|
||||
test("should be case insensitive for 'claude' detection", () => {
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "CLAUDE-models"),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "Claude-3.5"),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "some-model-Claude"),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
@ -4,7 +4,7 @@ import { AssistantUnrolled } from "@continuedev/config-yaml";
|
|||
export const defaultConfigYaml: AssistantUnrolled = {
|
||||
models: [],
|
||||
context: [],
|
||||
name: "Local Assistant",
|
||||
name: "Local Agent",
|
||||
version: "1.0.0",
|
||||
schema: "v1",
|
||||
};
|
||||
|
|
@ -12,7 +12,7 @@ export const defaultConfigYaml: AssistantUnrolled = {
|
|||
export const defaultConfigYamlJetBrains: AssistantUnrolled = {
|
||||
models: [],
|
||||
context: [],
|
||||
name: "Local Assistant",
|
||||
name: "Local Agent",
|
||||
version: "1.0.0",
|
||||
schema: "v1",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -14,18 +14,8 @@ import {
|
|||
} from "@continuedev/config-yaml";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
import {
|
||||
ContinueConfig,
|
||||
IContextProvider,
|
||||
IDE,
|
||||
IdeInfo,
|
||||
IdeSettings,
|
||||
ILLMLogger,
|
||||
} from "../..";
|
||||
import { ContinueConfig, IDE, IdeInfo, IdeSettings, ILLMLogger } from "../..";
|
||||
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
|
||||
import DocsContextProvider from "../../context/providers/DocsContextProvider";
|
||||
import FileContextProvider from "../../context/providers/FileContextProvider";
|
||||
import { contextProviderClassFromName } from "../../context/providers/index";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
|
||||
import { getAllPromptFiles } from "../../promptFiles/getPromptFiles";
|
||||
|
|
@ -35,8 +25,10 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
|
|||
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
|
||||
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
|
||||
import { getControlPlaneEnvSync } from "../../control-plane/env";
|
||||
import { getToolsForIde } from "../../tools";
|
||||
import { PolicySingleton } from "../../control-plane/PolicySingleton";
|
||||
import { getBaseToolDefinitions } from "../../tools";
|
||||
import { getCleanUriPath } from "../../util/uri";
|
||||
import { loadConfigContextProviders } from "../loadContextProviders";
|
||||
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
|
||||
import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks";
|
||||
import { LocalPlatformClient } from "./LocalPlatformClient";
|
||||
|
|
@ -177,7 +169,7 @@ async function configYamlToContinueConfig(options: {
|
|||
|
||||
const continueConfig: ContinueConfig = {
|
||||
slashCommands: [],
|
||||
tools: await getToolsForIde(ide),
|
||||
tools: getBaseToolDefinitions(),
|
||||
mcpServerStatuses: [],
|
||||
contextProviders: [],
|
||||
modelsByRole: {
|
||||
|
|
@ -376,60 +368,37 @@ async function configYamlToContinueConfig(options: {
|
|||
});
|
||||
}
|
||||
|
||||
// Context providers
|
||||
const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})];
|
||||
|
||||
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
|
||||
({ description: { title } }) => title,
|
||||
const { providers, errors: contextErrors } = loadConfigContextProviders(
|
||||
config.context,
|
||||
!!config.docs?.length,
|
||||
ideInfo.ideType,
|
||||
);
|
||||
|
||||
continueConfig.contextProviders = (config.context
|
||||
?.map((context) => {
|
||||
const cls = contextProviderClassFromName(context.provider) as any;
|
||||
if (!cls) {
|
||||
if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(context.provider)) {
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `Unknown context provider ${context.provider}`,
|
||||
});
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
const instance: IContextProvider = new cls({
|
||||
name: context.name,
|
||||
...context.params,
|
||||
});
|
||||
return instance;
|
||||
})
|
||||
.filter((p) => !!p) ?? []) as IContextProvider[];
|
||||
continueConfig.contextProviders.push(...DEFAULT_CONTEXT_PROVIDERS);
|
||||
|
||||
if (
|
||||
continueConfig.docs?.length &&
|
||||
!continueConfig.contextProviders?.some(
|
||||
(cp) => cp.description.title === "docs",
|
||||
)
|
||||
) {
|
||||
continueConfig.contextProviders.push(new DocsContextProvider({}));
|
||||
}
|
||||
continueConfig.contextProviders = providers;
|
||||
localErrors.push(...contextErrors);
|
||||
|
||||
// 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: [],
|
||||
...(server as any), // TODO: fix the types on mcpServers in config-yaml
|
||||
},
|
||||
timeout: server.connectionTimeout,
|
||||
})),
|
||||
false,
|
||||
{ ide },
|
||||
);
|
||||
}
|
||||
|
||||
return { config: continueConfig, errors: localErrors };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,14 +1,14 @@
|
|||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
validateConfigYaml,
|
||||
AssistantUnrolledNonNullable,
|
||||
validateConfigYaml,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
describe("MCP Server cwd configuration", () => {
|
||||
describe("YAML schema validation", () => {
|
||||
it("should accept valid MCP server with cwd", () => {
|
||||
const config: AssistantUnrolledNonNullable = {
|
||||
name: "test-assistant",
|
||||
name: "test-agent",
|
||||
version: "1.0.0",
|
||||
mcpServers: [
|
||||
{
|
||||
|
|
@ -28,7 +28,7 @@ describe("MCP Server cwd configuration", () => {
|
|||
|
||||
it("should accept MCP server without cwd", () => {
|
||||
const config: AssistantUnrolledNonNullable = {
|
||||
name: "test-assistant",
|
||||
name: "test-agent",
|
||||
version: "1.0.0",
|
||||
mcpServers: [
|
||||
{
|
||||
|
|
@ -45,7 +45,7 @@ describe("MCP Server cwd configuration", () => {
|
|||
|
||||
it("should accept relative paths in cwd", () => {
|
||||
const config: AssistantUnrolledNonNullable = {
|
||||
name: "test-assistant",
|
||||
name: "test-agent",
|
||||
version: "1.0.0",
|
||||
mcpServers: [
|
||||
{
|
||||
|
|
@ -63,7 +63,7 @@ describe("MCP Server cwd configuration", () => {
|
|||
|
||||
it("should accept empty string cwd", () => {
|
||||
const config: AssistantUnrolledNonNullable = {
|
||||
name: "test-assistant",
|
||||
name: "test-agent",
|
||||
version: "1.0.0",
|
||||
mcpServers: [
|
||||
{
|
||||
|
|
@ -115,7 +115,7 @@ describe("MCP Server cwd configuration", () => {
|
|||
|
||||
configs.forEach(({ name, server }) => {
|
||||
const config: AssistantUnrolledNonNullable = {
|
||||
name: "test-assistant",
|
||||
name: "test-agent",
|
||||
version: "1.0.0",
|
||||
mcpServers: [server],
|
||||
};
|
||||
|
|
|
|||
|
|
@ -32,12 +32,14 @@ async function modelConfigToBaseLLM({
|
|||
ideSettings,
|
||||
llmLogger,
|
||||
config,
|
||||
isFromAutoDetect,
|
||||
}: {
|
||||
model: ModelConfig;
|
||||
uniqueId: string;
|
||||
ideSettings: IdeSettings;
|
||||
llmLogger: ILLMLogger;
|
||||
config: ContinueConfig;
|
||||
isFromAutoDetect?: boolean;
|
||||
}): Promise<BaseLLM | undefined> {
|
||||
const cls = getModelClass(model);
|
||||
|
||||
|
|
@ -71,6 +73,7 @@ async function modelConfigToBaseLLM({
|
|||
nextEdit: model.capabilities?.includes("next_edit"),
|
||||
},
|
||||
autocompleteOptions: model.autocompleteOptions,
|
||||
isFromAutoDetect,
|
||||
};
|
||||
|
||||
// Model capabilities - need to be undefined if not found
|
||||
|
|
@ -173,7 +176,6 @@ async function autodetectModels({
|
|||
if (modelName === AUTODETECT) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return await modelConfigToBaseLLM({
|
||||
model: {
|
||||
...model,
|
||||
|
|
@ -184,6 +186,7 @@ async function autodetectModels({
|
|||
ideSettings,
|
||||
llmLogger,
|
||||
config,
|
||||
isFromAutoDetect: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
@ -393,6 +392,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 +408,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}`,
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -1,68 +0,0 @@
|
|||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
const HIGHLIGHTS_TOKEN_BUDGET = 2000;
|
||||
|
||||
class CodeHighlightsContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "highlights",
|
||||
displayTitle: "Highlights",
|
||||
description: "Code highlights from open files",
|
||||
type: "normal",
|
||||
renderInlineAs: "",
|
||||
};
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
// const { getHighlightsThatFit } = await import(
|
||||
// "llm-code-highlighter/src/index.continue.js"
|
||||
// );
|
||||
const ide = extras.ide;
|
||||
const openFiles = await ide.getOpenFiles();
|
||||
// const allFiles: { name: string; absPath: string; content: string }[] =
|
||||
// await Promise.all(
|
||||
// openFiles.map(async (filepath: string) => {
|
||||
// return {
|
||||
// name: getBasename(filepath),
|
||||
// absPath: filepath,
|
||||
// content: `${await ide.readFile(filepath)}`,
|
||||
// };
|
||||
// }),
|
||||
// );
|
||||
// const contextSizer = {
|
||||
// fits(content: string): boolean {
|
||||
// return countTokens(content, "") < HIGHLIGHTS_TOKEN_BUDGET;
|
||||
// },
|
||||
// };
|
||||
// const repoMap = await getHighlightsThatFit(
|
||||
// contextSizer,
|
||||
// [],
|
||||
// allFiles
|
||||
// .filter((file) => file.content.length > 0)
|
||||
// .map((file) => {
|
||||
// return {
|
||||
// relPath: file.name,
|
||||
// code: file.content,
|
||||
// };
|
||||
// }),
|
||||
// );
|
||||
// return [
|
||||
// {
|
||||
// content: repoMap ? repoMap : "",
|
||||
// name: "Code Highlights",
|
||||
// description: "Code highlights from open files",
|
||||
// },
|
||||
// ];
|
||||
return [];
|
||||
}
|
||||
|
||||
async load(): Promise<void> {}
|
||||
}
|
||||
|
||||
export default CodeHighlightsContextProvider;
|
||||
|
|
@ -1,56 +0,0 @@
|
|||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
class CodeOutlineContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "outline",
|
||||
displayTitle: "Outline",
|
||||
description: "Definition lines only (from open files)",
|
||||
type: "normal",
|
||||
renderInlineAs: "",
|
||||
};
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const ide = extras.ide;
|
||||
const openFiles = await ide.getOpenFiles();
|
||||
// const allFiles: { name: string; absPath: string; content: string }[] =
|
||||
// await Promise.all(
|
||||
// openFiles.map(async (filepath: string) => {
|
||||
// return {
|
||||
// name: getBasename(filepath),
|
||||
// absPath: filepath,
|
||||
// content: `${await ide.readFile(filepath)}`,
|
||||
// };
|
||||
// }),
|
||||
// );
|
||||
// const outlines = await getOutlines(
|
||||
// allFiles
|
||||
// .filter((file) => file.content.length > 0)
|
||||
// .map((file) => {
|
||||
// return {
|
||||
// relPath: file.name,
|
||||
// code: file.content,
|
||||
// };
|
||||
// })
|
||||
// );
|
||||
// return [
|
||||
// {
|
||||
// content: outlines ? outlines : "",
|
||||
// name: "Code Outline",
|
||||
// description: "Definition lines only (from open files)",
|
||||
// },
|
||||
// ];
|
||||
return [];
|
||||
}
|
||||
|
||||
async load(): Promise<void> {}
|
||||
}
|
||||
|
||||
export default CodeOutlineContextProvider;
|
||||
|
|
@ -13,6 +13,7 @@ class CodebaseContextProvider extends BaseContextProvider {
|
|||
description: "Automatically find relevant files",
|
||||
type: "normal",
|
||||
renderInlineAs: "",
|
||||
dependsOnIndexing: true,
|
||||
};
|
||||
|
||||
async getContextItems(
|
||||
|
|
|
|||
|
|
@ -18,6 +18,10 @@ class DatabaseContextProvider extends BaseContextProvider {
|
|||
renderInlineAs: "",
|
||||
};
|
||||
|
||||
get deprecationMessage() {
|
||||
return "The database context provider is deprecated and may be removed in a later version. Please consider using a database MCP server like postgres-mcp (https://hub.continue.dev/anthropic/postgres-mcp) instead.";
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
|
|
|
|||
|
|
@ -3,8 +3,8 @@ import {
|
|||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
FetchFunction,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../../index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
|
|
@ -43,6 +43,10 @@ class DiscordContextProvider extends BaseContextProvider {
|
|||
return `${this.baseUrl}${path}`;
|
||||
}
|
||||
|
||||
get deprecationMessage() {
|
||||
return "The Discord context provider is now deprecated and may be removed in a later version. Please consider using the Discord MCP (hub.docker.com/r/mcp/mcp-discord) instead.";
|
||||
}
|
||||
|
||||
async fetchMessages(
|
||||
channelId: string,
|
||||
fetch: FetchFunction,
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import {
|
|||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../../";
|
||||
import { isSecurityConcern } from "../../indexing/ignore";
|
||||
import { walkDirs } from "../../indexing/walkDir";
|
||||
import {
|
||||
getShortestUniqueRelativeUriPaths,
|
||||
|
|
|
|||
|
|
@ -44,6 +44,10 @@ class GitCommitContextProvider extends BaseContextProvider {
|
|||
type: "submenu",
|
||||
};
|
||||
|
||||
get deprecationMessage() {
|
||||
return "The git commits context provider is now deprecated and may be removed in a later version. Please consider using the Git MCP (https://hub.continue.dev/docker/mcp-git) instead.";
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
|
|
|
|||
|
|
@ -15,6 +15,10 @@ class GitHubIssuesContextProvider extends BaseContextProvider {
|
|||
type: "submenu",
|
||||
};
|
||||
|
||||
get deprecationMessage() {
|
||||
return "The GitHub issues context provider is now deprecated and will be removed in a later version. Please consider using the GitHub MCP server (https://hub.continue.dev/anthropic/github-mcp) instead.";
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
|
|
|
|||
|
|
@ -76,6 +76,10 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
|
|||
type: "normal",
|
||||
};
|
||||
|
||||
get deprecationMessage() {
|
||||
return "The Gitlab Merge Request context provider is now deprecated and will be removed in a later version. Please consider using the GitLab MCP (https://hub.continue.dev/docker/mcp-gitlab) instead.";
|
||||
}
|
||||
|
||||
private async getApi(): Promise<AxiosInstance> {
|
||||
const { default: Axios } = await import("axios");
|
||||
|
||||
|
|
|
|||
|
|
@ -20,6 +20,10 @@ class GoogleContextProvider extends BaseContextProvider {
|
|||
this._serperApiKey = options.serperApiKey;
|
||||
}
|
||||
|
||||
get deprecationMessage() {
|
||||
return "The Google context provider is now deprecated and will be removed in a later version. Please consider using github.com/jae-jae/g-search-mcp instead.";
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
|
|
|
|||
|
|
@ -17,6 +17,10 @@ class GreptileContextProvider extends BaseContextProvider {
|
|||
type: "query",
|
||||
};
|
||||
|
||||
get deprecationMessage() {
|
||||
return "The Greptile context provider is now deprecated and will be removed in a later version. Please consider viewing their docs at greptile.com/docs/code-review-bot/auto-resolve-with-mcp for resolving greptile queries.";
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
|
|
|
|||
|
|
@ -17,6 +17,10 @@ class JiraIssuesContextProvider extends BaseContextProvider {
|
|||
type: "submenu",
|
||||
};
|
||||
|
||||
get deprecationMessage() {
|
||||
return "The Jira issues context provider is now deprecated and will be removed in a later version. Please consider using the official Atlassian MCP server atlassian.com/platform/remote-mcp-server.";
|
||||
}
|
||||
|
||||
private getApi() {
|
||||
return new JiraClient({
|
||||
domain: this.options.domain,
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import {
|
|||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
import { isSecurityConcern } from "../../indexing/ignore.js";
|
||||
import { getUriDescription } from "../../util/uri.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
|
|
@ -27,10 +28,23 @@ class OpenFilesContextProvider extends BaseContextProvider {
|
|||
|
||||
return await Promise.all(
|
||||
openFiles.map(async (filepath: string) => {
|
||||
const content = await ide.readFile(filepath);
|
||||
const { relativePathOrBasename, last2Parts, baseName } =
|
||||
getUriDescription(filepath, workspaceDirs);
|
||||
|
||||
if (isSecurityConcern(filepath)) {
|
||||
return {
|
||||
description: last2Parts,
|
||||
content:
|
||||
"Content redacted, this file cannot be viewed for security reasons",
|
||||
name: baseName,
|
||||
uri: {
|
||||
type: "file",
|
||||
value: filepath,
|
||||
},
|
||||
};
|
||||
}
|
||||
const content = await ide.readFile(filepath);
|
||||
|
||||
return {
|
||||
description: last2Parts,
|
||||
content: `\`\`\`${relativePathOrBasename}\n${content}\n\`\`\``,
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import {
|
|||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
import { isSecurityConcern } from "../../indexing/ignore.js";
|
||||
import { getUriDescription } from "../../util/uri.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
|
|
@ -40,7 +41,7 @@ class ProblemsContextProvider extends BaseContextProvider {
|
|||
return {
|
||||
description: "Problems in current file",
|
||||
content: `\`\`\`${relativePathOrBasename}\n${rangeContent}\n\`\`\`\n${problem.message}\n\n`,
|
||||
name: `Warning in ${baseName}`,
|
||||
name: `Warnings in ${baseName}`,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import { BaseContextProvider } from "../";
|
||||
import { ContextProviderName } from "../../";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
|
||||
import ClipboardContextProvider from "./ClipboardContextProvider";
|
||||
import CodebaseContextProvider from "./CodebaseContextProvider";
|
||||
|
|
@ -12,6 +11,7 @@ import DebugLocalsProvider from "./DebugLocalsProvider";
|
|||
import DiffContextProvider from "./DiffContextProvider";
|
||||
import DiscordContextProvider from "./DiscordContextProvider";
|
||||
import DocsContextProvider from "./DocsContextProvider";
|
||||
import FileContextProvider from "./FileContextProvider";
|
||||
import FileTreeContextProvider from "./FileTreeContextProvider";
|
||||
import FolderContextProvider from "./FolderContextProvider";
|
||||
import GitCommitContextProvider from "./GitCommitContextProvider";
|
||||
|
|
@ -41,6 +41,7 @@ import WebContextProvider from "./WebContextProvider";
|
|||
* See this issue for details: https://github.com/continuedev/continue/issues/1365
|
||||
*/
|
||||
export const Providers: (typeof BaseContextProvider)[] = [
|
||||
FileContextProvider,
|
||||
DiffContextProvider,
|
||||
FileTreeContextProvider,
|
||||
GitHubIssuesContextProvider,
|
||||
|
|
@ -78,10 +79,5 @@ export function contextProviderClassFromName(
|
|||
): typeof BaseContextProvider | undefined {
|
||||
const provider = Providers.find((cls) => cls.description.title === name);
|
||||
|
||||
void Telemetry.capture("context_provider_load", {
|
||||
providerName: name,
|
||||
found: !!provider, // also capture those which user expected to be present
|
||||
});
|
||||
|
||||
return provider;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
const nFinal =
|
||||
options?.nFinal ??
|
||||
Math.min(DEFAULT_N_FINAL, contextLength / tokensPerSnippet / 2);
|
||||
const useReranking = !!extras.reranker;
|
||||
const useReranking = options?.useReranking ?? !!extras.reranker;
|
||||
const nRetrieve = useReranking ? options?.nRetrieve || 2 * nFinal : nFinal;
|
||||
|
||||
const branches = (await Promise.race([
|
||||
|
|
|
|||
58
core/core.ts
58
core/core.ts
|
|
@ -10,7 +10,6 @@ import {
|
|||
import { ConfigHandler } from "./config/ConfigHandler";
|
||||
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles";
|
||||
import { addModel, deleteModel } from "./config/util";
|
||||
import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
|
||||
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
|
||||
import { getControlPlaneEnv } from "./control-plane/env";
|
||||
import { DevDataSqliteDb } from "./data/devdataSqlite";
|
||||
|
|
@ -51,6 +50,7 @@ import {
|
|||
import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
|
||||
import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
|
||||
import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
|
||||
import { createNewAssistantFile } from "./config/createNewAssistantFile";
|
||||
import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
|
||||
import { CodebaseRulesCache } from "./config/markdown/loadCodebaseRules";
|
||||
import {
|
||||
|
|
@ -354,6 +354,13 @@ export class Core {
|
|||
);
|
||||
});
|
||||
|
||||
on("config/newAssistantFile", async (msg) => {
|
||||
await createNewAssistantFile(this.ide, undefined);
|
||||
await this.configHandler.reloadConfig(
|
||||
"Assistant file created (config/newAssistantFile message)",
|
||||
);
|
||||
});
|
||||
|
||||
on("config/addLocalWorkspaceBlock", async (msg) => {
|
||||
await createNewWorkspaceBlockFile(this.ide, msg.data.blockType);
|
||||
await this.configHandler.reloadConfig(
|
||||
|
|
@ -661,6 +668,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;
|
||||
|
|
@ -959,6 +968,10 @@ export class Core {
|
|||
on("docs/getDetails", async (msg) => {
|
||||
return await this.docsService.getDetails(msg.data.startUrl);
|
||||
});
|
||||
on("docs/getIndexedPages", async (msg) => {
|
||||
const pages = await this.docsService.getIndexedPages(msg.data.startUrl);
|
||||
return Array.from(pages);
|
||||
});
|
||||
|
||||
on("didChangeSelectedProfile", async (msg) => {
|
||||
if (msg.data.id) {
|
||||
|
|
@ -996,6 +1009,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);
|
||||
});
|
||||
|
|
@ -1273,15 +1317,9 @@ export class Core {
|
|||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
const provider =
|
||||
config.contextProviders?.find(
|
||||
(provider) => provider.description.title === name,
|
||||
) ??
|
||||
[
|
||||
// user doesn't need these in their config.json for the shortcuts to work
|
||||
// option+enter
|
||||
new CurrentFileContextProvider({}),
|
||||
].find((provider) => provider.description.title === name);
|
||||
const provider = config.contextProviders?.find(
|
||||
(provider) => provider.description.title === name,
|
||||
);
|
||||
if (!provider) {
|
||||
return [];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ const INFINITE_STREAM_SAFETY = 0.9;
|
|||
const DUD_PROMPT_LOG: PromptLog = {
|
||||
modelTitle: "",
|
||||
modelProvider: "",
|
||||
completionOptions: { model: "" },
|
||||
prompt: "",
|
||||
completion: "",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,713 +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("jaroWinklerFuzzyMatch strategy", () => {
|
||||
it("should match similar code with variable name differences", () => {
|
||||
const fileContent = `function calculateTotal(items) {
|
||||
let sum = 0;
|
||||
for (const item of items) {
|
||||
sum += item.price;
|
||||
}
|
||||
return sum;
|
||||
}`;
|
||||
const searchContent = `function calculateTotal(products) {
|
||||
let total = 0;
|
||||
for (const product of products) {
|
||||
total += product.price;
|
||||
}
|
||||
return total;
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.strategyName).toBe("jaroWinklerFuzzyMatch");
|
||||
});
|
||||
|
||||
it("should match code with minor typos", () => {
|
||||
const testCases = [
|
||||
{
|
||||
name: "typo in function name",
|
||||
fileContent: "function getUserName() { return this.name; }",
|
||||
searchContent: "function getUserNaem() { return this.name; }",
|
||||
},
|
||||
{
|
||||
name: "typo in variable",
|
||||
fileContent: "const message = 'Hello World';",
|
||||
searchContent: "const mesage = 'Hello World';",
|
||||
},
|
||||
{
|
||||
name: "missing character",
|
||||
fileContent: "console.log('Debug info');",
|
||||
searchContent: "console.log('Debug nfo');",
|
||||
},
|
||||
];
|
||||
|
||||
testCases.forEach(({ name, fileContent, searchContent }) => {
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.strategyName).toBe("jaroWinklerFuzzyMatch");
|
||||
});
|
||||
});
|
||||
|
||||
it("should not match when similarity is too low", () => {
|
||||
const fileContent = "function add(a, b) { return a + b; }";
|
||||
const searchContent =
|
||||
"class Calculator { multiply(x, y) { return x * y; } }";
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should handle multiline fuzzy matches", () => {
|
||||
const fileContent = `if (userIsLoggedIn) {
|
||||
showDashboard();
|
||||
loadUserData();
|
||||
}`;
|
||||
const searchContent = `if (isUserLoggedIn) {
|
||||
displayDashboard();
|
||||
fetchUserData();
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.strategyName).toBe("jaroWinklerFuzzyMatch");
|
||||
});
|
||||
|
||||
it("should verify replacement with fuzzy matches", () => {
|
||||
const fileContent = "const userName = 'John';";
|
||||
const searchContent = "const usrName = 'John';"; // Typo in variable name
|
||||
const replacement = "const userName = 'Jane';";
|
||||
|
||||
const match = findSearchMatch(fileContent, searchContent);
|
||||
expect(match).not.toBeNull();
|
||||
expect(match!.strategyName).toBe("jaroWinklerFuzzyMatch");
|
||||
|
||||
const result = performReplacement(fileContent, match!, replacement);
|
||||
expect(result).toBe(replacement);
|
||||
});
|
||||
|
||||
it("should handle edge case with very short strings", () => {
|
||||
const fileContent = "ab";
|
||||
const searchContent = "ac";
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
// Should not match due to low similarity on short strings
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
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");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,768 +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("No matches", () => {
|
||||
it("should return null when search content is not found", () => {
|
||||
const fileContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
const searchContent = `function goodbye() {
|
||||
console.log("world");
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result?.strategyName).toEqual("jaroWinklerFuzzyMatch");
|
||||
});
|
||||
|
||||
it("should return only fuzzy result when trimmed search content is not found", () => {
|
||||
const fileContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
const searchContent = `\n\nfunction goodbye() {
|
||||
console.log("world");
|
||||
}\n\n`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result?.strategyName).toEqual("jaroWinklerFuzzyMatch");
|
||||
});
|
||||
});
|
||||
|
||||
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",
|
||||
});
|
||||
});
|
||||
|
||||
describe("Jaro-Winkler fuzzy matching", () => {
|
||||
describe("Basic fuzzy matching", () => {
|
||||
it("should find fuzzy match for similar strings", () => {
|
||||
const fileContent = `function calculateSum(a, b) {
|
||||
return a + b;
|
||||
}`;
|
||||
const searchContent = `function calculateSum(x, y) {
|
||||
return x + y;
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
});
|
||||
|
||||
it("should find fuzzy match with minor typos", () => {
|
||||
const fileContent = `const message = "Hello World";`;
|
||||
const searchContent = `const mesage = "Hello World";`; // Missing 's' in 'message'
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.startIndex).toBe(0);
|
||||
});
|
||||
|
||||
it("should find fuzzy match with different variable names", () => {
|
||||
const fileContent = `let userAge = 25;
|
||||
let userName = "John";`;
|
||||
const searchContent = `let age = 25;
|
||||
let name = "John";`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
});
|
||||
|
||||
it("should find fuzzy match for similar function signature", () => {
|
||||
const fileContent = `function processUserData(userData) {
|
||||
validateInput(userData);
|
||||
return formatOutput(userData);
|
||||
}`;
|
||||
const searchContent = `function processData(data) {
|
||||
validateInput(data);
|
||||
return formatOutput(data);
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Multi-line fuzzy matching", () => {
|
||||
it("should find fuzzy match for multi-line blocks", () => {
|
||||
const fileContent = `class Calculator {
|
||||
constructor() {
|
||||
this.result = 0;
|
||||
}
|
||||
|
||||
add(value) {
|
||||
this.result += value;
|
||||
return this;
|
||||
}
|
||||
}`;
|
||||
const searchContent = `class Calculator {
|
||||
constructor() {
|
||||
this.value = 0;
|
||||
}
|
||||
|
||||
add(num) {
|
||||
this.value += num;
|
||||
return this;
|
||||
}
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
});
|
||||
|
||||
it("should find fuzzy match for partial blocks", () => {
|
||||
const fileContent = `function processData(input) {
|
||||
const validated = validateInput(input);
|
||||
const processed = transformData(validated);
|
||||
const result = formatOutput(processed);
|
||||
return result;
|
||||
}`;
|
||||
const searchContent = `const validated = validateInput(input);
|
||||
const processed = transformData(validated);`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Edge cases with fuzzy matching", () => {
|
||||
it("should handle empty search content with fuzzy matching enabled", () => {
|
||||
const fileContent = `function test() {}`;
|
||||
const searchContent = "";
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: 0,
|
||||
strategyName: "emptySearch",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle empty file content with fuzzy matching enabled", () => {
|
||||
const fileContent = "";
|
||||
const searchContent = "function test() {}";
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should prefer exact match over fuzzy match", () => {
|
||||
const fileContent = `function test() { return true; }
|
||||
function test() { return false; }`;
|
||||
const searchContent = `function test() { return true; }`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.startIndex).toBe(0);
|
||||
});
|
||||
|
||||
it("should handle very short strings", () => {
|
||||
const fileContent = `a b c`;
|
||||
const searchContent = `a c`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
// Should not match due to low similarity
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should handle special characters in fuzzy matching", () => {
|
||||
const fileContent = `const regex = /[a-zA-Z]+/g;
|
||||
const symbols = !@#$%^&*();`;
|
||||
const searchContent = `const regex = /[a-zA-Z0-9]+/g;
|
||||
const symbols = !@#$%^&*();`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -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",
|
||||
);
|
||||
});
|
||||
});
|
||||
18
core/index.d.ts
vendored
18
core/index.d.ts
vendored
|
|
@ -456,7 +456,6 @@ export type FileSymbolMap = Record<string, SymbolWithRange[]>;
|
|||
export interface PromptLog {
|
||||
modelTitle: string;
|
||||
modelProvider: string;
|
||||
completionOptions: CompletionOptions;
|
||||
prompt: string;
|
||||
completion: string;
|
||||
}
|
||||
|
|
@ -666,6 +665,7 @@ export interface LLMOptions {
|
|||
env?: Record<string, string | number | boolean>;
|
||||
|
||||
sourceFile?: string;
|
||||
isFromAutoDetect?: boolean;
|
||||
}
|
||||
|
||||
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
|
||||
|
|
@ -1070,11 +1070,6 @@ export interface ToolExtras {
|
|||
codeBaseIndexer?: CodebaseIndexer;
|
||||
}
|
||||
|
||||
export type ToolPolicy =
|
||||
| "allowedWithPermission"
|
||||
| "allowedWithoutPermission"
|
||||
| "disabled";
|
||||
|
||||
export interface Tool {
|
||||
type: "function";
|
||||
function: {
|
||||
|
|
@ -1099,6 +1094,10 @@ export interface Tool {
|
|||
exampleArgs?: Array<[string, string | number]>;
|
||||
};
|
||||
defaultToolPolicy?: ToolPolicy;
|
||||
evaluateToolCallPolicy?: (
|
||||
basePolicy: ToolPolicy,
|
||||
parsedArgs: Record<string, unknown>,
|
||||
) => ToolPolicy;
|
||||
}
|
||||
|
||||
interface ToolChoice {
|
||||
|
|
@ -1111,6 +1110,9 @@ interface ToolChoice {
|
|||
export interface ConfigDependentToolParams {
|
||||
rules: RuleWithSource[];
|
||||
enableExperimentalTools: boolean;
|
||||
isSignedIn: boolean;
|
||||
isRemote: boolean;
|
||||
modelName: string | undefined;
|
||||
}
|
||||
|
||||
export type GetTool = (params: ConfigDependentToolParams) => Tool;
|
||||
|
|
@ -1174,6 +1176,7 @@ export interface ModelDescription {
|
|||
configurationStatus?: LLMConfigurationStatuses;
|
||||
|
||||
sourceFile?: string;
|
||||
isFromAutoDetect?: boolean;
|
||||
}
|
||||
|
||||
export interface JSONEmbedOptions {
|
||||
|
|
@ -1342,6 +1345,7 @@ export interface ContinueUIConfig {
|
|||
codeWrap?: boolean;
|
||||
showSessionTabs?: boolean;
|
||||
autoAcceptEditToolDiffs?: boolean;
|
||||
continueAfterToolRejection?: boolean;
|
||||
}
|
||||
|
||||
export interface ContextMenuConfig {
|
||||
|
|
@ -1604,6 +1608,7 @@ export interface JSONModelDescription {
|
|||
aiGatewaySlug?: string;
|
||||
useLegacyCompletionsEndpoint?: boolean;
|
||||
deploymentId?: string;
|
||||
isFromAutoDetect?: boolean;
|
||||
}
|
||||
|
||||
// config.json
|
||||
|
|
@ -1681,6 +1686,7 @@ export interface Config {
|
|||
experimental?: ExperimentalConfig;
|
||||
/** Analytics configuration */
|
||||
analytics?: AnalyticsConfig;
|
||||
docs?: SiteIndexingConfig[];
|
||||
data?: DataDestination[];
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -64,8 +64,8 @@ class TestCodebaseIndexer extends CodebaseIndexer {
|
|||
}
|
||||
|
||||
// Add public methods to test private methods
|
||||
public testHasCodebaseContextProvider() {
|
||||
return (this as any).hasCodebaseContextProvider();
|
||||
public testHasIndexingProvider() {
|
||||
return (this as any).hasIndexingContextProvider();
|
||||
}
|
||||
|
||||
public async testHandleConfigUpdate(
|
||||
|
|
@ -202,7 +202,7 @@ describe("CodebaseIndexer", () => {
|
|||
|
||||
test("should have indexed all of the files", async () => {
|
||||
const indexed = await getAllIndexedFiles();
|
||||
expect(indexed.length).toBe(4); // Files are indexed twice due to test execution
|
||||
expect(indexed.length).toBe(2);
|
||||
expect(indexed.some((file) => file.endsWith("test.ts"))).toBe(true);
|
||||
expect(indexed.some((file) => file.endsWith("main.py"))).toBe(true);
|
||||
});
|
||||
|
|
@ -226,7 +226,7 @@ describe("CodebaseIndexer", () => {
|
|||
|
||||
// Check that the new file was indexed
|
||||
const files = await getAllIndexedFiles();
|
||||
expect(files.length).toBe(5); // Updated to match actual behavior
|
||||
expect(files.length).toBe(3);
|
||||
expect(files.some((file) => file.endsWith("main.rs"))).toBe(true);
|
||||
});
|
||||
|
||||
|
|
@ -240,7 +240,7 @@ describe("CodebaseIndexer", () => {
|
|||
|
||||
// Check that the deleted file was removed from the index
|
||||
const files = await getAllIndexedFiles();
|
||||
expect(files.length).toBe(4); // Updated to match actual behavior
|
||||
expect(files.length).toBe(2);
|
||||
expect(files.every((file) => !file.endsWith("main.rs"))).toBe(true);
|
||||
});
|
||||
|
||||
|
|
@ -474,20 +474,14 @@ describe("CodebaseIndexer", () => {
|
|||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("hasCodebaseContextProvider", () => {
|
||||
describe("hasIndexingProvider", () => {
|
||||
test("should return true when codebase context provider is present", () => {
|
||||
// Set up config with codebase context provider
|
||||
(testIndexer as any).config = {
|
||||
contextProviders: [
|
||||
{
|
||||
description: {
|
||||
title: CodebaseContextProvider.description.title,
|
||||
},
|
||||
},
|
||||
],
|
||||
contextProviders: [new CodebaseContextProvider({})],
|
||||
};
|
||||
|
||||
const result = testIndexer.testHasCodebaseContextProvider();
|
||||
const result = testIndexer.testHasIndexingProvider();
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
|
|
@ -496,7 +490,7 @@ describe("CodebaseIndexer", () => {
|
|||
contextProviders: undefined,
|
||||
};
|
||||
|
||||
const result = testIndexer.testHasCodebaseContextProvider();
|
||||
const result = testIndexer.testHasIndexingProvider();
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
|
|
@ -511,7 +505,7 @@ describe("CodebaseIndexer", () => {
|
|||
],
|
||||
};
|
||||
|
||||
const result = testIndexer.testHasCodebaseContextProvider();
|
||||
const result = testIndexer.testHasIndexingProvider();
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
|
|
@ -520,7 +514,7 @@ describe("CodebaseIndexer", () => {
|
|||
contextProviders: [],
|
||||
};
|
||||
|
||||
const result = testIndexer.testHasCodebaseContextProvider();
|
||||
const result = testIndexer.testHasIndexingProvider();
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
@ -535,9 +529,8 @@ describe("CodebaseIndexer", () => {
|
|||
|
||||
await testIndexer.testHandleConfigUpdate(configResult);
|
||||
|
||||
// These get called once on init, so we want them to not get called again
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
|
||||
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(0);
|
||||
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
test("should return early when newConfig is undefined", async () => {
|
||||
|
|
@ -549,9 +542,8 @@ describe("CodebaseIndexer", () => {
|
|||
|
||||
await testIndexer.testHandleConfigUpdate(configResult);
|
||||
|
||||
// These get called once on init, so we want them to not get called again
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
|
||||
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(0);
|
||||
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
test("should return early when no codebase context provider is present", async () => {
|
||||
|
|
@ -577,21 +569,14 @@ describe("CodebaseIndexer", () => {
|
|||
|
||||
await testIndexer.testHandleConfigUpdate(configResult);
|
||||
|
||||
// These get called once on init, so we want them to not get called again
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
|
||||
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(0);
|
||||
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
test("should return early when no embed model is configured", async () => {
|
||||
const configResult: ConfigResult<ContinueConfig> = {
|
||||
config: {
|
||||
contextProviders: [
|
||||
{
|
||||
description: {
|
||||
title: CodebaseContextProvider.description.title,
|
||||
},
|
||||
},
|
||||
],
|
||||
contextProviders: [new CodebaseContextProvider({})],
|
||||
selectedModelByRole: {
|
||||
embed: undefined,
|
||||
},
|
||||
|
|
@ -602,21 +587,14 @@ describe("CodebaseIndexer", () => {
|
|||
|
||||
await testIndexer.testHandleConfigUpdate(configResult);
|
||||
|
||||
// These get called once on init, so we want them to not get called again
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
|
||||
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(0);
|
||||
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
test("should call refreshCodebaseIndex when all conditions are met", async () => {
|
||||
const configResult: ConfigResult<ContinueConfig> = {
|
||||
config: {
|
||||
contextProviders: [
|
||||
{
|
||||
description: {
|
||||
title: CodebaseContextProvider.description.title,
|
||||
},
|
||||
},
|
||||
],
|
||||
contextProviders: [new CodebaseContextProvider({})],
|
||||
selectedModelByRole: {
|
||||
embed: {
|
||||
model: "test-model",
|
||||
|
|
@ -630,9 +608,8 @@ describe("CodebaseIndexer", () => {
|
|||
|
||||
await testIndexer.testHandleConfigUpdate(configResult);
|
||||
|
||||
// These get called once on init, and we want them to get called again
|
||||
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(2);
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
|
||||
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
|
||||
"/test/workspace",
|
||||
]);
|
||||
|
|
@ -640,13 +617,7 @@ describe("CodebaseIndexer", () => {
|
|||
|
||||
test("should set config property before checking conditions", async () => {
|
||||
const testConfig = {
|
||||
contextProviders: [
|
||||
{
|
||||
description: {
|
||||
title: CodebaseContextProvider.description.title,
|
||||
},
|
||||
},
|
||||
],
|
||||
contextProviders: [new CodebaseContextProvider({})],
|
||||
selectedModelByRole: {
|
||||
embed: {
|
||||
model: "test-model",
|
||||
|
|
@ -666,7 +637,7 @@ describe("CodebaseIndexer", () => {
|
|||
// Verify that the config was set
|
||||
expect((testIndexer as any).config).toBe(testConfig);
|
||||
// These get called once on init, and we want them to get called again
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("should handle multiple context providers correctly", async () => {
|
||||
|
|
@ -678,11 +649,7 @@ describe("CodebaseIndexer", () => {
|
|||
title: "SomeOtherProvider",
|
||||
},
|
||||
},
|
||||
{
|
||||
description: {
|
||||
title: CodebaseContextProvider.description.title,
|
||||
},
|
||||
},
|
||||
new CodebaseContextProvider({}),
|
||||
{
|
||||
description: {
|
||||
title: "AnotherProvider",
|
||||
|
|
@ -702,8 +669,7 @@ describe("CodebaseIndexer", () => {
|
|||
|
||||
await testIndexer.testHandleConfigUpdate(configResult);
|
||||
|
||||
// These get called once on init, and we want them to get called again
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
|
||||
"/test/workspace",
|
||||
]);
|
||||
|
|
|
|||
|
|
@ -12,11 +12,9 @@ import type { IMessenger } from "../protocol/messenger";
|
|||
import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
|
||||
import { Logger } from "../util/Logger.js";
|
||||
import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
|
||||
import { Telemetry } from "../util/posthog.js";
|
||||
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
|
||||
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js";
|
||||
import { ContinueServerClient } from "../continueServer/stubs/client";
|
||||
import { LLMError } from "../llm/index.js";
|
||||
import { getRootCause } from "../util/errors.js";
|
||||
|
|
@ -668,14 +666,6 @@ export class CodebaseIndexer {
|
|||
update.desc,
|
||||
update.debugInfo,
|
||||
);
|
||||
void Telemetry.capture(
|
||||
"indexing_error",
|
||||
{
|
||||
error: update.desc,
|
||||
stack: update.debugInfo,
|
||||
},
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -804,11 +794,9 @@ export class CodebaseIndexer {
|
|||
return this.codebaseIndexingState;
|
||||
}
|
||||
|
||||
private hasCodebaseContextProvider() {
|
||||
private hasIndexingContextProvider() {
|
||||
return !!this.config.contextProviders?.some(
|
||||
(provider) =>
|
||||
provider.description.title ===
|
||||
CodebaseContextProvider.description.title,
|
||||
({ description: { dependsOnIndexing } }) => dependsOnIndexing,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -837,8 +825,8 @@ export class CodebaseIndexer {
|
|||
this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in
|
||||
|
||||
// No point in indexing if no codebase context provider
|
||||
const hasCodebaseContextProvider = this.hasCodebaseContextProvider();
|
||||
if (!hasCodebaseContextProvider) {
|
||||
const hasIndexingProviders = this.hasIndexingContextProvider();
|
||||
if (!hasIndexingProviders) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -22,7 +22,22 @@ export async function* chunkDocumentWithoutId(
|
|||
return;
|
||||
}
|
||||
const extension = getUriFileExtension(fileUri);
|
||||
if (extension in supportedLanguages) {
|
||||
// Files that should use basicChunker despite having tree-sitter support
|
||||
// These files don't have code structure (classes/functions) that codeChunker expects
|
||||
const NON_CODE_EXTENSIONS = [
|
||||
"css",
|
||||
"html",
|
||||
"htm",
|
||||
"json",
|
||||
"toml",
|
||||
"yaml",
|
||||
"yml",
|
||||
];
|
||||
|
||||
if (
|
||||
extension in supportedLanguages &&
|
||||
!NON_CODE_EXTENSIONS.includes(extension)
|
||||
) {
|
||||
try {
|
||||
for await (const chunk of codeChunker(fileUri, contents, maxChunkSize)) {
|
||||
yield chunk;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ChunkWithoutID } from "../..";
|
||||
|
||||
import { cleanupAsyncEncoders, countTokensAsync } from "../../llm/countTokens";
|
||||
import { codeChunker } from "./code";
|
||||
|
||||
async function genToArr<T>(generator: AsyncGenerator<T>): Promise<T[]> {
|
||||
|
|
@ -71,3 +71,60 @@ describe.skip("codeChunker", () => {
|
|||
expect(chunks).toContain('def method20():\n return "Hello, 20!"');
|
||||
});
|
||||
});
|
||||
|
||||
async function collectContents(
|
||||
filepath: string,
|
||||
contents: string,
|
||||
maxChunkSize: number,
|
||||
): Promise<string[]> {
|
||||
const out: string[] = [];
|
||||
for await (const c of codeChunker(filepath, contents, maxChunkSize)) {
|
||||
out.push(c.content);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe("codeChunker function definition", () => {
|
||||
afterAll(async () => await cleanupAsyncEncoders());
|
||||
|
||||
test("class methods never exceed maxChunkSize", async () => {
|
||||
const body = Array.from(
|
||||
{ length: 200 },
|
||||
(_, i) => `console.log(${i});`,
|
||||
).join("\n");
|
||||
const contents = `
|
||||
class C {
|
||||
a() {
|
||||
${body}
|
||||
}
|
||||
b() {
|
||||
${body}
|
||||
}
|
||||
}
|
||||
`;
|
||||
const max = 50;
|
||||
const chunks = await collectContents("filename1.ts", contents, max);
|
||||
const counts = await Promise.all(chunks.map((s) => countTokensAsync(s)));
|
||||
counts.forEach((n) => expect(n).toBeLessThanOrEqual(max));
|
||||
});
|
||||
|
||||
test("top-level functions never exceed maxChunkSize", async () => {
|
||||
const body = Array.from(
|
||||
{ length: 150 },
|
||||
(_, i) => `const x${i} = ${i};`,
|
||||
).join("\n");
|
||||
const contents = `
|
||||
function f() {
|
||||
${body}
|
||||
}
|
||||
|
||||
function g() {
|
||||
${body}
|
||||
}
|
||||
`;
|
||||
const max = 60;
|
||||
const chunks = await collectContents("filename2.ts", contents, max);
|
||||
const counts = await Promise.all(chunks.map((s) => countTokensAsync(s)));
|
||||
counts.forEach((n) => expect(n).toBeLessThanOrEqual(max));
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -128,25 +128,46 @@ async function constructFunctionDefinitionChunk(
|
|||
maxChunkSize: number,
|
||||
): Promise<string> {
|
||||
const bodyNode = node.children[node.children.length - 1];
|
||||
const funcText =
|
||||
code.slice(node.startIndex, bodyNode.startIndex) +
|
||||
collapsedReplacement(bodyNode);
|
||||
const collapsedBody = collapsedReplacement(bodyNode);
|
||||
const signature = code.slice(node.startIndex, bodyNode.startIndex);
|
||||
const funcText = signature + collapsedBody;
|
||||
|
||||
if (
|
||||
const isInClass =
|
||||
node.parent &&
|
||||
["block", "declaration_list"].includes(node.parent.type) &&
|
||||
node.parent.parent &&
|
||||
["class_definition", "impl_item"].includes(node.parent.parent.type)
|
||||
) {
|
||||
// If inside a class, include the class header
|
||||
const classNode = node.parent.parent;
|
||||
const classBlock = node.parent;
|
||||
return `${code.slice(
|
||||
classNode.startIndex,
|
||||
classBlock.startIndex,
|
||||
)}...\n\n${" ".repeat(node.startPosition.column)}${funcText}`;
|
||||
["class_definition", "impl_item"].includes(node.parent.parent.type);
|
||||
|
||||
if (isInClass) {
|
||||
const classNode = node.parent!.parent!;
|
||||
const classBlock = node.parent!;
|
||||
const classHeader = code.slice(classNode.startIndex, classBlock.startIndex);
|
||||
const indent = " ".repeat(node.startPosition.column);
|
||||
const combined = `${classHeader}...\n\n${indent}${funcText}`;
|
||||
|
||||
if ((await countTokensAsync(combined)) <= maxChunkSize) {
|
||||
return combined;
|
||||
}
|
||||
if ((await countTokensAsync(funcText)) <= maxChunkSize) {
|
||||
return funcText;
|
||||
}
|
||||
const firstLine = signature.split("\n")[0] ?? "";
|
||||
const minimal = `${firstLine} ${collapsedBody}`;
|
||||
if ((await countTokensAsync(minimal)) <= maxChunkSize) {
|
||||
return minimal;
|
||||
}
|
||||
return collapsedBody;
|
||||
}
|
||||
return funcText;
|
||||
|
||||
if ((await countTokensAsync(funcText)) <= maxChunkSize) {
|
||||
return funcText;
|
||||
}
|
||||
const firstLine = signature.split("\n")[0] ?? "";
|
||||
const minimal = `${firstLine} ${collapsedBody}`;
|
||||
if ((await countTokensAsync(minimal)) <= maxChunkSize) {
|
||||
return minimal;
|
||||
}
|
||||
return collapsedBody;
|
||||
}
|
||||
|
||||
const collapsedNodeConstructors: {
|
||||
|
|
|
|||
26
core/indexing/continueignore.ts
Normal file
26
core/indexing/continueignore.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import fs from "fs";
|
||||
import { IDE } from "..";
|
||||
import { getGlobalContinueIgnorePath } from "../util/paths";
|
||||
import { gitIgArrayFromFile } from "./ignore";
|
||||
|
||||
export const getGlobalContinueIgArray = () => {
|
||||
const contents = fs.readFileSync(getGlobalContinueIgnorePath(), "utf8");
|
||||
return gitIgArrayFromFile(contents);
|
||||
};
|
||||
|
||||
export const getWorkspaceContinueIgArray = async (ide: IDE) => {
|
||||
const dirs = await ide.getWorkspaceDirs();
|
||||
return await dirs.reduce(
|
||||
async (accPromise, dir) => {
|
||||
const acc = await accPromise;
|
||||
try {
|
||||
const contents = await ide.readFile(`${dir}/.continueignore`);
|
||||
return [...acc, ...gitIgArrayFromFile(contents)];
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
return acc;
|
||||
}
|
||||
},
|
||||
Promise.resolve([] as string[]),
|
||||
);
|
||||
};
|
||||
|
|
@ -858,6 +858,27 @@ export default class DocsService {
|
|||
return docs.map(this.lanceDBRowToChunk);
|
||||
}
|
||||
|
||||
async getIndexedPages(startUrl: string): Promise<Set<string>> {
|
||||
try {
|
||||
const table = await this.getOrCreateLanceTable({
|
||||
initializationVector: [],
|
||||
startUrl,
|
||||
});
|
||||
|
||||
const rows = (await table
|
||||
.filter(`starturl = '${startUrl}'`)
|
||||
.select(["path"]) // Only select path to minimize data transfer
|
||||
.limit(99999999) // Default is 10, we want to show all
|
||||
.execute()) as { path: string }[];
|
||||
|
||||
// Get unique paths (pages)
|
||||
return new Set(rows.map((row) => row.path));
|
||||
} catch (e) {
|
||||
console.warn(`Error getting page list for ${startUrl}:`, e);
|
||||
return new Set();
|
||||
}
|
||||
}
|
||||
|
||||
// SQLITE DB
|
||||
private async getOrCreateSqliteDb() {
|
||||
if (!this.sqliteDb) {
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,11 +1,100 @@
|
|||
import fs from "fs";
|
||||
|
||||
import ignore from "ignore";
|
||||
|
||||
import { IDE } from "..";
|
||||
import { getGlobalContinueIgnorePath } from "../util/paths";
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
export const DEFAULT_IGNORE_FILETYPES = [
|
||||
// Security-focused ignore patterns - these should always be excluded for security reasons
|
||||
export const DEFAULT_SECURITY_IGNORE_FILETYPES = [
|
||||
// Environment and configuration files with secrets
|
||||
"*.env",
|
||||
"*.env.*",
|
||||
".env*",
|
||||
"config.json",
|
||||
"config.yaml",
|
||||
"config.yml",
|
||||
"settings.json",
|
||||
"appsettings.json",
|
||||
"appsettings.*.json",
|
||||
|
||||
// Certificate and key files
|
||||
"*.key",
|
||||
"*.pem",
|
||||
"*.p12",
|
||||
"*.pfx",
|
||||
"*.crt",
|
||||
"*.cer",
|
||||
"*.jks",
|
||||
"*.keystore",
|
||||
"*.truststore",
|
||||
|
||||
// Database files that may contain sensitive data
|
||||
"*.db",
|
||||
"*.sqlite",
|
||||
"*.sqlite3",
|
||||
"*.mdb",
|
||||
"*.accdb",
|
||||
|
||||
// Credential and secret files
|
||||
"*.secret",
|
||||
"*.secrets",
|
||||
"credentials",
|
||||
"credentials.*",
|
||||
"auth.json",
|
||||
"token",
|
||||
"token.*",
|
||||
"*.token",
|
||||
|
||||
// Backup files that might contain sensitive data
|
||||
"*.bak",
|
||||
"*.backup",
|
||||
"*.old",
|
||||
"*.orig",
|
||||
|
||||
// Docker secrets
|
||||
"docker-compose.override.yml",
|
||||
"docker-compose.override.yaml",
|
||||
|
||||
// SSH and GPG
|
||||
"id_rsa",
|
||||
"id_dsa",
|
||||
"id_ecdsa",
|
||||
"id_ed25519",
|
||||
"*.ppk",
|
||||
"*.gpg",
|
||||
];
|
||||
|
||||
export const DEFAULT_SECURITY_IGNORE_DIRS = [
|
||||
// Environment and configuration directories
|
||||
".env/",
|
||||
"env/",
|
||||
|
||||
// Cloud provider credential directories
|
||||
".aws/",
|
||||
".gcp/",
|
||||
".azure/",
|
||||
".kube/",
|
||||
".docker/",
|
||||
|
||||
// Secret directories
|
||||
"secrets/",
|
||||
".secrets/",
|
||||
"private/",
|
||||
".private/",
|
||||
"certs/",
|
||||
"certificates/",
|
||||
"keys/",
|
||||
".ssh/",
|
||||
".gnupg/",
|
||||
".gpg/",
|
||||
|
||||
// Temporary directories that might contain sensitive data
|
||||
"tmp/secrets/",
|
||||
"temp/secrets/",
|
||||
".tmp/",
|
||||
];
|
||||
|
||||
// Additional non-security patterns for general indexing exclusion
|
||||
export const ADDITIONAL_INDEXING_IGNORE_FILETYPES = [
|
||||
"*.DS_Store",
|
||||
"*-lock.json",
|
||||
"*.lock",
|
||||
|
|
@ -46,8 +135,6 @@ export const DEFAULT_IGNORE_FILETYPES = [
|
|||
"*.mpeg",
|
||||
"*.mov",
|
||||
"*.mp3",
|
||||
"*.mp4",
|
||||
"*.mkv",
|
||||
"*.mkv",
|
||||
"*.webm",
|
||||
"*.jar",
|
||||
|
|
@ -56,20 +143,15 @@ export const DEFAULT_IGNORE_FILETYPES = [
|
|||
"*.pqt",
|
||||
"*.wav",
|
||||
"*.webp",
|
||||
"*.db",
|
||||
"*.sqlite",
|
||||
"*.wasm",
|
||||
"*.plist",
|
||||
"*.profraw",
|
||||
"*.gcda",
|
||||
"*.gcno",
|
||||
"go.sum",
|
||||
"*.env",
|
||||
"*.gitignore",
|
||||
"*.gitkeep",
|
||||
"*.continueignore",
|
||||
"config.json",
|
||||
"config.yaml",
|
||||
"*.csv",
|
||||
"*.uasset",
|
||||
"*.pdb",
|
||||
|
|
@ -78,19 +160,13 @@ export const DEFAULT_IGNORE_FILETYPES = [
|
|||
"*.swp",
|
||||
"*.jsonl",
|
||||
// "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt
|
||||
// Application specific
|
||||
".continue/",
|
||||
];
|
||||
|
||||
export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES);
|
||||
export const DEFAULT_IGNORE_DIRS = [
|
||||
export const ADDITIONAL_INDEXING_IGNORE_DIRS = [
|
||||
".git/",
|
||||
".svn/",
|
||||
".vscode/",
|
||||
".idea/",
|
||||
".vs/",
|
||||
"venv/",
|
||||
".venv/",
|
||||
"env/",
|
||||
".env/",
|
||||
"node_modules/",
|
||||
"dist/",
|
||||
"build/",
|
||||
|
|
@ -100,7 +176,6 @@ export const DEFAULT_IGNORE_DIRS = [
|
|||
"bin/",
|
||||
".pytest_cache/",
|
||||
".vscode-test/",
|
||||
".continue/",
|
||||
"__pycache__/",
|
||||
"site-packages/",
|
||||
".gradle/",
|
||||
|
|
@ -108,42 +183,84 @@ export const DEFAULT_IGNORE_DIRS = [
|
|||
".cache/",
|
||||
"gems/",
|
||||
"vendor/",
|
||||
|
||||
".venv/",
|
||||
"venv/",
|
||||
|
||||
".vscode/",
|
||||
".idea/",
|
||||
".vs/",
|
||||
];
|
||||
|
||||
// Combined patterns: security + additional
|
||||
export const DEFAULT_IGNORE_FILETYPES = [
|
||||
...DEFAULT_SECURITY_IGNORE_FILETYPES,
|
||||
...ADDITIONAL_INDEXING_IGNORE_FILETYPES,
|
||||
];
|
||||
|
||||
export const DEFAULT_IGNORE_DIRS = [
|
||||
...DEFAULT_SECURITY_IGNORE_DIRS,
|
||||
...ADDITIONAL_INDEXING_IGNORE_DIRS,
|
||||
];
|
||||
|
||||
// Create ignore instances
|
||||
export const defaultSecurityIgnoreFile = ignore().add(
|
||||
DEFAULT_SECURITY_IGNORE_FILETYPES,
|
||||
);
|
||||
export const defaultSecurityIgnoreDir = ignore().add(
|
||||
DEFAULT_SECURITY_IGNORE_DIRS,
|
||||
);
|
||||
export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES);
|
||||
export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS);
|
||||
|
||||
// String representations
|
||||
export const DEFAULT_SECURITY_IGNORE =
|
||||
DEFAULT_SECURITY_IGNORE_FILETYPES.join("\n") +
|
||||
"\n" +
|
||||
DEFAULT_SECURITY_IGNORE_DIRS.join("\n");
|
||||
|
||||
export const DEFAULT_IGNORE =
|
||||
DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n");
|
||||
|
||||
// Combined ignore instances
|
||||
export const defaultFileAndFolderSecurityIgnores = ignore()
|
||||
.add(defaultSecurityIgnoreFile)
|
||||
.add(defaultSecurityIgnoreDir);
|
||||
|
||||
export const defaultIgnoreFileAndDir = ignore()
|
||||
.add(defaultIgnoreFile)
|
||||
.add(defaultIgnoreDir);
|
||||
|
||||
export function isSecurityConcern(filePathOrUri: string) {
|
||||
if (!filePathOrUri) {
|
||||
return false;
|
||||
}
|
||||
let filepath = filePathOrUri;
|
||||
try {
|
||||
filepath = fileURLToPath(filePathOrUri);
|
||||
} catch {}
|
||||
if (path.isAbsolute(filepath)) {
|
||||
const dir = path.dirname(filepath).split(/\/|\\/).at(-1) ?? "";
|
||||
const basename = path.basename(filepath);
|
||||
filepath = `${dir ? dir + "/" : ""}${basename}`;
|
||||
}
|
||||
if (!filepath) {
|
||||
return false;
|
||||
}
|
||||
return defaultFileAndFolderSecurityIgnores.ignores(filepath);
|
||||
}
|
||||
|
||||
export function throwIfFileIsSecurityConcern(filepath: string) {
|
||||
if (isSecurityConcern(filepath)) {
|
||||
throw new Error(
|
||||
`Reading or Editing ${filepath} is not allowed because it is a security concern. Do not attempt to read or edit this file in any way.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function gitIgArrayFromFile(file: string) {
|
||||
return file
|
||||
.split(/\r?\n/) // Split on new line
|
||||
.map((l) => l.trim()) // Remove whitespace
|
||||
.filter((l) => !/^#|^$/.test(l)); // Remove empty lines
|
||||
}
|
||||
|
||||
export const getGlobalContinueIgArray = () => {
|
||||
const contents = fs.readFileSync(getGlobalContinueIgnorePath(), "utf8");
|
||||
return gitIgArrayFromFile(contents);
|
||||
};
|
||||
|
||||
export const getWorkspaceContinueIgArray = async (ide: IDE) => {
|
||||
const dirs = await ide.getWorkspaceDirs();
|
||||
return await dirs.reduce(
|
||||
async (accPromise, dir) => {
|
||||
const acc = await accPromise;
|
||||
try {
|
||||
const contents = await ide.readFile(`${dir}/.continueignore`);
|
||||
return [...acc, ...gitIgArrayFromFile(contents)];
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
return acc;
|
||||
}
|
||||
},
|
||||
Promise.resolve([] as string[]),
|
||||
);
|
||||
};
|
||||
|
|
|
|||
257
core/indexing/ignore.vitest.ts
Normal file
257
core/indexing/ignore.vitest.ts
Normal file
|
|
@ -0,0 +1,257 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
DEFAULT_SECURITY_IGNORE_DIRS,
|
||||
DEFAULT_SECURITY_IGNORE_FILETYPES,
|
||||
defaultFileAndFolderSecurityIgnores,
|
||||
isSecurityConcern,
|
||||
} from "./ignore";
|
||||
|
||||
describe("isSecurityConcern", () => {
|
||||
describe("Security file types", () => {
|
||||
it("should detect environment files as security concerns", () => {
|
||||
expect(isSecurityConcern(".env")).toBe(true);
|
||||
expect(isSecurityConcern(".env.local")).toBe(true);
|
||||
expect(isSecurityConcern(".env.production")).toBe(true);
|
||||
expect(isSecurityConcern("config/.env")).toBe(true);
|
||||
expect(isSecurityConcern("/path/to/.env")).toBe(true);
|
||||
expect(isSecurityConcern("file:///path/to/.env")).toBe(true);
|
||||
});
|
||||
|
||||
it("should detect configuration files as security concerns", () => {
|
||||
expect(isSecurityConcern("config.json")).toBe(true);
|
||||
expect(isSecurityConcern("config.yaml")).toBe(true);
|
||||
expect(isSecurityConcern("config.yml")).toBe(true);
|
||||
expect(isSecurityConcern("settings.json")).toBe(true);
|
||||
expect(isSecurityConcern("appsettings.json")).toBe(true);
|
||||
expect(isSecurityConcern("appsettings.development.json")).toBe(true);
|
||||
expect(isSecurityConcern("appsettings.production.json")).toBe(true);
|
||||
});
|
||||
|
||||
it("should detect certificate and key files as security concerns", () => {
|
||||
expect(isSecurityConcern("private.key")).toBe(true);
|
||||
expect(isSecurityConcern("certificate.pem")).toBe(true);
|
||||
expect(isSecurityConcern("server.crt")).toBe(true);
|
||||
expect(isSecurityConcern("keystore.jks")).toBe(true);
|
||||
expect(isSecurityConcern("ssl/server.key")).toBe(true);
|
||||
expect(isSecurityConcern("/etc/ssl/certs/server.pem")).toBe(true);
|
||||
});
|
||||
|
||||
it("should detect database files as security concerns", () => {
|
||||
expect(isSecurityConcern("database.db")).toBe(true);
|
||||
expect(isSecurityConcern("users.sqlite")).toBe(true);
|
||||
expect(isSecurityConcern("data.sqlite3")).toBe(true);
|
||||
expect(isSecurityConcern("app.mdb")).toBe(true);
|
||||
expect(isSecurityConcern("data/users.db")).toBe(true);
|
||||
});
|
||||
|
||||
it("should detect credential files as security concerns", () => {
|
||||
expect(isSecurityConcern("app.secret")).toBe(true);
|
||||
expect(isSecurityConcern("api.secrets")).toBe(true);
|
||||
expect(isSecurityConcern("credentials")).toBe(true);
|
||||
expect(isSecurityConcern("credentials.json")).toBe(true);
|
||||
expect(isSecurityConcern("auth.json")).toBe(true);
|
||||
expect(isSecurityConcern("token")).toBe(true);
|
||||
expect(isSecurityConcern("api.token")).toBe(true);
|
||||
expect(isSecurityConcern("access.token")).toBe(true);
|
||||
});
|
||||
|
||||
it("should detect backup files as security concerns", () => {
|
||||
expect(isSecurityConcern("database.bak")).toBe(true);
|
||||
expect(isSecurityConcern("config.backup")).toBe(true);
|
||||
expect(isSecurityConcern("settings.old")).toBe(true);
|
||||
expect(isSecurityConcern("app.orig")).toBe(true);
|
||||
});
|
||||
|
||||
it("should detect Docker override files as security concerns", () => {
|
||||
expect(isSecurityConcern("docker-compose.override.yml")).toBe(true);
|
||||
expect(isSecurityConcern("docker-compose.override.yaml")).toBe(true);
|
||||
});
|
||||
|
||||
it("should detect SSH and GPG files as security concerns", () => {
|
||||
expect(isSecurityConcern("id_rsa")).toBe(true);
|
||||
expect(isSecurityConcern("id_dsa")).toBe(true);
|
||||
expect(isSecurityConcern("id_ecdsa")).toBe(true);
|
||||
expect(isSecurityConcern("id_ed25519")).toBe(true);
|
||||
expect(isSecurityConcern("private.ppk")).toBe(true);
|
||||
expect(isSecurityConcern("secret.gpg")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Security directories", () => {
|
||||
it("should detect environment directories as security concerns", () => {
|
||||
expect(isSecurityConcern(".env/")).toBe(true);
|
||||
expect(isSecurityConcern("env/")).toBe(true);
|
||||
expect(isSecurityConcern(".env/config")).toBe(true);
|
||||
});
|
||||
|
||||
it("should detect cloud provider directories as security concerns", () => {
|
||||
expect(isSecurityConcern(".aws/")).toBe(true);
|
||||
expect(isSecurityConcern(".gcp/")).toBe(true);
|
||||
expect(isSecurityConcern(".azure/")).toBe(true);
|
||||
expect(isSecurityConcern(".kube/")).toBe(true);
|
||||
expect(isSecurityConcern(".docker/")).toBe(true);
|
||||
expect(isSecurityConcern(".aws/credentials")).toBe(true);
|
||||
expect(isSecurityConcern(".kube/config")).toBe(true);
|
||||
});
|
||||
|
||||
it("should detect secret directories as security concerns", () => {
|
||||
expect(isSecurityConcern("secrets/")).toBe(true);
|
||||
expect(isSecurityConcern(".secrets/")).toBe(true);
|
||||
expect(isSecurityConcern("private/")).toBe(true);
|
||||
expect(isSecurityConcern(".private/")).toBe(true);
|
||||
expect(isSecurityConcern("certs/")).toBe(true);
|
||||
expect(isSecurityConcern("certificates/")).toBe(true);
|
||||
expect(isSecurityConcern("keys/")).toBe(true);
|
||||
expect(isSecurityConcern(".ssh/")).toBe(true);
|
||||
expect(isSecurityConcern(".gnupg/")).toBe(true);
|
||||
expect(isSecurityConcern(".gpg/")).toBe(true);
|
||||
});
|
||||
|
||||
it("should detect continue directory as security concern", () => {
|
||||
expect(isSecurityConcern(".continue/config.json")).toBe(true);
|
||||
});
|
||||
|
||||
it("should detect temporary secret directories as security concerns", () => {
|
||||
expect(isSecurityConcern("tmp/secrets/")).toBe(true);
|
||||
expect(isSecurityConcern("temp/secrets/")).toBe(true);
|
||||
expect(isSecurityConcern(".tmp/")).toBe(true);
|
||||
expect(isSecurityConcern("tmp/secrets/api.key")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Path variations", () => {
|
||||
it("should handle absolute paths", () => {
|
||||
expect(isSecurityConcern("/home/user/.env")).toBe(true);
|
||||
expect(isSecurityConcern("/var/www/.secrets/")).toBe(true);
|
||||
expect(isSecurityConcern("/etc/ssl/private.key")).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle URI schemes", () => {
|
||||
expect(isSecurityConcern("file:///home/user/.env")).toBe(true);
|
||||
expect(isSecurityConcern("file:///var/secrets/api.key")).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle nested paths", () => {
|
||||
expect(isSecurityConcern("project/config/.env")).toBe(true);
|
||||
expect(isSecurityConcern("src/main/resources/application.secret")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(isSecurityConcern("backend/certs/server.key")).toBe(true);
|
||||
});
|
||||
|
||||
// it("should handle Windows-style paths", () => {
|
||||
// expect(isSecurityConcern("C:\\Users\\user\\.env")).toBe(true);
|
||||
// expect(isSecurityConcern("D:\\projects\\app\\secrets\\")).toBe(true);
|
||||
// });
|
||||
});
|
||||
|
||||
describe("Non-security files", () => {
|
||||
it("should not flag regular source code files", () => {
|
||||
expect(isSecurityConcern("src/main.js")).toBe(false);
|
||||
expect(isSecurityConcern("components/App.tsx")).toBe(false);
|
||||
expect(isSecurityConcern("utils/helper.py")).toBe(false);
|
||||
expect(isSecurityConcern("models/User.java")).toBe(false);
|
||||
expect(isSecurityConcern("styles/main.css")).toBe(false);
|
||||
});
|
||||
|
||||
it("should not flag regular configuration files", () => {
|
||||
expect(isSecurityConcern("package.json")).toBe(false);
|
||||
expect(isSecurityConcern("tsconfig.json")).toBe(false);
|
||||
expect(isSecurityConcern("webpack.config.js")).toBe(false);
|
||||
expect(isSecurityConcern("babel.config.js")).toBe(false);
|
||||
expect(isSecurityConcern("jest.config.js")).toBe(false);
|
||||
});
|
||||
|
||||
it("should not flag documentation files", () => {
|
||||
expect(isSecurityConcern("README.md")).toBe(false);
|
||||
expect(isSecurityConcern("CHANGELOG.md")).toBe(false);
|
||||
expect(isSecurityConcern("docs/api.md")).toBe(false);
|
||||
expect(isSecurityConcern("LICENSE")).toBe(false);
|
||||
});
|
||||
|
||||
it("should not flag regular directories", () => {
|
||||
expect(isSecurityConcern("src/")).toBe(false);
|
||||
expect(isSecurityConcern("components/")).toBe(false);
|
||||
expect(isSecurityConcern("utils/")).toBe(false);
|
||||
expect(isSecurityConcern("tests/")).toBe(false);
|
||||
expect(isSecurityConcern("docs/")).toBe(false);
|
||||
});
|
||||
|
||||
it("should not flag files with similar names but different extensions", () => {
|
||||
expect(isSecurityConcern("environment.js")).toBe(false);
|
||||
expect(isSecurityConcern("config-template.json")).toBe(false);
|
||||
expect(isSecurityConcern("secret-utils.js")).toBe(false);
|
||||
expect(isSecurityConcern("token-validator.ts")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Edge cases", () => {
|
||||
it("should handle empty strings", () => {
|
||||
expect(isSecurityConcern("")).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle paths with only separators", () => {
|
||||
expect(isSecurityConcern("/")).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle paths with multiple extensions", () => {
|
||||
expect(isSecurityConcern("backup.env.old")).toBe(true); // matches *.old
|
||||
expect(isSecurityConcern("config.json.bak")).toBe(true); // matches *.bak
|
||||
expect(isSecurityConcern("server.key.backup")).toBe(true); // matches *.backup
|
||||
});
|
||||
|
||||
it("should handle files in root vs subdirectories", () => {
|
||||
expect(isSecurityConcern(".env")).toBe(true);
|
||||
expect(isSecurityConcern("project/.env")).toBe(true);
|
||||
expect(isSecurityConcern("deeply/nested/path/.env")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Pattern matching consistency", () => {
|
||||
it("should match all defined security file patterns", () => {
|
||||
// Test a sample from each category to ensure patterns work
|
||||
DEFAULT_SECURITY_IGNORE_FILETYPES.forEach((pattern) => {
|
||||
// Create a test file name that should match the pattern
|
||||
let testFile: string;
|
||||
if (pattern.startsWith("*.")) {
|
||||
testFile = `test${pattern.substring(1)}`;
|
||||
} else if (pattern.includes("*")) {
|
||||
testFile = pattern.replace("*", "test");
|
||||
} else {
|
||||
testFile = pattern;
|
||||
}
|
||||
|
||||
expect(isSecurityConcern(testFile)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("should match all defined security directory patterns", () => {
|
||||
DEFAULT_SECURITY_IGNORE_DIRS.forEach((pattern) => {
|
||||
// Test the directory pattern directly
|
||||
expect(isSecurityConcern(pattern)).toBe(true);
|
||||
|
||||
// Test a file inside the directory
|
||||
const fileInDir = `${pattern}testfile.txt`;
|
||||
expect(isSecurityConcern(fileInDir)).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Integration with ignore library", () => {
|
||||
it("should use the same ignore instance as defaultFileAndFolderSecurityIgnores", () => {
|
||||
// Test that our function uses the same logic as the exported ignore instance
|
||||
const testFiles = [
|
||||
".env",
|
||||
"secrets/api.key",
|
||||
".aws/credentials",
|
||||
"regular-file.js",
|
||||
];
|
||||
|
||||
testFiles.forEach((file) => {
|
||||
const functionResult = isSecurityConcern(file);
|
||||
const ignoreResult = defaultFileAndFolderSecurityIgnores.ignores(file);
|
||||
expect(functionResult).toBe(ignoreResult);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,7 +1,8 @@
|
|||
import ignore from "ignore";
|
||||
import type { FileType, IDE } from "../";
|
||||
import { findUriInDirs, getUriPathBasename } from "../util/uri";
|
||||
import { defaultIgnoreFileAndDir, getGlobalContinueIgArray } from "./ignore";
|
||||
import { getGlobalContinueIgArray } from "./continueignore";
|
||||
import { defaultIgnoreFileAndDir } from "./ignore";
|
||||
import { getIgnoreContext } from "./walkDir";
|
||||
|
||||
/*
|
||||
|
|
|
|||
|
|
@ -3,11 +3,8 @@ import ignore, { Ignore } from "ignore";
|
|||
import type { FileType, IDE } from "..";
|
||||
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
import {
|
||||
defaultIgnoreFileAndDir,
|
||||
getGlobalContinueIgArray,
|
||||
gitIgArrayFromFile,
|
||||
} from "./ignore";
|
||||
import { getGlobalContinueIgArray } from "./continueignore";
|
||||
import { defaultIgnoreFileAndDir, gitIgArrayFromFile } from "./ignore";
|
||||
|
||||
export interface WalkerOptions {
|
||||
include?: "dirs" | "files" | "both";
|
||||
|
|
|
|||
|
|
@ -177,7 +177,7 @@ function isProviderHandlesTemplatingOrNoTemplateTypeRequired(
|
|||
// NOTE: When updating this list,
|
||||
// update core/nextEdit/templating/NextEditPromptEngine.ts as well.
|
||||
const MODEL_SUPPORTS_NEXT_EDIT: string[] = [
|
||||
NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
|
||||
NEXT_EDIT_MODELS.MERCURY_CODER,
|
||||
NEXT_EDIT_MODELS.INSTINCT,
|
||||
];
|
||||
|
||||
|
|
|
|||
|
|
@ -220,7 +220,7 @@ describe("modelSupportsNextEdit", () => {
|
|||
expect(
|
||||
modelSupportsNextEdit(
|
||||
{ nextEdit: false },
|
||||
"mercury-coder-nextedit",
|
||||
"mercury-coder",
|
||||
"Mercury Coder",
|
||||
),
|
||||
).toBe(false);
|
||||
|
|
@ -231,7 +231,7 @@ describe("modelSupportsNextEdit", () => {
|
|||
expect(
|
||||
modelSupportsNextEdit(
|
||||
{ nextEdit: false },
|
||||
"mercury-coder-nextedit",
|
||||
"mercury-coder",
|
||||
"Mercury Coder",
|
||||
),
|
||||
).toBe(false);
|
||||
|
|
@ -239,10 +239,10 @@ describe("modelSupportsNextEdit", () => {
|
|||
});
|
||||
|
||||
describe("when capabilities.nextEdit is undefined", () => {
|
||||
it("should return true for mercury-coder-nextedit model (case insensitive)", () => {
|
||||
expect(
|
||||
modelSupportsNextEdit(undefined, "Mercury-Coder-Nextedit", undefined),
|
||||
).toBe(true);
|
||||
it("should return true for mercury-coder model (case insensitive)", () => {
|
||||
expect(modelSupportsNextEdit(undefined, "Mercury-Coder", undefined)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("should return true for instinct", () => {
|
||||
|
|
@ -255,7 +255,7 @@ describe("modelSupportsNextEdit", () => {
|
|||
expect(
|
||||
modelSupportsNextEdit(
|
||||
undefined,
|
||||
"provider/mercury-coder-nextedit-v2",
|
||||
"provider/mercury-coder-v2",
|
||||
undefined,
|
||||
),
|
||||
).toBe(true);
|
||||
|
|
@ -266,7 +266,7 @@ describe("modelSupportsNextEdit", () => {
|
|||
modelSupportsNextEdit(
|
||||
undefined,
|
||||
"some-model",
|
||||
"This is mercury-coder-nextedit model",
|
||||
"This is mercury-coder model",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
|
@ -312,14 +312,14 @@ describe("modelSupportsNextEdit", () => {
|
|||
});
|
||||
|
||||
it("should handle undefined title gracefully", () => {
|
||||
expect(
|
||||
modelSupportsNextEdit(undefined, "mercury-coder-nextedit", undefined),
|
||||
).toBe(true);
|
||||
expect(modelSupportsNextEdit(undefined, "mercury-coder", undefined)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle case sensitivity correctly", () => {
|
||||
expect(
|
||||
modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "instinct"),
|
||||
modelSupportsNextEdit(undefined, "MERCURY-CODER", "instinct"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ export enum LLMConfigurationStatuses {
|
|||
}
|
||||
|
||||
export enum NEXT_EDIT_MODELS {
|
||||
MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit",
|
||||
MERCURY_CODER = "mercury-coder",
|
||||
INSTINCT = "instinct",
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -46,6 +46,8 @@ export const EDIT_CODE_INSTRUCTIONS = `\
|
|||
of changes unless the user specifically asks for code only.
|
||||
`;
|
||||
|
||||
const BRIEF_LAZY_INSTRUCTIONS = `For larger codeblocks (>20 lines), use brief language-appropriate placeholders for unmodified sections, e.g. '// ... existing code ...'`;
|
||||
|
||||
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
|
||||
<important_rules>
|
||||
You are in chat mode.
|
||||
|
|
@ -64,6 +66,11 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
|
|||
If you need to use multiple tools, you can call multiple read only tools simultaneously.
|
||||
|
||||
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
|
||||
|
||||
${BRIEF_LAZY_INSTRUCTIONS}
|
||||
|
||||
However, only output codeblocks for suggestion and demonstration purposes, for example, when enumerating multiple hypothetical options. For implementing changes, use the edit tools.
|
||||
|
||||
</important_rules>`;
|
||||
|
||||
// The note about read-only tools is for MCP servers
|
||||
|
|
@ -75,7 +82,10 @@ export const DEFAULT_PLAN_SYSTEM_MESSAGE = `\
|
|||
If the user wants to make changes, offer that they can switch to Agent mode to give you access to write tools to make the suggested updates.
|
||||
|
||||
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
|
||||
${EDIT_CODE_INSTRUCTIONS}
|
||||
|
||||
${BRIEF_LAZY_INSTRUCTIONS}
|
||||
|
||||
However, only output codeblocks for suggestion and planning purposes. When ready to implement changes, request to switch to Agent mode.
|
||||
|
||||
In plan mode, only write code when directly suggesting changes. Prioritize understanding and developing a plan.
|
||||
</important_rules>`;
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@ import {
|
|||
import Handlebars from "handlebars";
|
||||
|
||||
import { DevDataSqliteDb } from "../data/devdataSqlite.js";
|
||||
import { Logger } from "../util/Logger.js";
|
||||
import { DataLogger } from "../data/log.js";
|
||||
import {
|
||||
CacheBehavior,
|
||||
|
|
@ -31,10 +30,11 @@ import {
|
|||
TemplateType,
|
||||
Usage,
|
||||
} from "../index.js";
|
||||
import { Logger } from "../util/Logger.js";
|
||||
import mergeJson from "../util/merge.js";
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
import { isOllamaInstalled } from "../util/ollamaHelper.js";
|
||||
import { Telemetry } from "../util/posthog.js";
|
||||
import { TokensBatchingService } from "../util/TokensBatchingService.js";
|
||||
import { withExponentialBackoff } from "../util/withExponentialBackoff.js";
|
||||
|
||||
import {
|
||||
|
|
@ -191,6 +191,8 @@ export abstract class BaseLLM implements ILLM {
|
|||
//URI to local block defining this LLM
|
||||
sourceFile?: string;
|
||||
|
||||
isFromAutoDetect?: boolean;
|
||||
|
||||
private _llmOptions: LLMOptions;
|
||||
|
||||
protected openaiAdapter?: BaseLlmApi;
|
||||
|
|
@ -294,6 +296,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
this.autocompleteOptions = options.autocompleteOptions;
|
||||
this.sourceFile = options.sourceFile;
|
||||
this.isFromAutoDetect = options.isFromAutoDetect;
|
||||
}
|
||||
|
||||
get contextLength() {
|
||||
|
|
@ -343,15 +346,11 @@ export abstract class BaseLLM implements ILLM {
|
|||
let generatedTokens = this.countTokens(completion);
|
||||
let thinkingTokens = thinking ? this.countTokens(thinking) : 0;
|
||||
|
||||
void Telemetry.capture(
|
||||
"tokens_generated",
|
||||
{
|
||||
model: model,
|
||||
provider: this.providerName,
|
||||
promptTokens: promptTokens,
|
||||
generatedTokens: generatedTokens,
|
||||
},
|
||||
true,
|
||||
TokensBatchingService.getInstance().addTokens(
|
||||
model,
|
||||
this.providerName,
|
||||
promptTokens,
|
||||
generatedTokens,
|
||||
);
|
||||
|
||||
void DevDataSqliteDb.logTokensGenerated(
|
||||
|
|
@ -371,8 +370,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,
|
||||
|
|
@ -394,15 +402,6 @@ export abstract class BaseLLM implements ILLM {
|
|||
});
|
||||
return "error";
|
||||
}
|
||||
} else {
|
||||
interaction?.logItem({
|
||||
kind: "success",
|
||||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
usage,
|
||||
});
|
||||
return "success";
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -616,6 +615,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
kind: "chunk",
|
||||
chunk: formattedContent,
|
||||
});
|
||||
|
||||
completion += formattedContent;
|
||||
yield content;
|
||||
}
|
||||
|
|
@ -631,6 +631,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
kind: "chunk",
|
||||
chunk,
|
||||
});
|
||||
|
||||
completion += chunk;
|
||||
yield chunk;
|
||||
}
|
||||
|
|
@ -1143,7 +1144,6 @@ export abstract class BaseLLM implements ILLM {
|
|||
modelProvider: this.underlyingProviderName,
|
||||
prompt,
|
||||
completion,
|
||||
completionOptions,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -19,9 +19,6 @@ async function dudLLMCall(llm: ILLM, messages: ChatMessage[]) {
|
|||
await gen.next();
|
||||
await gen.return({
|
||||
completion: "",
|
||||
completionOptions: {
|
||||
model: "",
|
||||
},
|
||||
modelTitle: "",
|
||||
modelProvider: "",
|
||||
prompt: "",
|
||||
|
|
|
|||
|
|
@ -145,6 +145,7 @@ function testLLM(
|
|||
description: "Say Hello",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["name"],
|
||||
properties: {
|
||||
name: {
|
||||
type: "string",
|
||||
|
|
@ -165,7 +166,7 @@ function testLLM(
|
|||
},
|
||||
)) {
|
||||
const typedChunk = chunk as AssistantChatMessage;
|
||||
if (!typedChunk.toolCalls) {
|
||||
if (!typedChunk.toolCalls || typedChunk.toolCalls.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const toolCall = typedChunk.toolCalls[0];
|
||||
|
|
@ -182,6 +183,15 @@ function testLLM(
|
|||
}
|
||||
}
|
||||
|
||||
// For Mistral, if no tool calls were received, skip the test
|
||||
// as it may not support forced tool use
|
||||
if (args === "" && llm.constructor.name === "Mistral") {
|
||||
console.log(
|
||||
"Mistral did not return tool calls, skipping assertion",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const parsedArgs = JSON.parse(args);
|
||||
expect(parsedArgs.name).toBe("Nate");
|
||||
}),
|
||||
|
|
@ -203,7 +213,7 @@ describe("LLM", () => {
|
|||
|
||||
testLLM(
|
||||
new Anthropic({
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
model: "claude-sonnet-4-0",
|
||||
apiKey: process.env.ANTHROPIC_API_KEY,
|
||||
}),
|
||||
{ skip: false, testToolCall: true },
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import { streamSse } from "@continuedev/fetch";
|
||||
import { CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
|
||||
import { ChatCompletionCreateParams } from "@continuedev/openai-adapters";
|
||||
import { UNIQUE_TOKEN } from "../../nextEdit/constants.js";
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
/**
|
||||
|
|
@ -32,6 +34,26 @@ class Inception extends OpenAI {
|
|||
return true;
|
||||
}
|
||||
|
||||
// It seems like this should be inherited automatically from the parent OpenAI class, but it sometimes doesn't.
|
||||
// protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [
|
||||
// "chat",
|
||||
// "embed",
|
||||
// "list",
|
||||
// "rerank",
|
||||
// "streamChat",
|
||||
// "streamFim",
|
||||
// ];
|
||||
|
||||
protected modifyChatBody(
|
||||
body: ChatCompletionCreateParams,
|
||||
): ChatCompletionCreateParams {
|
||||
const hasNextEditCapability = this.capabilities?.nextEdit ?? false;
|
||||
|
||||
// Add the nextEdit parameter for Inception-specific routing.
|
||||
(body as any).nextEdit = hasNextEditCapability;
|
||||
return body;
|
||||
}
|
||||
|
||||
async *_streamFim(
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
|
|
@ -67,6 +89,79 @@ class Inception extends OpenAI {
|
|||
yield chunk.choices[0].text;
|
||||
}
|
||||
}
|
||||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
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}`,
|
||||
},
|
||||
signal,
|
||||
});
|
||||
|
||||
for await (const chunk of streamSse(resp)) {
|
||||
if (chunk.choices?.[0]?.delta?.content) {
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: chunk.choices[0].delta.content,
|
||||
};
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Use regular chat/completions endpoint - call parent OpenAI implementation.
|
||||
yield* super._streamChat(messages, signal, options);
|
||||
}
|
||||
}
|
||||
|
||||
private isNextEdit(messages: ChatMessage[]): boolean {
|
||||
// Check if any message contains the unique next edit token.
|
||||
return messages.some(
|
||||
(message) =>
|
||||
typeof message.content === "string" &&
|
||||
message.content.endsWith(UNIQUE_TOKEN),
|
||||
);
|
||||
}
|
||||
|
||||
private removeNextEditToken(messages: ChatMessage[]): ChatMessage[] {
|
||||
const lastMessage = messages[messages.length - 1];
|
||||
|
||||
if (
|
||||
typeof lastMessage?.content === "string" &&
|
||||
lastMessage.content.endsWith(UNIQUE_TOKEN)
|
||||
) {
|
||||
const cleanedMessages = [...messages];
|
||||
cleanedMessages[cleanedMessages.length - 1] = {
|
||||
...lastMessage,
|
||||
content: lastMessage.content.slice(0, -UNIQUE_TOKEN.length),
|
||||
};
|
||||
return cleanedMessages;
|
||||
}
|
||||
|
||||
return messages;
|
||||
}
|
||||
}
|
||||
|
||||
export default Inception;
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue