merge: main
This commit is contained in:
commit
3bf58bd305
242 changed files with 16455 additions and 6355 deletions
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 }}'"
|
||||
15
.github/workflows/beta-release.yml
vendored
15
.github/workflows/beta-release.yml
vendored
|
|
@ -18,19 +18,28 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v3
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
always-auth: true
|
||||
|
||||
- name: Install dependencies
|
||||
- name: Setup packages
|
||||
uses: ./.github/actions/setup-packages
|
||||
|
||||
- name: Setup core component
|
||||
uses: ./.github/actions/setup-component
|
||||
with:
|
||||
component: core
|
||||
include-root: true
|
||||
|
||||
- name: Install CLI dependencies
|
||||
working-directory: extensions/cli
|
||||
run: npm ci
|
||||
env:
|
||||
|
|
|
|||
60
.github/workflows/cli-pr-checks.yml
vendored
60
.github/workflows/cli-pr-checks.yml
vendored
|
|
@ -3,8 +3,6 @@ name: CLI PR Checks
|
|||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "extensions/cli/**"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
|
@ -12,11 +10,19 @@ permissions:
|
|||
issues: write
|
||||
|
||||
jobs:
|
||||
track-rerun:
|
||||
runs-on: ubuntu-latest
|
||||
if: github.run_attempt > 1
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Track workflow rerun
|
||||
uses: ./.github/actions/track-rerun
|
||||
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
|
|
@ -25,10 +31,18 @@ jobs:
|
|||
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: Install dependencies
|
||||
run: |
|
||||
cd extensions/cli
|
||||
npm ci
|
||||
npm ci --include=optional
|
||||
|
||||
- name: Run linting
|
||||
run: |
|
||||
|
|
@ -44,38 +58,56 @@ jobs:
|
|||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Setup Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: "npm"
|
||||
cache-dependency-path: extensions/cli/package-lock.json
|
||||
|
||||
- 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: Install dependencies
|
||||
run: |
|
||||
cd extensions/cli
|
||||
npm ci
|
||||
npm ci --include=optional
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
cd extensions/cli
|
||||
npm run build
|
||||
|
||||
# e2e tests are failing on Windows specifically - likely due to stdout flush issues
|
||||
- name: Run smoke tests
|
||||
run: |
|
||||
cd extensions/cli
|
||||
npm run test:smoke
|
||||
|
||||
- name: Run tests
|
||||
if: matrix.os != 'windows-latest'
|
||||
run: |
|
||||
cd extensions/cli
|
||||
npm test
|
||||
|
||||
- name: Run tests (excluding e2e on Windows)
|
||||
if: matrix.os == 'windows-latest'
|
||||
shell: bash
|
||||
# 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 test -- --exclude='**/*.e2e.*' --exclude='**/e2e/**'
|
||||
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
|
||||
|
|
|
|||
2
.github/workflows/compliance.yaml
vendored
2
.github/workflows/compliance.yaml
vendored
|
|
@ -36,7 +36,7 @@ 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
|
||||
|
|
|
|||
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
|
||||
10
.github/workflows/jetbrains-release.yaml
vendored
10
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -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 }}
|
||||
|
|
@ -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
|
||||
|
|
|
|||
2
.github/workflows/main.yaml
vendored
2
.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:
|
||||
|
|
|
|||
8
.github/workflows/pr-checks.yaml
vendored
8
.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:
|
||||
|
|
|
|||
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
|
||||
|
|
|
|||
15
.github/workflows/stable-release.yml
vendored
15
.github/workflows/stable-release.yml
vendored
|
|
@ -34,13 +34,13 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v3
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
|
|
@ -141,6 +141,17 @@ jobs:
|
|||
# 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: Prepare package for direct stable release
|
||||
if: ${{ inputs.release_type == 'direct-stable' }}
|
||||
working-directory: 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,
|
||||
|
|
|
|||
189
binary/package-lock.json
generated
189
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",
|
||||
|
|
@ -139,6 +143,8 @@
|
|||
"@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 +2896,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 +3382,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 +3444,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 +3768,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 +3849,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 +3871,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 +3904,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 +3998,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 +4033,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 +5334,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 +6922,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"
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -59,7 +59,7 @@ import { localPathToUri } from "../util/pathToUri";
|
|||
|
||||
import { PolicySingleton } from "../control-plane/PolicySingleton";
|
||||
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
|
||||
import { getToolsForIde } from "../tools";
|
||||
import { getBaseToolDefinitions } from "../tools";
|
||||
import { resolveRelativePathInDir } from "../util/ideUtils";
|
||||
import { getWorkspaceRcConfigs } from "./json/loadRcConfigs";
|
||||
import { loadConfigContextProviders } from "./loadContextProviders";
|
||||
|
|
@ -283,6 +283,7 @@ async function intermediateToFinalConfig({
|
|||
...desc,
|
||||
model: modelName,
|
||||
title: modelName,
|
||||
isFromAutoDetect: true,
|
||||
},
|
||||
ide.readFile.bind(ide),
|
||||
getUriFromPath,
|
||||
|
|
@ -320,6 +321,7 @@ async function intermediateToFinalConfig({
|
|||
...desc.options,
|
||||
model: modelName,
|
||||
logger: llmLogger,
|
||||
isFromAutoDetect: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
|
@ -499,7 +501,7 @@ async function intermediateToFinalConfig({
|
|||
const continueConfig: ContinueConfig = {
|
||||
...config,
|
||||
contextProviders,
|
||||
tools: await getToolsForIde(ide),
|
||||
tools: getBaseToolDefinitions(),
|
||||
mcpServerStatuses: [],
|
||||
slashCommands: [],
|
||||
modelsByRole: {
|
||||
|
|
@ -632,6 +634,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
|
|||
apiKeyLocation: llm.apiKeyLocation,
|
||||
envSecretLocations: llm.envSecretLocations,
|
||||
sourceFile: llm.sourceFile,
|
||||
isFromAutoDetect: llm.isFromAutoDetect,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -29,11 +29,24 @@ export function loadConfigContextProviders(
|
|||
} {
|
||||
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) {
|
||||
if (
|
||||
!cls &&
|
||||
!defaultProviders.find((p) => p.description.title === config.provider)
|
||||
) {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Unknown context provider ${config.provider}`,
|
||||
|
|
@ -50,15 +63,6 @@ export function loadConfigContextProviders(
|
|||
}
|
||||
|
||||
// Add from defaults if not found in config
|
||||
const defaultProviders: IContextProvider[] = [
|
||||
new FileContextProvider({}),
|
||||
new CurrentFileContextProvider({}),
|
||||
new DiffContextProvider({}),
|
||||
new TerminalContextProvider({}),
|
||||
new ProblemsContextProvider({}),
|
||||
new RulesContextProvider({}),
|
||||
];
|
||||
|
||||
for (const defaultProvider of defaultProviders) {
|
||||
if (
|
||||
!providers.find(
|
||||
|
|
|
|||
|
|
@ -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, {
|
||||
|
|
|
|||
|
|
@ -18,6 +18,8 @@ describe("ASSISTANTS 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("ASSISTANTS 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("ASSISTANTS 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("ASSISTANTS 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("ASSISTANTS 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("ASSISTANTS 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("ASSISTANTS 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",
|
||||
|
|
|
|||
|
|
@ -282,6 +282,8 @@ export default async function doLoadConfig(options: {
|
|||
enableExperimentalTools:
|
||||
newConfig.experimental?.enableExperimentalTools ?? false,
|
||||
isSignedIn,
|
||||
isRemote: await ide.isWorkspaceRemote(),
|
||||
modelName: newConfig.selectedModelByRole.chat?.model,
|
||||
}),
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlo
|
|||
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
|
||||
import { getControlPlaneEnvSync } from "../../control-plane/env";
|
||||
import { PolicySingleton } from "../../control-plane/PolicySingleton";
|
||||
import { getToolsForIde } from "../../tools";
|
||||
import { getBaseToolDefinitions } from "../../tools";
|
||||
import { getCleanUriPath } from "../../util/uri";
|
||||
import { loadConfigContextProviders } from "../loadContextProviders";
|
||||
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
|
||||
|
|
@ -169,7 +169,7 @@ async function configYamlToContinueConfig(options: {
|
|||
|
||||
const continueConfig: ContinueConfig = {
|
||||
slashCommands: [],
|
||||
tools: await getToolsForIde(ide),
|
||||
tools: getBaseToolDefinitions(),
|
||||
mcpServerStatuses: [],
|
||||
contextProviders: [],
|
||||
modelsByRole: {
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import {
|
|||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../../";
|
||||
import { isSecurityConcern } from "../../indexing/ignore";
|
||||
import { walkDirs } from "../../indexing/walkDir";
|
||||
import {
|
||||
getShortestUniqueRelativeUriPaths,
|
||||
|
|
|
|||
|
|
@ -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}`,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -12,6 +12,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 +42,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,
|
||||
|
|
|
|||
|
|
@ -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([
|
||||
|
|
|
|||
5
core/index.d.ts
vendored
5
core/index.d.ts
vendored
|
|
@ -666,6 +666,7 @@ export interface LLMOptions {
|
|||
env?: Record<string, string | number | boolean>;
|
||||
|
||||
sourceFile?: string;
|
||||
isFromAutoDetect?: boolean;
|
||||
}
|
||||
|
||||
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
|
||||
|
|
@ -1112,6 +1113,8 @@ export interface ConfigDependentToolParams {
|
|||
rules: RuleWithSource[];
|
||||
enableExperimentalTools: boolean;
|
||||
isSignedIn: boolean;
|
||||
isRemote: boolean;
|
||||
modelName: string | undefined;
|
||||
}
|
||||
|
||||
export type GetTool = (params: ConfigDependentToolParams) => Tool;
|
||||
|
|
@ -1175,6 +1178,7 @@ export interface ModelDescription {
|
|||
configurationStatus?: LLMConfigurationStatuses;
|
||||
|
||||
sourceFile?: string;
|
||||
isFromAutoDetect?: boolean;
|
||||
}
|
||||
|
||||
export interface JSONEmbedOptions {
|
||||
|
|
@ -1605,6 +1609,7 @@ export interface JSONModelDescription {
|
|||
aiGatewaySlug?: string;
|
||||
useLegacyCompletionsEndpoint?: boolean;
|
||||
deploymentId?: string;
|
||||
isFromAutoDetect?: boolean;
|
||||
}
|
||||
|
||||
// config.json
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
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[]),
|
||||
);
|
||||
};
|
||||
|
|
@ -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";
|
||||
|
|
|
|||
|
|
@ -178,7 +178,6 @@ function isProviderHandlesTemplatingOrNoTemplateTypeRequired(
|
|||
// update core/nextEdit/templating/NextEditPromptEngine.ts as well.
|
||||
const MODEL_SUPPORTS_NEXT_EDIT: string[] = [
|
||||
NEXT_EDIT_MODELS.MERCURY_CODER,
|
||||
NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
|
||||
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);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -21,7 +21,6 @@ export enum LLMConfigurationStatuses {
|
|||
|
||||
export enum NEXT_EDIT_MODELS {
|
||||
MERCURY_CODER = "mercury-coder",
|
||||
MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit",
|
||||
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,6 +30,7 @@ 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";
|
||||
|
|
@ -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() {
|
||||
|
|
|
|||
|
|
@ -213,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 },
|
||||
|
|
|
|||
|
|
@ -148,7 +148,7 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
|
||||
if (options.model === "AUTODETECT") {
|
||||
if (options.isFromAutoDetect) {
|
||||
return;
|
||||
}
|
||||
const headers: Record<string, string> = {
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ class Vllm extends OpenAI {
|
|||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
|
||||
if (options.model === "AUTODETECT") {
|
||||
if (options.isFromAutoDetect) {
|
||||
this._setupCompletionOptions();
|
||||
}
|
||||
}
|
||||
|
|
@ -45,7 +45,7 @@ class Vllm extends OpenAI {
|
|||
// vLLM uses 'results' array instead of 'data'
|
||||
if (results.results && Array.isArray(results.results)) {
|
||||
const sortedResults = results.results.sort((a, b) => a.index - b.index);
|
||||
return sortedResults.map((result) => result.index);
|
||||
return sortedResults.map((result) => result.relevance_score);
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
|
|
|
|||
|
|
@ -280,6 +280,34 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("novita", () => {
|
||||
const supportsFn = PROVIDER_TOOL_SUPPORT["novita"];
|
||||
|
||||
it("should return true for exact match models", () => {
|
||||
expect(supportsFn("deepseek/deepseek-r1-0528")).toBe(true);
|
||||
expect(supportsFn("deepseek/deepseek-r1-turbo")).toBe(true);
|
||||
expect(supportsFn("deepseek/deepseek-v3-0324")).toBe(true);
|
||||
expect(supportsFn("deepseek/deepseek-v3-turbo")).toBe(true);
|
||||
expect(supportsFn("meta-llama/llama-3.3-70b-instruct")).toBe(true);
|
||||
expect(supportsFn("qwen/qwen-2.5-72b-instruct")).toBe(true);
|
||||
expect(supportsFn("zai-org/glm-4.5")).toBe(true);
|
||||
expect(supportsFn("moonshotai/kimi-k2-instruct")).toBe(true);
|
||||
});
|
||||
|
||||
it("should return true for prefix match models", () => {
|
||||
expect(supportsFn("qwen/qwen3-235b-a22b-instruct-2507")).toBe(true);
|
||||
expect(supportsFn("openai/gpt-oss-20b")).toBe(true);
|
||||
expect(supportsFn("openai/gpt-oss-120b")).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false for unsupported models", () => {
|
||||
expect(supportsFn("deepseek/deepseek-chat")).toBe(false);
|
||||
expect(supportsFn("meta-llama/llama-2-7b")).toBe(false);
|
||||
expect(supportsFn("qwen/qwen-2.0-7b")).toBe(false);
|
||||
expect(supportsFn("openai/gpt-4")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("openrouter", () => {
|
||||
const supportsFn = PROVIDER_TOOL_SUPPORT["openrouter"];
|
||||
|
||||
|
|
@ -297,6 +325,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
|
|||
expect(PROVIDER_TOOL_SUPPORT["gemini"]("")).toBe(false);
|
||||
expect(PROVIDER_TOOL_SUPPORT["bedrock"]("")).toBe(false);
|
||||
expect(PROVIDER_TOOL_SUPPORT["ollama"]("")).toBe(false);
|
||||
expect(PROVIDER_TOOL_SUPPORT["novita"]("")).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle non-existent provider", () => {
|
||||
|
|
|
|||
|
|
@ -334,6 +334,36 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
novita: (model) => {
|
||||
const lower = model.toLowerCase();
|
||||
|
||||
// Exact match models
|
||||
const exactMatches = [
|
||||
"deepseek/deepseek-r1-0528",
|
||||
"deepseek/deepseek-r1-turbo",
|
||||
"deepseek/deepseek-v3-0324",
|
||||
"deepseek/deepseek-v3-turbo",
|
||||
"meta-llama/llama-3.3-70b-instruct",
|
||||
"qwen/qwen-2.5-72b-instruct",
|
||||
"zai-org/glm-4.5",
|
||||
"moonshotai/kimi-k2-instruct",
|
||||
];
|
||||
|
||||
if (exactMatches.includes(lower)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Prefix match models
|
||||
const prefixMatches = ["qwen/qwen3", "openai/gpt-oss"];
|
||||
|
||||
for (const prefix of prefixMatches) {
|
||||
if (lower.startsWith(prefix)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
};
|
||||
|
|
@ -345,6 +375,7 @@ export function isRecommendedAgentModel(modelName: string): boolean {
|
|||
[/deepseek/, /r1|reasoner/],
|
||||
[/gemini/, /2\.5/, /pro/],
|
||||
[/gpt/, /4/],
|
||||
[/gpt-5/],
|
||||
[/claude/, /sonnet/, /3\.5|3\.7|3-5|3-7|-4/],
|
||||
[/claude/, /opus/, /-4/],
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,15 +1,6 @@
|
|||
import * as path from "path";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { ConfigHandler } from "../config/ConfigHandler.js";
|
||||
import {
|
||||
ChatMessage,
|
||||
DiffLine,
|
||||
IDE,
|
||||
ILLM,
|
||||
Position,
|
||||
Range,
|
||||
RangeInFile,
|
||||
} from "../index.js";
|
||||
import { ChatMessage, IDE, ILLM, Range, RangeInFile } from "../index.js";
|
||||
import OpenAI from "../llm/llms/OpenAI.js";
|
||||
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
|
||||
|
||||
|
|
@ -18,10 +9,7 @@ import { ContextRetrievalService } from "../autocomplete/context/ContextRetrieva
|
|||
import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js";
|
||||
import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js";
|
||||
import { shouldPrefilter } from "../autocomplete/prefiltering/index.js";
|
||||
import {
|
||||
getAllSnippetsWithoutRace,
|
||||
SnippetPayload,
|
||||
} from "../autocomplete/snippets/index.js";
|
||||
import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js";
|
||||
import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types.js";
|
||||
import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
|
||||
import { getAst } from "../autocomplete/util/ast.js";
|
||||
|
|
@ -29,38 +17,23 @@ import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebounce
|
|||
import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js";
|
||||
import { HelperVars } from "../autocomplete/util/HelperVars.js";
|
||||
import { AutocompleteInput } from "../autocomplete/util/types.js";
|
||||
import { myersDiff } from "../diff/myers.js";
|
||||
import { isSecurityConcern } from "../indexing/ignore.js";
|
||||
import { modelSupportsNextEdit } from "../llm/autodetect.js";
|
||||
import { NEXT_EDIT_MODELS } from "../llm/constants.js";
|
||||
import { countTokens } from "../llm/countTokens.js";
|
||||
import { localPathOrUriToPath } from "../util/pathToUri.js";
|
||||
import {
|
||||
INSTINCT_SYSTEM_PROMPT,
|
||||
MERCURY_SYSTEM_PROMPT,
|
||||
MODEL_WINDOW_SIZES,
|
||||
UNIQUE_TOKEN,
|
||||
} from "./constants.js";
|
||||
import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
|
||||
import {
|
||||
calculateFinalCursorPosition,
|
||||
DiffGroup,
|
||||
groupDiffLines,
|
||||
} from "./diff/diff.js";
|
||||
import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js";
|
||||
import { NextEditLoggingService } from "./NextEditLoggingService.js";
|
||||
import { PrefetchQueue } from "./NextEditPrefetchQueue.js";
|
||||
import { NextEditProviderFactory } from "./NextEditProviderFactory.js";
|
||||
import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js";
|
||||
import {
|
||||
renderDefaultSystemPrompt,
|
||||
renderDefaultUserPrompt,
|
||||
renderPrompt,
|
||||
} from "./templating/NextEditPromptEngine.js";
|
||||
import {
|
||||
ModelSpecificContext,
|
||||
NextEditOutcome,
|
||||
Prompt,
|
||||
PromptMetadata,
|
||||
RecentlyEditedRange,
|
||||
} from "./types.js";
|
||||
import { isWhitespaceOnlyDeletion } from "./utils.js";
|
||||
|
||||
const autocompleteCache = AutocompleteLruCache.get();
|
||||
|
||||
|
|
@ -91,6 +64,9 @@ export class NextEditProvider {
|
|||
private previousCompletions: NextEditOutcome[] = [];
|
||||
// private nextEditableRegionsInTheCurrentChain: RangeInFile[] = [];
|
||||
|
||||
// Model-specific provider instance.
|
||||
private modelProvider: BaseNextEditProvider | null = null;
|
||||
|
||||
private constructor(
|
||||
private readonly configHandler: ConfigHandler,
|
||||
private readonly ide: IDE,
|
||||
|
|
@ -285,6 +261,9 @@ export class NextEditProvider {
|
|||
usingFullFileDiff: boolean;
|
||||
},
|
||||
): Promise<NextEditOutcome | undefined> {
|
||||
if (isSecurityConcern(input.filepath)) {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
this.previousRequest = input;
|
||||
const {
|
||||
|
|
@ -294,28 +273,23 @@ export class NextEditProvider {
|
|||
} = await this._initializeCompletionRequest(input, token);
|
||||
if (!helper) return undefined;
|
||||
|
||||
// Create model-specific provider based on the model name.
|
||||
this.modelProvider = NextEditProviderFactory.createProvider(
|
||||
helper.modelName,
|
||||
);
|
||||
|
||||
const { editableRegionStartLine, editableRegionEndLine, prompts } =
|
||||
await this._generatePrompts(helper, opts);
|
||||
|
||||
if (this.endpointType === "default") {
|
||||
return await this._handleDefaultEndpointCompletion(
|
||||
helper,
|
||||
prompts,
|
||||
abortToken,
|
||||
startTime,
|
||||
editableRegionEndLine,
|
||||
);
|
||||
} else {
|
||||
return await this._handleFineTunedEndpointCompletion(
|
||||
helper,
|
||||
prompts,
|
||||
abortToken,
|
||||
startTime,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
opts,
|
||||
);
|
||||
}
|
||||
return await this._handleCompletion(
|
||||
helper,
|
||||
prompts,
|
||||
abortToken,
|
||||
startTime,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
opts,
|
||||
);
|
||||
} catch (e: any) {
|
||||
this.onError(e);
|
||||
} finally {
|
||||
|
|
@ -331,7 +305,7 @@ export class NextEditProvider {
|
|||
startTime: number;
|
||||
helper: HelperVars | undefined;
|
||||
}> {
|
||||
// Create abort signal if not given.
|
||||
// Create abort signal if not given
|
||||
if (!token) {
|
||||
const controller = this.loggingService.createAbortController(
|
||||
input.completionId,
|
||||
|
|
@ -341,7 +315,7 @@ export class NextEditProvider {
|
|||
const startTime = Date.now();
|
||||
const options = await this._getAutocompleteOptions();
|
||||
|
||||
// Debounce.
|
||||
// Debounce
|
||||
if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) {
|
||||
return { token, startTime, helper: undefined };
|
||||
}
|
||||
|
|
@ -351,9 +325,7 @@ export class NextEditProvider {
|
|||
return { token, startTime, helper: undefined };
|
||||
}
|
||||
|
||||
// In vscode, this check is done in extensions/vscode/src/extension/VsCodeExtension.ts.
|
||||
// For other editors, this check should be done in their respective config reloaders.
|
||||
// This is left for a final check.
|
||||
// Check model capabilities
|
||||
if (!modelSupportsNextEdit(llm.capabilities, llm.model, llm.title)) {
|
||||
console.error(`${llm.model} is not capable of next edit.`);
|
||||
return { token, startTime, helper: undefined };
|
||||
|
|
@ -383,6 +355,10 @@ export class NextEditProvider {
|
|||
editableRegionEndLine: number;
|
||||
prompts: Prompt[];
|
||||
}> {
|
||||
if (!this.modelProvider) {
|
||||
throw new Error("Model provider not initialized");
|
||||
}
|
||||
|
||||
const [snippetPayload, workspaceDirs] = await Promise.all([
|
||||
getAllSnippetsWithoutRace({
|
||||
helper,
|
||||
|
|
@ -393,56 +369,118 @@ export class NextEditProvider {
|
|||
this.ide.getWorkspaceDirs(),
|
||||
]);
|
||||
|
||||
const modelName = helper.modelName.includes(
|
||||
NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
|
||||
)
|
||||
? NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT
|
||||
: helper.modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER)
|
||||
? NEXT_EDIT_MODELS.MERCURY_CODER
|
||||
: NEXT_EDIT_MODELS.INSTINCT;
|
||||
|
||||
// Calculate editable region based on model and options.
|
||||
const { editableRegionStartLine, editableRegionEndLine } =
|
||||
opts?.usingFullFileDiff
|
||||
? this._calculateOptimalEditableRegion(helper, "tokenizer")
|
||||
: {
|
||||
editableRegionStartLine: Math.max(
|
||||
helper.pos.line - MODEL_WINDOW_SIZES[modelName].topMargin,
|
||||
0,
|
||||
),
|
||||
editableRegionEndLine: Math.min(
|
||||
helper.pos.line + MODEL_WINDOW_SIZES[modelName].bottomMargin,
|
||||
helper.fileLines.length - 1,
|
||||
),
|
||||
};
|
||||
this.modelProvider.calculateEditableRegion(
|
||||
helper,
|
||||
opts?.usingFullFileDiff ?? false,
|
||||
);
|
||||
|
||||
// const editableRegionStartLine = opts?.usingFullFileDiff
|
||||
// ? 0
|
||||
// : Math.max(helper.pos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN, 0);
|
||||
// Build context for model-specific prompt generation.
|
||||
const context: ModelSpecificContext = {
|
||||
helper,
|
||||
snippetPayload,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
diffContext: this.diffContext,
|
||||
autocompleteContext: this.autocompleteContext,
|
||||
historyDiff: createDiff({
|
||||
beforeContent:
|
||||
DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory(
|
||||
localPathOrUriToPath(helper.filepath),
|
||||
) ?? "",
|
||||
afterContent: helper.fileContents,
|
||||
filePath: helper.filepath,
|
||||
diffType: DiffFormatType.Unified,
|
||||
contextLines: 3,
|
||||
}),
|
||||
};
|
||||
|
||||
// const editableRegionEndLine = opts?.usingFullFileDiff
|
||||
// ? helper.fileLines.length - 1
|
||||
// : Math.min(
|
||||
// helper.pos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
|
||||
// helper.fileLines.length - 1,
|
||||
// );
|
||||
const prompts = await this.modelProvider.generatePrompts(context);
|
||||
|
||||
const prompts: Prompt[] = [];
|
||||
this.promptMetadata = this.modelProvider.buildPromptMetadata(context);
|
||||
|
||||
if (this.endpointType === "default") {
|
||||
prompts.push(renderDefaultSystemPrompt());
|
||||
prompts.push(renderDefaultUserPrompt(snippetPayload, helper));
|
||||
return { editableRegionStartLine, editableRegionEndLine, prompts };
|
||||
}
|
||||
|
||||
private async _handleCompletion(
|
||||
helper: HelperVars,
|
||||
prompts: Prompt[],
|
||||
token: AbortSignal,
|
||||
startTime: number,
|
||||
editableRegionStartLine: number,
|
||||
editableRegionEndLine: number,
|
||||
opts?: {
|
||||
withChain: boolean;
|
||||
usingFullFileDiff: boolean;
|
||||
},
|
||||
): Promise<NextEditOutcome | undefined> {
|
||||
if (!this.modelProvider) {
|
||||
throw new Error("Model provider not initialized");
|
||||
}
|
||||
|
||||
const llm = await this._prepareLlm();
|
||||
if (!llm) return undefined;
|
||||
|
||||
// Inject unique token if needed (for Mercury models).
|
||||
if (this.modelProvider.shouldInjectUniqueToken()) {
|
||||
const uniqueToken = this.modelProvider.getUniqueToken();
|
||||
if (uniqueToken) {
|
||||
const lastPrompt = prompts[prompts.length - 1];
|
||||
if (lastPrompt && typeof lastPrompt.content === "string") {
|
||||
lastPrompt.content += uniqueToken;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Send prompts to LLM (using only user prompt for fine-tuned models).
|
||||
const msg: ChatMessage = await llm.chat([prompts[1]], token, {
|
||||
stream: false,
|
||||
});
|
||||
|
||||
if (typeof msg.content !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Extract completion using model-specific logic.
|
||||
const nextCompletion = this.modelProvider.extractCompletion(msg.content);
|
||||
|
||||
let outcome: NextEditOutcome | undefined;
|
||||
|
||||
// Handle based on diff type.
|
||||
if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
|
||||
outcome = await this.modelProvider.handlePartialFileDiff(
|
||||
helper,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
startTime,
|
||||
llm,
|
||||
nextCompletion,
|
||||
this.promptMetadata!,
|
||||
this.ide,
|
||||
);
|
||||
} else {
|
||||
prompts.push(
|
||||
...(await this._generateFineTunedPrompts(
|
||||
helper,
|
||||
snippetPayload,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
)),
|
||||
outcome = await this.modelProvider.handleFullFileDiff(
|
||||
helper,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
startTime,
|
||||
llm,
|
||||
nextCompletion,
|
||||
this.promptMetadata!,
|
||||
this.ide,
|
||||
);
|
||||
}
|
||||
|
||||
return { editableRegionStartLine, editableRegionEndLine, prompts };
|
||||
if (outcome) {
|
||||
// Handle NextEditProvider-specific state
|
||||
this.previousCompletions.push(outcome);
|
||||
|
||||
// Mark as displayed for JetBrains
|
||||
await this._markDisplayedIfJetBrains(helper.input.completionId, outcome);
|
||||
}
|
||||
|
||||
return outcome;
|
||||
}
|
||||
|
||||
private _calculateOptimalEditableRegion(
|
||||
|
|
@ -536,500 +574,6 @@ export class NextEditProvider {
|
|||
};
|
||||
}
|
||||
|
||||
private async _generateFineTunedPrompts(
|
||||
helper: HelperVars,
|
||||
snippetPayload: SnippetPayload,
|
||||
editableRegionStartLine: number,
|
||||
editableRegionEndLine: number,
|
||||
): Promise<Prompt[]> {
|
||||
const historyDiff = createDiff({
|
||||
beforeContent:
|
||||
DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory(
|
||||
localPathOrUriToPath(helper.filepath),
|
||||
) ?? "",
|
||||
afterContent: helper.fileContents,
|
||||
filePath: helper.filepath,
|
||||
diffType: DiffFormatType.Unified,
|
||||
contextLines: 3,
|
||||
});
|
||||
|
||||
const modelName = helper.modelName;
|
||||
let ctx: any;
|
||||
|
||||
if (
|
||||
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) ||
|
||||
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT)
|
||||
) {
|
||||
ctx = {
|
||||
recentlyViewedCodeSnippets:
|
||||
snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({
|
||||
filepath: snip.filepath,
|
||||
content: snip.content,
|
||||
})) ?? [],
|
||||
currentFileContent: helper.fileContents,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
editDiffHistory: this.diffContext,
|
||||
currentFilePath: helper.filepath,
|
||||
};
|
||||
} else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) {
|
||||
// Calculate the window around the cursor position (25 lines above and below).
|
||||
const windowStart = Math.max(0, helper.pos.line - 25);
|
||||
const windowEnd = Math.min(
|
||||
helper.fileLines.length - 1,
|
||||
helper.pos.line + 25,
|
||||
);
|
||||
|
||||
// // The editable region is defined as: cursor line - 1 to cursor line + 5 (inclusive).
|
||||
// const actualEditableStart = Math.max(
|
||||
// 0,
|
||||
// helper.pos.line - MODEL_WINDOW_SIZES["instinct"].topMargin,
|
||||
// );
|
||||
// const actualEditableEnd = Math.min(
|
||||
// helper.fileLines.length - 1,
|
||||
// helper.pos.line + MODEL_WINDOW_SIZES["instinct"].bottomMargin,
|
||||
// );
|
||||
|
||||
// Ensure editable region boundaries are within the window.
|
||||
const adjustedEditableStart = Math.max(
|
||||
windowStart,
|
||||
editableRegionStartLine,
|
||||
);
|
||||
const adjustedEditableEnd = Math.min(windowEnd, editableRegionEndLine);
|
||||
ctx = {
|
||||
contextSnippets: this.autocompleteContext,
|
||||
currentFileContent: helper.fileContents,
|
||||
windowStart,
|
||||
windowEnd,
|
||||
editableRegionStartLine: adjustedEditableStart,
|
||||
editableRegionEndLine: adjustedEditableEnd,
|
||||
editDiffHistory: this.diffContext,
|
||||
currentFilePath: helper.filepath,
|
||||
languageShorthand: helper.lang.name,
|
||||
};
|
||||
} else {
|
||||
ctx = {};
|
||||
}
|
||||
|
||||
const promptMetadata = await renderPrompt(helper, ctx);
|
||||
this.promptMetadata = promptMetadata;
|
||||
|
||||
const systemPrompt: Prompt = {
|
||||
role: "system",
|
||||
content:
|
||||
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) ||
|
||||
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT)
|
||||
? MERCURY_SYSTEM_PROMPT
|
||||
: INSTINCT_SYSTEM_PROMPT,
|
||||
};
|
||||
|
||||
return [systemPrompt, promptMetadata.prompt];
|
||||
}
|
||||
|
||||
private async _handleDefaultEndpointCompletion(
|
||||
helper: HelperVars,
|
||||
prompts: Prompt[],
|
||||
token: AbortSignal,
|
||||
startTime: number,
|
||||
editableRegionEndLine: number,
|
||||
): Promise<NextEditOutcome | undefined> {
|
||||
const llm = await this._prepareLlm();
|
||||
if (!llm) return undefined;
|
||||
|
||||
const msg: ChatMessage = await llm.chat(prompts, token);
|
||||
|
||||
if (typeof msg.content === "string") {
|
||||
const nextCompletion = JSON.parse(msg.content).newCode;
|
||||
const finalCursorPos: Position = {
|
||||
line: editableRegionEndLine,
|
||||
character: 0,
|
||||
};
|
||||
|
||||
const outcomeNext = await this._createNextEditOutcome({
|
||||
helper,
|
||||
startTime,
|
||||
llm,
|
||||
promptContent: prompts.join("\n"),
|
||||
completion: nextCompletion,
|
||||
finalCursorPosition: finalCursorPos,
|
||||
editableRegionStartLine: 0,
|
||||
editableRegionEndLine: 0,
|
||||
userEdits: "",
|
||||
userExcerpts: "",
|
||||
originalEditableRange: "",
|
||||
diffLines: [],
|
||||
});
|
||||
|
||||
// Mark as displayed for JetBrains extension
|
||||
await this._markDisplayedIfJetBrains(
|
||||
helper.input.completionId,
|
||||
outcomeNext,
|
||||
);
|
||||
|
||||
return outcomeNext;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private async _handleFineTunedEndpointCompletion(
|
||||
helper: HelperVars,
|
||||
prompts: Prompt[],
|
||||
token: AbortSignal,
|
||||
startTime: number,
|
||||
editableRegionStartLine: number,
|
||||
editableRegionEndLine: number,
|
||||
opts?: {
|
||||
withChain: boolean;
|
||||
usingFullFileDiff: boolean;
|
||||
},
|
||||
): Promise<NextEditOutcome | undefined> {
|
||||
const llm = await this._prepareLlm();
|
||||
if (!llm) return undefined;
|
||||
|
||||
// Check for mercury models, and inject unique token for next edit.
|
||||
// Capture the unique tokens in llm Inception.ts and apis Inception.ts
|
||||
const modelName = helper.modelName;
|
||||
if (
|
||||
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) ||
|
||||
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT)
|
||||
) {
|
||||
// Inject the unique token to the last prompt's content.
|
||||
const lastPrompt = prompts[prompts.length - 1];
|
||||
if (lastPrompt && typeof lastPrompt.content === "string") {
|
||||
lastPrompt.content += UNIQUE_TOKEN;
|
||||
}
|
||||
}
|
||||
|
||||
const msg: ChatMessage = await llm.chat([prompts[1]], token, {
|
||||
stream: false,
|
||||
});
|
||||
|
||||
if (typeof msg.content !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// NOTE: Keep this in case there is a change in spec.
|
||||
// const nextCompletion =
|
||||
// msg.content
|
||||
// .split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1]
|
||||
// .replace(/\n$/, "") ?? msg.content;
|
||||
const nextCompletion = msg.content.slice(
|
||||
msg.content.indexOf("\`\`\`\n") + "\'\'\'\n".length,
|
||||
msg.content.lastIndexOf("\n\n\`\`\`"),
|
||||
);
|
||||
|
||||
if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
|
||||
return await this._handlePartialFileDiff(
|
||||
// we could use fillFileDiff
|
||||
helper,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
startTime,
|
||||
llm,
|
||||
nextCompletion,
|
||||
);
|
||||
} else {
|
||||
return await this._handleFullFileDiff(
|
||||
helper,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
startTime,
|
||||
llm,
|
||||
nextCompletion,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async _handlePartialFileDiff(
|
||||
helper: HelperVars,
|
||||
editableRegionStartLine: number,
|
||||
editableRegionEndLine: number,
|
||||
startTime: number,
|
||||
llm: ILLM,
|
||||
nextCompletion: string,
|
||||
): Promise<NextEditOutcome | undefined> {
|
||||
const oldEditRangeSlice = helper.fileContents
|
||||
.split("\n")
|
||||
.slice(editableRegionStartLine, editableRegionEndLine + 1)
|
||||
.join("\n");
|
||||
|
||||
const finalCursorPos = calculateFinalCursorPosition(
|
||||
helper.pos,
|
||||
editableRegionStartLine,
|
||||
oldEditRangeSlice,
|
||||
nextCompletion,
|
||||
);
|
||||
|
||||
const outcomeNext = await this._createNextEditOutcome({
|
||||
helper,
|
||||
startTime,
|
||||
llm,
|
||||
promptContent: this.promptMetadata!.prompt.content,
|
||||
completion: nextCompletion,
|
||||
finalCursorPosition: finalCursorPos,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
userEdits: this.promptMetadata!.userEdits,
|
||||
userExcerpts: this.promptMetadata!.userExcerpts,
|
||||
originalEditableRange: oldEditRangeSlice,
|
||||
diffLines: [],
|
||||
});
|
||||
|
||||
this.previousCompletions.push(outcomeNext);
|
||||
|
||||
// Mark as displayed for JetBrains extension
|
||||
await this._markDisplayedIfJetBrains(
|
||||
helper.input.completionId,
|
||||
outcomeNext,
|
||||
);
|
||||
|
||||
return outcomeNext;
|
||||
}
|
||||
|
||||
private async _handleFullFileDiff(
|
||||
helper: HelperVars,
|
||||
editableRegionStartLine: number,
|
||||
editableRegionEndLine: number,
|
||||
startTime: number,
|
||||
llm: ILLM,
|
||||
nextCompletion: string,
|
||||
): Promise<NextEditOutcome | undefined> {
|
||||
const fileSlice = helper.fileLines
|
||||
.slice(editableRegionStartLine, editableRegionEndLine + 1)
|
||||
.join("\n");
|
||||
const diffLines = myersDiff(fileSlice, nextCompletion);
|
||||
const diffGroups = groupDiffLines(
|
||||
diffLines,
|
||||
editableRegionStartLine,
|
||||
5,
|
||||
).filter((group) => !isWhitespaceOnlyDeletion(group.lines));
|
||||
const currentLine = helper.pos.line;
|
||||
const prefetchQueue = PrefetchQueue.getInstance();
|
||||
|
||||
// Process diff groups and find the one containing the cursor
|
||||
const cursorLocalDiffGroup = await this._processDiffGroups(
|
||||
diffGroups,
|
||||
currentLine,
|
||||
helper,
|
||||
startTime,
|
||||
llm,
|
||||
prefetchQueue,
|
||||
);
|
||||
|
||||
// Handle the diff group containing the cursor if found
|
||||
if (cursorLocalDiffGroup) {
|
||||
return await this._createOutcomeFromDiffGroup(
|
||||
cursorLocalDiffGroup,
|
||||
helper,
|
||||
startTime,
|
||||
llm,
|
||||
helper.input.completionId,
|
||||
true,
|
||||
);
|
||||
// } else if (diffGroups.length > 0) {
|
||||
// // Fallback to first diff group if cursor's group not found
|
||||
// return await this._createOutcomeFromDiffGroup(
|
||||
// diffGroups[0],
|
||||
// helper,
|
||||
// startTime,
|
||||
// llm,
|
||||
// helper.input.completionId,
|
||||
// false,
|
||||
// );
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private async _processDiffGroups(
|
||||
diffGroups: DiffGroup[],
|
||||
currentLine: number,
|
||||
helper: HelperVars,
|
||||
startTime: number,
|
||||
llm: ILLM,
|
||||
prefetchQueue: PrefetchQueue,
|
||||
): Promise<DiffGroup | undefined> {
|
||||
let cursorGroup: DiffGroup | undefined;
|
||||
|
||||
console.log("diffGroups:");
|
||||
console.log(diffGroups);
|
||||
|
||||
for (const group of diffGroups) {
|
||||
if (currentLine >= group.startLine && currentLine <= group.endLine) {
|
||||
cursorGroup = group;
|
||||
} else {
|
||||
// Add non-cursor groups to prefetch queue
|
||||
await this._addDiffGroupToPrefetchQueue(
|
||||
group,
|
||||
helper,
|
||||
startTime,
|
||||
llm,
|
||||
prefetchQueue,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return cursorGroup;
|
||||
}
|
||||
|
||||
private async _addDiffGroupToPrefetchQueue(
|
||||
group: DiffGroup,
|
||||
helper: HelperVars,
|
||||
startTime: number,
|
||||
llm: ILLM,
|
||||
prefetchQueue: PrefetchQueue,
|
||||
): Promise<void> {
|
||||
const groupContent = group.lines
|
||||
.filter((l) => l.type !== "old")
|
||||
.map((l) => l.line)
|
||||
.join("\n");
|
||||
|
||||
// Create a range for this diff group
|
||||
const rangeInFile: RangeInFile = {
|
||||
filepath: helper.filepath,
|
||||
range: {
|
||||
start: { line: group.startLine, character: 0 },
|
||||
end: {
|
||||
line: group.endLine,
|
||||
character: group.lines[group.lines.length - 1].line.length,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const originalContent = group.lines
|
||||
.filter((l) => l.type !== "new")
|
||||
.map((l) => l.line)
|
||||
.join("\n");
|
||||
|
||||
// Build outcome for this diff group
|
||||
const groupOutcome = await this._createNextEditOutcome({
|
||||
helper,
|
||||
startTime,
|
||||
llm,
|
||||
promptContent: this.promptMetadata!.prompt.content,
|
||||
completion: groupContent,
|
||||
finalCursorPosition: {
|
||||
line: group.endLine,
|
||||
character: group.lines[group.lines.length - 1].line.length,
|
||||
},
|
||||
editableRegionStartLine: group.startLine,
|
||||
editableRegionEndLine: group.endLine,
|
||||
userEdits: this.promptMetadata!.userEdits,
|
||||
userExcerpts: this.promptMetadata!.userExcerpts,
|
||||
originalEditableRange: originalContent,
|
||||
cursorPosition: { line: group.startLine, character: 0 },
|
||||
completionId: uuidv4(), // Generate a new ID for this prefetched item
|
||||
diffLines: group.lines,
|
||||
});
|
||||
|
||||
// Add to prefetch queue
|
||||
prefetchQueue.enqueueProcessed({
|
||||
location: rangeInFile,
|
||||
outcome: groupOutcome,
|
||||
});
|
||||
}
|
||||
|
||||
private async _createOutcomeFromDiffGroup(
|
||||
diffGroup: DiffGroup,
|
||||
helper: HelperVars,
|
||||
startTime: number,
|
||||
llm: ILLM,
|
||||
completionId: string,
|
||||
isCurrentCursorGroup: boolean,
|
||||
): Promise<NextEditOutcome> {
|
||||
const groupContent = diffGroup.lines
|
||||
.filter((l) => l.type !== "old")
|
||||
.map((line) => line.line)
|
||||
.join("\n");
|
||||
|
||||
const originalContent = diffGroup.lines
|
||||
.filter((l) => l.type !== "new")
|
||||
.map((l) => l.line)
|
||||
.join("\n");
|
||||
|
||||
// Use the actual cursor position if this is the group containing the cursor
|
||||
// Otherwise use the start of the diff group
|
||||
const cursorPos = isCurrentCursorGroup
|
||||
? helper.pos
|
||||
: { line: diffGroup.startLine, character: 0 };
|
||||
|
||||
const finalCursorPos = calculateFinalCursorPosition(
|
||||
cursorPos,
|
||||
diffGroup.startLine,
|
||||
originalContent,
|
||||
groupContent,
|
||||
);
|
||||
|
||||
const outcomeNext = await this._createNextEditOutcome({
|
||||
helper,
|
||||
startTime,
|
||||
llm,
|
||||
promptContent: this.promptMetadata!.prompt.content,
|
||||
completion: groupContent,
|
||||
finalCursorPosition: finalCursorPos,
|
||||
editableRegionStartLine: diffGroup.startLine,
|
||||
editableRegionEndLine: diffGroup.endLine,
|
||||
userEdits: this.promptMetadata!.userEdits,
|
||||
userExcerpts: this.promptMetadata!.userExcerpts,
|
||||
originalEditableRange: originalContent,
|
||||
cursorPosition: cursorPos,
|
||||
completionId,
|
||||
diffLines: diffGroup.lines,
|
||||
});
|
||||
|
||||
this.previousCompletions.push(outcomeNext);
|
||||
|
||||
// Mark as displayed for JetBrains
|
||||
await this._markDisplayedIfJetBrains(completionId, outcomeNext);
|
||||
|
||||
return outcomeNext;
|
||||
}
|
||||
|
||||
private async _createNextEditOutcome(outcomeCtx: {
|
||||
helper: HelperVars;
|
||||
startTime: number;
|
||||
llm: ILLM;
|
||||
promptContent: string;
|
||||
completion: string;
|
||||
finalCursorPosition: Position;
|
||||
editableRegionStartLine: number;
|
||||
editableRegionEndLine: number;
|
||||
userEdits: string;
|
||||
userExcerpts: string;
|
||||
originalEditableRange: string;
|
||||
cursorPosition?: Position;
|
||||
completionId?: string;
|
||||
diffLines: DiffLine[];
|
||||
}): Promise<NextEditOutcome> {
|
||||
return {
|
||||
elapsed: Date.now() - outcomeCtx.startTime,
|
||||
modelProvider: outcomeCtx.llm.underlyingProviderName,
|
||||
modelName: outcomeCtx.llm.model + ":zetaDataset",
|
||||
completionOptions: null,
|
||||
completionId:
|
||||
outcomeCtx.completionId || outcomeCtx.helper.input.completionId,
|
||||
gitRepo: await this.ide.getRepoName(outcomeCtx.helper.filepath),
|
||||
uniqueId: await this.ide.getUniqueId(),
|
||||
timestamp: Date.now(),
|
||||
fileUri: outcomeCtx.helper.filepath,
|
||||
workspaceDirUri:
|
||||
outcomeCtx.helper.workspaceUris[0] ??
|
||||
path.dirname(outcomeCtx.helper.filepath),
|
||||
prompt: outcomeCtx.promptContent,
|
||||
userEdits: outcomeCtx.userEdits ?? "",
|
||||
userExcerpts: outcomeCtx.userExcerpts ?? "",
|
||||
originalEditableRange: outcomeCtx.originalEditableRange ?? "",
|
||||
completion: outcomeCtx.completion,
|
||||
cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos,
|
||||
finalCursorPosition: outcomeCtx.finalCursorPosition,
|
||||
editableRegionStartLine: outcomeCtx.editableRegionStartLine,
|
||||
editableRegionEndLine: outcomeCtx.editableRegionEndLine,
|
||||
diffLines: outcomeCtx.diffLines,
|
||||
...outcomeCtx.helper.options,
|
||||
};
|
||||
}
|
||||
|
||||
private async _markDisplayedIfJetBrains(
|
||||
completionId: string,
|
||||
outcome: NextEditOutcome,
|
||||
|
|
|
|||
16
core/nextEdit/NextEditProviderFactory.ts
Normal file
16
core/nextEdit/NextEditProviderFactory.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { NEXT_EDIT_MODELS } from "../llm/constants.js";
|
||||
import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js";
|
||||
import { InstinctProvider } from "./providers/InstinctNextEditProvider.js";
|
||||
import { MercuryCoderProvider } from "./providers/MercuryCoderNextEditProvider.js";
|
||||
|
||||
export class NextEditProviderFactory {
|
||||
static createProvider(modelName: string): BaseNextEditProvider {
|
||||
if (modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER)) {
|
||||
return new MercuryCoderProvider();
|
||||
} else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) {
|
||||
return new InstinctProvider();
|
||||
} else {
|
||||
throw new Error(`Unsupported model: ${modelName}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -12,10 +12,6 @@ export const MODEL_WINDOW_SIZES: Record<
|
|||
topMargin: 0,
|
||||
bottomMargin: 5,
|
||||
}, // mercury coder uses full file diff, so this should be unnecessary
|
||||
"mercury-coder-nextedit": {
|
||||
topMargin: 0,
|
||||
bottomMargin: 5,
|
||||
}, // mercury coder nextedit uses full file diff, so this should be unnecessary
|
||||
instinct: { topMargin: 1, bottomMargin: 5 },
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import {
|
|||
} from "../../autocomplete/util/types";
|
||||
import { ConfigHandler } from "../../config/ConfigHandler";
|
||||
import { IDE, ILLM } from "../../index";
|
||||
import { isSecurityConcern } from "../../indexing/ignore";
|
||||
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../util/parameters";
|
||||
|
||||
/**
|
||||
|
|
@ -61,6 +62,10 @@ export const getAutocompleteContext = async (
|
|||
throw new Error("No config available");
|
||||
}
|
||||
|
||||
if (isSecurityConcern(input.filepath)) {
|
||||
throw new Error("File is a security concern, autocomplete disabled");
|
||||
}
|
||||
|
||||
// Use provided autocomplete model or fall back to configured autocomplete model
|
||||
let finalModel: ILLM;
|
||||
let modelNameForTemplating: string;
|
||||
|
|
|
|||
415
core/nextEdit/providers/BaseNextEditProvider.ts
Normal file
415
core/nextEdit/providers/BaseNextEditProvider.ts
Normal file
|
|
@ -0,0 +1,415 @@
|
|||
import * as path from "path";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import { HelperVars } from "../../autocomplete/util/HelperVars.js";
|
||||
import { myersDiff } from "../../diff/myers.js";
|
||||
import { DiffLine, IDE, ILLM, Position, RangeInFile } from "../../index.js";
|
||||
import { countTokens } from "../../llm/countTokens.js";
|
||||
import {
|
||||
calculateFinalCursorPosition,
|
||||
DiffGroup,
|
||||
groupDiffLines,
|
||||
} from "../diff/diff.js";
|
||||
import { PrefetchQueue } from "../NextEditPrefetchQueue.js";
|
||||
import {
|
||||
ModelSpecificContext,
|
||||
NextEditOutcome,
|
||||
Prompt,
|
||||
PromptMetadata,
|
||||
} from "../types.js";
|
||||
import { isWhitespaceOnlyDeletion } from "../utils.js";
|
||||
|
||||
export abstract class BaseNextEditProvider {
|
||||
protected readonly modelName: string;
|
||||
|
||||
constructor(modelName: string) {
|
||||
this.modelName = modelName;
|
||||
}
|
||||
|
||||
// Leave methods as abstract when you must have the models implement their own versions.
|
||||
abstract getSystemPrompt(): string;
|
||||
abstract generatePrompts(context: ModelSpecificContext): Promise<Prompt[]>;
|
||||
abstract extractCompletion(message: string): string;
|
||||
abstract buildPromptContext(context: ModelSpecificContext): any;
|
||||
abstract buildPromptMetadata(context: ModelSpecificContext): PromptMetadata;
|
||||
abstract getWindowSize(): { topMargin: number; bottomMargin: number };
|
||||
abstract calculateEditableRegion(
|
||||
helper: HelperVars,
|
||||
usingFullFileDiff: boolean,
|
||||
): {
|
||||
editableRegionStartLine: number;
|
||||
editableRegionEndLine: number;
|
||||
};
|
||||
|
||||
// Methods that can be used as default fallback.
|
||||
public async handlePartialFileDiff(
|
||||
helper: HelperVars,
|
||||
editableRegionStartLine: number,
|
||||
editableRegionEndLine: number,
|
||||
startTime: number,
|
||||
llm: ILLM,
|
||||
nextCompletion: string,
|
||||
promptMetadata: PromptMetadata,
|
||||
ide: IDE,
|
||||
): Promise<NextEditOutcome> {
|
||||
const oldEditRangeSlice = helper.fileContents
|
||||
.split("\n")
|
||||
.slice(editableRegionStartLine, editableRegionEndLine + 1)
|
||||
.join("\n");
|
||||
|
||||
const finalCursorPos = calculateFinalCursorPosition(
|
||||
helper.pos,
|
||||
editableRegionStartLine,
|
||||
oldEditRangeSlice,
|
||||
nextCompletion,
|
||||
);
|
||||
|
||||
const outcome = await this.createNextEditOutcome({
|
||||
helper,
|
||||
startTime,
|
||||
llm,
|
||||
promptContent: promptMetadata.prompt.content,
|
||||
completion: nextCompletion,
|
||||
finalCursorPosition: finalCursorPos,
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
userEdits: promptMetadata.userEdits,
|
||||
userExcerpts: promptMetadata.userExcerpts,
|
||||
originalEditableRange: oldEditRangeSlice,
|
||||
diffLines: [],
|
||||
ide,
|
||||
});
|
||||
|
||||
return outcome;
|
||||
}
|
||||
|
||||
public async handleFullFileDiff(
|
||||
helper: HelperVars,
|
||||
editableRegionStartLine: number,
|
||||
editableRegionEndLine: number,
|
||||
startTime: number,
|
||||
llm: ILLM,
|
||||
nextCompletion: string,
|
||||
promptMetadata: PromptMetadata,
|
||||
ide: IDE,
|
||||
): Promise<NextEditOutcome | undefined> {
|
||||
const fileSlice = helper.fileLines
|
||||
.slice(editableRegionStartLine, editableRegionEndLine + 1)
|
||||
.join("\n");
|
||||
|
||||
const diffLines = myersDiff(fileSlice, nextCompletion);
|
||||
const diffGroups = groupDiffLines(
|
||||
diffLines,
|
||||
editableRegionStartLine,
|
||||
5,
|
||||
).filter((group) => !isWhitespaceOnlyDeletion(group.lines));
|
||||
const currentLine = helper.pos.line;
|
||||
const prefetchQueue = PrefetchQueue.getInstance();
|
||||
|
||||
const cursorLocalDiffGroup = await this.processDiffGroups(
|
||||
diffGroups,
|
||||
currentLine,
|
||||
helper,
|
||||
startTime,
|
||||
llm,
|
||||
prefetchQueue,
|
||||
promptMetadata,
|
||||
ide,
|
||||
);
|
||||
|
||||
if (cursorLocalDiffGroup) {
|
||||
return await this.createOutcomeFromDiffGroup(
|
||||
cursorLocalDiffGroup,
|
||||
helper,
|
||||
startTime,
|
||||
llm,
|
||||
helper.input.completionId,
|
||||
true,
|
||||
promptMetadata,
|
||||
ide,
|
||||
);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process diff groups and find the one containing the cursor.
|
||||
*/
|
||||
private async processDiffGroups(
|
||||
diffGroups: DiffGroup[],
|
||||
currentLine: number,
|
||||
helper: HelperVars,
|
||||
startTime: number,
|
||||
llm: ILLM,
|
||||
prefetchQueue: PrefetchQueue,
|
||||
promptMetadata: PromptMetadata,
|
||||
ide: IDE,
|
||||
): Promise<DiffGroup | undefined> {
|
||||
let cursorGroup: DiffGroup | undefined;
|
||||
|
||||
for (const group of diffGroups) {
|
||||
if (currentLine >= group.startLine && currentLine <= group.endLine) {
|
||||
cursorGroup = group;
|
||||
} else {
|
||||
await this.addDiffGroupToPrefetchQueue(
|
||||
group,
|
||||
helper,
|
||||
startTime,
|
||||
llm,
|
||||
prefetchQueue,
|
||||
promptMetadata,
|
||||
ide,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return cursorGroup;
|
||||
}
|
||||
|
||||
private async addDiffGroupToPrefetchQueue(
|
||||
group: DiffGroup,
|
||||
helper: HelperVars,
|
||||
startTime: number,
|
||||
llm: ILLM,
|
||||
prefetchQueue: PrefetchQueue,
|
||||
promptMetadata: PromptMetadata,
|
||||
ide: IDE,
|
||||
): Promise<void> {
|
||||
// Extract lines that are not old.
|
||||
const groupContent = group.lines
|
||||
.filter((l) => l.type !== "old")
|
||||
.map((l) => l.line)
|
||||
.join("\n");
|
||||
|
||||
const rangeInFile: RangeInFile = {
|
||||
filepath: helper.filepath,
|
||||
range: {
|
||||
start: { line: group.startLine, character: 0 },
|
||||
end: {
|
||||
line: group.endLine,
|
||||
character: group.lines[group.lines.length - 1].line.length,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// Extract lines that are not new.
|
||||
const originalContent = group.lines
|
||||
.filter((l) => l.type !== "new")
|
||||
.map((l) => l.line)
|
||||
.join("\n");
|
||||
|
||||
const groupOutcome = await this.createNextEditOutcome({
|
||||
helper,
|
||||
startTime,
|
||||
llm,
|
||||
promptContent: promptMetadata.prompt.content,
|
||||
completion: groupContent,
|
||||
finalCursorPosition: {
|
||||
line: group.endLine,
|
||||
character: group.lines[group.lines.length - 1].line.length,
|
||||
},
|
||||
editableRegionStartLine: group.startLine,
|
||||
editableRegionEndLine: group.endLine,
|
||||
userEdits: promptMetadata.userEdits,
|
||||
userExcerpts: promptMetadata.userExcerpts,
|
||||
originalEditableRange: originalContent,
|
||||
cursorPosition: { line: group.startLine, character: 0 },
|
||||
completionId: uuidv4(), // Generate a new ID for this prefetched item.
|
||||
diffLines: group.lines,
|
||||
ide,
|
||||
});
|
||||
|
||||
prefetchQueue.enqueueProcessed({
|
||||
location: rangeInFile,
|
||||
outcome: groupOutcome,
|
||||
});
|
||||
}
|
||||
|
||||
private async createOutcomeFromDiffGroup(
|
||||
diffGroup: DiffGroup,
|
||||
helper: HelperVars,
|
||||
startTime: number,
|
||||
llm: ILLM,
|
||||
completionId: string,
|
||||
isCurrentCursorGroup: boolean,
|
||||
promptMetadata: PromptMetadata,
|
||||
ide: IDE,
|
||||
): Promise<NextEditOutcome> {
|
||||
const groupContent = diffGroup.lines
|
||||
.filter((l) => l.type !== "old")
|
||||
.map((l) => l.line)
|
||||
.join("\n");
|
||||
|
||||
const originalContent = diffGroup.lines
|
||||
.filter((l) => l.type !== "new")
|
||||
.map((l) => l.line)
|
||||
.join("\n");
|
||||
|
||||
const cursorPos = isCurrentCursorGroup
|
||||
? helper.pos
|
||||
: { line: diffGroup.startLine, character: 0 };
|
||||
|
||||
const finalCursorPos = calculateFinalCursorPosition(
|
||||
cursorPos,
|
||||
diffGroup.startLine,
|
||||
originalContent,
|
||||
groupContent,
|
||||
);
|
||||
|
||||
const outcomeNext = await this.createNextEditOutcome({
|
||||
helper,
|
||||
startTime,
|
||||
llm,
|
||||
promptContent: promptMetadata.prompt.content,
|
||||
completion: groupContent,
|
||||
finalCursorPosition: finalCursorPos,
|
||||
editableRegionStartLine: diffGroup.startLine,
|
||||
editableRegionEndLine: diffGroup.endLine,
|
||||
userEdits: promptMetadata.userEdits,
|
||||
userExcerpts: promptMetadata.userExcerpts,
|
||||
originalEditableRange: originalContent,
|
||||
cursorPosition: cursorPos,
|
||||
completionId,
|
||||
diffLines: diffGroup.lines,
|
||||
ide,
|
||||
});
|
||||
|
||||
return outcomeNext;
|
||||
}
|
||||
|
||||
protected async createNextEditOutcome(outcomeCtx: {
|
||||
helper: HelperVars;
|
||||
startTime: number;
|
||||
llm: ILLM;
|
||||
promptContent: string;
|
||||
completion: string;
|
||||
finalCursorPosition: Position;
|
||||
editableRegionStartLine: number;
|
||||
editableRegionEndLine: number;
|
||||
userEdits: string;
|
||||
userExcerpts: string;
|
||||
originalEditableRange: string;
|
||||
cursorPosition?: Position;
|
||||
completionId?: string;
|
||||
diffLines: DiffLine[];
|
||||
ide: IDE;
|
||||
}): Promise<NextEditOutcome> {
|
||||
return {
|
||||
elapsed: Date.now() - outcomeCtx.startTime,
|
||||
modelProvider: outcomeCtx.llm.underlyingProviderName,
|
||||
modelName: outcomeCtx.llm.model + ":zetaDataset",
|
||||
completionOptions: null,
|
||||
completionId:
|
||||
outcomeCtx.completionId || outcomeCtx.helper.input.completionId,
|
||||
gitRepo: await outcomeCtx.ide.getRepoName(outcomeCtx.helper.filepath),
|
||||
uniqueId: await outcomeCtx.ide.getUniqueId(),
|
||||
timestamp: Date.now(),
|
||||
fileUri: outcomeCtx.helper.filepath,
|
||||
workspaceDirUri:
|
||||
outcomeCtx.helper.workspaceUris[0] ??
|
||||
path.dirname(outcomeCtx.helper.filepath),
|
||||
prompt: outcomeCtx.promptContent,
|
||||
userEdits: outcomeCtx.userEdits ?? "",
|
||||
userExcerpts: outcomeCtx.userExcerpts ?? "",
|
||||
originalEditableRange: outcomeCtx.originalEditableRange ?? "",
|
||||
completion: outcomeCtx.completion,
|
||||
cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos,
|
||||
finalCursorPosition: outcomeCtx.finalCursorPosition,
|
||||
editableRegionStartLine: outcomeCtx.editableRegionStartLine,
|
||||
editableRegionEndLine: outcomeCtx.editableRegionEndLine,
|
||||
diffLines: outcomeCtx.diffLines,
|
||||
...outcomeCtx.helper.options,
|
||||
};
|
||||
}
|
||||
|
||||
// Shared utility for calculating editable regions.
|
||||
protected calculateOptimalEditableRegion(
|
||||
helper: HelperVars,
|
||||
maxTokens: number = 512,
|
||||
heuristic: "fourChars" | "tokenizer" = "tokenizer",
|
||||
): {
|
||||
editableRegionStartLine: number;
|
||||
editableRegionEndLine: number;
|
||||
} {
|
||||
const cursorLine = helper.pos.line;
|
||||
const fileLines = helper.fileLines;
|
||||
|
||||
let editableRegionStartLine = cursorLine;
|
||||
let editableRegionEndLine = cursorLine;
|
||||
|
||||
let currentContent = fileLines[cursorLine];
|
||||
let totalTokens =
|
||||
heuristic === "tokenizer"
|
||||
? countTokens(currentContent, helper.modelName)
|
||||
: Math.ceil(currentContent.length / 4);
|
||||
|
||||
let addingAbove = true;
|
||||
|
||||
while (totalTokens < maxTokens) {
|
||||
let addedLine = false;
|
||||
|
||||
if (addingAbove) {
|
||||
if (editableRegionStartLine > 0) {
|
||||
editableRegionStartLine--;
|
||||
const lineContent = fileLines[editableRegionStartLine];
|
||||
const lineTokens =
|
||||
heuristic === "tokenizer"
|
||||
? countTokens(lineContent, helper.modelName)
|
||||
: Math.ceil(lineContent.length / 4);
|
||||
|
||||
totalTokens += lineTokens;
|
||||
addedLine = true;
|
||||
}
|
||||
} else {
|
||||
if (editableRegionEndLine < fileLines.length - 1) {
|
||||
editableRegionEndLine++;
|
||||
const lineContent = fileLines[editableRegionEndLine];
|
||||
const lineTokens =
|
||||
heuristic === "tokenizer"
|
||||
? countTokens(lineContent, helper.modelName)
|
||||
: Math.ceil(lineContent.length / 4);
|
||||
|
||||
totalTokens += lineTokens;
|
||||
addedLine = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!addedLine) {
|
||||
if (
|
||||
editableRegionStartLine === 0 &&
|
||||
editableRegionEndLine === fileLines.length - 1
|
||||
) {
|
||||
break;
|
||||
}
|
||||
addingAbove = !addingAbove;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (totalTokens > maxTokens) {
|
||||
if (addingAbove) {
|
||||
editableRegionStartLine++;
|
||||
} else {
|
||||
editableRegionEndLine--;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
addingAbove = !addingAbove;
|
||||
}
|
||||
|
||||
return {
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
};
|
||||
}
|
||||
|
||||
// Optional methods with defaults.
|
||||
shouldInjectUniqueToken(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
getUniqueToken(): string | null {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
155
core/nextEdit/providers/InstinctNextEditProvider.ts
Normal file
155
core/nextEdit/providers/InstinctNextEditProvider.ts
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
import { HelperVars } from "../../autocomplete/util/HelperVars.js";
|
||||
import { NEXT_EDIT_MODELS } from "../../llm/constants.js";
|
||||
import { INSTINCT_SYSTEM_PROMPT } from "../constants.js";
|
||||
import {
|
||||
contextSnippetsBlock,
|
||||
currentFileContentBlock,
|
||||
editHistoryBlock,
|
||||
} from "../templating/instinct.js";
|
||||
import {
|
||||
NEXT_EDIT_MODEL_TEMPLATES,
|
||||
PromptTemplateRenderer,
|
||||
} from "../templating/NextEditPromptEngine.js";
|
||||
import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js";
|
||||
import { BaseNextEditProvider } from "./BaseNextEditProvider.js";
|
||||
|
||||
export class InstinctProvider extends BaseNextEditProvider {
|
||||
private templateRenderer: PromptTemplateRenderer;
|
||||
|
||||
constructor() {
|
||||
super(NEXT_EDIT_MODELS.INSTINCT);
|
||||
|
||||
const template = NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.INSTINCT];
|
||||
this.templateRenderer = new PromptTemplateRenderer(template.template);
|
||||
}
|
||||
|
||||
getSystemPrompt(): string {
|
||||
return INSTINCT_SYSTEM_PROMPT;
|
||||
}
|
||||
|
||||
getWindowSize() {
|
||||
return { topMargin: 1, bottomMargin: 5 };
|
||||
}
|
||||
|
||||
shouldInjectUniqueToken(): boolean {
|
||||
return false; // Instinct doesn't use unique tokens.
|
||||
}
|
||||
|
||||
extractCompletion(message: string): string {
|
||||
return message; // Instinct returns the completion directly.
|
||||
}
|
||||
|
||||
buildPromptContext(context: ModelSpecificContext): any {
|
||||
// Calculate the window around the cursor position (25 lines above and below).
|
||||
const windowStart = Math.max(0, context.helper.pos.line - 25);
|
||||
const windowEnd = Math.min(
|
||||
context.helper.fileLines.length - 1,
|
||||
context.helper.pos.line + 25,
|
||||
);
|
||||
|
||||
// Ensure editable region boundaries are within the window.
|
||||
const adjustedEditableStart = Math.max(
|
||||
windowStart,
|
||||
context.editableRegionStartLine,
|
||||
);
|
||||
const adjustedEditableEnd = Math.min(
|
||||
windowEnd,
|
||||
context.editableRegionEndLine,
|
||||
);
|
||||
|
||||
return {
|
||||
contextSnippets: context.autocompleteContext,
|
||||
currentFileContent: context.helper.fileContents,
|
||||
windowStart,
|
||||
windowEnd,
|
||||
editableRegionStartLine: adjustedEditableStart,
|
||||
editableRegionEndLine: adjustedEditableEnd,
|
||||
editDiffHistory: context.diffContext,
|
||||
currentFilePath: context.helper.filepath,
|
||||
languageShorthand: context.helper.lang.name,
|
||||
};
|
||||
}
|
||||
|
||||
async generatePrompts(context: ModelSpecificContext): Promise<Prompt[]> {
|
||||
const promptCtx = this.buildPromptContext(context);
|
||||
|
||||
const templateVars = {
|
||||
contextSnippets: contextSnippetsBlock(promptCtx.contextSnippets),
|
||||
currentFileContent: currentFileContentBlock(
|
||||
promptCtx.currentFileContent,
|
||||
promptCtx.windowStart,
|
||||
promptCtx.windowEnd,
|
||||
promptCtx.editableRegionStartLine,
|
||||
promptCtx.editableRegionEndLine,
|
||||
context.helper.pos,
|
||||
),
|
||||
editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory),
|
||||
currentFilePath: promptCtx.currentFilePath,
|
||||
languageShorthand: promptCtx.languageShorthand,
|
||||
};
|
||||
|
||||
const userPromptContent = this.templateRenderer.render(templateVars);
|
||||
|
||||
return [
|
||||
{
|
||||
role: "system",
|
||||
content: this.getSystemPrompt(),
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
content: userPromptContent,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
buildPromptMetadata(context: ModelSpecificContext): PromptMetadata {
|
||||
const promptCtx = this.buildPromptContext(context);
|
||||
|
||||
const templateVars = {
|
||||
contextSnippets: contextSnippetsBlock(promptCtx.contextSnippets),
|
||||
currentFileContent: currentFileContentBlock(
|
||||
promptCtx.currentFileContent,
|
||||
promptCtx.windowStart,
|
||||
promptCtx.windowEnd,
|
||||
promptCtx.editableRegionStartLine,
|
||||
promptCtx.editableRegionEndLine,
|
||||
context.helper.pos,
|
||||
),
|
||||
editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory),
|
||||
currentFilePath: promptCtx.currentFilePath,
|
||||
languageShorthand: promptCtx.languageShorthand,
|
||||
};
|
||||
|
||||
const userPromptContent = this.templateRenderer.render(templateVars);
|
||||
|
||||
return {
|
||||
prompt: {
|
||||
role: "user",
|
||||
content: userPromptContent,
|
||||
},
|
||||
userEdits: promptCtx.editDiffHistory.join("\n"),
|
||||
userExcerpts: templateVars.currentFileContent,
|
||||
};
|
||||
}
|
||||
|
||||
calculateEditableRegion(
|
||||
helper: HelperVars,
|
||||
usingFullFileDiff: boolean,
|
||||
): {
|
||||
editableRegionStartLine: number;
|
||||
editableRegionEndLine: number;
|
||||
} {
|
||||
if (usingFullFileDiff) {
|
||||
return this.calculateOptimalEditableRegion(helper, 512, "tokenizer");
|
||||
} else {
|
||||
const { topMargin, bottomMargin } = this.getWindowSize();
|
||||
return {
|
||||
editableRegionStartLine: Math.max(helper.pos.line - topMargin, 0),
|
||||
editableRegionEndLine: Math.min(
|
||||
helper.pos.line + bottomMargin,
|
||||
helper.fileLines.length - 1,
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
145
core/nextEdit/providers/MercuryCoderNextEditProvider.ts
Normal file
145
core/nextEdit/providers/MercuryCoderNextEditProvider.ts
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
import { HelperVars } from "../../autocomplete/util/HelperVars.js";
|
||||
import { NEXT_EDIT_MODELS } from "../../llm/constants.js";
|
||||
import { MERCURY_SYSTEM_PROMPT, UNIQUE_TOKEN } from "../constants.js";
|
||||
import {
|
||||
currentFileContentBlock,
|
||||
editHistoryBlock,
|
||||
recentlyViewedCodeSnippetsBlock,
|
||||
} from "../templating/mercuryCoderNextEdit.js";
|
||||
import {
|
||||
NEXT_EDIT_MODEL_TEMPLATES,
|
||||
PromptTemplateRenderer,
|
||||
} from "../templating/NextEditPromptEngine.js";
|
||||
import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js";
|
||||
import { BaseNextEditProvider } from "./BaseNextEditProvider.js";
|
||||
|
||||
export class MercuryCoderProvider extends BaseNextEditProvider {
|
||||
private templateRenderer: PromptTemplateRenderer;
|
||||
|
||||
constructor() {
|
||||
super(NEXT_EDIT_MODELS.MERCURY_CODER);
|
||||
|
||||
const template = NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER];
|
||||
this.templateRenderer = new PromptTemplateRenderer(template.template);
|
||||
}
|
||||
|
||||
getSystemPrompt(): string {
|
||||
return MERCURY_SYSTEM_PROMPT;
|
||||
}
|
||||
|
||||
getWindowSize() {
|
||||
return { topMargin: 0, bottomMargin: 5 };
|
||||
}
|
||||
|
||||
shouldInjectUniqueToken(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
getUniqueToken(): string {
|
||||
return UNIQUE_TOKEN;
|
||||
}
|
||||
|
||||
extractCompletion(message: string): string {
|
||||
// Extract the code between the markdown code blocks.
|
||||
return message.slice(
|
||||
message.indexOf("```\n") + "```\n".length,
|
||||
message.lastIndexOf("\n\n```"),
|
||||
);
|
||||
}
|
||||
|
||||
buildPromptContext(context: ModelSpecificContext): any {
|
||||
return {
|
||||
recentlyViewedCodeSnippets:
|
||||
context.snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({
|
||||
filepath: snip.filepath,
|
||||
content: snip.content,
|
||||
})) ?? [],
|
||||
currentFileContent: context.helper.fileContents,
|
||||
editableRegionStartLine: context.editableRegionStartLine,
|
||||
editableRegionEndLine: context.editableRegionEndLine,
|
||||
editDiffHistory: context.diffContext,
|
||||
currentFilePath: context.helper.filepath,
|
||||
};
|
||||
}
|
||||
|
||||
async generatePrompts(context: ModelSpecificContext): Promise<Prompt[]> {
|
||||
const promptCtx = this.buildPromptContext(context);
|
||||
|
||||
const templateVars = {
|
||||
recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
|
||||
promptCtx.recentlyViewedCodeSnippets,
|
||||
),
|
||||
currentFileContent: currentFileContentBlock(
|
||||
promptCtx.currentFileContent,
|
||||
promptCtx.editableRegionStartLine,
|
||||
promptCtx.editableRegionEndLine,
|
||||
context.helper.pos,
|
||||
),
|
||||
editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory),
|
||||
currentFilePath: promptCtx.currentFilePath,
|
||||
};
|
||||
|
||||
const userPromptContent = this.templateRenderer.render(templateVars);
|
||||
|
||||
return [
|
||||
{
|
||||
role: "system",
|
||||
content: this.getSystemPrompt(),
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
content: userPromptContent,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
buildPromptMetadata(context: ModelSpecificContext): PromptMetadata {
|
||||
const promptCtx = this.buildPromptContext(context);
|
||||
|
||||
const templateVars = {
|
||||
recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
|
||||
promptCtx.recentlyViewedCodeSnippets,
|
||||
),
|
||||
currentFileContent: currentFileContentBlock(
|
||||
promptCtx.currentFileContent,
|
||||
promptCtx.editableRegionStartLine,
|
||||
promptCtx.editableRegionEndLine,
|
||||
context.helper.pos,
|
||||
),
|
||||
editDiffHistory: editHistoryBlock(promptCtx.editDiffHistory),
|
||||
currentFilePath: promptCtx.currentFilePath,
|
||||
};
|
||||
|
||||
const userPromptContent = this.templateRenderer.render(templateVars);
|
||||
|
||||
return {
|
||||
prompt: {
|
||||
role: "user",
|
||||
content: userPromptContent,
|
||||
},
|
||||
userEdits: promptCtx.editDiffHistory.join("\n"),
|
||||
userExcerpts: templateVars.currentFileContent,
|
||||
};
|
||||
}
|
||||
|
||||
calculateEditableRegion(
|
||||
helper: HelperVars,
|
||||
usingFullFileDiff: boolean,
|
||||
): {
|
||||
editableRegionStartLine: number;
|
||||
editableRegionEndLine: number;
|
||||
} {
|
||||
if (usingFullFileDiff) {
|
||||
return this.calculateOptimalEditableRegion(helper, 512, "tokenizer");
|
||||
} else {
|
||||
const { topMargin, bottomMargin } = this.getWindowSize();
|
||||
return {
|
||||
editableRegionStartLine: Math.max(helper.pos.line - topMargin, 0),
|
||||
editableRegionEndLine: Math.min(
|
||||
helper.pos.line + bottomMargin,
|
||||
helper.fileLines.length - 1,
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,7 +1,4 @@
|
|||
import Handlebars from "handlebars";
|
||||
import { Position } from "../..";
|
||||
import { SnippetPayload } from "../../autocomplete/snippets";
|
||||
import { HelperVars } from "../../autocomplete/util/HelperVars";
|
||||
import { NEXT_EDIT_MODELS } from "../../llm/constants";
|
||||
import {
|
||||
INSTINCT_USER_PROMPT_PREFIX,
|
||||
|
|
@ -12,274 +9,39 @@ import {
|
|||
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
|
||||
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
|
||||
} from "../constants";
|
||||
import {
|
||||
InstinctTemplateVars,
|
||||
MercuryTemplateVars,
|
||||
NextEditTemplate,
|
||||
PromptMetadata,
|
||||
SystemPrompt,
|
||||
TemplateVars,
|
||||
UserPrompt,
|
||||
} from "../types";
|
||||
import {
|
||||
contextSnippetsBlock,
|
||||
currentFileContentBlock as instinctCurrentFileContentBlock,
|
||||
editHistoryBlock as instinctEditHistoryBlock,
|
||||
} from "./instinct";
|
||||
import {
|
||||
currentFileContentBlock,
|
||||
editHistoryBlock,
|
||||
recentlyViewedCodeSnippetsBlock,
|
||||
} from "./mercuryCoderNextEdit";
|
||||
import {
|
||||
insertCursorToken,
|
||||
insertEditableRegionTokensWithStaticRange,
|
||||
} from "./utils";
|
||||
import { NextEditTemplate, TemplateVars } from "../types";
|
||||
|
||||
type TemplateRenderer = (vars: TemplateVars) => string;
|
||||
|
||||
const NEXT_EDIT_MODEL_TEMPLATES: Record<NEXT_EDIT_MODELS, NextEditTemplate> = {
|
||||
// Keep the template registry
|
||||
export const NEXT_EDIT_MODEL_TEMPLATES: Record<
|
||||
NEXT_EDIT_MODELS,
|
||||
NextEditTemplate
|
||||
> = {
|
||||
"mercury-coder": {
|
||||
template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n`,
|
||||
},
|
||||
"mercury-coder-nextedit": {
|
||||
template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n`,
|
||||
},
|
||||
instinct: {
|
||||
template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpt:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`,
|
||||
},
|
||||
};
|
||||
|
||||
function templateRendererOfModel(
|
||||
modelName: NEXT_EDIT_MODELS,
|
||||
): TemplateRenderer {
|
||||
let template = NEXT_EDIT_MODEL_TEMPLATES[modelName];
|
||||
// Export a utility for providers to use
|
||||
export class PromptTemplateRenderer {
|
||||
private compiledTemplate: HandlebarsTemplateDelegate;
|
||||
|
||||
constructor(template: string) {
|
||||
this.compiledTemplate = Handlebars.compile(template);
|
||||
}
|
||||
|
||||
render(vars: TemplateVars): string {
|
||||
return this.compiledTemplate(vars);
|
||||
}
|
||||
}
|
||||
|
||||
// Keep for backward compatibility or remove if not needed
|
||||
export function getTemplateForModel(modelName: NEXT_EDIT_MODELS): string {
|
||||
const template = NEXT_EDIT_MODEL_TEMPLATES[modelName];
|
||||
if (!template) {
|
||||
throw new Error(`Model ${modelName} is not supported for next edit.`);
|
||||
}
|
||||
|
||||
const compiledTemplate = Handlebars.compile(template.template);
|
||||
|
||||
return (vars: TemplateVars): string => {
|
||||
return compiledTemplate(vars);
|
||||
};
|
||||
}
|
||||
|
||||
export async function renderPrompt(
|
||||
helper: HelperVars,
|
||||
ctx: any,
|
||||
): Promise<PromptMetadata> {
|
||||
let modelName = helper.modelName as NEXT_EDIT_MODELS;
|
||||
|
||||
// Validate that the modelName is actually a supported model.
|
||||
if (!Object.keys(NEXT_EDIT_MODEL_TEMPLATES).includes(modelName)) {
|
||||
// Check if modelName includes any known model name as substring.
|
||||
const matchingModel = Object.keys(NEXT_EDIT_MODEL_TEMPLATES).find((key) =>
|
||||
modelName.includes(key),
|
||||
);
|
||||
|
||||
if (matchingModel) {
|
||||
modelName = matchingModel as NEXT_EDIT_MODELS;
|
||||
} else {
|
||||
throw new Error(
|
||||
`${helper.modelName} is not yet supported for next edit.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const renderer = templateRendererOfModel(modelName);
|
||||
let userEdits = "";
|
||||
let editedCodeWithTokens = "";
|
||||
let tv: TemplateVars;
|
||||
|
||||
switch (modelName) {
|
||||
case NEXT_EDIT_MODELS.MERCURY_CODER: {
|
||||
userEdits = ctx.editDiffHistory;
|
||||
|
||||
// editedCodeWithTokens = insertTokens(
|
||||
// helper.fileContents.split("\n"),
|
||||
// helper.pos,
|
||||
// MERCURY_CURSOR,
|
||||
// );
|
||||
|
||||
const mercuryCtx: MercuryTemplateVars = {
|
||||
recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
|
||||
ctx.recentlyViewedCodeSnippets,
|
||||
),
|
||||
currentFileContent: currentFileContentBlock(
|
||||
ctx.currentFileContent,
|
||||
ctx.editableRegionStartLine,
|
||||
ctx.editableRegionEndLine,
|
||||
helper.pos,
|
||||
),
|
||||
editDiffHistory: editHistoryBlock(ctx.editDiffHistory),
|
||||
currentFilePath: ctx.currentFilePath,
|
||||
};
|
||||
|
||||
tv = mercuryCtx;
|
||||
|
||||
editedCodeWithTokens = mercuryCtx.currentFileContent;
|
||||
|
||||
break;
|
||||
}
|
||||
case NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT: {
|
||||
userEdits = ctx.editDiffHistory;
|
||||
|
||||
// editedCodeWithTokens = insertTokens(
|
||||
// helper.fileContents.split("\n"),
|
||||
// helper.pos,
|
||||
// MERCURY_CURSOR,
|
||||
// );
|
||||
|
||||
const mercuryCtx: MercuryTemplateVars = {
|
||||
recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
|
||||
ctx.recentlyViewedCodeSnippets,
|
||||
),
|
||||
currentFileContent: currentFileContentBlock(
|
||||
ctx.currentFileContent,
|
||||
ctx.editableRegionStartLine,
|
||||
ctx.editableRegionEndLine,
|
||||
helper.pos,
|
||||
),
|
||||
editDiffHistory: editHistoryBlock(ctx.editDiffHistory),
|
||||
currentFilePath: ctx.currentFilePath,
|
||||
};
|
||||
|
||||
tv = mercuryCtx;
|
||||
|
||||
editedCodeWithTokens = mercuryCtx.currentFileContent;
|
||||
|
||||
break;
|
||||
}
|
||||
case NEXT_EDIT_MODELS.INSTINCT: {
|
||||
userEdits = ctx.editDiffHistory;
|
||||
|
||||
// editedCodeWithTokens = insertTokens(
|
||||
// helper.fileContents.split("\n"),
|
||||
// helper.pos,
|
||||
// INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
|
||||
// );
|
||||
|
||||
const instinctCtx: InstinctTemplateVars = {
|
||||
contextSnippets: contextSnippetsBlock(ctx.contextSnippets),
|
||||
currentFileContent: instinctCurrentFileContentBlock(
|
||||
ctx.currentFileContent,
|
||||
ctx.windowStart,
|
||||
ctx.windowEnd,
|
||||
ctx.editableRegionStartLine,
|
||||
ctx.editableRegionEndLine,
|
||||
helper.pos,
|
||||
),
|
||||
editDiffHistory: instinctEditHistoryBlock(ctx.editDiffHistory),
|
||||
currentFilePath: ctx.currentFilePath,
|
||||
languageShorthand: ctx.languageShorthand,
|
||||
};
|
||||
|
||||
tv = instinctCtx;
|
||||
|
||||
editedCodeWithTokens = instinctCtx.currentFileContent;
|
||||
|
||||
break;
|
||||
}
|
||||
default:
|
||||
tv = {};
|
||||
break;
|
||||
}
|
||||
|
||||
return {
|
||||
prompt: {
|
||||
role: "user",
|
||||
content: renderer(tv),
|
||||
},
|
||||
userEdits,
|
||||
userExcerpts: editedCodeWithTokens,
|
||||
};
|
||||
}
|
||||
|
||||
export function renderDefaultSystemPrompt(): SystemPrompt {
|
||||
return {
|
||||
role: "system",
|
||||
content: [
|
||||
/* Identity forming */
|
||||
"You are an expert polyglot developer who is overseeing a junior developer write code in some language.",
|
||||
"You are psychic as well, so you are an expert at reading minds just from what the junior has done.",
|
||||
"As an expert, you know what the next edit of the junior is going to be, and you want to suggest it to save both of your's time.",
|
||||
/* Action crash course */
|
||||
"An action is a change in code state that preserves the well-formedness of the code.",
|
||||
"Well-formedness means that given a cursor location, the local syntax tree that the cursor is in is syntactically correct, and the semantic correctness in the current cursor's character location - 1.",
|
||||
/* Input description */
|
||||
// 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "originalCode": string; "newCode": string }.',
|
||||
// "language is the language the code is written in.",
|
||||
// "originalCode is the code state before the junior has taken some edit action.",
|
||||
// "editedCode is the code state after the junior has taken some edit action.",
|
||||
// "If we put originalCode and editedCode on a timeline, originalCode lives in the past, and editedCode is the current code state.",
|
||||
// "Measure the difference between the originalCode and editedCode inside the prompt, make your best understanding of what the junior wants to accomplish, and figure out what the junior will do next.",
|
||||
'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "rootPathSnippets": string; "importDefinitionSnippets": string; "ideSnippets": string; "recentlyEditedRangeSnippets": string; "diffSnippets": string; "clipboardSnippets": string; "recentlyVisitedRangesSnippets": string; }.',
|
||||
"rootPathSnippet is all the code that is part of an AST path from the root node to the node at the current cursor.",
|
||||
"recentlyEditedRange is the code that the junior has recently edited.",
|
||||
"Do not guess what previous edit the junior has taken right before the request -- this is already given to you.",
|
||||
"The next edit action can happen any location, so do not default to where the junior left off. A potential next edit action can happen before or after the junior edit.",
|
||||
"The junior might want to add new code, delete existing code, or replace different parts of code.",
|
||||
"The next edit action isn't strictly additive. It could be deleting existing code, or replacing parts of code.",
|
||||
/* Output description */
|
||||
'Reply with a JSON that has the following type: { "actionType": string; "newCode": string }.',
|
||||
/* NOTE: Jacob -- try toggling between these two descriptions of actionType.*/
|
||||
/* NOTE: Without reasoning, mercury tends to skew greatly towards not deleting things. */
|
||||
"actionType is a four-sentence description of the type of action the junior has taken and the reason why you determined that to be the case. Actually analyze the given edit.",
|
||||
// "actionType is the type of action the junior has taken.",
|
||||
"newCode is what the full code looks like after applying your nextEditContent.",
|
||||
// "Make sure that newCode does not have errors. You are given the language, and you should know what the typescript compiler will complain about.",
|
||||
"Given the above definition of an action, you should prioritize fixing the following:",
|
||||
"- Patterns and repetition in code.",
|
||||
"- Static errors that the compiler of the language may return.",
|
||||
"- The junior's code style.",
|
||||
"If the junior has deleted some code, there's a good chance that the next edit will also be deletions.",
|
||||
"If the junior has added some code, there's a good chance that the next edit will also be additions.",
|
||||
"If the junior has performed an action on some part of the code, and you see similar code remaining, there's a good chance that the next edit will also target these remaining similar code.",
|
||||
"Careful of language intricacies.",
|
||||
// "Always try deletion and replacements. Add code if there are no other valid or reasonable edit actions.",
|
||||
"Do not reply in markdown.",
|
||||
"Do not hallucinate.",
|
||||
].join(" "),
|
||||
};
|
||||
}
|
||||
|
||||
export function renderDefaultUserPrompt(
|
||||
// originalCode: string,
|
||||
// editedCode: string,
|
||||
snippets: SnippetPayload,
|
||||
helper: HelperVars,
|
||||
): UserPrompt {
|
||||
const userEdit = {
|
||||
language: helper.lang,
|
||||
rootPathSnippets: snippets.rootPathSnippets,
|
||||
importDefinitionSnippets: snippets.importDefinitionSnippets,
|
||||
ideSnippets: snippets.ideSnippets,
|
||||
recentlyEditedRangeSnippets: snippets.recentlyEditedRangeSnippets,
|
||||
diffSnippets: snippets.diffSnippets,
|
||||
clipboardSnippets: snippets.clipboardSnippets,
|
||||
recentlyVisitedRangesSnippets: snippets.recentlyVisitedRangesSnippets,
|
||||
};
|
||||
|
||||
return {
|
||||
role: "user",
|
||||
content: `Your junior made the following edit: ${JSON.stringify(userEdit)}. What is the most possible next edit your junior ${helper.lang.name} developer will make?`,
|
||||
};
|
||||
}
|
||||
|
||||
function insertTokens(
|
||||
lines: string[],
|
||||
cursorPos: Position,
|
||||
cursorToken: string,
|
||||
editableRegionStart?: number,
|
||||
editableRegionEnd?: number,
|
||||
) {
|
||||
const a = insertCursorToken(lines, cursorPos, cursorToken);
|
||||
const b = insertEditableRegionTokensWithStaticRange(
|
||||
a,
|
||||
cursorPos,
|
||||
editableRegionStart,
|
||||
editableRegionEnd,
|
||||
);
|
||||
return b.join("\n");
|
||||
return template.template;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,243 +1,112 @@
|
|||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { Position } from "../..";
|
||||
import { SnippetPayload } from "../../autocomplete/snippets";
|
||||
import { AutocompleteSnippetType } from "../../autocomplete/snippets/types";
|
||||
import { HelperVars } from "../../autocomplete/util/HelperVars";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { NEXT_EDIT_MODELS } from "../../llm/constants";
|
||||
import {
|
||||
INSTINCT_USER_CURSOR_IS_HERE_TOKEN,
|
||||
INSTINCT_USER_PROMPT_PREFIX,
|
||||
MERCURY_CURRENT_FILE_CONTENT_CLOSE,
|
||||
MERCURY_CURRENT_FILE_CONTENT_OPEN,
|
||||
MERCURY_CURSOR,
|
||||
MERCURY_EDIT_DIFF_HISTORY_CLOSE,
|
||||
MERCURY_EDIT_DIFF_HISTORY_OPEN,
|
||||
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
|
||||
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
|
||||
MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE,
|
||||
MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN,
|
||||
} from "../constants";
|
||||
import {
|
||||
renderDefaultSystemPrompt,
|
||||
renderDefaultUserPrompt,
|
||||
renderPrompt,
|
||||
NEXT_EDIT_MODEL_TEMPLATES,
|
||||
PromptTemplateRenderer,
|
||||
getTemplateForModel,
|
||||
} from "./NextEditPromptEngine";
|
||||
|
||||
describe("NextEditPromptEngine", () => {
|
||||
describe("renderPrompt", () => {
|
||||
let mercuryHelper: HelperVars;
|
||||
let instinctHelper: HelperVars;
|
||||
let testHelper: HelperVars;
|
||||
let unsupportedHelper: HelperVars;
|
||||
let ctx: any;
|
||||
|
||||
beforeEach(() => {
|
||||
mercuryHelper = {
|
||||
modelName: "inception/mercury-coder" as NEXT_EDIT_MODELS,
|
||||
fileContents: "function test() {\n const a = 1;\n return a;\n}",
|
||||
pos: { line: 1, character: 12 } as Position,
|
||||
lang: { name: "typescript" },
|
||||
} as HelperVars;
|
||||
instinctHelper = {
|
||||
modelName: "continuedev/instinct" as NEXT_EDIT_MODELS,
|
||||
fileContents: "function test() {\n const a = 1;\n return a;\n}",
|
||||
pos: { line: 1, character: 12 } as Position,
|
||||
lang: { name: "typescript" },
|
||||
} as HelperVars;
|
||||
unsupportedHelper = {
|
||||
modelName: "mistral/codestral" as NEXT_EDIT_MODELS,
|
||||
fileContents: "function test() {\n const a = 1;\n return a;\n}",
|
||||
pos: { line: 1, character: 12 } as Position,
|
||||
lang: { name: "typescript" },
|
||||
} as HelperVars;
|
||||
|
||||
ctx = {
|
||||
recentlyViewedCodeSnippets: [
|
||||
{ filepath: "/path/to/file1.ts", content: "const b = 2;" },
|
||||
],
|
||||
currentFileContent: "function test() {\n const a = 1;\n return a;\n}",
|
||||
editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"],
|
||||
editableRegionStartLine: 0,
|
||||
editableRegionEndLine: 3,
|
||||
userEdits: "Added constant a",
|
||||
languageShorthand: "ts",
|
||||
userExcerpts: "const a = 1;",
|
||||
};
|
||||
});
|
||||
|
||||
it("should render mercury-coder prompt correctly", async () => {
|
||||
const result = await renderPrompt(mercuryHelper, ctx);
|
||||
|
||||
expect(result).toHaveProperty("prompt");
|
||||
expect(result.prompt.role).toBe("user");
|
||||
|
||||
const content = result.prompt.content;
|
||||
expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN);
|
||||
expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE);
|
||||
expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN);
|
||||
expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE);
|
||||
expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_OPEN);
|
||||
expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_CLOSE);
|
||||
expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_OPEN);
|
||||
expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_CLOSE);
|
||||
|
||||
expect(result.userEdits).toBe(ctx.editDiffHistory);
|
||||
expect(result.userExcerpts).toContain(MERCURY_CURSOR);
|
||||
});
|
||||
|
||||
it("should render instinct prompt correctly", async () => {
|
||||
// Create proper instinct context structure matching NextEditProvider.ts
|
||||
const instinctCtx = {
|
||||
contextSnippets:
|
||||
"+++++ /path/to/context.ts\nconst contextVar = 'test';",
|
||||
currentFileContent: instinctHelper.fileContents,
|
||||
windowStart: 0, // Math.max(0, helper.pos.line - 25)
|
||||
windowEnd: 3, // Math.min(helper.fileLines.length - 1, helper.pos.line + 25)
|
||||
editableRegionStartLine: 0, // Math.max(0, helper.pos.line - 1) within window
|
||||
editableRegionEndLine: 2, // Math.min(helper.pos.line + 5) within window
|
||||
editDiffHistory: [
|
||||
"diff --git a/file.ts b/file.ts\nindex 123..456 789\n--- a/file.ts\n+++ b/file.ts\n@@ -1,3 +1,4 @@\n function test() {\n+ const a = 1;\n return a;\n }",
|
||||
], // unified diff
|
||||
currentFilePath: "/path/to/file.ts",
|
||||
languageShorthand: "ts",
|
||||
};
|
||||
|
||||
const result = await renderPrompt(instinctHelper, instinctCtx);
|
||||
console.log(result);
|
||||
|
||||
expect(result).toHaveProperty("prompt");
|
||||
expect(result.prompt.role).toBe("user");
|
||||
expect(result.prompt.content).toContain(INSTINCT_USER_PROMPT_PREFIX);
|
||||
expect(result.prompt.content).toContain("### Context:");
|
||||
expect(result.prompt.content).toContain("### User Edits:");
|
||||
expect(result.prompt.content).toContain("### User Excerpt:");
|
||||
|
||||
expect(result.userEdits).toBe(instinctCtx.editDiffHistory);
|
||||
expect(result.userExcerpts).toContain(INSTINCT_USER_CURSOR_IS_HERE_TOKEN);
|
||||
});
|
||||
|
||||
it("should throw error for unsupported model name", async () => {
|
||||
await expect(renderPrompt(unsupportedHelper, ctx)).rejects.toThrow(
|
||||
"mistral/codestral is not yet supported for next edit.",
|
||||
describe("NEXT_EDIT_MODEL_TEMPLATES", () => {
|
||||
it("should contain templates for all supported models", () => {
|
||||
expect(NEXT_EDIT_MODEL_TEMPLATES).toHaveProperty(
|
||||
NEXT_EDIT_MODELS.MERCURY_CODER,
|
||||
);
|
||||
expect(NEXT_EDIT_MODEL_TEMPLATES).toHaveProperty(
|
||||
NEXT_EDIT_MODELS.INSTINCT,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("renderDefaultSystemPrompt", () => {
|
||||
it("should return a system prompt with expected role and content", () => {
|
||||
const result = renderDefaultSystemPrompt();
|
||||
it("mercury-coder template should contain expected tokens", () => {
|
||||
const template =
|
||||
NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template;
|
||||
|
||||
expect(result.role).toBe("system");
|
||||
expect(result.content).toContain("You are an expert polyglot developer");
|
||||
expect(result.content).toContain("Do not hallucinate.");
|
||||
expect(template).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN);
|
||||
expect(template).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE);
|
||||
expect(template).toContain(MERCURY_CURRENT_FILE_CONTENT_OPEN);
|
||||
expect(template).toContain(MERCURY_CURRENT_FILE_CONTENT_CLOSE);
|
||||
expect(template).toContain(MERCURY_EDIT_DIFF_HISTORY_OPEN);
|
||||
expect(template).toContain(MERCURY_EDIT_DIFF_HISTORY_CLOSE);
|
||||
expect(template).toContain("{{{recentlyViewedCodeSnippets}}}");
|
||||
expect(template).toContain("{{{currentFileContent}}}");
|
||||
expect(template).toContain("{{{editDiffHistory}}}");
|
||||
});
|
||||
|
||||
it("instinct template should contain expected tokens", () => {
|
||||
const template =
|
||||
NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.INSTINCT].template;
|
||||
|
||||
expect(template).toContain(INSTINCT_USER_PROMPT_PREFIX);
|
||||
expect(template).toContain("### Context:");
|
||||
expect(template).toContain("### User Edits:");
|
||||
expect(template).toContain("### User Excerpt:");
|
||||
expect(template).toContain("{{{contextSnippets}}}");
|
||||
expect(template).toContain("{{{currentFileContent}}}");
|
||||
expect(template).toContain("{{{editDiffHistory}}}");
|
||||
expect(template).toContain("{{{currentFilePath}}}");
|
||||
});
|
||||
});
|
||||
|
||||
describe("renderDefaultUserPrompt", () => {
|
||||
it("should render a user prompt with the correct structure", () => {
|
||||
const snippets: SnippetPayload = {
|
||||
rootPathSnippets: [
|
||||
{
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath: "",
|
||||
content: "root path",
|
||||
},
|
||||
],
|
||||
importDefinitionSnippets: [
|
||||
{
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath: "",
|
||||
content: "import def",
|
||||
},
|
||||
],
|
||||
ideSnippets: [
|
||||
{
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath: "",
|
||||
content: "ide snippets",
|
||||
},
|
||||
],
|
||||
recentlyEditedRangeSnippets: [
|
||||
{
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath: "",
|
||||
content: "recent edits",
|
||||
},
|
||||
],
|
||||
diffSnippets: [
|
||||
{
|
||||
type: AutocompleteSnippetType.Diff,
|
||||
content: "diff snippets",
|
||||
},
|
||||
],
|
||||
clipboardSnippets: [
|
||||
{
|
||||
type: AutocompleteSnippetType.Clipboard,
|
||||
content: "clipboard",
|
||||
copiedAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
recentlyVisitedRangesSnippets: [
|
||||
{
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath: "",
|
||||
content: "visited ranges",
|
||||
},
|
||||
],
|
||||
recentlyOpenedFileSnippets: [
|
||||
{
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath: "",
|
||||
content: "recently opened files",
|
||||
},
|
||||
],
|
||||
staticSnippet: [
|
||||
{
|
||||
type: AutocompleteSnippetType.Static,
|
||||
filepath: "",
|
||||
content: "static content",
|
||||
},
|
||||
],
|
||||
};
|
||||
describe("PromptTemplateRenderer", () => {
|
||||
it("should render a template with provided variables", () => {
|
||||
const template = "Hello {{{name}}}, you have {{{count}}} messages";
|
||||
const renderer = new PromptTemplateRenderer(template);
|
||||
|
||||
const helper: HelperVars = {
|
||||
lang: { name: "typescript" },
|
||||
} as HelperVars;
|
||||
|
||||
const result = renderDefaultUserPrompt(snippets, helper);
|
||||
|
||||
expect(result.role).toBe("user");
|
||||
expect(result.content).toContain("Your junior made the following edit:");
|
||||
expect(result.content).toContain("typescript");
|
||||
expect(result.content).toContain("root path");
|
||||
});
|
||||
});
|
||||
|
||||
describe("insertTokens", () => {
|
||||
it("should correctly insert cursor and editable region tokens", () => {
|
||||
const mercuryHelper = {
|
||||
modelName: "inception/mercury-coder-nextedit" as NEXT_EDIT_MODELS,
|
||||
fileContents: "function test() {\n const a = 1;\n return a;\n}",
|
||||
pos: { line: 1, character: 12 } as Position,
|
||||
lang: { name: "typescript" },
|
||||
} as HelperVars;
|
||||
|
||||
const ctx = {
|
||||
recentlyViewedCodeSnippets: [
|
||||
{ filepath: "/path/to/file1.ts", content: "const b = 2;" },
|
||||
],
|
||||
currentFileContent: "function test() {\n const a = 1;\n return a;\n}",
|
||||
editDiffHistory: ["diff --git a/file.ts b/file.ts\n@@ -1,3 +1,4 @@"],
|
||||
editableRegionStartLine: 0,
|
||||
editableRegionEndLine: 3,
|
||||
userEdits: "Added constant a",
|
||||
languageShorthand: "ts",
|
||||
userExcerpts: "const a = 1;",
|
||||
};
|
||||
|
||||
return renderPrompt(mercuryHelper, ctx).then((result) => {
|
||||
expect(result.userExcerpts).toContain(MERCURY_CURSOR);
|
||||
const result = renderer.render({
|
||||
name: "Alice",
|
||||
count: "5",
|
||||
});
|
||||
|
||||
expect(result).toBe("Hello Alice, you have 5 messages");
|
||||
});
|
||||
|
||||
it("should handle missing variables gracefully", () => {
|
||||
const template = "Hello {{{name}}}";
|
||||
const renderer = new PromptTemplateRenderer(template);
|
||||
|
||||
const result = renderer.render({});
|
||||
|
||||
expect(result).toBe("Hello ");
|
||||
});
|
||||
|
||||
it("should render complex templates correctly", () => {
|
||||
const template =
|
||||
NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template;
|
||||
const renderer = new PromptTemplateRenderer(template);
|
||||
|
||||
const result = renderer.render({
|
||||
recentlyViewedCodeSnippets: "snippet1",
|
||||
currentFileContent: "file content",
|
||||
editDiffHistory: "diff history",
|
||||
});
|
||||
|
||||
expect(result).toContain("snippet1");
|
||||
expect(result).toContain("file content");
|
||||
expect(result).toContain("diff history");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getTemplateForModel", () => {
|
||||
it("should return the correct template for a supported model", () => {
|
||||
const template = getTemplateForModel(NEXT_EDIT_MODELS.MERCURY_CODER);
|
||||
expect(template).toBe(
|
||||
NEXT_EDIT_MODEL_TEMPLATES[NEXT_EDIT_MODELS.MERCURY_CODER].template,
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw an error for an unsupported model", () => {
|
||||
expect(() =>
|
||||
getTemplateForModel("unsupported" as NEXT_EDIT_MODELS),
|
||||
).toThrow("Model unsupported is not supported for next edit.");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -5,7 +5,9 @@ import {
|
|||
RangeInFile,
|
||||
TabAutocompleteOptions,
|
||||
} from "../";
|
||||
import { SnippetPayload } from "../autocomplete/snippets";
|
||||
import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types";
|
||||
import { HelperVars } from "../autocomplete/util/HelperVars";
|
||||
|
||||
export type RecentlyEditedRange = RangeInFile & {
|
||||
timestamp: number;
|
||||
|
|
@ -104,3 +106,36 @@ export interface MercuryTemplateVars extends TemplateVars {
|
|||
editDiffHistory: string; // could be a singe large unified diff
|
||||
currentFilePath: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Context object containing all necessary information for model-specific operations.
|
||||
*/
|
||||
export interface ModelSpecificContext {
|
||||
helper: HelperVars;
|
||||
snippetPayload: SnippetPayload;
|
||||
editableRegionStartLine: number;
|
||||
editableRegionEndLine: number;
|
||||
diffContext: string[];
|
||||
autocompleteContext: string;
|
||||
historyDiff?: string;
|
||||
workspaceDirs?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for editable region calculation.
|
||||
*/
|
||||
export interface EditableRegionConfig {
|
||||
usingFullFileDiff?: boolean;
|
||||
maxTokens?: number;
|
||||
topMargin?: number;
|
||||
bottomMargin?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for prompt generation.
|
||||
*/
|
||||
export interface PromptConfig {
|
||||
includeHistory?: boolean;
|
||||
includeRecentEdits?: boolean;
|
||||
maxContextSnippets?: number;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { DiffLine } from "..";
|
||||
import { NEXT_EDIT_MODELS } from "../llm/constants";
|
||||
|
||||
export function isNextEditTest(): boolean {
|
||||
const enabled = process.env.NEXT_EDIT_TEST_ENABLED;
|
||||
|
|
@ -21,3 +22,11 @@ export function isWhitespaceOnlyDeletion(diffLines: DiffLine[]): boolean {
|
|||
(diff.line.trim() === "" || /^\s+$/.test(diff.line)),
|
||||
);
|
||||
}
|
||||
|
||||
export function convertNextEditModelNameToEnum(
|
||||
modelName: string,
|
||||
): NEXT_EDIT_MODELS | undefined {
|
||||
const nextEditModels = Object.values(NEXT_EDIT_MODELS);
|
||||
|
||||
return nextEditModels.find((model) => modelName.includes(model));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,11 @@
|
|||
import { describe, expect, test, vi } from "vitest";
|
||||
import { DiffLine } from "..";
|
||||
import { isNextEditTest, isWhitespaceOnlyDeletion } from "./utils";
|
||||
import { NEXT_EDIT_MODELS } from "../llm/constants";
|
||||
import {
|
||||
convertNextEditModelNameToEnum,
|
||||
isNextEditTest,
|
||||
isWhitespaceOnlyDeletion,
|
||||
} from "./utils";
|
||||
|
||||
describe("isNextEditTest", () => {
|
||||
test("returns true when NEXT_EDIT_TEST_ENABLED is 'true'", () => {
|
||||
|
|
@ -57,3 +62,35 @@ describe("isWhitespaceOnlyDeletion", () => {
|
|||
expect(isWhitespaceOnlyDeletion(diffLines)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("convertNextEditModelNameToEnum", () => {
|
||||
test("returns correct enum for exact matches", () => {
|
||||
Object.values(NEXT_EDIT_MODELS).forEach((model) => {
|
||||
expect(convertNextEditModelNameToEnum(model)).toBe(model);
|
||||
});
|
||||
});
|
||||
|
||||
test("returns correct enum when model name is contained in a longer string", () => {
|
||||
expect(convertNextEditModelNameToEnum("inception/mercury-coder")).toBe(
|
||||
NEXT_EDIT_MODELS.MERCURY_CODER,
|
||||
);
|
||||
expect(convertNextEditModelNameToEnum("blah/instinct")).toBe(
|
||||
NEXT_EDIT_MODELS.INSTINCT,
|
||||
);
|
||||
});
|
||||
|
||||
test("returns undefined for non-matching model names", () => {
|
||||
expect(convertNextEditModelNameToEnum("unknown-model")).toBeUndefined();
|
||||
expect(convertNextEditModelNameToEnum("random-string")).toBeUndefined();
|
||||
expect(convertNextEditModelNameToEnum("")).toBeUndefined();
|
||||
});
|
||||
|
||||
test("returns first match when multiple models could match", () => {
|
||||
const modelName = "model-that-contains-multiple-matches";
|
||||
const result = convertNextEditModelNameToEnum(modelName);
|
||||
|
||||
if (result !== undefined) {
|
||||
expect(Object.values(NEXT_EDIT_MODELS)).toContain(result);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
346
core/package-lock.json
generated
346
core/package-lock.json
generated
|
|
@ -25,7 +25,6 @@
|
|||
"@sentry/esbuild-plugin": "^4.0.2",
|
||||
"@sentry/node": "^9.43.0",
|
||||
"@sentry/vite-plugin": "^4.0.2",
|
||||
"@typescript-eslint/eslint-plugin": "^7.8.0",
|
||||
"@xenova/transformers": "2.14.0",
|
||||
"adf-to-md": "^1.1.0",
|
||||
"async-mutex": "^0.5.0",
|
||||
|
|
@ -44,7 +43,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",
|
||||
|
|
@ -105,6 +104,8 @@
|
|||
"@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",
|
||||
|
|
@ -227,6 +228,7 @@
|
|||
"@types/follow-redirects": "^1.14.4",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/json-schema": "^7.0.15",
|
||||
"@types/node": "^24.3.0",
|
||||
"cross-env": "^7.0.3",
|
||||
"semantic-release": "^24.2.7",
|
||||
"ts-jest": "^29.2.3",
|
||||
|
|
@ -3388,9 +3390,10 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@eslint-community/eslint-utils": {
|
||||
"version": "4.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.1.tgz",
|
||||
"integrity": "sha512-s3O3waFUrMV8P/XaF/+ZTp1X9XBZW1a4B97ZnjQF2KYWaFD2A8KyFBsrsfSjEmjn3RGWAIuvlneuZm3CUK3jbA==",
|
||||
"version": "4.7.0",
|
||||
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.7.0.tgz",
|
||||
"integrity": "sha512-dyybb3AcajC7uha6CvhdVRJqaKyn7w2YKqKyAN37NKYgZT36w+iRb0Dymmc5qEJ549c/S31cMMSFd75bteCpCw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"eslint-visitor-keys": "^3.4.3"
|
||||
},
|
||||
|
|
@ -3458,6 +3461,15 @@
|
|||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/@eslint/eslintrc/node_modules/ignore": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
||||
"integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 4"
|
||||
}
|
||||
},
|
||||
"node_modules/@eslint/eslintrc/node_modules/minimatch": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
|
||||
|
|
@ -6975,113 +6987,150 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/eslint-plugin": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.18.0.tgz",
|
||||
"integrity": "sha512-94EQTWZ40mzBc42ATNIBimBEDltSJ9RQHCC8vc/PDbxi4k8dVwUAv4o98dk50M1zB+JGFxp43FP7f8+FP8R6Sw==",
|
||||
"version": "8.40.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.40.0.tgz",
|
||||
"integrity": "sha512-w/EboPlBwnmOBtRbiOvzjD+wdiZdgFeo17lkltrtn7X37vagKKWJABvyfsJXTlHe6XBzugmYgd4A4nW+k8Mixw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@eslint-community/regexpp": "^4.10.0",
|
||||
"@typescript-eslint/scope-manager": "7.18.0",
|
||||
"@typescript-eslint/type-utils": "7.18.0",
|
||||
"@typescript-eslint/utils": "7.18.0",
|
||||
"@typescript-eslint/visitor-keys": "7.18.0",
|
||||
"@typescript-eslint/scope-manager": "8.40.0",
|
||||
"@typescript-eslint/type-utils": "8.40.0",
|
||||
"@typescript-eslint/utils": "8.40.0",
|
||||
"@typescript-eslint/visitor-keys": "8.40.0",
|
||||
"graphemer": "^1.4.0",
|
||||
"ignore": "^5.3.1",
|
||||
"ignore": "^7.0.0",
|
||||
"natural-compare": "^1.4.0",
|
||||
"ts-api-utils": "^1.3.0"
|
||||
"ts-api-utils": "^2.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || >=20.0.0"
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@typescript-eslint/parser": "^7.0.0",
|
||||
"eslint": "^8.56.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"typescript": {
|
||||
"optional": true
|
||||
}
|
||||
"@typescript-eslint/parser": "^8.40.0",
|
||||
"eslint": "^8.57.0 || ^9.0.0",
|
||||
"typescript": ">=4.8.4 <6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/parser": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-7.18.0.tgz",
|
||||
"integrity": "sha512-4Z+L8I2OqhZV8qA132M4wNL30ypZGYOQVBfMgxDH/K5UX0PNqTu1c6za9ST5r9+tavvHiTWmBnKzpCJ/GlVFtg==",
|
||||
"peer": true,
|
||||
"version": "8.40.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.40.0.tgz",
|
||||
"integrity": "sha512-jCNyAuXx8dr5KJMkecGmZ8KI61KBUhkCob+SD+C+I5+Y1FWI2Y3QmY4/cxMCC5WAsZqoEtEETVhUiUMIGCf6Bw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "7.18.0",
|
||||
"@typescript-eslint/types": "7.18.0",
|
||||
"@typescript-eslint/typescript-estree": "7.18.0",
|
||||
"@typescript-eslint/visitor-keys": "7.18.0",
|
||||
"@typescript-eslint/scope-manager": "8.40.0",
|
||||
"@typescript-eslint/types": "8.40.0",
|
||||
"@typescript-eslint/typescript-estree": "8.40.0",
|
||||
"@typescript-eslint/visitor-keys": "8.40.0",
|
||||
"debug": "^4.3.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || >=20.0.0"
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"eslint": "^8.56.0"
|
||||
"eslint": "^8.57.0 || ^9.0.0",
|
||||
"typescript": ">=4.8.4 <6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/project-service": {
|
||||
"version": "8.40.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.40.0.tgz",
|
||||
"integrity": "sha512-/A89vz7Wf5DEXsGVvcGdYKbVM9F7DyFXj52lNYUDS1L9yJfqjW/fIp5PgMuEJL/KeqVTe2QSbXAGUZljDUpArw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/tsconfig-utils": "^8.40.0",
|
||||
"@typescript-eslint/types": "^8.40.0",
|
||||
"debug": "^4.3.4"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"typescript": {
|
||||
"optional": true
|
||||
}
|
||||
"engines": {
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": ">=4.8.4 <6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/scope-manager": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-7.18.0.tgz",
|
||||
"integrity": "sha512-jjhdIE/FPF2B7Z1uzc6i3oWKbGcHb87Qw7AWj6jmEqNOfDFbJWtjt/XfwCpvNkpGWlcJaog5vTR+VV8+w9JflA==",
|
||||
"version": "8.40.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.40.0.tgz",
|
||||
"integrity": "sha512-y9ObStCcdCiZKzwqsE8CcpyuVMwRouJbbSrNuThDpv16dFAj429IkM6LNb1dZ2m7hK5fHyzNcErZf7CEeKXR4w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/types": "7.18.0",
|
||||
"@typescript-eslint/visitor-keys": "7.18.0"
|
||||
"@typescript-eslint/types": "8.40.0",
|
||||
"@typescript-eslint/visitor-keys": "8.40.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || >=20.0.0"
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/type-utils": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-7.18.0.tgz",
|
||||
"integrity": "sha512-XL0FJXuCLaDuX2sYqZUUSOJ2sG5/i1AAze+axqmLnSkNEVMVYLF+cbwlB2w8D1tinFuSikHmFta+P+HOofrLeA==",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/typescript-estree": "7.18.0",
|
||||
"@typescript-eslint/utils": "7.18.0",
|
||||
"debug": "^4.3.4",
|
||||
"ts-api-utils": "^1.3.0"
|
||||
},
|
||||
"node_modules/@typescript-eslint/tsconfig-utils": {
|
||||
"version": "8.40.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.40.0.tgz",
|
||||
"integrity": "sha512-jtMytmUaG9d/9kqSl/W3E3xaWESo4hFDxAIHGVW/WKKtQhesnRIJSAJO6XckluuJ6KDB5woD1EiqknriCtAmcw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^18.18.0 || >=20.0.0"
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"eslint": "^8.56.0"
|
||||
"typescript": ">=4.8.4 <6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/type-utils": {
|
||||
"version": "8.40.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.40.0.tgz",
|
||||
"integrity": "sha512-eE60cK4KzAc6ZrzlJnflXdrMqOBaugeukWICO2rB0KNvwdIMaEaYiywwHMzA1qFpTxrLhN9Lp4E/00EgWcD3Ow==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/types": "8.40.0",
|
||||
"@typescript-eslint/typescript-estree": "8.40.0",
|
||||
"@typescript-eslint/utils": "8.40.0",
|
||||
"debug": "^4.3.4",
|
||||
"ts-api-utils": "^2.1.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"typescript": {
|
||||
"optional": true
|
||||
}
|
||||
"engines": {
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"eslint": "^8.57.0 || ^9.0.0",
|
||||
"typescript": ">=4.8.4 <6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/types": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.18.0.tgz",
|
||||
"integrity": "sha512-iZqi+Ds1y4EDYUtlOOC+aUmxnE9xS/yCigkjA7XpTKV6nCBd3Hp/PRGGmdwnfkV2ThMyYldP1wRpm/id99spTQ==",
|
||||
"version": "8.40.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.40.0.tgz",
|
||||
"integrity": "sha512-ETdbFlgbAmXHyFPwqUIYrfc12ArvpBhEVgGAxVYSwli26dn8Ko+lIo4Su9vI9ykTZdJn+vJprs/0eZU0YMAEQg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^18.18.0 || >=20.0.0"
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
|
|
@ -7089,36 +7138,40 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/typescript-estree": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-7.18.0.tgz",
|
||||
"integrity": "sha512-aP1v/BSPnnyhMHts8cf1qQ6Q1IFwwRvAQGRvBFkWlo3/lH29OXA3Pts+c10nxRxIBrDnoMqzhgdwVe5f2D6OzA==",
|
||||
"version": "8.40.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.40.0.tgz",
|
||||
"integrity": "sha512-k1z9+GJReVVOkc1WfVKs1vBrR5MIKKbdAjDTPvIK3L8De6KbFfPFt6BKpdkdk7rZS2GtC/m6yI5MYX+UsuvVYQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/types": "7.18.0",
|
||||
"@typescript-eslint/visitor-keys": "7.18.0",
|
||||
"@typescript-eslint/project-service": "8.40.0",
|
||||
"@typescript-eslint/tsconfig-utils": "8.40.0",
|
||||
"@typescript-eslint/types": "8.40.0",
|
||||
"@typescript-eslint/visitor-keys": "8.40.0",
|
||||
"debug": "^4.3.4",
|
||||
"globby": "^11.1.0",
|
||||
"fast-glob": "^3.3.2",
|
||||
"is-glob": "^4.0.3",
|
||||
"minimatch": "^9.0.4",
|
||||
"semver": "^7.6.0",
|
||||
"ts-api-utils": "^1.3.0"
|
||||
"ts-api-utils": "^2.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || >=20.0.0"
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"typescript": {
|
||||
"optional": true
|
||||
}
|
||||
"peerDependencies": {
|
||||
"typescript": ">=4.8.4 <6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/typescript-estree/node_modules/semver": {
|
||||
"version": "7.6.3",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.6.3.tgz",
|
||||
"integrity": "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A==",
|
||||
"version": "7.7.2",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz",
|
||||
"integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
},
|
||||
|
|
@ -7127,42 +7180,60 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/utils": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-7.18.0.tgz",
|
||||
"integrity": "sha512-kK0/rNa2j74XuHVcoCZxdFBMF+aq/vH83CXAOHieC+2Gis4mF8jJXT5eAfyD3K0sAxtPuwxaIOIOvhwzVDt/kw==",
|
||||
"version": "8.40.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.40.0.tgz",
|
||||
"integrity": "sha512-Cgzi2MXSZyAUOY+BFwGs17s7ad/7L+gKt6Y8rAVVWS+7o6wrjeFN4nVfTpbE25MNcxyJ+iYUXflbs2xR9h4UBg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.4.0",
|
||||
"@typescript-eslint/scope-manager": "7.18.0",
|
||||
"@typescript-eslint/types": "7.18.0",
|
||||
"@typescript-eslint/typescript-estree": "7.18.0"
|
||||
"@eslint-community/eslint-utils": "^4.7.0",
|
||||
"@typescript-eslint/scope-manager": "8.40.0",
|
||||
"@typescript-eslint/types": "8.40.0",
|
||||
"@typescript-eslint/typescript-estree": "8.40.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || >=20.0.0"
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"eslint": "^8.56.0"
|
||||
"eslint": "^8.57.0 || ^9.0.0",
|
||||
"typescript": ">=4.8.4 <6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/visitor-keys": {
|
||||
"version": "7.18.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.18.0.tgz",
|
||||
"integrity": "sha512-cDF0/Gf81QpY3xYyJKDV14Zwdmid5+uuENhjH2EqFaF0ni+yAyq/LzMaIJdhNJXZI7uLzwIlA+V7oWoyn6Curg==",
|
||||
"version": "8.40.0",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.40.0.tgz",
|
||||
"integrity": "sha512-8CZ47QwalyRjsypfwnbI3hKy5gJDPmrkLjkgMxhi0+DZZ2QNx2naS6/hWoVYUHU7LU2zleF68V9miaVZvhFfTA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@typescript-eslint/types": "7.18.0",
|
||||
"eslint-visitor-keys": "^3.4.3"
|
||||
"@typescript-eslint/types": "8.40.0",
|
||||
"eslint-visitor-keys": "^4.2.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.18.0 || >=20.0.0"
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": {
|
||||
"version": "4.2.1",
|
||||
"resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz",
|
||||
"integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://opencollective.com/eslint"
|
||||
}
|
||||
},
|
||||
"node_modules/@ungap/structured-clone": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.2.1.tgz",
|
||||
|
|
@ -7634,14 +7705,6 @@
|
|||
"resolved": "https://registry.npmjs.org/array-timsort/-/array-timsort-1.0.3.tgz",
|
||||
"integrity": "sha512-/+3GRL7dDAGEfM6TseQk/U+mi18TU2Ms9I3UlLdUMhz2hbvGNTKdj9xniwXfUqgYhHxRx0+8UnKkvlNwVU+cWQ=="
|
||||
},
|
||||
"node_modules/array-union": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz",
|
||||
"integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/array.prototype.findlastindex": {
|
||||
"version": "1.2.5",
|
||||
"resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.5.tgz",
|
||||
|
|
@ -9432,17 +9495,6 @@
|
|||
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/dir-glob": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz",
|
||||
"integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==",
|
||||
"dependencies": {
|
||||
"path-type": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/doctrine": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz",
|
||||
|
|
@ -10577,6 +10629,15 @@
|
|||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/eslint/node_modules/ignore": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
||||
"integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 4"
|
||||
}
|
||||
},
|
||||
"node_modules/eslint/node_modules/minimatch": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
|
||||
|
|
@ -10929,15 +10990,17 @@
|
|||
"integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ=="
|
||||
},
|
||||
"node_modules/fast-glob": {
|
||||
"version": "3.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz",
|
||||
"integrity": "sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==",
|
||||
"version": "3.3.3",
|
||||
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz",
|
||||
"integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@nodelib/fs.stat": "^2.0.2",
|
||||
"@nodelib/fs.walk": "^1.2.3",
|
||||
"glob-parent": "^5.1.2",
|
||||
"merge2": "^1.3.0",
|
||||
"micromatch": "^4.0.4"
|
||||
"micromatch": "^4.0.8"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8.6.0"
|
||||
|
|
@ -10947,6 +11010,8 @@
|
|||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
|
||||
"integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"is-glob": "^4.0.1"
|
||||
},
|
||||
|
|
@ -11660,25 +11725,6 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/globby": {
|
||||
"version": "11.1.0",
|
||||
"resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz",
|
||||
"integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==",
|
||||
"dependencies": {
|
||||
"array-union": "^2.1.0",
|
||||
"dir-glob": "^3.0.1",
|
||||
"fast-glob": "^3.2.9",
|
||||
"ignore": "^5.2.0",
|
||||
"merge2": "^1.4.1",
|
||||
"slash": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/google-auth-library": {
|
||||
"version": "9.15.0",
|
||||
"resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-9.15.0.tgz",
|
||||
|
|
@ -12133,9 +12179,10 @@
|
|||
]
|
||||
},
|
||||
"node_modules/ignore": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
||||
"integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
|
||||
"version": "7.0.5",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz",
|
||||
"integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 4"
|
||||
}
|
||||
|
|
@ -14477,6 +14524,8 @@
|
|||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
|
||||
"integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
|
|
@ -14579,6 +14628,7 @@
|
|||
"version": "4.0.8",
|
||||
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
|
||||
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"braces": "^3.0.3",
|
||||
"picomatch": "^2.3.1"
|
||||
|
|
@ -15804,14 +15854,6 @@
|
|||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/path-type": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz",
|
||||
"integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/pathe": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
|
||||
|
|
@ -17587,6 +17629,7 @@
|
|||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz",
|
||||
"integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==",
|
||||
"dev": true,
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
|
|
@ -18577,14 +18620,16 @@
|
|||
}
|
||||
},
|
||||
"node_modules/ts-api-utils": {
|
||||
"version": "1.4.3",
|
||||
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.4.3.tgz",
|
||||
"integrity": "sha512-i3eMG77UTMD0hZhgRS562pv83RC6ukSAC2GMNWc+9dieh/+jDM5u5YG+NHX6VNDRHQcHwmsTHctP9LhbC3WxVw==",
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz",
|
||||
"integrity": "sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
"node": ">=18.12"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"typescript": ">=4.2.0"
|
||||
"typescript": ">=4.8.4"
|
||||
}
|
||||
},
|
||||
"node_modules/ts-jest": {
|
||||
|
|
@ -18848,6 +18893,7 @@
|
|||
"version": "5.7.2",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.2.tgz",
|
||||
"integrity": "sha512-i5t66RHxDvVN40HfDd1PsEThGNnlMCMT3jMUuoh9/0TaqWevNontacunWyN02LA9/fIbEWlcHZcgTKb9QoaLfg==",
|
||||
"devOptional": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
|
|
|
|||
|
|
@ -36,6 +36,8 @@
|
|||
"@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",
|
||||
|
|
@ -66,7 +68,6 @@
|
|||
"@sentry/esbuild-plugin": "^4.0.2",
|
||||
"@sentry/node": "^9.43.0",
|
||||
"@sentry/vite-plugin": "^4.0.2",
|
||||
"@typescript-eslint/eslint-plugin": "^7.8.0",
|
||||
"@xenova/transformers": "2.14.0",
|
||||
"adf-to-md": "^1.1.0",
|
||||
"async-mutex": "^0.5.0",
|
||||
|
|
@ -85,7 +86,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",
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@ export enum BuiltInToolNames {
|
|||
ReadFile = "read_file",
|
||||
EditExistingFile = "edit_existing_file",
|
||||
SearchAndReplaceInFile = "search_and_replace_in_file",
|
||||
SingleFindAndReplace = "single_find_and_replace",
|
||||
MultiEdit = "multi_edit",
|
||||
ReadCurrentlyOpenFile = "read_currently_open_file",
|
||||
CreateNewFile = "create_new_file",
|
||||
RunTerminalCommand = "run_terminal_command",
|
||||
|
|
@ -25,4 +27,6 @@ export const BUILT_IN_GROUP_NAME = "Built-In";
|
|||
export const CLIENT_TOOLS_IMPLS = [
|
||||
BuiltInToolNames.EditExistingFile,
|
||||
BuiltInToolNames.SearchAndReplaceInFile,
|
||||
BuiltInToolNames.SingleFindAndReplace,
|
||||
BuiltInToolNames.MultiEdit,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -6,12 +6,14 @@ export { fetchUrlContentTool } from "./fetchUrlContent";
|
|||
export { globSearchTool } from "./globSearch";
|
||||
export { grepSearchTool } from "./grepSearch";
|
||||
export { lsTool } from "./ls";
|
||||
export { multiEditTool } from "./multiEdit";
|
||||
export { readCurrentlyOpenFileTool } from "./readCurrentlyOpenFile";
|
||||
export { readFileTool } from "./readFile";
|
||||
export { requestRuleTool } from "./requestRule";
|
||||
export { runTerminalCommandTool } from "./runTerminalCommand";
|
||||
export { searchAndReplaceInFileTool } from "./searchAndReplaceInFile";
|
||||
export { searchWebTool } from "./searchWeb";
|
||||
export { singleFindAndReplaceTool } from "./singleFindAndReplace";
|
||||
export { viewDiffTool } from "./viewDiff";
|
||||
export { viewRepoMapTool } from "./viewRepoMap";
|
||||
export { viewSubdirectoryTool } from "./viewSubdirectory";
|
||||
|
|
|
|||
131
core/tools/definitions/multiEdit.ts
Normal file
131
core/tools/definitions/multiEdit.ts
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export interface EditOperation {
|
||||
old_string: string;
|
||||
new_string: string;
|
||||
replace_all?: boolean;
|
||||
}
|
||||
|
||||
export interface MultiEditArgs {
|
||||
filepath: string;
|
||||
edits: EditOperation[];
|
||||
}
|
||||
|
||||
export const multiEditTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Multi Edit",
|
||||
wouldLikeTo: "edit {{{ filepath }}}",
|
||||
isCurrently: "editing {{{ filepath }}}",
|
||||
hasAlready: "edited {{{ filepath }}}",
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
readonly: false,
|
||||
isInstant: false,
|
||||
function: {
|
||||
name: BuiltInToolNames.MultiEdit,
|
||||
description: `This is a tool for making multiple edits to a single file in one operation. It
|
||||
is built on top of the single find and replace tool and allows you to perform multiple
|
||||
find-and-replace operations efficiently. Prefer this tool over the single find and replace tool
|
||||
when you need to make multiple edits to the same file.
|
||||
|
||||
Before using this tool:
|
||||
|
||||
1. Use the read_file tool to understand the file's contents and context
|
||||
2. Verify the directory path is correct
|
||||
|
||||
To make multiple file edits, provide the following:
|
||||
|
||||
1. filepath: The path to the file to modify (relative to the root of the workspace)
|
||||
2. edits: An array of edit operations to perform, where each edit contains:
|
||||
- old_string: The text to replace (must match the file contents exactly, including all whitespace and indentation)
|
||||
- new_string: The edited text to replace the old_string
|
||||
- replace_all: Replace all occurrences of old_string. This parameter is optional and defaults to false.
|
||||
|
||||
IMPORTANT:
|
||||
- All edits are applied in sequence, in the order they are provided
|
||||
- Each edit operates on the result of the previous edit
|
||||
- All edits must be valid for the operation to succeed - if any edit fails,
|
||||
none will be applied
|
||||
- This tool is ideal when you need to make several changes to different parts
|
||||
of the same file
|
||||
|
||||
CRITICAL REQUIREMENTS:
|
||||
|
||||
1. All edits follow the same requirements as the single find and replace tool
|
||||
2. The edits are atomic - either all succeed or none are applied
|
||||
3. Plan your edits carefully to avoid conflicts between sequential operations
|
||||
|
||||
WARNING:
|
||||
|
||||
- The tool will fail if edits.old_string doesn't match the file contents
|
||||
exactly (including whitespace)
|
||||
- The tool will fail if edits.old_string and edits.new_string are the same
|
||||
- Since edits are applied in sequence, ensure that earlier edits don't affect
|
||||
the text that later edits are trying to find
|
||||
|
||||
When making edits:
|
||||
|
||||
- Ensure all edits result in idiomatic, correct code
|
||||
- Do not leave the code in a broken state
|
||||
- Only use emojis if the user explicitly requests it. Avoid adding emojis to
|
||||
files unless asked.
|
||||
- Use replace_all for replacing and renaming strings across the file. This
|
||||
parameter is useful if you want to rename a variable for instance.
|
||||
|
||||
If you want to create a new file, use:
|
||||
- A new file path
|
||||
- First edit: empty old_string and the new file's contents as new_string
|
||||
- Subsequent edits are not allowed - there is no need since you are creating`,
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "edits"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path to the file to modify, relative to the root of the workspace",
|
||||
},
|
||||
edits: {
|
||||
type: "array",
|
||||
description:
|
||||
"Array of edit operations to perform sequentially on the file",
|
||||
items: {
|
||||
type: "object",
|
||||
required: ["old_string", "new_string"],
|
||||
properties: {
|
||||
old_string: {
|
||||
type: "string",
|
||||
description: "The text to replace",
|
||||
},
|
||||
new_string: {
|
||||
type: "string",
|
||||
description: "The text to replace it with",
|
||||
},
|
||||
replace_all: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"Replace all occurrences of old_string (default false)",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: {
|
||||
prefix: `To make multiple edits to a single file, use the ${BuiltInToolNames.MultiEdit} tool with a filepath (relative to the root of the workspace) and an array of edit operations.
|
||||
|
||||
For example, you could respond with:`,
|
||||
exampleArgs: [
|
||||
["filepath", "path/to/file.ts"],
|
||||
[
|
||||
"edits",
|
||||
`[
|
||||
{ "old_string": "const oldVar = 'value'", "new_string": "const newVar = 'updated'" },
|
||||
{ "old_string": "oldFunction()", "new_string": "newFunction()", "replace_all": true }
|
||||
]`,
|
||||
],
|
||||
],
|
||||
},
|
||||
defaultToolPolicy: "allowedWithPermission",
|
||||
};
|
||||
|
|
@ -13,7 +13,7 @@ export const readCurrentlyOpenFileTool: Tool = {
|
|||
function: {
|
||||
name: BuiltInToolNames.ReadCurrentlyOpenFile,
|
||||
description:
|
||||
"Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, try using this",
|
||||
"Read the currently open file in the IDE. If the user seems to be referring to a file that you can't see, or is requesting an action on content that seems missing, try using this tool.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {},
|
||||
|
|
|
|||
84
core/tools/definitions/singleFindAndReplace.ts
Normal file
84
core/tools/definitions/singleFindAndReplace.ts
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export interface SingleFindAndReplaceArgs {
|
||||
filepath: string;
|
||||
old_string: string;
|
||||
new_string: string;
|
||||
replace_all?: boolean;
|
||||
}
|
||||
|
||||
export const singleFindAndReplaceTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Find and Replace",
|
||||
wouldLikeTo: "find and replace in {{{ filepath }}}",
|
||||
isCurrently: "finding and replacing in {{{ filepath }}}",
|
||||
hasAlready: "found and replaced in {{{ filepath }}}",
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
readonly: false,
|
||||
isInstant: false,
|
||||
function: {
|
||||
name: BuiltInToolNames.SingleFindAndReplace,
|
||||
description: `Performs exact string replacements in files.
|
||||
|
||||
Usage:
|
||||
|
||||
- You must use your \`read_file\` tool at least once in the conversation before
|
||||
editing. This tool will error if you attempt an edit without reading the file.
|
||||
|
||||
- When editing text from read_file tool output, ensure you preserve the exact
|
||||
indentation (tabs/spaces) as it appears AFTER the line number prefix. The line
|
||||
number prefix format is: spaces + line number + tab. Everything after that tab
|
||||
is the actual file content to match. Never include any part of the line number
|
||||
prefix in the old_string or new_string.
|
||||
|
||||
- ALWAYS prefer editing existing files in the codebase. NEVER write new files
|
||||
unless explicitly required.
|
||||
|
||||
- Only use emojis if the user explicitly requests it. Avoid adding emojis to
|
||||
files unless asked.
|
||||
|
||||
- The edit will FAIL if \`old_string\` is not unique in the file. Either provide
|
||||
a larger string with more surrounding context to make it unique or use
|
||||
\`replace_all\` to change every instance of \`old_string\`.
|
||||
|
||||
- Use \`replace_all\` for replacing and renaming strings across the file. This
|
||||
parameter is useful if you want to rename a variable for instance.`,
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "old_string", "new_string"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path to the file to modify, relative to the root of the workspace",
|
||||
},
|
||||
old_string: {
|
||||
type: "string",
|
||||
description: "The text to replace",
|
||||
},
|
||||
new_string: {
|
||||
type: "string",
|
||||
description:
|
||||
"The text to replace it with (must be different from old_string)",
|
||||
},
|
||||
replace_all: {
|
||||
type: "boolean",
|
||||
description: "Replace all occurrences of old_string (default false)",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: {
|
||||
prefix: `To perform exact string replacements in files, use the ${BuiltInToolNames.SingleFindAndReplace} tool with a filepath (relative to the root of the workspace) and the strings to find and replace.
|
||||
|
||||
For example, you could respond with:`,
|
||||
exampleArgs: [
|
||||
["filepath", "path/to/file.ts"],
|
||||
["old_string", "const oldVariable = 'value'"],
|
||||
["new_string", "const newVariable = 'updated'"],
|
||||
["replace_all", "false"],
|
||||
],
|
||||
},
|
||||
defaultToolPolicy: "allowedWithPermission",
|
||||
};
|
||||
|
|
@ -8,6 +8,8 @@ describe("Tool Definitions", () => {
|
|||
rules: [],
|
||||
enableExperimentalTools: false,
|
||||
isSignedIn: false,
|
||||
isRemote: false,
|
||||
modelName: "a model",
|
||||
};
|
||||
|
||||
// Helper function to get the actual tool object
|
||||
|
|
|
|||
|
|
@ -27,8 +27,8 @@ export const fetchUrlContentImpl: ToolImpl = async (args, extras) => {
|
|||
// Add truncation warning if needed
|
||||
if (truncatedUrls.length > 0) {
|
||||
processedItems.push({
|
||||
name: "URL content truncation warning",
|
||||
description: "Informs that URL content was truncated",
|
||||
name: "Truncation warning",
|
||||
description: "",
|
||||
content: `The content from ${truncatedUrls.join(", ")} was truncated because it exceeded the ${DEFAULT_FETCH_URL_CHAR_LIMIT} character limit. If you need more content, consider fetching specific sections or using a more targeted approach.`,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ test("fetchUrlContent should truncate content exceeding character limit", async
|
|||
|
||||
expect(result).toHaveLength(2); // Original item + warning
|
||||
expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT);
|
||||
expect(result[1].name).toBe("URL content truncation warning");
|
||||
expect(result[1].name).toBe("Truncation warning");
|
||||
expect(result[1].content).toContain("was truncated");
|
||||
expect(result[1].content).toContain("20000 character limit");
|
||||
});
|
||||
|
|
@ -87,5 +87,5 @@ test("fetchUrlContent should add truncation warning with multiple truncated item
|
|||
expect(result).toHaveLength(3); // Two original items + warning
|
||||
expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT);
|
||||
expect(result[1].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT);
|
||||
expect(result[2].name).toBe("URL content truncation warning");
|
||||
expect(result[2].name).toBe("Truncation warning");
|
||||
});
|
||||
|
|
|
|||
|
|
@ -10,10 +10,20 @@ export const fileGlobSearchImpl: ToolImpl = async (args, extras) => {
|
|||
pattern,
|
||||
MAX_AGENT_GLOB_RESULTS,
|
||||
);
|
||||
|
||||
if (results.length === 0) {
|
||||
return [
|
||||
{
|
||||
name: "File results",
|
||||
description: "glob search",
|
||||
content: "The glob search returned no results.",
|
||||
},
|
||||
];
|
||||
}
|
||||
const contextItems: ContextItem[] = [
|
||||
{
|
||||
name: "File results",
|
||||
description: "Results from file glob search",
|
||||
description: "glob search",
|
||||
content: results.join("\n"),
|
||||
},
|
||||
];
|
||||
|
|
@ -22,7 +32,7 @@ export const fileGlobSearchImpl: ToolImpl = async (args, extras) => {
|
|||
if (results.length === MAX_AGENT_GLOB_RESULTS) {
|
||||
contextItems.push({
|
||||
name: "Truncation warning",
|
||||
description: "Inform the model that results were truncated",
|
||||
description: "",
|
||||
content: `Warning: the results above were truncated to the first ${MAX_AGENT_GLOB_RESULTS} files. If the results are not satisfactory, refine your search pattern`,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,18 +1,15 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { ContextItem } from "../..";
|
||||
import { formatGrepSearchResults } from "../../util/grepSearch";
|
||||
import { prepareQueryForRipgrep } from "../../util/regexValidator";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
|
||||
const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100;
|
||||
const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now
|
||||
const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 7500; // ~1500 tokens, will keep truncation simply for now
|
||||
|
||||
function splitGrepResultsByFile(content: string): ContextItem[] {
|
||||
const matches = [...content.matchAll(/^\.\/([^\n]+)$/gm)];
|
||||
|
||||
if (matches.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const contextItems: ContextItem[] = [];
|
||||
|
||||
for (let i = 0; i < matches.length; i++) {
|
||||
|
|
@ -42,16 +39,48 @@ function splitGrepResultsByFile(content: string): ContextItem[] {
|
|||
}
|
||||
|
||||
export const grepSearchImpl: ToolImpl = async (args, extras) => {
|
||||
const query = getStringArg(args, "query");
|
||||
const rawQuery = getStringArg(args, "query");
|
||||
|
||||
const { query, warning } = prepareQueryForRipgrep(rawQuery);
|
||||
|
||||
let results: string;
|
||||
try {
|
||||
results = await extras.ide.getSearchResults(
|
||||
query,
|
||||
DEFAULT_GREP_SEARCH_RESULTS_LIMIT,
|
||||
);
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
|
||||
// Helpful error for common ripgrep exit code
|
||||
if (errorMessage.includes("Process exited with code 2")) {
|
||||
return [
|
||||
{
|
||||
name: "Search error",
|
||||
description: "The search query could not be processed",
|
||||
content: `The search failed due to an invalid regex pattern.\n\nOriginal query: ${rawQuery}\nProcessed query: ${query}\n\nError: ${errorMessage}\n\nTip: If you're searching for literal text with special characters, the query was automatically escaped. If you need regex patterns, ensure they use proper regex syntax.`,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
const results = await extras.ide.getSearchResults(
|
||||
query,
|
||||
DEFAULT_GREP_SEARCH_RESULTS_LIMIT,
|
||||
);
|
||||
const { formatted, numResults, truncated } = formatGrepSearchResults(
|
||||
results,
|
||||
DEFAULT_GREP_SEARCH_CHAR_LIMIT,
|
||||
);
|
||||
|
||||
if (numResults === 0) {
|
||||
return [
|
||||
{
|
||||
name: "Search results",
|
||||
description: "Results from grep search",
|
||||
content: "The search returned no results.",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const truncationReasons: string[] = [];
|
||||
if (numResults === DEFAULT_GREP_SEARCH_RESULTS_LIMIT) {
|
||||
truncationReasons.push(
|
||||
|
|
@ -64,7 +93,7 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => {
|
|||
);
|
||||
}
|
||||
|
||||
let contextItems: ContextItem[] = [];
|
||||
let contextItems: ContextItem[];
|
||||
|
||||
const splitByFile: boolean = args?.splitByFile || false;
|
||||
if (splitByFile) {
|
||||
|
|
@ -79,10 +108,21 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => {
|
|||
];
|
||||
}
|
||||
|
||||
// Add warnings about query modifications or truncation
|
||||
const warnings: string[] = [];
|
||||
if (warning) {
|
||||
warnings.push(warning);
|
||||
}
|
||||
if (truncationReasons.length > 0) {
|
||||
warnings.push(
|
||||
`Results were truncated because ${truncationReasons.join(" and ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (truncationReasons.length > 0) {
|
||||
contextItems.push({
|
||||
name: "Search truncation warning",
|
||||
description: "Informs the model that search results were truncated",
|
||||
name: "Truncation warning",
|
||||
description: "",
|
||||
content: `The above search results were truncated because ${truncationReasons.join(" and ")}. If the results are not satisfactory, try refining your search query.`,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -53,8 +53,8 @@ export const lsToolImpl: ToolImpl = async (args, extras) => {
|
|||
warningContent += ". Try using a non-recursive search";
|
||||
}
|
||||
contextItems.push({
|
||||
name: "ls truncation warning",
|
||||
description: "Informs the model that ls results were truncated",
|
||||
name: "Truncation warning",
|
||||
description: "",
|
||||
content: warningContent,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,12 +1,14 @@
|
|||
import { getUriDescription } from "../../util/uri";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
import { throwIfFileIsSecurityConcern } from "../../indexing/ignore";
|
||||
import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
|
||||
|
||||
export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => {
|
||||
export const readCurrentlyOpenFileImpl: ToolImpl = async (_, extras) => {
|
||||
const result = await extras.ide.getCurrentFile();
|
||||
|
||||
if (result) {
|
||||
throwIfFileIsSecurityConcern(result.path);
|
||||
await throwIfFileExceedsHalfOfContext(
|
||||
result.path,
|
||||
result.contents,
|
||||
|
|
|
|||
|
|
@ -2,11 +2,13 @@ import { resolveRelativePathInDir } from "../../util/ideUtils";
|
|||
import { getUriPathBasename } from "../../util/uri";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
import { throwIfFileIsSecurityConcern } from "../../indexing/ignore";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
|
||||
|
||||
export const readFileImpl: ToolImpl = async (args, extras) => {
|
||||
const filepath = getStringArg(args, "filepath");
|
||||
throwIfFileIsSecurityConcern(filepath);
|
||||
|
||||
const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide);
|
||||
if (!firstUriMatch) {
|
||||
|
|
|
|||
|
|
@ -29,8 +29,8 @@ export const searchWebImpl: ToolImpl = async (args, extras) => {
|
|||
// Add truncation warning if needed
|
||||
if (truncatedResults.length > 0) {
|
||||
processedResults.push({
|
||||
name: "Web search truncation warning",
|
||||
description: "Informs that search results were truncated",
|
||||
name: "Truncation warning",
|
||||
description: "",
|
||||
content: `The content from the following search results was truncated because it exceeded the ${DEFAULT_WEB_SEARCH_CHAR_LIMIT} character limit: ${truncatedResults.join(", ")}. For more detailed information, consider refining your search query.`,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -62,7 +62,7 @@ test("searchWeb should truncate results exceeding character limit", async () =>
|
|||
expect(result).toHaveLength(3); // Two results + warning
|
||||
expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT);
|
||||
expect(result[1].content).toBe(shortContent);
|
||||
expect(result[2].name).toBe("Web search truncation warning");
|
||||
expect(result[2].name).toBe("Truncation warning");
|
||||
expect(result[2].content).toContain("truncated");
|
||||
expect(result[2].content).toContain("Result 1");
|
||||
expect(result[2].content).not.toContain("Result 2");
|
||||
|
|
@ -100,7 +100,7 @@ test("searchWeb should include all truncated results in the warning", async () =
|
|||
expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT);
|
||||
expect(result[1].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT);
|
||||
expect(result[2].content).toBe(shortContent);
|
||||
expect(result[3].name).toBe("Web search truncation warning");
|
||||
expect(result[3].name).toBe("Truncation warning");
|
||||
expect(result[3].content).toContain("Result 1");
|
||||
expect(result[3].content).toContain("Result 2");
|
||||
expect(result[3].content).not.toContain("Result 3");
|
||||
|
|
|
|||
|
|
@ -29,8 +29,8 @@ export const viewDiffImpl: ToolImpl = async (args, extras) => {
|
|||
|
||||
if (truncated) {
|
||||
contextItems.push({
|
||||
name: "Diff truncation warning",
|
||||
description: "Informs that git diff was truncated",
|
||||
name: "Truncation warning",
|
||||
description: "",
|
||||
content: `The git diff was truncated because it exceeded ${DEFAULT_GIT_DIFF_LINE_LIMIT} lines. Consider viewing specific files or focusing on smaller changes.`,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -58,7 +58,7 @@ test("viewDiff should truncate diffs exceeding line limit", async () => {
|
|||
expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT);
|
||||
|
||||
// Check the warning
|
||||
expect(result[1].name).toBe("Diff truncation warning");
|
||||
expect(result[1].name).toBe("Truncation warning");
|
||||
expect(result[1].content).toContain("truncated");
|
||||
expect(result[1].content).toContain(`${DEFAULT_GIT_DIFF_LINE_LIMIT} lines`);
|
||||
});
|
||||
|
|
@ -83,5 +83,5 @@ test("viewDiff should handle multiple diffs correctly", async () => {
|
|||
expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT);
|
||||
|
||||
// Check the warning
|
||||
expect(result[1].name).toBe("Diff truncation warning");
|
||||
expect(result[1].name).toBe("Truncation warning");
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,12 +1,8 @@
|
|||
import { ConfigDependentToolParams, IDE, Tool } from "..";
|
||||
import { ConfigDependentToolParams, Tool } from "..";
|
||||
import * as toolDefinitions from "./definitions";
|
||||
|
||||
// I'm writing these as functions because we've messed up 3 TIMES by pushing to const, causing duplicate tool definitions on subsequent config loads.
|
||||
|
||||
// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269
|
||||
const getLocalOnlyToolDefinitions = () => [toolDefinitions.grepSearchTool];
|
||||
|
||||
const getBaseToolDefinitions = () => [
|
||||
export const getBaseToolDefinitions = () => [
|
||||
toolDefinitions.readFileTool,
|
||||
toolDefinitions.createNewFileTool,
|
||||
toolDefinitions.runTerminalCommandTool,
|
||||
|
|
@ -16,28 +12,42 @@ const getBaseToolDefinitions = () => [
|
|||
toolDefinitions.lsTool,
|
||||
toolDefinitions.createRuleBlock,
|
||||
toolDefinitions.fetchUrlContentTool,
|
||||
toolDefinitions.singleFindAndReplaceTool,
|
||||
];
|
||||
|
||||
export const getConfigDependentToolDefinitions = (
|
||||
params: ConfigDependentToolParams,
|
||||
): Tool[] => [
|
||||
toolDefinitions.requestRuleTool(params),
|
||||
// Search and replace is now generally available
|
||||
toolDefinitions.searchAndReplaceInFileTool,
|
||||
// Keep edit file tool available for models that need it
|
||||
toolDefinitions.editFileTool,
|
||||
// Web search is only available for signed-in users
|
||||
...(params.isSignedIn ? [toolDefinitions.searchWebTool] : []),
|
||||
...(params.enableExperimentalTools
|
||||
? [
|
||||
toolDefinitions.viewRepoMapTool,
|
||||
toolDefinitions.viewSubdirectoryTool,
|
||||
toolDefinitions.codebaseTool,
|
||||
]
|
||||
: []),
|
||||
];
|
||||
): Tool[] => {
|
||||
const { modelName, isSignedIn, enableExperimentalTools, isRemote } = params;
|
||||
const tools: Tool[] = [];
|
||||
|
||||
export const getToolsForIde = async (ide: IDE): Promise<Tool[]> =>
|
||||
(await ide.isWorkspaceRemote())
|
||||
? getBaseToolDefinitions()
|
||||
: [...getBaseToolDefinitions(), ...getLocalOnlyToolDefinitions()];
|
||||
tools.push(toolDefinitions.requestRuleTool(params));
|
||||
|
||||
if (isSignedIn) {
|
||||
// Web search is only available for signed-in users
|
||||
tools.push(toolDefinitions.searchWebTool);
|
||||
}
|
||||
|
||||
if (enableExperimentalTools) {
|
||||
tools.push(
|
||||
toolDefinitions.viewRepoMapTool,
|
||||
toolDefinitions.viewSubdirectoryTool,
|
||||
toolDefinitions.codebaseTool,
|
||||
);
|
||||
}
|
||||
|
||||
// OLD SEARCH AND REPLACE IS CURRENTLY NOT USED
|
||||
// toolDefinitions.searchAndReplaceInFileTool
|
||||
if (modelName?.includes("claude") || modelName?.includes("gpt-5")) {
|
||||
tools.push(toolDefinitions.multiEditTool);
|
||||
} else {
|
||||
tools.push(toolDefinitions.editFileTool);
|
||||
}
|
||||
|
||||
// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269
|
||||
if (!isRemote) {
|
||||
tools.push(toolDefinitions.grepSearchTool);
|
||||
}
|
||||
|
||||
return tools;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -20,11 +20,11 @@ export function getStringArg(
|
|||
): string {
|
||||
if (!args || !(argName in args) || typeof args[argName] !== "string") {
|
||||
throw new Error(
|
||||
`\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty"}. (type string)`,
|
||||
`\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty or whitespace-only"}. (type string)`,
|
||||
);
|
||||
}
|
||||
if (!allowEmpty && !args[argName].trim()) {
|
||||
throw new Error(`Argument ${argName} must not be empty`);
|
||||
throw new Error(`Argument ${argName} must not be empty or whitespace-only`);
|
||||
}
|
||||
return args[argName];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -102,26 +102,26 @@ describe("getStringArg", () => {
|
|||
it("should throw error when argument is missing", () => {
|
||||
const args = { otherArg: "test" };
|
||||
expect(() => getStringArg(args, "name")).toThrowError(
|
||||
"`name` argument is required and must not be empty. (type string)",
|
||||
"`name` argument is required and must not be empty or whitespace-only. (type string)",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error when argument is not a string", () => {
|
||||
const args = { name: 123 };
|
||||
expect(() => getStringArg(args, "name")).toThrowError(
|
||||
"`name` argument is required and must not be empty. (type string)",
|
||||
"`name` argument is required and must not be empty or whitespace-only. (type string)",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error when argument is empty and empty not allowed", () => {
|
||||
const args = { name: "" };
|
||||
expect(() => getStringArg(args, "name")).toThrowError(
|
||||
"Argument name must not be empty",
|
||||
"Argument name must not be empty or whitespace-only",
|
||||
);
|
||||
|
||||
const argsWithSpace = { name: " " };
|
||||
expect(() => getStringArg(argsWithSpace, "name")).toThrowError(
|
||||
"Argument name must not be empty",
|
||||
"Argument name must not be empty or whitespace-only",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -137,10 +137,10 @@ describe("getStringArg", () => {
|
|||
|
||||
it("should handle null or undefined args", () => {
|
||||
expect(() => getStringArg(null, "name")).toThrowError(
|
||||
"`name` argument is required and must not be empty. (type string)",
|
||||
"`name` argument is required and must not be empty or whitespace-only. (type string)",
|
||||
);
|
||||
expect(() => getStringArg(undefined, "name")).toThrowError(
|
||||
"`name` argument is required and must not be empty. (type string)",
|
||||
"`name` argument is required and must not be empty or whitespace-only. (type string)",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -161,14 +161,14 @@ describe("getOptionalStringArg", () => {
|
|||
it("should throw error when argument is not a string", () => {
|
||||
const args = { name: 123 };
|
||||
expect(() => getOptionalStringArg(args, "name")).toThrowError(
|
||||
"`name` argument is required and must not be empty. (type string)",
|
||||
"`name` argument is required and must not be empty or whitespace-only. (type string)",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error when argument is empty and empty not allowed", () => {
|
||||
const args = { name: "" };
|
||||
expect(() => getOptionalStringArg(args, "name")).toThrowError(
|
||||
"Argument name must not be empty",
|
||||
"Argument name must not be empty or whitespace-only",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { test, expect } from "vitest";
|
||||
import { getConfigDependentToolDefinitions } from "./index";
|
||||
import { expect, test } from "vitest";
|
||||
import { BuiltInToolNames } from "./builtIn";
|
||||
import { getConfigDependentToolDefinitions } from "./index";
|
||||
|
||||
test("searchWeb tool is only available when user is signed in", () => {
|
||||
// Test with signed-in user
|
||||
|
|
@ -8,6 +8,8 @@ test("searchWeb tool is only available when user is signed in", () => {
|
|||
rules: [],
|
||||
enableExperimentalTools: false,
|
||||
isSignedIn: true,
|
||||
isRemote: false,
|
||||
modelName: "",
|
||||
});
|
||||
|
||||
const searchWebToolSignedIn = signedInTools.find(
|
||||
|
|
@ -21,6 +23,8 @@ test("searchWeb tool is only available when user is signed in", () => {
|
|||
rules: [],
|
||||
enableExperimentalTools: false,
|
||||
isSignedIn: false,
|
||||
isRemote: false,
|
||||
modelName: "",
|
||||
});
|
||||
|
||||
const searchWebToolNotSignedIn = notSignedInTools.find(
|
||||
|
|
|
|||
169
core/util/regexValidator.ts
Normal file
169
core/util/regexValidator.ts
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
/**
|
||||
* Validates and sanitizes regex patterns for use with ripgrep
|
||||
*/
|
||||
|
||||
export interface RegexValidationResult {
|
||||
isValid: boolean;
|
||||
sanitizedQuery?: string;
|
||||
error?: string;
|
||||
warning?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a regex pattern and attempts to sanitize common issues
|
||||
* @param query The regex pattern to validate
|
||||
* @returns Validation result with sanitized query if possible
|
||||
*/
|
||||
export function validateAndSanitizeRegex(query: string): RegexValidationResult {
|
||||
// Check for common problematic patterns that often fail with ripgrep
|
||||
const problematicPatterns = [
|
||||
{
|
||||
// Triple-escaped quotes
|
||||
pattern: /\\\\\\/g,
|
||||
issue: "Triple backslash sequences may cause parsing errors",
|
||||
fix: (s: string) => s.replace(/\\\\\\/g, "\\\\"),
|
||||
},
|
||||
{
|
||||
// Unescaped brackets/parentheses that are NOT part of valid regex constructs
|
||||
pattern: /(?<!\\)[\[\]()]/g, // Removed {} from here since they're valid quantifiers
|
||||
issue: "Unescaped brackets or parentheses",
|
||||
fix: null, // Just warn, don't auto-fix as it might be intentional
|
||||
},
|
||||
{
|
||||
// Unescaped braces that are NOT quantifiers (quantifiers are handled separately)
|
||||
pattern: /(?<!\\)\{(?![0-9,}]*\})/g,
|
||||
issue: "Unescaped braces that don't appear to be quantifiers",
|
||||
fix: null,
|
||||
},
|
||||
{
|
||||
// Raw tab/newline characters (not escaped)
|
||||
pattern: /[\t\n\r]/g,
|
||||
issue: "Raw whitespace characters should be escaped",
|
||||
fix: (s: string) =>
|
||||
s.replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r"),
|
||||
},
|
||||
];
|
||||
|
||||
let sanitizedQuery = query;
|
||||
let warnings: string[] = [];
|
||||
|
||||
// Apply fixes for known issues
|
||||
for (const check of problematicPatterns) {
|
||||
if (check.pattern.test(query)) {
|
||||
if (check.fix) {
|
||||
sanitizedQuery = check.fix(sanitizedQuery);
|
||||
warnings.push(`Fixed: ${check.issue}`);
|
||||
} else {
|
||||
warnings.push(`Warning: ${check.issue}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Try to compile as a JavaScript regex to catch basic syntax errors
|
||||
try {
|
||||
new RegExp(sanitizedQuery);
|
||||
} catch (e) {
|
||||
let errorMessage = e instanceof Error ? e.message : "Unknown error";
|
||||
// If it fails as a JS regex, it might still be valid for ripgrep
|
||||
// (ripgrep supports some patterns JS doesn't), but warn the user
|
||||
warnings.push(`Pattern may have syntax issues: ${errorMessage}`);
|
||||
}
|
||||
|
||||
// Check for patterns that are valid regex but might not work as expected with ripgrep
|
||||
const ripgrepSpecificIssues = [
|
||||
{
|
||||
pattern: /\\[0-7]{3}/g,
|
||||
warning: "Octal escape sequences may not work as expected in ripgrep",
|
||||
},
|
||||
{
|
||||
pattern: /\(\?[<!=]/,
|
||||
warning:
|
||||
"Lookahead/lookbehind assertions require ripgrep to be compiled with PCRE2",
|
||||
},
|
||||
];
|
||||
|
||||
for (const issue of ripgrepSpecificIssues) {
|
||||
if (issue.pattern.test(sanitizedQuery)) {
|
||||
warnings.push(issue.warning);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isValid: true,
|
||||
sanitizedQuery,
|
||||
warning: warnings.length > 0 ? warnings.join("; ") : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Escapes a literal string to be used as a regex pattern
|
||||
* @param literal The literal string to escape
|
||||
* @returns Escaped string safe for regex use
|
||||
*/
|
||||
export function escapeLiteralForRegex(literal: string): string {
|
||||
// Escape all regex metacharacters
|
||||
return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
/**
|
||||
* Detects if a query looks like it's meant to be a literal search
|
||||
* rather than a regex pattern
|
||||
* @param query The search query
|
||||
* @returns true if it appears to be a literal search
|
||||
*/
|
||||
export function looksLikeLiteralSearch(query: string): boolean {
|
||||
// If it contains regex metacharacters but they're not escaped,
|
||||
// and it doesn't look like an intentional regex pattern
|
||||
const hasUnescapedMetachars = /[.*+?^${}()|[\]]/g.test(query);
|
||||
const hasEscapedMetachars = /\\[.*+?^${}()|[\]\\]/g.test(query);
|
||||
|
||||
// Check for regex constructs, but be more specific about what we consider regex
|
||||
const hasEscapeSequences = /\\[dws]/g.test(query); // \d, \w, \s
|
||||
const hasQuantifiers = /\{[0-9,]+\}/g.test(query); // {2,4}, {3}
|
||||
|
||||
// Check for bracket patterns and distinguish between character classes and array access
|
||||
const bracketPattern = /\[[^\]]*\]/g;
|
||||
const brackets = query.match(bracketPattern);
|
||||
let hasCharacterClasses = false;
|
||||
|
||||
if (brackets) {
|
||||
hasCharacterClasses = brackets.some((bracket) => {
|
||||
const inside = bracket.slice(1, -1); // Remove [ ]
|
||||
// Character class indicators: ranges (a-z), multiple chars, negation (^)
|
||||
return /-/.test(inside) || inside.length > 1 || inside.startsWith("^");
|
||||
});
|
||||
}
|
||||
|
||||
const hasRegexConstructs =
|
||||
hasEscapeSequences || hasQuantifiers || hasCharacterClasses;
|
||||
|
||||
// Likely a literal search if it has unescaped metachars but no regex constructs
|
||||
return hasUnescapedMetachars && !hasEscapedMetachars && !hasRegexConstructs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares a query for ripgrep by sanitizing problematic patterns
|
||||
* @param query The search query
|
||||
* @returns Object with sanitized query and any warnings
|
||||
*/
|
||||
export function prepareQueryForRipgrep(query: string): {
|
||||
query: string;
|
||||
warning?: string;
|
||||
} {
|
||||
// Check if it looks like a literal search that should be escaped
|
||||
if (looksLikeLiteralSearch(query)) {
|
||||
return {
|
||||
query: escapeLiteralForRegex(query),
|
||||
warning:
|
||||
"Query contained special regex characters and was escaped for literal text search",
|
||||
};
|
||||
}
|
||||
|
||||
// Otherwise validate and sanitize as regex
|
||||
const validation = validateAndSanitizeRegex(query);
|
||||
|
||||
return {
|
||||
query: validation.sanitizedQuery || query,
|
||||
warning: validation.warning,
|
||||
};
|
||||
}
|
||||
310
core/util/regexValidator.vitest.ts
Normal file
310
core/util/regexValidator.vitest.ts
Normal file
|
|
@ -0,0 +1,310 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
escapeLiteralForRegex,
|
||||
looksLikeLiteralSearch,
|
||||
prepareQueryForRipgrep,
|
||||
validateAndSanitizeRegex,
|
||||
} from "./regexValidator";
|
||||
|
||||
describe("validateAndSanitizeRegex", () => {
|
||||
it("should accept valid basic regex patterns", () => {
|
||||
const result = validateAndSanitizeRegex("function\\s+\\w+");
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.sanitizedQuery).toBe("function\\s+\\w+");
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.warning).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should fix triple-escaped sequences", () => {
|
||||
const result = validateAndSanitizeRegex("\\\\\\");
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.sanitizedQuery).toBe("\\\\");
|
||||
expect(result.warning).toContain("Fixed: Triple backslash sequences");
|
||||
});
|
||||
|
||||
it("should fix raw tab characters", () => {
|
||||
const result = validateAndSanitizeRegex("hello\tworld");
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.sanitizedQuery).toBe("hello\\tworld");
|
||||
expect(result.warning).toContain("Fixed: Raw whitespace characters");
|
||||
});
|
||||
|
||||
it("should fix raw newline characters", () => {
|
||||
const result = validateAndSanitizeRegex("line1\nline2");
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.sanitizedQuery).toBe("line1\\nline2");
|
||||
expect(result.warning).toContain("Fixed: Raw whitespace characters");
|
||||
});
|
||||
|
||||
it("should warn about unescaped brackets without fixing", () => {
|
||||
const result = validateAndSanitizeRegex("hello[world]");
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.sanitizedQuery).toBe("hello[world]");
|
||||
expect(result.warning).toContain(
|
||||
"Warning: Unescaped brackets or parentheses",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle multiple issues", () => {
|
||||
const result = validateAndSanitizeRegex("function()\t\\\\\\");
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.sanitizedQuery).toBe("function()\\t\\\\");
|
||||
expect(result.warning).toContain("Fixed: Raw whitespace characters");
|
||||
expect(result.warning).toContain("Fixed: Triple backslash sequences");
|
||||
});
|
||||
|
||||
it("should warn about lookbehind assertions", () => {
|
||||
const result = validateAndSanitizeRegex("(?<=foo)bar");
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.warning).toContain(
|
||||
"Lookahead/lookbehind assertions require ripgrep to be compiled with PCRE2",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("escapeLiteralForRegex", () => {
|
||||
it("should escape basic regex metacharacters", () => {
|
||||
expect(escapeLiteralForRegex("hello.world")).toBe("hello\\.world");
|
||||
expect(escapeLiteralForRegex("test*")).toBe("test\\*");
|
||||
expect(escapeLiteralForRegex("file+")).toBe("file\\+");
|
||||
expect(escapeLiteralForRegex("query?")).toBe("query\\?");
|
||||
});
|
||||
|
||||
it("should escape brackets and braces", () => {
|
||||
expect(escapeLiteralForRegex("array[0]")).toBe("array\\[0\\]");
|
||||
expect(escapeLiteralForRegex("{key}")).toBe("\\{key\\}");
|
||||
expect(escapeLiteralForRegex("func()")).toBe("func\\(\\)");
|
||||
});
|
||||
|
||||
it("should handle multiple metacharacters", () => {
|
||||
expect(escapeLiteralForRegex("$regex.test(input)")).toBe(
|
||||
"\\$regex\\.test\\(input\\)",
|
||||
);
|
||||
});
|
||||
|
||||
it("should not escape normal characters", () => {
|
||||
expect(escapeLiteralForRegex("hello world")).toBe("hello world");
|
||||
});
|
||||
});
|
||||
|
||||
describe("looksLikeLiteralSearch", () => {
|
||||
it("should identify literal searches with unescaped metacharacters", () => {
|
||||
expect(looksLikeLiteralSearch("hello.world")).toBe(true);
|
||||
expect(looksLikeLiteralSearch("test*")).toBe(true);
|
||||
expect(looksLikeLiteralSearch("func()")).toBe(true);
|
||||
expect(looksLikeLiteralSearch("array[0]")).toBe(true);
|
||||
});
|
||||
|
||||
it("should not identify regex patterns as literal", () => {
|
||||
expect(looksLikeLiteralSearch("hello\\.world")).toBe(false);
|
||||
expect(looksLikeLiteralSearch("\\d+")).toBe(false);
|
||||
expect(looksLikeLiteralSearch("[a-z]+")).toBe(false);
|
||||
expect(looksLikeLiteralSearch("a{2,4}")).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle plain text", () => {
|
||||
expect(looksLikeLiteralSearch("hello world")).toBe(false);
|
||||
expect(looksLikeLiteralSearch("simple text")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("prepareQueryForRipgrep", () => {
|
||||
it("should escape literal-looking queries", () => {
|
||||
const result = prepareQueryForRipgrep("hello.world");
|
||||
expect(result.query).toBe("hello\\.world");
|
||||
expect(result.warning).toContain("escaped for literal text search");
|
||||
});
|
||||
|
||||
it("should sanitize regex patterns", () => {
|
||||
const result = prepareQueryForRipgrep("function\t\\\\\\");
|
||||
expect(result.query).toBe("function\\t\\\\");
|
||||
expect(result.warning).toContain("Fixed:");
|
||||
});
|
||||
|
||||
it("should handle plain text without changes", () => {
|
||||
const result = prepareQueryForRipgrep("hello world");
|
||||
expect(result.query).toBe("hello world");
|
||||
expect(result.warning).toBeUndefined();
|
||||
});
|
||||
|
||||
describe("real-world examples", () => {
|
||||
it("should escape file patterns", () => {
|
||||
const result = prepareQueryForRipgrep("*.js");
|
||||
expect(result.query).toBe("\\*\\.js");
|
||||
expect(result.warning).toContain("escaped for literal text search");
|
||||
});
|
||||
|
||||
it("should escape function calls", () => {
|
||||
const result = prepareQueryForRipgrep("console.log()");
|
||||
expect(result.query).toBe("console\\.log\\(\\)");
|
||||
expect(result.warning).toContain("escaped for literal text search");
|
||||
});
|
||||
|
||||
it("should not escape proper regex patterns", () => {
|
||||
const result = prepareQueryForRipgrep("function\\s+\\w+");
|
||||
expect(result.query).toBe("function\\s+\\w+");
|
||||
expect(result.warning).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("problematic patterns that originally failed", () => {
|
||||
it("should handle triple-escaped quotes", () => {
|
||||
const result = prepareQueryForRipgrep('\\\\\\"');
|
||||
expect(result.query).toBe('\\\\"'); // Triple backslash -> double backslash, quote stays
|
||||
expect(result.warning).toContain("Fixed:");
|
||||
});
|
||||
|
||||
it("should handle newline-tab sequences", () => {
|
||||
const result = prepareQueryForRipgrep("\n\t");
|
||||
expect(result.query).toBe("\\n\\t");
|
||||
expect(result.warning).toContain("Fixed:");
|
||||
});
|
||||
|
||||
it("should handle dollar signs in shell patterns", () => {
|
||||
const result = prepareQueryForRipgrep("$(command)");
|
||||
expect(result.query).toBe("\\$\\(command\\)");
|
||||
expect(result.warning).toContain("escaped for literal text search");
|
||||
});
|
||||
|
||||
it("should handle escaped dollar signs", () => {
|
||||
const result = prepareQueryForRipgrep("\\$\\(");
|
||||
expect(result.query).toBe("\\$\\(");
|
||||
expect(result.warning).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("patterns that should NOT be over-sanitized", () => {
|
||||
describe("valid regex patterns that contain suspicious sequences", () => {
|
||||
it("should not escape properly formed character classes", () => {
|
||||
const result = prepareQueryForRipgrep("[a-zA-Z0-9_-]+");
|
||||
expect(result.query).toBe("[a-zA-Z0-9_-]+");
|
||||
expect(result.warning).toContain("Warning: Unescaped brackets"); // Warn but don't break
|
||||
});
|
||||
|
||||
it("should not escape quantifiers in regex patterns", () => {
|
||||
const result = prepareQueryForRipgrep("\\w{2,5}");
|
||||
expect(result.query).toBe("\\w{2,5}");
|
||||
expect(result.warning).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should not escape properly formed lookarounds", () => {
|
||||
const result = prepareQueryForRipgrep("(?<!\\w)test(?!\\w)");
|
||||
expect(result.query).toBe("(?<!\\w)test(?!\\w)");
|
||||
expect(result.warning).toContain("Lookahead/lookbehind assertions"); // Warn about compatibility
|
||||
});
|
||||
|
||||
it("should not break escaped metacharacters in regex", () => {
|
||||
const result = prepareQueryForRipgrep("console\\.log\\(\\)");
|
||||
expect(result.query).toBe("console\\.log\\(\\)");
|
||||
expect(result.warning).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("patterns that look problematic but are intentional", () => {
|
||||
it("should not over-escape already escaped sequences", () => {
|
||||
const result = prepareQueryForRipgrep("\\\\t"); // Already escaped tab
|
||||
expect(result.query).toBe("\\\\t");
|
||||
expect(result.warning).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should not double-escape backslashes in Windows paths", () => {
|
||||
const result = prepareQueryForRipgrep("C:\\\\Users\\\\file");
|
||||
expect(result.query).toBe("C:\\\\Users\\\\file");
|
||||
expect(result.warning).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should not break raw strings that contain regex-like patterns", () => {
|
||||
const result = prepareQueryForRipgrep('"\\d+\\s+\\w+"');
|
||||
expect(result.query).toBe('"\\d+\\s+\\w+"'); // Escaped sequences in quotes should stay
|
||||
expect(result.warning).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should not break JSON with escaped quotes", () => {
|
||||
const result = prepareQueryForRipgrep('"key": "value"');
|
||||
expect(result.query).toBe('"key": "value"');
|
||||
expect(result.warning).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("complex patterns that mix literal and regex", () => {
|
||||
it("should not break URLs with query parameters", () => {
|
||||
const result = prepareQueryForRipgrep(
|
||||
"https://api\\.example\\.com\\?param=\\w+",
|
||||
);
|
||||
expect(result.query).toBe("https://api\\.example\\.com\\?param=\\w+");
|
||||
expect(result.warning).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should not break file paths with regex metacharacters", () => {
|
||||
const result = prepareQueryForRipgrep("/path/to/file\\.[jt]sx?");
|
||||
expect(result.query).toBe("/path/to/file\\.[jt]sx?");
|
||||
expect(result.warning).toContain("Warning: Unescaped brackets"); // Warn but preserve
|
||||
});
|
||||
|
||||
it("should handle mixed escaped and unescaped patterns correctly", () => {
|
||||
// This is a regex that matches function calls with optional whitespace
|
||||
const result = prepareQueryForRipgrep("\\w+\\s*\\(");
|
||||
expect(result.query).toBe("\\w+\\s*\\(");
|
||||
expect(result.warning).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("edge cases that could trigger false positives", () => {
|
||||
it("should not treat mathematical expressions as problematic", () => {
|
||||
const result = prepareQueryForRipgrep("a + b * c");
|
||||
expect(result.query).toBe("a \\+ b \\* c"); // Should be escaped as literal
|
||||
expect(result.warning).toContain("escaped for literal text search");
|
||||
});
|
||||
|
||||
it("should not break regex that uses word boundaries", () => {
|
||||
const result = prepareQueryForRipgrep("\\bclass\\b");
|
||||
expect(result.query).toBe("\\bclass\\b");
|
||||
expect(result.warning).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should not break negated character classes", () => {
|
||||
const result = prepareQueryForRipgrep("[^a-z]+");
|
||||
expect(result.query).toBe("[^a-z]+");
|
||||
expect(result.warning).toContain("Warning: Unescaped brackets"); // Warn but preserve
|
||||
});
|
||||
|
||||
it("should not treat IPv4 addresses as problematic regex", () => {
|
||||
const result = prepareQueryForRipgrep("192.168.1.1");
|
||||
expect(result.query).toBe("192\\.168\\.1\\.1"); // Should be escaped as literal
|
||||
expect(result.warning).toContain("escaped for literal text search");
|
||||
});
|
||||
|
||||
it("should not break hex color codes", () => {
|
||||
const result = prepareQueryForRipgrep("#[0-9a-fA-F]{6}");
|
||||
expect(result.query).toBe("#[0-9a-fA-F]{6}");
|
||||
expect(result.warning).toContain("Warning: Unescaped brackets"); // Warn but preserve regex
|
||||
});
|
||||
});
|
||||
|
||||
describe("patterns that should preserve user intent", () => {
|
||||
it("should not sanitize intentional regex alternation", () => {
|
||||
const result = prepareQueryForRipgrep("(foo|bar)");
|
||||
expect(result.query).toBe("\\(foo\\|bar\\)"); // Should be escaped as literal since unescaped
|
||||
expect(result.warning).toContain("escaped for literal text search");
|
||||
});
|
||||
|
||||
it("should preserve escaped alternation in regex", () => {
|
||||
const result = prepareQueryForRipgrep("\\(foo\\|bar\\)");
|
||||
expect(result.query).toBe("\\(foo\\|bar\\)");
|
||||
expect(result.warning).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should not break SQL LIKE patterns when used as literal search", () => {
|
||||
const result = prepareQueryForRipgrep("name LIKE '%john%'");
|
||||
expect(result.query).toBe("name LIKE '%john%'"); // No regex metacharacters here
|
||||
expect(result.warning).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should not break CSS selectors when used as literal search", () => {
|
||||
const result = prepareQueryForRipgrep(".class-name > div:nth-child(2)");
|
||||
expect(result.query).toBe("\\.class-name > div:nth-child\\(2\\)");
|
||||
expect(result.warning).toContain("escaped for literal text search");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -16,18 +16,18 @@ description: "These blocks form the foundation of the entire assistant experienc
|
|||
|
||||
### Best Models by Role
|
||||
|
||||
| Model role | Best open models | Best closed models | Notes |
|
||||
|:------------|:------------------|:-------------------|:--------|
|
||||
| Agent / Plan | Qwen 3 Coder (480B), Qwen 3 Coder (30B), Devstral (24B), GLM 4.5 (355B), GLM 4.5 Air (106B), Kimi K2 (1T), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed models are slightly better than open models |
|
||||
| Chat / Edit | Qwen 3 Coder (480B), Qwen 3 Coder (30B), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed and open models have pretty similar performance |
|
||||
| Autocomplete | [QwenCoder2.5 (1.5B)](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b), QwenCoder2.5 (7B) | [Codestral](https://hub.continue.dev/mistral/codestral), Mercury Coder | Closed models are slightly better than open models |
|
||||
| Apply | N/A | [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply), [Morph Fast Apply](https://hub.continue.dev/morphllm/morph-v2) | Open models are basically non-existent / not good enough for this model role |
|
||||
| Embed | N/A | [Voyage Code 3](https://hub.continue.dev/voyageai/voyage-code-3), [Morph Embeddings](https://hub.continue.dev/morphllm/morph-embedding-v2), Codestral Embed | Open models are basically non-existent / not good enough for this model role |
|
||||
| Rerank | zerank-1, zerank-1-small | rerank-2.5, Relace Code Rerank, [Morph Rerank](https://hub.continue.dev/morphllm/morph-rerank-v2) | Open models are beginning to emerge for this model role |
|
||||
| Next Edit | Zeta | Mercury Coder | Closed models are significantly better than open models |
|
||||
| Model role | Best open models | Best closed models | Notes |
|
||||
| :----------- | :------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------- |
|
||||
| Agent / Plan | Qwen 3 Coder (480B), Qwen 3 Coder (30B), Devstral (27B), Devstral, GLM 4.5 (355B), GLM 4.5 Air (106B), Kimi K2 (1T), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed models are slightly better than open models |
|
||||
| Chat / Edit | Qwen 3 Coder (480B), Qwen 3 Coder (30B), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed and open models have pretty similar performance |
|
||||
| Autocomplete | [QwenCoder2.5 (1.5B)](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b), QwenCoder2.5 (7B) | [Codestral](https://hub.continue.dev/mistral/codestral), Mercury Coder | Closed models are slightly better than open models |
|
||||
| Apply | N/A | [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply), [Morph Fast Apply](https://hub.continue.dev/morphllm/morph-v2) | Open models are basically non-existent / not good enough for this model role |
|
||||
| Embed | Nomic Embed Text | [Voyage Code 3](https://hub.continue.dev/voyageai/voyage-code-3), [Morph Embeddings](https://hub.continue.dev/morphllm/morph-embedding-v2), Codestral Embed, | Open embeddings models are emerging but closed models still perform better |
|
||||
| Rerank | zerank-1, zerank-1-small | rerank-2.5, Relace Code Rerank, [Morph Rerank](https://hub.continue.dev/morphllm/morph-rerank-v2) | Open models are beginning to emerge for this model role |
|
||||
| Next Edit | Zeta | Mercury Coder | Closed models are significantly better than open models |
|
||||
|
||||
## Learn More About Model Blocks
|
||||
|
||||
Continue supports [many model providers](/customize/model-providers/top-level/openai), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have various roles like `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`.
|
||||
Continue supports [many model providers](/customize/model-providers/top-level/openai), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, and more. Models can have various roles like `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`.
|
||||
|
||||
Read more about roles [here](/customize/model-roles) and view [`models`](/reference#models) in the YAML Reference.
|
||||
|
|
|
|||
|
|
@ -92,7 +92,7 @@ If you use Azure Machine Learning Studio to deploy Codestral:
|
|||
|
||||
## How to Configure Azure AI Foundry Embeddings Models
|
||||
|
||||
We recommend configuring **text-embedding-3-large** as your embeddings model.
|
||||
For recommended embeddings models, please refer to our [Model Recommendations page](/customization/models).
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ We recommend configuring **DeepSeek Chat** as your chat model.
|
|||
|
||||
## How to Set Up DeepSeek Autocomplete Models
|
||||
|
||||
We recommend configuring **DeepSeek Coder** as your autocomplete model.
|
||||
For recommended autocomplete models, please refer to our [Model Recommendations page](/customization/models).
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ Gemini currently does not offer any autocomplete models.
|
|||
|
||||
## How to Configure Gemini Embeddings Models
|
||||
|
||||
We recommend configuring **text-embedding-004** as your embeddings model.
|
||||
For recommended embeddings models, please refer to our [Model Recommendations page](/customization/models).
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
|
|
|
|||
|
|
@ -65,7 +65,7 @@ We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model.
|
|||
|
||||
## How to Set Up Ollama Embeddings Models
|
||||
|
||||
We recommend configuring **Nomic Embed Text** as your embeddings model.
|
||||
For recommended embeddings models, please refer to our [Model Recommendations page](/customization/models).
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
|
|
@ -123,7 +123,7 @@ To configure a remote instance of Ollama, add the `"apiBase"` property to your m
|
|||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## How to Configure Model Capabilities in Ollama
|
||||
|
|
|
|||
|
|
@ -364,6 +364,10 @@
|
|||
"source": "/hub/blocks",
|
||||
"destination": "/hub/blocks/intro"
|
||||
},
|
||||
{
|
||||
"source": "/hub/agents/intro",
|
||||
"destination": "/hub/assistants/intro"
|
||||
},
|
||||
{
|
||||
"source": "/customize",
|
||||
"destination": "/customization/overview"
|
||||
|
|
@ -1099,6 +1103,10 @@
|
|||
{
|
||||
"source": "/customize/model-providers",
|
||||
"destination": "/customize/model-providers/overview"
|
||||
},
|
||||
{
|
||||
"source": "/features/edit/next-edit",
|
||||
"destination": "/features/autocomplete/next-edit"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,22 +27,7 @@ Instead of relying solely on native tool calling APIs (which vary between provid
|
|||
- **Better reliability** - Models that struggle with native tools often perform better with system message tools
|
||||
- **Seamless switching** - Change between providers without modifying your workflow
|
||||
|
||||
### What Models Are Recommended for Agent Mode
|
||||
|
||||
For the best Agent mode experience, we recommend models with strong reasoning and instruction-following capabilities:
|
||||
|
||||
**Premium Models:**
|
||||
|
||||
- **Claude Sonnet 4** (Anthropic) - Our top recommendation for its exceptional tool use and reasoning
|
||||
- **GPT-4** models (OpenAI) - Excellent native tool support
|
||||
- **DeepSeek** models - Strong performance with competitive pricing
|
||||
|
||||
**Local Models:**
|
||||
While more limited in capabilities, these models can work with system message tools:
|
||||
|
||||
- Qwen2.5-Coder 32B - Best local option for Agent mode
|
||||
- Devstral 27B - Good for code-specific tasks
|
||||
- Smaller models (7B-13B) - May struggle with complex tool interactions
|
||||
For recommended Agent models, please refer to our [Model Recommendations page](/customization/models).
|
||||
|
||||
### How to Configure Agent Mode
|
||||
|
||||
|
|
|
|||
|
|
@ -10,49 +10,11 @@ Setting up the right model for autocomplete is crucial for a smooth coding exper
|
|||
For a complete comparison of all autocomplete models, see our [comprehensive model recommendations](/customization/models#recommended-models).
|
||||
</Info>
|
||||
|
||||
## Recommended Models for Autocomplete in Continue
|
||||
|
||||
### Hosted (Best Performance)
|
||||
|
||||
For the highest quality autocomplete suggestions, we recommend **[Codestral](https://hub.continue.dev/mistral/codestral)** from Mistral.
|
||||
|
||||
This model is specifically designed for code completion and offers excellent performance across multiple programming languages.
|
||||
|
||||
**Codestral Quick Setup:**
|
||||
|
||||
1. Get your API key from [Mistral AI](https://console.mistral.ai)
|
||||
2. Add [Codestral](https://hub.continue.dev/mistral/codestral) to your assistant on Continue Hub
|
||||
3. Add `MISTRAL_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
|
||||
### Hosted (Best Speed/Quality Tradeoff)
|
||||
|
||||
For fast, quality autocomplete suggestions, we recommend **[Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small)** from Inception.
|
||||
|
||||
This model is specifically designed for code completion and is particularly fast because it is a diffusion model.
|
||||
|
||||
**Mercury Coder Small Quick Setup:**
|
||||
|
||||
1. Get your API key from [Inception](https://platform.inceptionlabs.ai/)
|
||||
2. Add [Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small) to your assistant on Continue Hub
|
||||
3. Add `INCEPTION_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
|
||||
### Local (Offline / Privacy First)
|
||||
|
||||
For a fully local autocomplete experience, we recommend **[Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b)**.
|
||||
|
||||
This model provides good suggestions while keeping your code completely private.
|
||||
|
||||
**Quick Setup:**
|
||||
|
||||
1. Install [Ollama](https://ollama.ai/)
|
||||
2. Add [Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b) to your assistant on Continue Hub
|
||||
3. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
For model recommendations, please refer to our [Model Recommendations page](/customization/models).
|
||||
|
||||
## Next Edit Model
|
||||
|
||||
For proactive code prediction that anticipates your next edit, Continue supports specialized [Next Edit](/features/edit/next-edit) models:
|
||||
For proactive code prediction that anticipates your next edit, Continue supports specialized [Next Edit](/features/autocomplete/next-edit) models:
|
||||
|
||||
**Supported Next Edit model:**
|
||||
|
||||
|
|
|
|||
|
|
@ -7,16 +7,7 @@ The model you use for for Chat mode will be
|
|||
For a comprehensive comparison of all available models by role, see our [model recommendations table](/customization/models#recommended-models).
|
||||
</Info>
|
||||
|
||||
## What Models Are Recommended for Chat?
|
||||
|
||||
Our strong recommendation is to use [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet) from Anthropic.
|
||||
|
||||
Its strong tool calling and reasoning capabilities make it the best model for Agent mode.
|
||||
|
||||
1. Get your API key from [Anthropic](https://console.anthropic.com/)
|
||||
2. Add [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet) to your assistant on Continue Hub
|
||||
3. Add `ANTHROPIC_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
For model recommendations, please refer to our [Model Recommendations page](/customization/models).
|
||||
|
||||
### What Other Hosted Models Are Available?
|
||||
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ When you start an edit session, Continue:
|
|||
If you accept the diff, we remove the previously highlighted lines, and if you reject the diff, we remove the proposed changes.
|
||||
|
||||
<Info>
|
||||
**Looking for AI that predicts your next edit?** Check out [Next Edit](/features/edit/next-edit), an experimental feature that proactively suggests code changes before you even start typing, going beyond traditional autocomplete to anticipate entire code modifications.
|
||||
**Looking for AI that predicts your next edit?** Check out [Next Edit](/features/autocomplete/next-edit), an experimental feature that proactively suggests code changes before you even start typing, going beyond traditional autocomplete to anticipate entire code modifications.
|
||||
</Info>
|
||||
|
||||
If you would like to view the exact prompt that is sent to the model during an edit, you can [find it in the prompt logs](/troubleshooting#check-the-logs).
|
||||
|
|
|
|||
|
|
@ -16,10 +16,7 @@ The recommended models and how to set them up can be found [here](/features/chat
|
|||
|
||||
We also recommend setting up an Apply model for the best Edit experience.
|
||||
|
||||
**Recommended Apply models:**
|
||||
|
||||
- [Morph v3](https://hub.continue.dev/morphllm/morph-v2)
|
||||
- [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply)
|
||||
For recommended Apply models, please refer to our [Model Recommendations page](/customization/models).
|
||||
|
||||
## How to Determine Model Compatibility
|
||||
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ Before getting started, ensure your system meets these requirements:
|
|||
|
||||
## How to Install Ollama - Step-by-Step
|
||||
|
||||
### Step 1: How to Install Ollama
|
||||
### Step 1: Install Ollama
|
||||
|
||||
Choose the installation method for your operating system:
|
||||
|
||||
|
|
@ -29,7 +29,7 @@ curl -fsSL https://ollama.ai/install.sh | sh
|
|||
# Download from ollama.ai
|
||||
```
|
||||
|
||||
### Step 2: How to Start Ollama
|
||||
### Step 2: Start Ollama Service
|
||||
|
||||
After installation, start the Ollama service:
|
||||
|
||||
|
|
@ -40,12 +40,17 @@ ollama serve
|
|||
# Verify it's running
|
||||
curl http://localhost:11434
|
||||
# Should return "Ollama is running"
|
||||
|
||||
# Check Ollama version
|
||||
ollama --version
|
||||
```
|
||||
|
||||
### Step 3: How to Download Models
|
||||
### Step 3: Download Models
|
||||
|
||||
<Warning>
|
||||
**Important**: Always use `ollama pull` instead of `ollama run` to download models. The `run` command starts an interactive session which isn't needed for Continue.
|
||||
**Important**: Always use `ollama pull` instead of `ollama run` to download
|
||||
models. The `run` command starts an interactive session which isn't needed for
|
||||
Continue.
|
||||
</Warning>
|
||||
|
||||
Download models using the exact tag specified:
|
||||
|
|
@ -62,12 +67,15 @@ ollama list
|
|||
```
|
||||
|
||||
**Common Model Tags:**
|
||||
|
||||
- `:latest` - Default version (used if no tag specified)
|
||||
- `:32b`, `:7b`, `:1.5b` - Parameter count versions
|
||||
- `:instruct`, `:base` - Model variants
|
||||
|
||||
<Note>
|
||||
If a model page shows `deepseek-r1:32b` on Ollama's website, you must pull it with that exact tag. Using just `deepseek-r1` will pull `:latest` which may be a different size.
|
||||
If a model page shows `deepseek-r1:32b` on Ollama's website, you must pull it
|
||||
with that exact tag. Using just `deepseek-r1` will pull `:latest` which may be
|
||||
a different size.
|
||||
</Note>
|
||||
|
||||
## How to Configure Ollama with Continue
|
||||
|
|
@ -76,10 +84,9 @@ There are multiple ways to configure Ollama models in Continue:
|
|||
|
||||
### Method 1: Using Hub Model Blocks in Local config.yaml
|
||||
|
||||
The easiest way is to use pre-configured model blocks from the Continue Hub in your local configuration:
|
||||
The easiest way is to use [pre-configured model blocks](/reference#local-blocks) from the Continue Hub in your local configuration:
|
||||
|
||||
```yaml
|
||||
# ~/.continue/assistants/My Local Assistant.yaml
|
||||
```yaml title="~/.continue/assistants/My Local Assistant.yaml"
|
||||
name: My Local Assistant
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
|
|
@ -90,20 +97,20 @@ models:
|
|||
```
|
||||
|
||||
<Warning>
|
||||
**Important**: Hub blocks only provide configuration - you still need to pull the model locally. The hub block `ollama/deepseek-r1-32b` configures Continue to use `model: deepseek-r1:32b`, but the actual model must be installed:
|
||||
```bash
|
||||
# Check what the hub block expects (view on hub.continue.dev)
|
||||
# Then pull that exact model tag locally
|
||||
ollama pull deepseek-r1:32b # Required for ollama/deepseek-r1-32b hub block
|
||||
```
|
||||
If the model isn't installed, Ollama will return: `404 model "deepseek-r1:32b" not found, try pulling it first`
|
||||
**Important**: Hub blocks only provide configuration - you still need to pull
|
||||
the model locally. The hub block `ollama/deepseek-r1-32b` configures Continue
|
||||
to use `model: deepseek-r1:32b`, but the actual model must be installed:
|
||||
```bash # Check what the hub block expects (view on hub.continue.dev) # Then
|
||||
pull that exact model tag locally ollama pull deepseek-r1:32b # Required for
|
||||
ollama/deepseek-r1-32b hub block ``` If the model isn't installed, Ollama will
|
||||
return: `404 model "deepseek-r1:32b" not found, try pulling it first`
|
||||
</Warning>
|
||||
|
||||
### Method 2: Using Autodetect
|
||||
|
||||
Continue can automatically detect available Ollama models. You can configure this in your YAML:
|
||||
|
||||
```yaml
|
||||
```yaml title="~/.continue/config.yaml"
|
||||
models:
|
||||
- name: Autodetect
|
||||
provider: ollama
|
||||
|
|
@ -112,6 +119,8 @@ models:
|
|||
- chat
|
||||
- edit
|
||||
- apply
|
||||
- rerank
|
||||
- autocomplete
|
||||
```
|
||||
|
||||
Or use it through the GUI:
|
||||
|
|
@ -122,7 +131,12 @@ Or use it through the GUI:
|
|||
4. Select your desired model from the detected list
|
||||
|
||||
<Note>
|
||||
The Autodetect feature scans your local Ollama installation and lists all available models. When set to `AUTODETECT`, Continue will dynamically populate the model list based on what's installed locally via `ollama list`. This is useful for quickly switching between models without manual configuration.
|
||||
The Autodetect feature scans your local Ollama installation and lists all
|
||||
available models. When set to `AUTODETECT`, Continue will dynamically populate
|
||||
the model list based on what's installed locally via `ollama list`. This is
|
||||
useful for quickly switching between models without manual configuration. For
|
||||
any roles not covered by the detected models, you may need to manually
|
||||
configure them.
|
||||
</Note>
|
||||
|
||||
You can update `apiBase` with the IP address of a remote machine serving Ollama.
|
||||
|
|
@ -135,12 +149,12 @@ For custom configurations or models not on the hub:
|
|||
models:
|
||||
- name: DeepSeek R1 32B
|
||||
provider: ollama
|
||||
model: deepseek-r1:32b # Must match exactly what `ollama list` shows
|
||||
model: deepseek-r1:32b # Must match exactly what `ollama list` shows
|
||||
apiBase: http://localhost:11434
|
||||
roles:
|
||||
- chat
|
||||
- edit
|
||||
capabilities: # Add if not auto-detected
|
||||
capabilities: # Add if not auto-detected
|
||||
- tool_use
|
||||
- name: Qwen2.5-Coder 1.5B
|
||||
provider: ollama
|
||||
|
|
@ -161,14 +175,16 @@ models:
|
|||
provider: ollama
|
||||
model: deepseek-r1:latest
|
||||
capabilities:
|
||||
- tool_use # Add this to enable tools
|
||||
- tool_use # Add this to enable tools
|
||||
```
|
||||
|
||||
<Warning>
|
||||
**Known Issue**: Some models like DeepSeek R1 may show "Agent mode is not supported" or "does not support tools" even with capabilities configured. This is a known limitation where the model's actual tool support differs from its advertised capabilities.
|
||||
**Known Issue**: Some models like DeepSeek R1 may show "Agent mode is not
|
||||
supported" or "does not support tools" even with capabilities configured. This
|
||||
is a known limitation where the model's actual tool support differs from its
|
||||
advertised capabilities.
|
||||
</Warning>
|
||||
|
||||
|
||||
#### If Agent Mode Shows "Not Supported"
|
||||
|
||||
1. First, add `capabilities: [tool_use]` to your model config
|
||||
|
|
@ -181,29 +197,70 @@ See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for
|
|||
|
||||
For optimal performance, consider these advanced configuration options:
|
||||
|
||||
- Memory optimization: Adjust `num_ctx` for context window size
|
||||
- GPU acceleration: Use `num_gpu` to control GPU layers
|
||||
- Custom model parameters: Temperature, top_p, top_k settings
|
||||
- Performance tuning: Batch size and threading options
|
||||
```yaml
|
||||
models:
|
||||
- name: Optimized DeepSeek
|
||||
provider: ollama
|
||||
model: deepseek-r1:32b
|
||||
contextLength: 8192 # Adjust context window (default varies by model)
|
||||
completionOptions:
|
||||
temperature: 0.7 # Controls randomness (0.0-1.0)
|
||||
top_p: 0.9 # Nucleus sampling threshold
|
||||
top_k: 40 # Top-k sampling
|
||||
num_predict: 2048 # Max tokens to generate
|
||||
# Ollama-specific options (set via environment or modelfile)
|
||||
# num_gpu: 35 # Number of GPU layers to offload
|
||||
# num_thread: 8 # CPU threads to use
|
||||
```
|
||||
|
||||
For GPU acceleration and memory tuning, create an Ollama Modelfile:
|
||||
|
||||
```
|
||||
# Create custom model with optimizations
|
||||
FROM deepseek-r1:32b
|
||||
PARAMETER num_gpu 35
|
||||
PARAMETER num_thread 8
|
||||
PARAMETER num_ctx 4096
|
||||
```
|
||||
|
||||
## What Are the Best Practices for Ollama
|
||||
|
||||
### How to Choose the Right Model
|
||||
|
||||
Choose models based on your specific needs:
|
||||
Choose models based on your specific needs (see [recommended models](/customization/models#recommended-models) for more options):
|
||||
|
||||
1. **Code Generation**: Use CodeLlama or Mistral
|
||||
2. **Chat**: Llama2 or Mistral
|
||||
3. **Specialized Tasks**: Domain-specific models
|
||||
1. **Code Generation**:
|
||||
|
||||
- `qwen2.5-coder:7b` - Excellent for code completion
|
||||
- `codellama:13b` - Strong general coding support
|
||||
- `deepseek-coder:6.7b` - Fast and efficient
|
||||
|
||||
2. **Chat & Reasoning**:
|
||||
|
||||
- `llama3.1:8b` - Latest Llama with tool support
|
||||
- `mistral:7b` - Fast and versatile
|
||||
- `deepseek-r1:32b` - Advanced reasoning capabilities
|
||||
|
||||
3. **Autocomplete**:
|
||||
|
||||
- `qwen2.5-coder:1.5b` - Lightweight and fast
|
||||
- `starcoder2:3b` - Optimized for code completion
|
||||
|
||||
4. **Memory Requirements**:
|
||||
- 1.5B-3B models: ~4GB RAM
|
||||
- 7B models: ~8GB RAM
|
||||
- 13B models: ~16GB RAM
|
||||
- 32B models: ~32GB RAM
|
||||
|
||||
### How to Optimize Performance
|
||||
|
||||
To get the best performance from Ollama:
|
||||
|
||||
- Monitor system resources
|
||||
- Adjust context window size
|
||||
- Use appropriate model sizes
|
||||
- Enable GPU acceleration when available
|
||||
- Monitor system resources with `ollama ps` to see memory usage
|
||||
- Adjust context window size based on available RAM
|
||||
- Use appropriate model sizes for your hardware
|
||||
- Enable GPU acceleration when available (NVIDIA CUDA or AMD ROCm)
|
||||
- Use `ollama logs` to debug performance issues
|
||||
|
||||
## How to Troubleshoot Ollama Issues
|
||||
|
||||
|
|
@ -214,7 +271,8 @@ To get the best performance from Ollama:
|
|||
This error occurs when the model isn't installed locally:
|
||||
|
||||
**Problem**: Using a hub block or config that references a model not yet pulled
|
||||
**Solution**:
|
||||
**Solution**:
|
||||
|
||||
```bash
|
||||
# Check what models you have
|
||||
ollama list
|
||||
|
|
@ -227,6 +285,7 @@ ollama pull model-name:tag # e.g., deepseek-r1:32b
|
|||
|
||||
**Problem**: `ollama pull deepseek-r1` installs `:latest` but hub block expects `:32b`
|
||||
**Solution**: Always pull with the exact tag:
|
||||
|
||||
```bash
|
||||
# Wrong - pulls :latest
|
||||
ollama pull deepseek-r1
|
||||
|
|
@ -239,6 +298,7 @@ ollama pull deepseek-r1:32b
|
|||
|
||||
**Problem**: Model doesn't support tools/function calling
|
||||
**Solutions**:
|
||||
|
||||
1. Add `capabilities: [tool_use]` to your model config
|
||||
2. If still not working, the model may not actually support tools
|
||||
3. Switch to a model with confirmed tool support (Llama 3.1, Mistral)
|
||||
|
|
@ -247,6 +307,7 @@ ollama pull deepseek-r1:32b
|
|||
|
||||
**Problem**: Unclear how to use hub models locally
|
||||
**Solution**: Create a local assistant file:
|
||||
|
||||
```yaml
|
||||
# ~/.continue/assistants/Local.yaml
|
||||
name: Local Assistant
|
||||
|
|
@ -269,13 +330,29 @@ models:
|
|||
- Model too large: Check available memory with `ollama ps`
|
||||
- GPU issues: Verify CUDA/ROCm installation for GPU acceleration
|
||||
- Slow generation: Adjust `num_gpu` layers in model configuration
|
||||
- Check system diagnostics: `ollama ps` for active models and memory usage
|
||||
|
||||
## What Are Example Workflows with Ollama
|
||||
|
||||
### How to Use Ollama for Code Generation
|
||||
|
||||
```
|
||||
# Example: Generate a FastAPI endpointdef create_user_endpoint(): # Continue will help generate the implementation pass
|
||||
```python
|
||||
# Example: Generate a FastAPI endpoint
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
class User(BaseModel):
|
||||
name: str
|
||||
email: str
|
||||
age: int
|
||||
|
||||
@app.post("/users/")
|
||||
async def create_user(user: User):
|
||||
# Continue will help complete this implementation
|
||||
# Use Cmd+I (Mac) or Ctrl+I (Windows/Linux) to generate code
|
||||
pass
|
||||
```
|
||||
|
||||
### How to Use Ollama for Code Review
|
||||
|
|
@ -293,4 +370,4 @@ Ollama with Continue provides a powerful local development environment for AI-as
|
|||
|
||||
---
|
||||
|
||||
_This guide is based on Ollama v0.1.x and Continue v0.8.x. Please check for updates regularly._
|
||||
_This guide is based on Ollama v0.11.x and Continue v1.1.x. Please check for updates regularly._
|
||||
|
|
|
|||
74
extensions/cli/BUILD.md
Normal file
74
extensions/cli/BUILD.md
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
# Build Process Documentation
|
||||
|
||||
## Overview
|
||||
|
||||
The Continue CLI uses esbuild to bundle the application along with local packages (`@continuedev/config-yaml` and `@continuedev/openai-adapters`) into a single distributable file. This ensures that users who install the CLI from npm don't need to worry about local file references.
|
||||
|
||||
## Build Steps
|
||||
|
||||
1. **Install dependencies**: `npm install`
|
||||
2. **Build**: `npm run build`
|
||||
- This first builds the local packages
|
||||
- Then bundles everything with esbuild
|
||||
|
||||
## How it Works
|
||||
|
||||
### Bundling Strategy
|
||||
|
||||
The `build.mjs` script uses esbuild to:
|
||||
|
||||
- Bundle all TypeScript/JavaScript code into a single ES module
|
||||
- Include local packages (`@continuedev/config-yaml`, `@continuedev/openai-adapters`) directly in the bundle
|
||||
- Keep problematic or native dependencies external (e.g., `@sentry/profiling-node`, `winston`, `express`)
|
||||
- Create a wrapper script (`dist/cn.js`) with the proper shebang for CLI execution
|
||||
|
||||
### Key Features
|
||||
|
||||
- **Local Package Bundling**: Local packages are bundled directly, avoiding `file:` reference issues
|
||||
- **Stub for Optional Dependencies**: `react-devtools-core` is stubbed to prevent runtime errors
|
||||
- **CommonJS Compatibility**: Adds `createRequire` to support packages that use dynamic requires
|
||||
- **Source Maps**: Generates source maps for debugging
|
||||
- **Metadata**: Creates `dist/meta.json` with bundle analysis information
|
||||
|
||||
## Testing
|
||||
|
||||
### Smoke Tests
|
||||
|
||||
Run smoke tests to verify the build:
|
||||
|
||||
```bash
|
||||
npm run test:smoke
|
||||
```
|
||||
|
||||
The smoke tests verify:
|
||||
|
||||
- Bundle files exist
|
||||
- CLI commands work (--version, --help)
|
||||
- Bundle size is reasonable (<20MB)
|
||||
- Local packages are properly bundled
|
||||
- No missing runtime dependencies
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **Module not found errors**: Check if the module needs to be added to the external list in `build.mjs`
|
||||
2. **Native module issues**: Native modules should be marked as external
|
||||
3. **Bundle too large**: Review bundled packages in `dist/meta.json` and consider marking large packages as external
|
||||
|
||||
### Analyzing the Bundle
|
||||
|
||||
After building, check `dist/meta.json` to see:
|
||||
|
||||
- What packages were bundled
|
||||
- Bundle size breakdown
|
||||
- Input/output file mappings
|
||||
|
||||
## Publishing
|
||||
|
||||
When publishing to npm:
|
||||
|
||||
1. The bundled files in `dist/` are included
|
||||
2. Users install via `npm install -g @continuedev/cli`
|
||||
3. The `cn` command becomes available globally
|
||||
4. No local file references or missing dependencies
|
||||
97
extensions/cli/build.mjs
Normal file
97
extensions/cli/build.mjs
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
import * as esbuild from "esbuild";
|
||||
import { chmodSync, writeFileSync } from "fs";
|
||||
import { dirname, resolve } from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
// List of packages to mark as external (ONLY native modules that cannot be bundled)
|
||||
// Note: Everything else will be bundled to create a self-contained CLI
|
||||
// Users should not need to install any additional dependencies
|
||||
const external = [
|
||||
"@sentry/profiling-node", // Contains native profiler bindings (optional)
|
||||
"fsevents", // macOS native file watcher (optional dependency)
|
||||
];
|
||||
|
||||
console.log("Building CLI with esbuild...");
|
||||
|
||||
// Plugin to handle optional react-devtools-core
|
||||
const optionalDevtoolsPlugin = {
|
||||
name: "optional-devtools",
|
||||
setup(build) {
|
||||
build.onResolve({ filter: /^react-devtools-core$/ }, () => {
|
||||
// Return path to our stub instead of marking as external
|
||||
return { path: resolve(__dirname, "stubs/react-devtools-core.js") };
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
const result = await esbuild.build({
|
||||
entryPoints: ["src/index.ts"],
|
||||
bundle: true,
|
||||
platform: "node",
|
||||
target: "node18",
|
||||
format: "esm",
|
||||
outfile: "dist/index.js",
|
||||
external,
|
||||
sourcemap: true,
|
||||
minify: true, // Minify for smaller bundle size
|
||||
metafile: true,
|
||||
plugins: [optionalDevtoolsPlugin],
|
||||
|
||||
// Handle .js extensions in imports
|
||||
resolveExtensions: [".ts", ".tsx", ".js", ".jsx", ".json"],
|
||||
|
||||
// Handle TypeScript paths and local packages
|
||||
alias: {
|
||||
"@continuedev/config-yaml": resolve(
|
||||
__dirname,
|
||||
"../../packages/config-yaml/dist/index.js",
|
||||
),
|
||||
"@continuedev/openai-adapters": resolve(
|
||||
__dirname,
|
||||
"../../packages/openai-adapters/dist/index.js",
|
||||
),
|
||||
"@continuedev/config-types": resolve(
|
||||
__dirname,
|
||||
"../../packages/config-types/dist/index.js",
|
||||
),
|
||||
core: resolve(__dirname, "../../core"),
|
||||
"@continuedev/fetch": resolve(
|
||||
__dirname,
|
||||
"../../packages/fetch/dist/index.js",
|
||||
),
|
||||
"@continuedev/llm-info": resolve(
|
||||
__dirname,
|
||||
"../../packages/llm-info/dist/index.js",
|
||||
),
|
||||
},
|
||||
|
||||
// Add banner to create require for CommonJS packages
|
||||
banner: {
|
||||
js: `import { createRequire } from 'module';
|
||||
const require = createRequire(import.meta.url);`,
|
||||
},
|
||||
});
|
||||
|
||||
// Write metafile for analysis
|
||||
writeFileSync("dist/meta.json", JSON.stringify(result.metafile, null, 2));
|
||||
|
||||
// Create wrapper script with shebang
|
||||
writeFileSync("dist/cn.js", "#!/usr/bin/env node\nimport('./index.js');");
|
||||
|
||||
// Make the wrapper script executable
|
||||
chmodSync("dist/cn.js", 0o755);
|
||||
|
||||
// Calculate bundle size
|
||||
const bundleSize = result.metafile.outputs["dist/index.js"].bytes;
|
||||
console.log(
|
||||
`✓ Build complete! Bundle size: ${(bundleSize / 1024 / 1024).toFixed(2)} MB`,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Build failed:", error);
|
||||
process.exit(1);
|
||||
}
|
||||
5232
extensions/cli/package-lock.json
generated
5232
extensions/cli/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -6,15 +6,20 @@
|
|||
"types": "dist/index.d.ts",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"cn": "dist/index.js"
|
||||
"cn": "dist/cn.js"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest watch",
|
||||
"test:ui": "vitest --ui",
|
||||
"test:e2e": "vitest run --config vitest.e2e.config.ts",
|
||||
"build": "tsc -p tsconfig.build.json",
|
||||
"start": "node dist/index.js",
|
||||
"test:smoke": "node smoke-test.mjs",
|
||||
"build:tsc": "tsc -p tsconfig.build.json",
|
||||
"build:local-deps": "cd ../../packages/config-types && npm i && npm run build && cd ../fetch && npm i && npm run build && cd ../llm-info && npm i && npm run build && cd ../config-yaml && npm i && npm run build && cd ../openai-adapters && npm i && npm run build && cd ../../core && npm i && cd ../extensions/cli && npm i",
|
||||
"build:validate": "node validate-aliases.mjs",
|
||||
"build:bundle": "node build.mjs",
|
||||
"build": "npm run build:validate && npm run build:bundle",
|
||||
"start": "node dist/cn.js",
|
||||
"dev": "tsx src/index.ts",
|
||||
"repomix:sdk": "npx repomix node_modules/@continuedev/sdk --ignore **/api,cli-repomix.xml -o sdk-repomix.xml",
|
||||
"repomix:cli": "npx repomix --ignore sdk-repomix.xml -o cli-repomix.xml",
|
||||
|
|
@ -39,8 +44,11 @@
|
|||
},
|
||||
"homepage": "https://continue.dev",
|
||||
"dependencies": {
|
||||
"@continuedev/config-yaml": "^1.0.96",
|
||||
"@continuedev/openai-adapters": "^1.4.1",
|
||||
"@sentry/profiling-node": "^9.43.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@continuedev/config-yaml": "file:../../packages/config-yaml",
|
||||
"@continuedev/openai-adapters": "file:../../packages/openai-adapters",
|
||||
"@continuedev/sdk": "^0.0.13",
|
||||
"@modelcontextprotocol/sdk": "^1.17.2",
|
||||
"@opentelemetry/api": "^1.9.0",
|
||||
|
|
@ -52,13 +60,13 @@
|
|||
"@opentelemetry/sdk-node": "^0.203.0",
|
||||
"@opentelemetry/semantic-conventions": "^1.36.0",
|
||||
"@sentry/node": "^9.43.0",
|
||||
"@sentry/profiling-node": "^9.43.0",
|
||||
"@types/express": "^5.0.3",
|
||||
"@types/react": "^19.1.8",
|
||||
"@types/turndown": "^5.0.5",
|
||||
"@workos-inc/node": "^7.45.0",
|
||||
"chalk": "^5.4.1",
|
||||
"commander": "^14.0.0",
|
||||
"core": "file:../../core",
|
||||
"date-fns": "^4.1.0",
|
||||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.5.0",
|
||||
|
|
@ -66,6 +74,7 @@
|
|||
"glob": "^11.0.3",
|
||||
"gpt-tokenizer": "^3.0.1",
|
||||
"gradient-string": "^3.0.0",
|
||||
"ignore": "^7.0.5",
|
||||
"ignore-walk": "^7.0.0",
|
||||
"ink": "^6.1.0",
|
||||
"jszip": "^3.10.1",
|
||||
|
|
@ -83,9 +92,7 @@
|
|||
"typescript": "^5.8.3",
|
||||
"uuid": "^9.0.1",
|
||||
"winston": "^3.17.0",
|
||||
"yaml": "^2.8.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"yaml": "^2.8.0",
|
||||
"@semantic-release/changelog": "^6.0.3",
|
||||
"@semantic-release/git": "^10.0.1",
|
||||
"@semantic-release/github": "^11.0.3",
|
||||
|
|
@ -93,7 +100,6 @@
|
|||
"@testing-library/react": "^16.3.0",
|
||||
"@types/date-fns": "^2.5.3",
|
||||
"@types/diff": "^7.0.2",
|
||||
"@types/express": "^5.0.3",
|
||||
"@types/glob": "^8.1.0",
|
||||
"@types/ignore-walk": "^4.0.3",
|
||||
"@types/ink-testing-library": "^1.0.4",
|
||||
|
|
@ -102,17 +108,18 @@
|
|||
"@types/readline-sync": "^1.4.8",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"@types/supertest": "^6.0.3",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"@typescript-eslint/eslint-plugin": "^8.39.0",
|
||||
"@typescript-eslint/parser": "^8.39.0",
|
||||
"@vitest/ui": "^3.2.4",
|
||||
"conventional-changelog-conventionalcommits": "^9.1.0",
|
||||
"cross-env": "^7.0.3",
|
||||
"esbuild": "^0.25.9",
|
||||
"eslint": "^9.32.0",
|
||||
"eslint-import-resolver-typescript": "^4.4.4",
|
||||
"eslint-plugin-import": "^2.32.0",
|
||||
"eslint-plugin-unused-imports": "^4.1.4",
|
||||
"execa": "^9.6.0",
|
||||
"express": "^5.1.0",
|
||||
"happy-dom": "^18.0.1",
|
||||
"ink-testing-library": "^4.0.0",
|
||||
"jsdom": "^26.1.0",
|
||||
|
|
|
|||
230
extensions/cli/smoke-test.mjs
Executable file
230
extensions/cli/smoke-test.mjs
Executable file
|
|
@ -0,0 +1,230 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
import { execSync } from "child_process";
|
||||
import { existsSync, readFileSync } from "fs";
|
||||
import { resolve, dirname } from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
// Colors for output
|
||||
const colors = {
|
||||
green: "\x1b[32m",
|
||||
red: "\x1b[31m",
|
||||
yellow: "\x1b[33m",
|
||||
reset: "\x1b[0m",
|
||||
};
|
||||
|
||||
let testsPassed = 0;
|
||||
let testsFailed = 0;
|
||||
|
||||
function runTest(name, testFn) {
|
||||
process.stdout.write(`Testing ${name}... `);
|
||||
try {
|
||||
testFn();
|
||||
console.log(`${colors.green}✓${colors.reset}`);
|
||||
testsPassed++;
|
||||
} catch (error) {
|
||||
console.log(`${colors.red}✗${colors.reset}`);
|
||||
console.error(` Error: ${error.message}`);
|
||||
testsFailed++;
|
||||
}
|
||||
}
|
||||
|
||||
function execCommand(command, options = {}) {
|
||||
return execSync(command, {
|
||||
cwd: __dirname,
|
||||
encoding: "utf8",
|
||||
stdio: "pipe",
|
||||
...options,
|
||||
});
|
||||
}
|
||||
|
||||
console.log("🧪 Running smoke tests for bundled CLI...\n");
|
||||
|
||||
// Test 1: Check if bundle exists
|
||||
runTest("Bundle file exists", () => {
|
||||
if (!existsSync(resolve(__dirname, "dist/index.js"))) {
|
||||
throw new Error("dist/index.js not found");
|
||||
}
|
||||
if (!existsSync(resolve(__dirname, "dist/cn.js"))) {
|
||||
throw new Error("dist/cn.js not found");
|
||||
}
|
||||
});
|
||||
|
||||
// Test 2: Check if wrapper script is executable
|
||||
runTest("Wrapper script has shebang", () => {
|
||||
const content = readFileSync(resolve(__dirname, "dist/cn.js"), "utf8");
|
||||
if (!content.startsWith("#!/usr/bin/env node")) {
|
||||
throw new Error("Wrapper script missing shebang");
|
||||
}
|
||||
});
|
||||
|
||||
// Cross-platform command execution helper
|
||||
function getCLICommand(args = "") {
|
||||
const isWindows = process.platform === "win32";
|
||||
if (isWindows) {
|
||||
return `node dist/cn.js ${args}`;
|
||||
} else {
|
||||
return `./dist/cn.js ${args}`;
|
||||
}
|
||||
}
|
||||
|
||||
// Test 3: Version command works
|
||||
runTest("Version command", () => {
|
||||
const output = execCommand(getCLICommand("--version"));
|
||||
const packageJson = JSON.parse(
|
||||
readFileSync(resolve(__dirname, "package.json"), "utf8"),
|
||||
);
|
||||
if (!output.includes(packageJson.version)) {
|
||||
throw new Error(
|
||||
`Version mismatch. Expected ${packageJson.version}, got: ${output}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Test 4: Help command works
|
||||
runTest("Help command", () => {
|
||||
const output = execCommand(getCLICommand("--help"));
|
||||
if (!output.includes("Continue CLI") || !output.includes("--version")) {
|
||||
throw new Error("Help output missing expected content");
|
||||
}
|
||||
});
|
||||
|
||||
// Test 5: Check bundle size
|
||||
runTest("Bundle size is reasonable", () => {
|
||||
const isWindows = process.platform === "win32";
|
||||
const command = isWindows
|
||||
? `powershell -Command "(Get-Item dist/index.js).length / 1MB"`
|
||||
: `ls -lh dist/index.js`;
|
||||
|
||||
let sizeInMB;
|
||||
|
||||
if (isWindows) {
|
||||
try {
|
||||
const output = execCommand(command);
|
||||
sizeInMB = parseFloat(output.trim());
|
||||
} catch {
|
||||
// Fallback for Windows if PowerShell fails
|
||||
const stats = readFileSync(resolve(__dirname, "dist/index.js"));
|
||||
sizeInMB = stats.length / (1024 * 1024);
|
||||
}
|
||||
} else {
|
||||
const stats = execCommand(command);
|
||||
const sizeMatch = stats.match(/(\d+(?:\.\d+)?[MK])/);
|
||||
if (sizeMatch) {
|
||||
const size = sizeMatch[1];
|
||||
const numSize = parseFloat(size);
|
||||
const unit = size.slice(-1);
|
||||
sizeInMB = unit === "M" ? numSize : numSize / 1024;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`(${sizeInMB.toFixed(1)}M)`);
|
||||
|
||||
// This is arbitrary. We might go over at some point,
|
||||
// in which case you can just increase this.
|
||||
if (sizeInMB > 20) {
|
||||
throw new Error(`Bundle too large: ${sizeInMB.toFixed(1)}M`);
|
||||
}
|
||||
});
|
||||
|
||||
// Test 6: Check that local packages are bundled
|
||||
runTest("Local packages are bundled", () => {
|
||||
const bundleContent = readFileSync(
|
||||
resolve(__dirname, "dist/index.js"),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
// Check for code from @continuedev/config-yaml
|
||||
if (
|
||||
!bundleContent.includes("AssistantUnrolled") &&
|
||||
!bundleContent.includes("config-yaml")
|
||||
) {
|
||||
throw new Error("@continuedev/config-yaml not properly bundled");
|
||||
}
|
||||
|
||||
// Check for code from @continuedev/openai-adapters
|
||||
// Since the bundle is minified, check for strings that would be present
|
||||
// even after minification (e.g., error messages, property names)
|
||||
if (
|
||||
!bundleContent.includes("anthropic") &&
|
||||
!bundleContent.includes("gemini") &&
|
||||
!bundleContent.includes("openai") &&
|
||||
!bundleContent.includes("azure") &&
|
||||
!bundleContent.includes("bedrock")
|
||||
) {
|
||||
throw new Error("@continuedev/openai-adapters not properly bundled");
|
||||
}
|
||||
});
|
||||
|
||||
// Test 7: Test that the CLI can be invoked programmatically
|
||||
runTest("CLI can be invoked", () => {
|
||||
try {
|
||||
// Test that the CLI runs without crashing when given no args
|
||||
const isWindows = process.platform === "win32";
|
||||
const nullDevice = isWindows ? "nul" : "/dev/null";
|
||||
execCommand(`${getCLICommand("--help")} > ${nullDevice} 2>&1`);
|
||||
} catch (error) {
|
||||
throw new Error(`CLI invocation failed: ${error.message}`);
|
||||
}
|
||||
});
|
||||
|
||||
// Test 8: Check metadata file
|
||||
runTest("Build metadata exists", () => {
|
||||
if (!existsSync(resolve(__dirname, "dist/meta.json"))) {
|
||||
throw new Error("dist/meta.json not found");
|
||||
}
|
||||
|
||||
const meta = JSON.parse(
|
||||
readFileSync(resolve(__dirname, "dist/meta.json"), "utf8"),
|
||||
);
|
||||
if (!meta.inputs || !meta.outputs) {
|
||||
throw new Error("Invalid metadata structure");
|
||||
}
|
||||
});
|
||||
|
||||
// Test 9: Verify no missing external dependencies
|
||||
runTest("No missing runtime dependencies", () => {
|
||||
// This would fail in Test 3 if dependencies were missing, but let's be explicit
|
||||
const output = execCommand(`${getCLICommand("--version")} 2>&1`, {
|
||||
env: { ...process.env, NODE_ENV: "production" },
|
||||
});
|
||||
|
||||
if (
|
||||
output.includes("Cannot find module") ||
|
||||
output.includes("MODULE_NOT_FOUND")
|
||||
) {
|
||||
throw new Error("Missing module detected in output");
|
||||
}
|
||||
});
|
||||
|
||||
// Test 10: Test npm link scenario
|
||||
runTest("CLI works via npm link", () => {
|
||||
try {
|
||||
// Simply test that we can execute with node directly
|
||||
const output = execCommand("node dist/cn.js --version 2>&1");
|
||||
const packageJson = JSON.parse(
|
||||
readFileSync(resolve(__dirname, "package.json"), "utf8"),
|
||||
);
|
||||
if (!output.includes(packageJson.version)) {
|
||||
throw new Error("Version not found when running via node");
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(`npm link scenario failed: ${error.message}`);
|
||||
}
|
||||
});
|
||||
|
||||
// Summary
|
||||
console.log("\n" + "=".repeat(50));
|
||||
if (testsFailed === 0) {
|
||||
console.log(
|
||||
`${colors.green}✅ All ${testsPassed} tests passed!${colors.reset}`,
|
||||
);
|
||||
process.exit(0);
|
||||
} else {
|
||||
console.log(
|
||||
`${colors.red}❌ ${testsFailed} test(s) failed, ${testsPassed} passed${colors.reset}`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
|
@ -1,3 +1,5 @@
|
|||
import { vi } from "vitest";
|
||||
|
||||
export const processRule = vi.fn<(rule: string) => Promise<string>>();
|
||||
export const processPromptOrRule = vi.fn<(spec: string) => Promise<string>>();
|
||||
|
||||
export const processPrompt = vi.fn<(prompt: string) => Promise<string>>();
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue