Merge branch 'main' of https://github.com/continuedev/continue into drag-over-message
This commit is contained in:
commit
a1c4a5608a
500 changed files with 28127 additions and 12733 deletions
55
.github/actions/check-llm-changes/action.yml
vendored
Normal file
55
.github/actions/check-llm-changes/action.yml
vendored
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
name: "Check LLM Changes"
|
||||
description: "Check if LLM-related files have changed and set environment variable to control API tests"
|
||||
outputs:
|
||||
llm_changed:
|
||||
description: "Whether LLM-related files have changed"
|
||||
value: ${{ steps.check-changes.outputs.llm_changed }}
|
||||
ignore_api_tests:
|
||||
description: "Whether to ignore API tests based on file changes and other conditions"
|
||||
value: ${{ steps.check-changes.outputs.ignore_api_tests }}
|
||||
inputs:
|
||||
is_fork:
|
||||
description: "Whether this is a fork PR"
|
||||
required: false
|
||||
default: "false"
|
||||
is_dependabot:
|
||||
description: "Whether this is a dependabot PR"
|
||||
required: false
|
||||
default: "false"
|
||||
|
||||
runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- name: Check if LLM-related files changed
|
||||
id: check-changes
|
||||
shell: bash
|
||||
run: |
|
||||
if [ "${{ github.event_name }}" = "push" ]; then
|
||||
# For push events, compare against the previous commit
|
||||
CHANGED_FILES=$(git diff --name-only HEAD~1...HEAD)
|
||||
else
|
||||
# For PR events, compare against the base branch
|
||||
git fetch origin ${{ github.event.pull_request.base.ref }}
|
||||
CHANGED_FILES=$(git diff --name-only origin/${{ github.event.pull_request.base.ref }}...HEAD)
|
||||
fi
|
||||
|
||||
echo "Changed files:"
|
||||
echo "$CHANGED_FILES"
|
||||
|
||||
# Check if any LLM-related files were changed
|
||||
LLM_CHANGED=false
|
||||
if echo "$CHANGED_FILES" | grep -E "(^core/llm/|^core/index\.ts|^core/package\.json|^core/jest\.config\.js|^packages/.*/(.*llm.*|.*openai.*|.*anthropic.*)|\.github/workflows/pr-checks\.yaml|\.github/actions/check-llm-changes/)" > /dev/null; then
|
||||
LLM_CHANGED=true
|
||||
fi
|
||||
|
||||
echo "LLM files changed: $LLM_CHANGED"
|
||||
echo "llm_changed=$LLM_CHANGED" >> $GITHUB_OUTPUT
|
||||
|
||||
# Determine whether to ignore API tests
|
||||
IGNORE_API_TESTS=false
|
||||
if [ "${{ inputs.is_fork }}" = "true" ] || [ "${{ inputs.is_dependabot }}" = "true" ] || [ "$LLM_CHANGED" = "false" ]; then
|
||||
IGNORE_API_TESTS=true
|
||||
fi
|
||||
|
||||
echo "Ignore API tests: $IGNORE_API_TESTS"
|
||||
echo "ignore_api_tests=$IGNORE_API_TESTS" >> $GITHUB_OUTPUT
|
||||
21
.github/actions/run-vscode-e2e-test/action.yml
vendored
21
.github/actions/run-vscode-e2e-test/action.yml
vendored
|
|
@ -1,25 +1,25 @@
|
|||
name: 'Run VS Code E2E Test'
|
||||
description: 'Run a single VS Code E2E test with all required setup'
|
||||
name: "Run VS Code E2E Test"
|
||||
description: "Run a single VS Code E2E test with all required setup"
|
||||
inputs:
|
||||
test_file:
|
||||
description: 'E2E test file to run'
|
||||
description: "E2E test file to run"
|
||||
required: true
|
||||
command:
|
||||
description: 'Command to run (e2e:ci:run or e2e:ci:run-yaml)'
|
||||
description: "Command to run (e2e:ci:run or e2e:ci:run-yaml)"
|
||||
required: true
|
||||
ssh_key:
|
||||
description: 'SSH private key for testing'
|
||||
description: "SSH private key for testing"
|
||||
required: false
|
||||
ssh_host:
|
||||
description: 'SSH host for testing'
|
||||
description: "SSH host for testing"
|
||||
required: false
|
||||
is_fork:
|
||||
description: 'Whether this is a fork (affects SSH tests)'
|
||||
description: "Whether this is a fork (affects SSH tests)"
|
||||
required: false
|
||||
default: 'false'
|
||||
default: "false"
|
||||
|
||||
runs:
|
||||
using: 'composite'
|
||||
using: "composite"
|
||||
steps:
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
|
|
@ -58,6 +58,7 @@ runs:
|
|||
cd core
|
||||
npm ci
|
||||
cd ../extensions/vscode
|
||||
npm ci
|
||||
npm run e2e:ci:download
|
||||
else
|
||||
cd core
|
||||
|
|
@ -131,4 +132,4 @@ runs:
|
|||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-logs-${{ steps.sanitize_filename.outputs.sanitized_test_file || 'unknown' }}-${{ inputs.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }}
|
||||
path: extensions/vscode/e2e.log
|
||||
path: extensions/vscode/e2e.log
|
||||
|
|
|
|||
170
.github/workflows/auto-fix-failed-tests.yml
vendored
Normal file
170
.github/workflows/auto-fix-failed-tests.yml
vendored
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
name: Auto Fix Failed Tests
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: ["PR Checks", "CLI PR Checks"]
|
||||
types:
|
||||
- completed
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
issues: write
|
||||
actions: read
|
||||
|
||||
jobs:
|
||||
fix-failed-tests:
|
||||
# Only run if the workflow failed
|
||||
# DISABLED: Remove 'false && ' on the next line to enable auto-fixing
|
||||
if: false && github.event.workflow_run.conclusion == 'failure'
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Get workflow run details
|
||||
id: workflow-details
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const workflowRun = context.payload.workflow_run;
|
||||
const { data: jobs } = await github.rest.actions.listJobsForWorkflowRun({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
run_id: workflowRun.id
|
||||
});
|
||||
|
||||
// Find all failed jobs since we're only monitoring specific test workflows
|
||||
const failedJobs = jobs.jobs.filter(job => job.conclusion === 'failure');
|
||||
|
||||
if (failedJobs.length === 0) {
|
||||
core.info('No failed jobs found');
|
||||
return null;
|
||||
}
|
||||
|
||||
core.setOutput('has_failed_tests', 'true');
|
||||
core.setOutput('workflow_name', workflowRun.name);
|
||||
core.setOutput('workflow_run_id', workflowRun.id);
|
||||
core.setOutput('head_branch', workflowRun.head_branch);
|
||||
core.setOutput('head_sha', workflowRun.head_sha);
|
||||
core.setOutput('failed_jobs', JSON.stringify(failedJobs.map(j => j.name)));
|
||||
|
||||
return failedJobs;
|
||||
|
||||
- name: Get job logs for failed tests
|
||||
if: steps.workflow-details.outputs.has_failed_tests == 'true'
|
||||
id: get-logs
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const workflowRunId = ${{ github.event.workflow_run.id }};
|
||||
const { data: jobs } = await github.rest.actions.listJobsForWorkflowRun({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
run_id: workflowRunId
|
||||
});
|
||||
|
||||
let errorLogs = '';
|
||||
|
||||
for (const job of jobs.jobs) {
|
||||
if (job.conclusion === 'failure') {
|
||||
try {
|
||||
const { data: logData } = await github.rest.actions.downloadJobLogsForWorkflowRun({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
job_id: job.id
|
||||
});
|
||||
|
||||
errorLogs += `\n\n=== Job: ${job.name} ===\n`;
|
||||
errorLogs += logData;
|
||||
} catch (error) {
|
||||
core.warning(`Could not fetch logs for job ${job.name}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Store logs in environment file for next step
|
||||
const fs = require('fs');
|
||||
fs.writeFileSync('/tmp/test_failure_logs.txt', errorLogs);
|
||||
|
||||
core.setOutput('has_logs', errorLogs.length > 0 ? 'true' : 'false');
|
||||
|
||||
- name: Checkout repository
|
||||
if: steps.workflow-details.outputs.has_failed_tests == 'true'
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
fetch-depth: 0
|
||||
ref: ${{ steps.workflow-details.outputs.head_sha }}
|
||||
|
||||
- name: Setup Node.js
|
||||
if: steps.workflow-details.outputs.has_failed_tests == 'true'
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
|
||||
- name: Install Continue CLI globally
|
||||
if: steps.workflow-details.outputs.has_failed_tests == 'true'
|
||||
run: npm i -g @continuedev/cli
|
||||
|
||||
- name: Start remote session to fix failed tests
|
||||
if: steps.workflow-details.outputs.has_failed_tests == 'true'
|
||||
id: remote-session
|
||||
env:
|
||||
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
|
||||
run: |
|
||||
# Create a detailed prompt for fixing the failed tests
|
||||
cat > /tmp/fix_tests_prompt.txt << 'PROMPT_EOF'
|
||||
🔧 **Auto Test Fix Request**
|
||||
|
||||
The following tests failed in workflow "${{ steps.workflow-details.outputs.workflow_name }}" (Run ID: ${{ steps.workflow-details.outputs.workflow_run_id }}):
|
||||
|
||||
**Failed Jobs:** ${{ steps.workflow-details.outputs.failed_jobs }}
|
||||
**Branch:** ${{ steps.workflow-details.outputs.head_branch }}
|
||||
**Commit:** ${{ steps.workflow-details.outputs.head_sha }}
|
||||
|
||||
**Your Task:**
|
||||
1. Analyze the test failure logs and error messages
|
||||
2. Identify the root cause of the test failures
|
||||
3. Fix the failing tests by updating the test code or the underlying implementation
|
||||
4. Ensure all tests pass after your changes
|
||||
5. Commit your fixes with a descriptive message
|
||||
|
||||
**Test Failure Context:**
|
||||
Please examine the repository structure, run the failing tests locally to understand the errors, and implement appropriate fixes.
|
||||
|
||||
Focus on:
|
||||
- Understanding what the tests are trying to validate
|
||||
- Identifying why they're failing (code changes, environment issues, test logic errors)
|
||||
- Making minimal, targeted fixes that address the root cause
|
||||
- Ensuring the fixes don't break other functionality
|
||||
|
||||
Please start by examining the failing tests and their error messages, then proceed with the necessary fixes.
|
||||
PROMPT_EOF
|
||||
|
||||
echo "Starting Continue CLI remote session for test fixes..."
|
||||
echo "Prompt content:"
|
||||
cat /tmp/fix_tests_prompt.txt
|
||||
|
||||
# Start remote session and capture JSON output
|
||||
SESSION_OUTPUT=$(cat /tmp/fix_tests_prompt.txt | cn remote -s --branch ${{ steps.workflow-details.outputs.head_branch }})
|
||||
echo "Raw session output: $SESSION_OUTPUT"
|
||||
|
||||
# Extract URL from JSON output
|
||||
SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty')
|
||||
|
||||
if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then
|
||||
echo "Failed to extract session URL from output: $SESSION_OUTPUT"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT
|
||||
echo "✅ Started remote session: $SESSION_URL"
|
||||
|
||||
- name: Log session details
|
||||
if: steps.workflow-details.outputs.has_failed_tests == 'true'
|
||||
run: |
|
||||
echo "✅ Successfully started auto-fix session for failed tests"
|
||||
echo "Workflow: ${{ steps.workflow-details.outputs.workflow_name }}"
|
||||
echo "Run ID: ${{ steps.workflow-details.outputs.workflow_run_id }}"
|
||||
echo "Branch: ${{ steps.workflow-details.outputs.head_branch }}"
|
||||
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
|
||||
echo "Failed jobs: ${{ steps.workflow-details.outputs.failed_jobs }}"
|
||||
5
.github/workflows/beta-release.yml
vendored
5
.github/workflows/beta-release.yml
vendored
|
|
@ -39,6 +39,11 @@ jobs:
|
|||
component: core
|
||||
include-root: true
|
||||
|
||||
- name: Build core
|
||||
run: |
|
||||
cd core
|
||||
npm run build
|
||||
|
||||
- name: Install CLI dependencies
|
||||
working-directory: extensions/cli
|
||||
run: npm ci
|
||||
|
|
|
|||
14
.github/workflows/cli-pr-checks.yml
vendored
14
.github/workflows/cli-pr-checks.yml
vendored
|
|
@ -14,7 +14,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
if: github.run_attempt > 1
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: Track workflow rerun
|
||||
uses: ./.github/actions/track-rerun
|
||||
|
||||
|
|
@ -39,6 +39,11 @@ jobs:
|
|||
component: core
|
||||
include-root: true
|
||||
|
||||
- name: Build core
|
||||
run: |
|
||||
cd core
|
||||
npm run build
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd extensions/cli
|
||||
|
|
@ -54,6 +59,7 @@ jobs:
|
|||
matrix:
|
||||
os: [ubuntu-latest, windows-latest, macos-latest]
|
||||
node-version: [18, 20, 22, 24]
|
||||
fail-fast: false
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
||||
steps:
|
||||
|
|
@ -81,6 +87,11 @@ jobs:
|
|||
component: core
|
||||
include-root: true
|
||||
|
||||
- name: Build core
|
||||
run: |
|
||||
cd core
|
||||
npm run build
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd extensions/cli
|
||||
|
|
@ -108,7 +119,6 @@ jobs:
|
|||
cd extensions/cli
|
||||
npm run test:e2e
|
||||
|
||||
|
||||
# GitHub does not have a way of requiring that all checks pass (you must manually select each job)
|
||||
# This action at least lets us manage the list of required tests via source control
|
||||
# so that creators of new jobs can add them to this list
|
||||
|
|
|
|||
2
.github/workflows/compliance.yaml
vendored
2
.github/workflows/compliance.yaml
vendored
|
|
@ -41,7 +41,7 @@ jobs:
|
|||
|
||||
- name: Add PR title guidance comment
|
||||
if: always() && steps.pr-title-check.outputs.valid == 'false'
|
||||
uses: actions/github-script@v7
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const { data: comments } = await github.rest.issues.listComments({
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ jobs:
|
|||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Run Detailed PR Review
|
||||
uses: continuedev/continue/actions/detailed-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe
|
||||
uses: continuedev/continue/actions/detailed-review@80c679747b7c7b2624d15db31ff5bdadc9681c65
|
||||
with:
|
||||
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
|
||||
continue-org: continuedev
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ jobs:
|
|||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Run Continue PR Review Action
|
||||
uses: continuedev/continue/actions/general-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe
|
||||
uses: continuedev/continue/actions/general-review@80c679747b7c7b2624d15db31ff5bdadc9681c65
|
||||
with:
|
||||
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
|
||||
continue-org: "continuedev"
|
||||
|
|
|
|||
2
.github/workflows/label-merged-prs.yml
vendored
2
.github/workflows/label-merged-prs.yml
vendored
|
|
@ -44,7 +44,7 @@ jobs:
|
|||
|
||||
- name: Determine and apply tier label
|
||||
if: steps.check-author.outputs.should_label == 'true'
|
||||
uses: actions/github-script@v7
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const pr = context.payload.pull_request;
|
||||
|
|
|
|||
2
.github/workflows/main.yaml
vendored
2
.github/workflows/main.yaml
vendored
|
|
@ -20,7 +20,7 @@ jobs:
|
|||
- id: check
|
||||
working-directory: .
|
||||
run: |
|
||||
if [[ "${{ github.event.release.tag_name }}" == v1.0.*-vscode ]]; then
|
||||
if [[ "${{ github.event.release.tag_name }}" == v1.2.*-vscode ]]; then
|
||||
echo "should_run=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "should_run=false" >> $GITHUB_OUTPUT
|
||||
|
|
|
|||
22
.github/workflows/pr-checks.yaml
vendored
22
.github/workflows/pr-checks.yaml
vendored
|
|
@ -44,6 +44,8 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0 # Needed for git diff to work
|
||||
- name: Setup packages
|
||||
uses: ./.github/actions/setup-packages
|
||||
- name: Setup core component
|
||||
|
|
@ -52,6 +54,13 @@ jobs:
|
|||
component: core
|
||||
include-root: true
|
||||
|
||||
- name: Check if LLM-related files changed
|
||||
id: llm-changes
|
||||
uses: ./.github/actions/check-llm-changes
|
||||
with:
|
||||
is_fork: ${{ github.event.pull_request.head.repo.fork == true }}
|
||||
is_dependabot: ${{ github.actor == 'dependabot[bot]' }}
|
||||
|
||||
- name: Type check and lint
|
||||
run: |
|
||||
cd core
|
||||
|
|
@ -66,7 +75,7 @@ jobs:
|
|||
npm test
|
||||
npm run vitest
|
||||
env:
|
||||
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}
|
||||
IGNORE_API_KEY_TESTS: ${{ steps.llm-changes.outputs.ignore_api_tests }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
|
||||
|
|
@ -180,16 +189,25 @@ jobs:
|
|||
package: ${{ fromJson(needs.get-packages-matrix.outputs.packages) }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0 # Needed for git diff to work
|
||||
- name: Setup packages
|
||||
uses: ./.github/actions/setup-packages
|
||||
|
||||
- name: Check if LLM-related files changed
|
||||
id: llm-changes
|
||||
uses: ./.github/actions/check-llm-changes
|
||||
with:
|
||||
is_fork: ${{ github.event.pull_request.head.repo.fork == true }}
|
||||
is_dependabot: ${{ github.actor == 'dependabot[bot]' }}
|
||||
|
||||
- name: Test and check ${{ matrix.package }}
|
||||
run: |
|
||||
cd packages/${{ matrix.package }}
|
||||
npm ci
|
||||
npm test
|
||||
env:
|
||||
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}
|
||||
IGNORE_API_KEY_TESTS: ${{ steps.llm-changes.outputs.ignore_api_tests }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
|
||||
|
|
|
|||
|
|
@ -27,9 +27,21 @@ jobs:
|
|||
echo "contains_mention=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Add eyes reaction to comment
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
await github.rest.reactions.createForIssueComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: ${{ github.event.comment.id }},
|
||||
content: 'eyes'
|
||||
});
|
||||
|
||||
- name: Checkout PR branch
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
fetch-depth: 0
|
||||
|
|
@ -37,7 +49,7 @@ jobs:
|
|||
- name: Get PR information
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
id: pr-info
|
||||
uses: actions/github-script@v7
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const { data: pr } = await github.rest.pulls.get({
|
||||
|
|
@ -95,7 +107,7 @@ jobs:
|
|||
|
||||
- name: Comment with session URL
|
||||
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
|
||||
uses: actions/github-script@v7
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
|
||||
|
|
@ -130,9 +142,21 @@ jobs:
|
|||
echo "contains_mention=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Add eyes reaction to comment
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
await github.rest.reactions.createForPullRequestReviewComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: ${{ github.event.comment.id }},
|
||||
content: 'eyes'
|
||||
});
|
||||
|
||||
- name: Checkout PR branch
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
fetch-depth: 0
|
||||
|
|
@ -148,21 +172,59 @@ jobs:
|
|||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
run: npm i -g @continuedev/cli
|
||||
|
||||
- name: Get review context
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
id: review-context
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
let reviewContext = '';
|
||||
|
||||
// Check if this comment is a reply to another review comment
|
||||
if (context.payload.comment.in_reply_to_id) {
|
||||
try {
|
||||
const { data: originalComment } = await github.rest.pulls.getReviewComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: context.payload.comment.in_reply_to_id
|
||||
});
|
||||
|
||||
reviewContext = `**Original review comment by @${originalComment.user.login}:**
|
||||
${originalComment.body}
|
||||
|
||||
**Reply by @${{ github.event.comment.user.login }}:**
|
||||
${{ github.event.comment.body }}`;
|
||||
} catch (error) {
|
||||
console.log('Could not fetch original comment, using current comment only');
|
||||
reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:**
|
||||
${{ github.event.comment.body }}`;
|
||||
}
|
||||
} else {
|
||||
reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:**
|
||||
${{ github.event.comment.body }}`;
|
||||
}
|
||||
|
||||
core.setOutput('context', reviewContext);
|
||||
|
||||
- name: Start remote session
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
id: remote-session
|
||||
env:
|
||||
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
|
||||
run: |
|
||||
# Debug: Echo the branch we're starting the session on
|
||||
echo "Starting remote session on branch: ${{ github.event.pull_request.head.ref }}"
|
||||
|
||||
# Create a temporary file for the prompt to handle special characters and newlines properly
|
||||
cat > /tmp/prompt.txt << 'PROMPT_EOF'
|
||||
Please help with the following code review comment from @${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}:
|
||||
Please help with the following code review discussion from PR #${{ github.event.pull_request.number }}:
|
||||
|
||||
**File:** ${{ github.event.comment.path }}
|
||||
**Line:** ${{ github.event.comment.line || github.event.comment.original_line || 'N/A' }}
|
||||
**Comment:** ${{ github.event.comment.body }}
|
||||
|
||||
Please analyze the specific file and line mentioned, understand the review feedback, implement the necessary changes, and commit them to this branch.
|
||||
${{ steps.review-context.outputs.context }}
|
||||
|
||||
Please analyze the specific file and line mentioned, understand the review feedback and any discussion context, implement the necessary changes, and commit them to this branch.
|
||||
PROMPT_EOF
|
||||
|
||||
# Debug output
|
||||
|
|
@ -187,7 +249,7 @@ jobs:
|
|||
|
||||
- name: Comment with session URL
|
||||
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
|
||||
uses: actions/github-script@v7
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
|
||||
4
.github/workflows/similar-issues.yml
vendored
4
.github/workflows/similar-issues.yml
vendored
|
|
@ -190,7 +190,7 @@ jobs:
|
|||
echo "confidence=$CONFIDENCE" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Comment with analysis
|
||||
uses: actions/github-script@v7
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
let comment = '';
|
||||
|
|
@ -307,7 +307,7 @@ jobs:
|
|||
|
||||
- name: Add labels
|
||||
if: github.event_name == 'issues'
|
||||
uses: actions/github-script@v7
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const labels = [];
|
||||
|
|
|
|||
5
.github/workflows/stable-release.yml
vendored
5
.github/workflows/stable-release.yml
vendored
|
|
@ -152,6 +152,11 @@ jobs:
|
|||
component: core
|
||||
include-root: true
|
||||
|
||||
- name: Build core
|
||||
run: |
|
||||
cd core
|
||||
npm run build
|
||||
|
||||
- name: Prepare package for direct stable release
|
||||
if: ${{ inputs.release_type == 'direct-stable' }}
|
||||
working-directory: extensions/cli
|
||||
|
|
|
|||
|
|
@ -23,5 +23,5 @@ CHANGELOG.md
|
|||
**/CODEOWNERS
|
||||
core/vendor
|
||||
coverage
|
||||
e2e
|
||||
# e2e
|
||||
packages/continue-sdk
|
||||
|
|
@ -176,9 +176,9 @@ See [`intellij/CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the
|
|||
### Our Git Workflow
|
||||
|
||||
We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the
|
||||
`main` branch titled `v1.1.x-vscode`, which automatically triggers the workflow
|
||||
`main` branch titled `v1.3.x-vscode`, which automatically triggers the workflow
|
||||
in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When
|
||||
a release has been sufficiently tested, we will create a new release titled `v1.0x-vscode`, triggering a similar
|
||||
a release has been sufficiently tested, we will create a new release titled `v1.2.x-vscode`, triggering a similar
|
||||
workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code
|
||||
extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow
|
||||
is well explained by <http://releaseflow.org>.
|
||||
|
|
|
|||
|
|
@ -35,25 +35,25 @@ Get started in [VS Code](https://marketplace.visualstudio.com/items?itemName=Con
|
|||
|
||||
## Agent
|
||||
|
||||
[Agent](/features/agent/quick-start) to work on development tasks together with AI
|
||||
[Agent](https://docs.continue.dev/features/agent/quick-start) to work on development tasks together with AI
|
||||
|
||||

|
||||
|
||||
## Chat
|
||||
|
||||
[Chat](/features/chat/quick-start) to ask general questions and clarify code sections
|
||||
[Chat](https://docs.continue.dev/features/chat/quick-start) to ask general questions and clarify code sections
|
||||
|
||||

|
||||
|
||||
## Edit
|
||||
|
||||
[Edit](/features/edit/quick-start) to modify a code section without leaving your current file
|
||||
[Edit](https://docs.continue.dev/features/edit/quick-start) to modify a code section without leaving your current file
|
||||
|
||||

|
||||
|
||||
## Autocomplete
|
||||
|
||||
[Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type
|
||||
[Autocomplete](https://docs.continue.dev/features/autocomplete/quick-start) to receive inline code suggestions as you type
|
||||
|
||||

|
||||
|
||||
|
|
|
|||
|
|
@ -73,7 +73,7 @@ runs:
|
|||
- name: Install Continue CLI
|
||||
if: env.SKIP_REVIEW != 'true'
|
||||
shell: bash
|
||||
run: npm install -g @continuedev/cli@1.4.25
|
||||
run: npm install -g @continuedev/cli@1.4.30
|
||||
|
||||
- name: Build Inline Review Prompt
|
||||
if: env.SKIP_REVIEW != 'true'
|
||||
|
|
@ -194,6 +194,21 @@ runs:
|
|||
exit 1
|
||||
fi
|
||||
|
||||
# Validate API key
|
||||
if [ -z "$CONTINUE_API_KEY" ]; then
|
||||
echo "Warning: CONTINUE_API_KEY environment variable is not set"
|
||||
# Create fallback review and continue
|
||||
cat > inline_review.json << 'EOF'
|
||||
{
|
||||
"review_summary": "AI review skipped: CONTINUE_API_KEY not configured.",
|
||||
"comments": []
|
||||
}
|
||||
EOF
|
||||
echo "SKIP_CLI=true" >> $GITHUB_ENV
|
||||
else
|
||||
echo "SKIP_CLI=false" >> $GITHUB_ENV
|
||||
fi
|
||||
|
||||
# Log the prompt for debugging
|
||||
echo "===== START REVIEW PROMPT ====="
|
||||
head -n 50 inline_review_prompt.txt
|
||||
|
|
@ -201,23 +216,67 @@ runs:
|
|||
tail -n 20 inline_review_prompt.txt
|
||||
echo "===== END REVIEW PROMPT ====="
|
||||
|
||||
# Run the CLI and capture JSON output
|
||||
cn --readonly --format json --org "${{ inputs.continue-org }}" --config "${{ inputs.continue-config }}" -p "$(cat inline_review_prompt.txt)" > inline_review_raw.json
|
||||
|
||||
# Log the output for debugging
|
||||
echo "Initial Continue CLI output:"
|
||||
cat inline_review_raw.json
|
||||
|
||||
# Validate JSON output and use it directly
|
||||
if ! jq empty inline_review_raw.json 2>/dev/null; then
|
||||
echo "Error: Invalid JSON output from Continue CLI"
|
||||
exit 1
|
||||
# Test Continue CLI availability
|
||||
if [ "$SKIP_CLI" != "true" ]; then
|
||||
echo "Testing Continue CLI..."
|
||||
if ! cn --version; then
|
||||
echo "Warning: Continue CLI not found or not working"
|
||||
cat > inline_review.json << 'EOF'
|
||||
{
|
||||
"review_summary": "AI review skipped: Continue CLI installation failed.",
|
||||
"comments": []
|
||||
}
|
||||
EOF
|
||||
echo "SKIP_CLI=true" >> $GITHUB_ENV
|
||||
else
|
||||
echo "Continue CLI version: $(cn --version)"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Run the CLI and capture JSON output with error handling
|
||||
if [ "$SKIP_CLI" != "true" ]; then
|
||||
echo "Executing Continue CLI with config: ${{ inputs.continue-org }}/${{ inputs.continue-config }}"
|
||||
|
||||
# Write prompt to temp file for better handling
|
||||
PROMPT_FILE="/tmp/continue-prompt-$.txt"
|
||||
cp inline_review_prompt.txt "$PROMPT_FILE"
|
||||
|
||||
# Use timeout to prevent hanging (240 seconds = 4 minutes)
|
||||
if ! timeout 240 cn --config "${{ inputs.continue-org }}/${{ inputs.continue-config }}" -p "@$PROMPT_FILE" --allow Bash --format json > inline_review_raw.json 2>cli_error.log; then
|
||||
echo "Warning: Continue CLI command failed"
|
||||
echo "CLI error log:"
|
||||
cat cli_error.log
|
||||
|
||||
# Create fallback review
|
||||
cat > inline_review.json << 'EOF'
|
||||
{
|
||||
"review_summary": "AI review failed due to service initialization issues. Please check the Continue API key and configuration.",
|
||||
"comments": []
|
||||
}
|
||||
EOF
|
||||
echo "Created fallback review due to CLI failure"
|
||||
else
|
||||
# Log the output for debugging
|
||||
echo "Initial Continue CLI output:"
|
||||
cat inline_review_raw.json
|
||||
|
||||
# Validate JSON output and use it directly
|
||||
if ! jq empty inline_review_raw.json 2>/dev/null; then
|
||||
echo "Warning: Invalid JSON output from Continue CLI, using fallback"
|
||||
cat > inline_review.json << 'EOF'
|
||||
{
|
||||
"review_summary": "AI review completed but failed to parse output correctly.",
|
||||
"comments": []
|
||||
}
|
||||
EOF
|
||||
else
|
||||
# Use the JSON output directly
|
||||
cp inline_review_raw.json inline_review.json
|
||||
echo "Review output:"
|
||||
cat inline_review.json
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Use the JSON output directly
|
||||
cp inline_review_raw.json inline_review.json
|
||||
echo "Review output:"
|
||||
cat inline_review.json
|
||||
|
||||
- name: Post Inline Review Comments
|
||||
if: env.SKIP_REVIEW != 'true'
|
||||
|
|
|
|||
|
|
@ -68,7 +68,7 @@ runs:
|
|||
- name: Install Continue CLI
|
||||
if: env.SHOULD_RUN == 'true'
|
||||
shell: bash
|
||||
run: npm install -g @continuedev/cli@1.4.25
|
||||
run: npm install -g @continuedev/cli@1.4.30
|
||||
|
||||
- name: Build PR Review Prompt
|
||||
if: env.SHOULD_RUN == 'true'
|
||||
|
|
@ -157,6 +157,24 @@ runs:
|
|||
echo "=================================="
|
||||
echo ""
|
||||
|
||||
# Validate API key
|
||||
if [ -z "$CONTINUE_API_KEY" ]; then
|
||||
echo "Warning: CONTINUE_API_KEY environment variable is not set"
|
||||
# Create fallback review and continue
|
||||
cat > code_review.md << 'EOF'
|
||||
## Code Review Summary
|
||||
|
||||
⚠️ AI review skipped: CONTINUE_API_KEY not configured.
|
||||
|
||||
### Configuration Required
|
||||
- Please set the CONTINUE_API_KEY secret in repository settings
|
||||
- Verify that the organization and config path are valid
|
||||
EOF
|
||||
echo "SKIP_CLI=true" >> $GITHUB_ENV
|
||||
else
|
||||
echo "SKIP_CLI=false" >> $GITHUB_ENV
|
||||
fi
|
||||
|
||||
# Validate inputs to prevent command injection
|
||||
if [[ ! "$CONTINUE_ORG" =~ ^[a-zA-Z0-9_-]+$ ]]; then
|
||||
echo "Error: Invalid organization name. Must contain only alphanumeric characters, hyphens, and underscores."
|
||||
|
|
@ -168,8 +186,55 @@ runs:
|
|||
exit 1
|
||||
fi
|
||||
|
||||
# Run the CLI with validated config
|
||||
cn --readonly --org "$CONTINUE_ORG" --config "$CONTINUE_CONFIG" -p "$(cat review_prompt.txt)" > code_review.md
|
||||
# Test Continue CLI availability
|
||||
if [ "$SKIP_CLI" != "true" ]; then
|
||||
echo "Testing Continue CLI..."
|
||||
if ! cn --version; then
|
||||
echo "Warning: Continue CLI not found or not working"
|
||||
cat > code_review.md << 'EOF'
|
||||
## Code Review Summary
|
||||
|
||||
⚠️ AI review skipped: Continue CLI installation failed.
|
||||
|
||||
### Troubleshooting
|
||||
- Check that npm installation succeeded
|
||||
- Verify @continuedev/cli package is available
|
||||
EOF
|
||||
echo "SKIP_CLI=true" >> $GITHUB_ENV
|
||||
else
|
||||
echo "Continue CLI version: $(cn --version)"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Run the CLI with validated config and error handling
|
||||
if [ "$SKIP_CLI" != "true" ]; then
|
||||
echo "Executing Continue CLI with config: $CONTINUE_ORG/$CONTINUE_CONFIG"
|
||||
|
||||
# Write prompt to temp file for better handling
|
||||
PROMPT_FILE="/tmp/continue-prompt-$.txt"
|
||||
cp review_prompt.txt "$PROMPT_FILE"
|
||||
|
||||
# Use timeout to prevent hanging (240 seconds = 4 minutes)
|
||||
if ! timeout 240 cn --config "$CONTINUE_ORG/$CONTINUE_CONFIG" -p "@$PROMPT_FILE" --allow Bash > code_review.md 2>cli_error.log; then
|
||||
echo "Error: Continue CLI command failed"
|
||||
echo "CLI error log:"
|
||||
cat cli_error.log
|
||||
|
||||
# Create fallback review
|
||||
cat > code_review.md << 'EOF'
|
||||
## Code Review Summary
|
||||
|
||||
⚠️ AI review failed due to service initialization issues. Please check the Continue API key and configuration.
|
||||
|
||||
### Troubleshooting
|
||||
- Verify the CONTINUE_API_KEY secret is set correctly
|
||||
- Check that the organization and config path are valid
|
||||
- Ensure the Continue service is accessible
|
||||
EOF
|
||||
else
|
||||
echo "Review generated successfully"
|
||||
fi
|
||||
fi
|
||||
|
||||
- name: Upload Review Results
|
||||
if: env.SHOULD_RUN == 'true' && always()
|
||||
|
|
|
|||
2
binary/package-lock.json
generated
2
binary/package-lock.json
generated
|
|
@ -106,6 +106,7 @@
|
|||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
"request": "^2.88.2",
|
||||
"shell-quote": "^1.8.3",
|
||||
"socket.io-client": "^4.7.3",
|
||||
"sqlite": "^5.1.1",
|
||||
"sqlite3": "^5.1.7",
|
||||
|
|
@ -140,6 +141,7 @@
|
|||
"@types/pg": "^8.11.6",
|
||||
"@types/plist": "^3.0.5",
|
||||
"@types/request": "^2.48.12",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"@types/tar": "^6.1.13",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/win-ca": "^3.5.4",
|
||||
|
|
|
|||
|
|
@ -215,12 +215,6 @@ export class CompletionProvider {
|
|||
const multiline =
|
||||
!helper.options.transform || shouldCompleteMultiline(helper);
|
||||
|
||||
const rawGeneration = await llm.complete(
|
||||
prompt,
|
||||
token,
|
||||
completionOptions,
|
||||
);
|
||||
|
||||
const completionStream =
|
||||
this.completionStreamer.streamCompletionWithFilters(
|
||||
token,
|
||||
|
|
|
|||
|
|
@ -202,6 +202,8 @@ export class ConfigHandler {
|
|||
message: `Error loading Continue Hub assistants${e instanceof Error ? ":\n" + e.message : ""}`,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
PolicySingleton.getInstance().policy = null;
|
||||
}
|
||||
// Load local org if not signed in or hub orgs fail
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -57,6 +57,7 @@ import {
|
|||
} from "../util/paths";
|
||||
import { localPathToUri } from "../util/pathToUri";
|
||||
|
||||
import { PolicySingleton } from "../control-plane/PolicySingleton";
|
||||
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
|
||||
import { getBaseToolDefinitions } from "../tools";
|
||||
import { resolveRelativePathInDir } from "../util/ideUtils";
|
||||
|
|
@ -544,16 +545,21 @@ async function intermediateToFinalConfig({
|
|||
|
||||
// Trigger MCP server refreshes (Config is reloaded again once connected!)
|
||||
const mcpManager = MCPManagerSingleton.getInstance();
|
||||
mcpManager.setConnections(
|
||||
(config.experimental?.modelContextProtocolServers ?? []).map(
|
||||
(server, index) => ({
|
||||
id: `continue-mcp-server-${index + 1}`,
|
||||
name: `MCP Server`,
|
||||
...server,
|
||||
}),
|
||||
),
|
||||
false,
|
||||
);
|
||||
const orgPolicy = PolicySingleton.getInstance().policy;
|
||||
if (orgPolicy?.policy?.allowMcpServers === false) {
|
||||
await mcpManager.shutdown();
|
||||
} else {
|
||||
mcpManager.setConnections(
|
||||
(config.experimental?.modelContextProtocolServers ?? []).map(
|
||||
(server, index) => ({
|
||||
id: `continue-mcp-server-${index + 1}`,
|
||||
name: `MCP Server`,
|
||||
...server,
|
||||
}),
|
||||
),
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
// Handle experimental modelRole config values for apply and edit
|
||||
const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;
|
||||
|
|
|
|||
|
|
@ -332,12 +332,14 @@ export default async function doLoadConfig(options: {
|
|||
}
|
||||
}
|
||||
|
||||
if (
|
||||
PolicySingleton.getInstance().policy?.policy?.allowAnonymousTelemetry ===
|
||||
false
|
||||
) {
|
||||
// Org policies
|
||||
const policy = PolicySingleton.getInstance().policy?.policy;
|
||||
if (policy?.allowAnonymousTelemetry === false) {
|
||||
newConfig.allowAnonymousTelemetry = false;
|
||||
}
|
||||
if (policy?.allowCodebaseIndexing === false) {
|
||||
newConfig.disableIndexing = true;
|
||||
}
|
||||
|
||||
// Setup telemetry only after (and if) we know it is enabled
|
||||
await Telemetry.setup(
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ export const sharedConfigSchema = z
|
|||
displayRawMarkdown: z.boolean(),
|
||||
showChatScrollbar: z.boolean(),
|
||||
autoAcceptEditToolDiffs: z.boolean(),
|
||||
continueAfterToolRejection: z.boolean(),
|
||||
|
||||
// `tabAutocompleteOptions` in `ContinueConfig`
|
||||
useAutocompleteCache: z.boolean(),
|
||||
|
|
@ -158,6 +159,11 @@ export function modifyAnyConfigWithSharedConfig<
|
|||
configCopy.ui.showSessionTabs = sharedConfig.showSessionTabs;
|
||||
}
|
||||
|
||||
if (sharedConfig.continueAfterToolRejection !== undefined) {
|
||||
configCopy.ui.continueAfterToolRejection =
|
||||
sharedConfig.continueAfterToolRejection;
|
||||
}
|
||||
|
||||
configCopy.experimental = {
|
||||
...configCopy.experimental,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,31 +0,0 @@
|
|||
import { ModelDescription } from "../index.d";
|
||||
|
||||
/**
|
||||
* Determines if system message tools should be auto-enabled for the given model.
|
||||
* This is used to automatically enable system message tools for certain provider/model combinations
|
||||
* where we have a strong preference, taking priority over user manual settings.
|
||||
*
|
||||
* System message tools are an alternative to native tool calling where tool definitions and calls
|
||||
* are embedded in the system message as text rather than using the provider's native tool calling API.
|
||||
* This can be beneficial for providers/models that don't support native tool calling or have
|
||||
* poor tool calling performance.
|
||||
*
|
||||
* Current auto-enable rules:
|
||||
* - OpenRouter provider: true for all models except those containing "claude" (since Claude models
|
||||
* generally have good native tool calling support)
|
||||
* - All other providers: undefined (no auto-preference, use manual setting)
|
||||
*
|
||||
* @param model The model description to check
|
||||
* @returns true to force enable, false to force disable, undefined for no auto-preference
|
||||
*/
|
||||
export function shouldAutoEnableSystemMessageTools(
|
||||
model: ModelDescription,
|
||||
): boolean | undefined {
|
||||
// Auto-enable for OpenRouter, but exclude Claude models which have good native tool calling
|
||||
if (model.provider === "openrouter") {
|
||||
return !model.model.toLowerCase().includes("claude");
|
||||
}
|
||||
|
||||
// No auto-preference for all other providers - use manual setting
|
||||
return undefined;
|
||||
}
|
||||
|
|
@ -1,85 +0,0 @@
|
|||
import { describe, expect, test } from "vitest";
|
||||
import { ModelDescription } from "../index.d";
|
||||
import { shouldAutoEnableSystemMessageTools } from "./shouldAutoEnableSystemMessageTools";
|
||||
|
||||
describe("shouldAutoEnableSystemMessageTools", () => {
|
||||
const createModel = (provider: string, model: string): ModelDescription => ({
|
||||
title: "Test Model",
|
||||
provider,
|
||||
underlyingProviderName: provider,
|
||||
model,
|
||||
});
|
||||
|
||||
test("should return true for OpenRouter models that don't contain 'claude'", () => {
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(createModel("openrouter", "gpt-4o")),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "llama-3.3-70b-instruct"),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "qwen/qwen-2.5-72b-instruct"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("should return false for OpenRouter Claude models", () => {
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "anthropic/claude-3-sonnet"),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "anthropic/claude-3.5-sonnet"),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "claude-3-haiku"),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("should return undefined for all other providers", () => {
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(createModel("openai", "gpt-4o")),
|
||||
).toBe(undefined);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("anthropic", "claude-3.5-sonnet"),
|
||||
),
|
||||
).toBe(undefined);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("groq", "llama-3.3-70b-versatile"),
|
||||
),
|
||||
).toBe(undefined);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("together", "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo"),
|
||||
),
|
||||
).toBe(undefined);
|
||||
});
|
||||
|
||||
test("should be case insensitive for 'claude' detection", () => {
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "CLAUDE-models"),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "Claude-3.5"),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldAutoEnableSystemMessageTools(
|
||||
createModel("openrouter", "some-model-Claude"),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
@ -25,6 +25,7 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
|
|||
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
|
||||
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
|
||||
import { getControlPlaneEnvSync } from "../../control-plane/env";
|
||||
import { PolicySingleton } from "../../control-plane/PolicySingleton";
|
||||
import { getBaseToolDefinitions } from "../../tools";
|
||||
import { getCleanUriPath } from "../../util/uri";
|
||||
import { loadConfigContextProviders } from "../loadContextProviders";
|
||||
|
|
@ -378,21 +379,26 @@ async function configYamlToContinueConfig(options: {
|
|||
|
||||
// Trigger MCP server refreshes (Config is reloaded again once connected!)
|
||||
const mcpManager = MCPManagerSingleton.getInstance();
|
||||
mcpManager.setConnections(
|
||||
(config.mcpServers ?? []).map((server) => ({
|
||||
id: server.name,
|
||||
name: server.name,
|
||||
sourceFile: server.sourceFile,
|
||||
transport: {
|
||||
type: "stdio",
|
||||
args: [],
|
||||
...(server as any), // TODO: fix the types on mcpServers in config-yaml
|
||||
},
|
||||
timeout: server.connectionTimeout,
|
||||
})),
|
||||
false,
|
||||
{ ide },
|
||||
);
|
||||
const orgPolicy = PolicySingleton.getInstance().policy;
|
||||
if (orgPolicy?.policy?.allowMcpServers === false) {
|
||||
await mcpManager.shutdown();
|
||||
} else {
|
||||
mcpManager.setConnections(
|
||||
(config.mcpServers ?? []).map((server) => ({
|
||||
id: server.name,
|
||||
name: server.name,
|
||||
sourceFile: server.sourceFile,
|
||||
transport: {
|
||||
type: "stdio",
|
||||
args: [],
|
||||
...(server as any), // TODO: fix the types on mcpServers in config-yaml
|
||||
},
|
||||
timeout: server.connectionTimeout,
|
||||
})),
|
||||
false,
|
||||
{ ide },
|
||||
);
|
||||
}
|
||||
|
||||
return { config: continueConfig, errors: localErrors };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,4 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
||||
|
||||
import {
|
||||
SSEClientTransport,
|
||||
SseError,
|
||||
|
|
@ -8,7 +6,8 @@ import {
|
|||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
|
||||
|
||||
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
||||
import { Agent as HttpsAgent } from "https";
|
||||
import {
|
||||
IDE,
|
||||
MCPConnectionStatus,
|
||||
|
|
@ -393,6 +392,11 @@ class MCPConnection {
|
|||
case "websocket":
|
||||
return new WebSocketClientTransport(new URL(options.transport.url));
|
||||
case "sse":
|
||||
const sseAgent =
|
||||
options.transport.requestOptions?.verifySsl === false
|
||||
? new HttpsAgent({ rejectUnauthorized: false })
|
||||
: undefined;
|
||||
|
||||
return new SSEClientTransport(new URL(options.transport.url), {
|
||||
eventSourceInit: {
|
||||
fetch: (input, init) =>
|
||||
|
|
@ -404,17 +408,27 @@ class MCPConnection {
|
|||
| Record<string, string>
|
||||
| undefined),
|
||||
},
|
||||
...(sseAgent && { agent: sseAgent }),
|
||||
}),
|
||||
},
|
||||
requestInit: { headers: options.transport.requestOptions?.headers },
|
||||
requestInit: {
|
||||
headers: options.transport.requestOptions?.headers,
|
||||
...(sseAgent && { agent: sseAgent }),
|
||||
},
|
||||
});
|
||||
case "streamable-http":
|
||||
return new StreamableHTTPClientTransport(
|
||||
new URL(options.transport.url),
|
||||
{
|
||||
requestInit: { headers: options.transport.requestOptions?.headers },
|
||||
const { url, requestOptions } = options.transport;
|
||||
const streamableAgent =
|
||||
requestOptions?.verifySsl === false
|
||||
? new HttpsAgent({ rejectUnauthorized: false })
|
||||
: undefined;
|
||||
|
||||
return new StreamableHTTPClientTransport(new URL(url), {
|
||||
requestInit: {
|
||||
headers: requestOptions?.headers,
|
||||
...(streamableAgent && { agent: streamableAgent }),
|
||||
},
|
||||
);
|
||||
});
|
||||
default:
|
||||
throw new Error(
|
||||
`Unsupported transport type: ${(options.transport as any).type}`,
|
||||
|
|
|
|||
|
|
@ -48,6 +48,21 @@ export class MCPManagerSingleton {
|
|||
this.connections.delete(id);
|
||||
}
|
||||
|
||||
async shutdown() {
|
||||
if (this.connections.size > 0) {
|
||||
await Promise.allSettled(
|
||||
Array.from(this.connections.entries()).map(([id, connection]) => {
|
||||
try {
|
||||
connection.abortController.abort();
|
||||
void connection.client.close();
|
||||
} finally {
|
||||
this.connections.delete(id);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
setConnections(
|
||||
servers: MCPOptions[],
|
||||
forceRefresh: boolean,
|
||||
|
|
|
|||
|
|
@ -1,68 +0,0 @@
|
|||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
const HIGHLIGHTS_TOKEN_BUDGET = 2000;
|
||||
|
||||
class CodeHighlightsContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "highlights",
|
||||
displayTitle: "Highlights",
|
||||
description: "Code highlights from open files",
|
||||
type: "normal",
|
||||
renderInlineAs: "",
|
||||
};
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
// const { getHighlightsThatFit } = await import(
|
||||
// "llm-code-highlighter/src/index.continue.js"
|
||||
// );
|
||||
const ide = extras.ide;
|
||||
const openFiles = await ide.getOpenFiles();
|
||||
// const allFiles: { name: string; absPath: string; content: string }[] =
|
||||
// await Promise.all(
|
||||
// openFiles.map(async (filepath: string) => {
|
||||
// return {
|
||||
// name: getBasename(filepath),
|
||||
// absPath: filepath,
|
||||
// content: `${await ide.readFile(filepath)}`,
|
||||
// };
|
||||
// }),
|
||||
// );
|
||||
// const contextSizer = {
|
||||
// fits(content: string): boolean {
|
||||
// return countTokens(content, "") < HIGHLIGHTS_TOKEN_BUDGET;
|
||||
// },
|
||||
// };
|
||||
// const repoMap = await getHighlightsThatFit(
|
||||
// contextSizer,
|
||||
// [],
|
||||
// allFiles
|
||||
// .filter((file) => file.content.length > 0)
|
||||
// .map((file) => {
|
||||
// return {
|
||||
// relPath: file.name,
|
||||
// code: file.content,
|
||||
// };
|
||||
// }),
|
||||
// );
|
||||
// return [
|
||||
// {
|
||||
// content: repoMap ? repoMap : "",
|
||||
// name: "Code Highlights",
|
||||
// description: "Code highlights from open files",
|
||||
// },
|
||||
// ];
|
||||
return [];
|
||||
}
|
||||
|
||||
async load(): Promise<void> {}
|
||||
}
|
||||
|
||||
export default CodeHighlightsContextProvider;
|
||||
|
|
@ -1,56 +0,0 @@
|
|||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
class CodeOutlineContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "outline",
|
||||
displayTitle: "Outline",
|
||||
description: "Definition lines only (from open files)",
|
||||
type: "normal",
|
||||
renderInlineAs: "",
|
||||
};
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const ide = extras.ide;
|
||||
const openFiles = await ide.getOpenFiles();
|
||||
// const allFiles: { name: string; absPath: string; content: string }[] =
|
||||
// await Promise.all(
|
||||
// openFiles.map(async (filepath: string) => {
|
||||
// return {
|
||||
// name: getBasename(filepath),
|
||||
// absPath: filepath,
|
||||
// content: `${await ide.readFile(filepath)}`,
|
||||
// };
|
||||
// }),
|
||||
// );
|
||||
// const outlines = await getOutlines(
|
||||
// allFiles
|
||||
// .filter((file) => file.content.length > 0)
|
||||
// .map((file) => {
|
||||
// return {
|
||||
// relPath: file.name,
|
||||
// code: file.content,
|
||||
// };
|
||||
// })
|
||||
// );
|
||||
// return [
|
||||
// {
|
||||
// content: outlines ? outlines : "",
|
||||
// name: "Code Outline",
|
||||
// description: "Definition lines only (from open files)",
|
||||
// },
|
||||
// ];
|
||||
return [];
|
||||
}
|
||||
|
||||
async load(): Promise<void> {}
|
||||
}
|
||||
|
||||
export default CodeOutlineContextProvider;
|
||||
|
|
@ -18,6 +18,10 @@ class DatabaseContextProvider extends BaseContextProvider {
|
|||
renderInlineAs: "",
|
||||
};
|
||||
|
||||
get deprecationMessage() {
|
||||
return "The database context provider is deprecated and may be removed in a later version. Please consider using a database MCP server like postgres-mcp (https://hub.continue.dev/anthropic/postgres-mcp) instead.";
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
|
|
|
|||
|
|
@ -3,8 +3,8 @@ import {
|
|||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
FetchFunction,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../../index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
|
|
@ -43,6 +43,10 @@ class DiscordContextProvider extends BaseContextProvider {
|
|||
return `${this.baseUrl}${path}`;
|
||||
}
|
||||
|
||||
get deprecationMessage() {
|
||||
return "The Discord context provider is now deprecated and may be removed in a later version. Please consider using the Discord MCP (hub.docker.com/r/mcp/mcp-discord) instead.";
|
||||
}
|
||||
|
||||
async fetchMessages(
|
||||
channelId: string,
|
||||
fetch: FetchFunction,
|
||||
|
|
|
|||
|
|
@ -44,6 +44,10 @@ class GitCommitContextProvider extends BaseContextProvider {
|
|||
type: "submenu",
|
||||
};
|
||||
|
||||
get deprecationMessage() {
|
||||
return "The git commits context provider is now deprecated and may be removed in a later version. Please consider using the Git MCP (https://hub.continue.dev/docker/mcp-git) instead.";
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
|
|
|
|||
|
|
@ -15,6 +15,10 @@ class GitHubIssuesContextProvider extends BaseContextProvider {
|
|||
type: "submenu",
|
||||
};
|
||||
|
||||
get deprecationMessage() {
|
||||
return "The GitHub issues context provider is now deprecated and will be removed in a later version. Please consider using the GitHub MCP server (https://hub.continue.dev/anthropic/github-mcp) instead.";
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
|
|
|
|||
|
|
@ -76,6 +76,10 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
|
|||
type: "normal",
|
||||
};
|
||||
|
||||
get deprecationMessage() {
|
||||
return "The Gitlab Merge Request context provider is now deprecated and will be removed in a later version. Please consider using the GitLab MCP (https://hub.continue.dev/docker/mcp-gitlab) instead.";
|
||||
}
|
||||
|
||||
private async getApi(): Promise<AxiosInstance> {
|
||||
const { default: Axios } = await import("axios");
|
||||
|
||||
|
|
|
|||
|
|
@ -20,6 +20,10 @@ class GoogleContextProvider extends BaseContextProvider {
|
|||
this._serperApiKey = options.serperApiKey;
|
||||
}
|
||||
|
||||
get deprecationMessage() {
|
||||
return "The Google context provider is now deprecated and will be removed in a later version. Please consider using github.com/jae-jae/g-search-mcp instead.";
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
|
|
|
|||
|
|
@ -17,6 +17,10 @@ class GreptileContextProvider extends BaseContextProvider {
|
|||
type: "query",
|
||||
};
|
||||
|
||||
get deprecationMessage() {
|
||||
return "The Greptile context provider is now deprecated and will be removed in a later version. Please consider viewing their docs at greptile.com/docs/code-review-bot/auto-resolve-with-mcp for resolving greptile queries.";
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
|
|
|
|||
|
|
@ -17,6 +17,10 @@ class JiraIssuesContextProvider extends BaseContextProvider {
|
|||
type: "submenu",
|
||||
};
|
||||
|
||||
get deprecationMessage() {
|
||||
return "The Jira issues context provider is now deprecated and will be removed in a later version. Please consider using the official Atlassian MCP server atlassian.com/platform/remote-mcp-server.";
|
||||
}
|
||||
|
||||
private getApi() {
|
||||
return new JiraClient({
|
||||
domain: this.options.domain,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import { BaseContextProvider } from "../";
|
||||
import { ContextProviderName } from "../../";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
|
||||
import ClipboardContextProvider from "./ClipboardContextProvider";
|
||||
import CodebaseContextProvider from "./CodebaseContextProvider";
|
||||
|
|
@ -80,10 +79,5 @@ export function contextProviderClassFromName(
|
|||
): typeof BaseContextProvider | undefined {
|
||||
const provider = Providers.find((cls) => cls.description.title === name);
|
||||
|
||||
void Telemetry.capture("context_provider_load", {
|
||||
providerName: name,
|
||||
found: !!provider, // also capture those which user expected to be present
|
||||
});
|
||||
|
||||
return provider;
|
||||
}
|
||||
|
|
|
|||
37
core/core.ts
37
core/core.ts
|
|
@ -668,6 +668,8 @@ export class Core {
|
|||
return queue.dequeueProcessed() || null;
|
||||
});
|
||||
|
||||
// NOTE: This is not used unless prefetch is used.
|
||||
// At this point this is not used because I opted to rely on the model to return multiple diffs than to use prefetching.
|
||||
on("nextEdit/queue/processOne", async (msg) => {
|
||||
console.log("nextEdit/queue/processOne");
|
||||
const { ctx, recentlyVisitedRanges, recentlyEditedRanges } = msg.data;
|
||||
|
|
@ -966,6 +968,10 @@ export class Core {
|
|||
on("docs/getDetails", async (msg) => {
|
||||
return await this.docsService.getDetails(msg.data.startUrl);
|
||||
});
|
||||
on("docs/getIndexedPages", async (msg) => {
|
||||
const pages = await this.docsService.getIndexedPages(msg.data.startUrl);
|
||||
return Array.from(pages);
|
||||
});
|
||||
|
||||
on("didChangeSelectedProfile", async (msg) => {
|
||||
if (msg.data.id) {
|
||||
|
|
@ -1003,6 +1009,37 @@ export class Core {
|
|||
this.handleToolCall(toolCall),
|
||||
);
|
||||
|
||||
on(
|
||||
"tools/evaluatePolicy",
|
||||
async ({ data: { toolName, basePolicy, args } }) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("Config not loaded");
|
||||
}
|
||||
|
||||
const tool = config.tools.find((t) => t.function.name === toolName);
|
||||
if (!tool) {
|
||||
// Tool not found, return base policy
|
||||
return { policy: basePolicy };
|
||||
}
|
||||
|
||||
// Extract display value for specific tools
|
||||
let displayValue: string | undefined;
|
||||
if (toolName === "runTerminalCommand" && args.command) {
|
||||
displayValue = args.command as string;
|
||||
}
|
||||
|
||||
// If tool has evaluateToolCallPolicy function, use it
|
||||
if (tool.evaluateToolCallPolicy) {
|
||||
const evaluatedPolicy = tool.evaluateToolCallPolicy(basePolicy, args);
|
||||
return { policy: evaluatedPolicy, displayValue };
|
||||
}
|
||||
|
||||
// Otherwise return base policy unchanged
|
||||
return { policy: basePolicy, displayValue };
|
||||
},
|
||||
);
|
||||
|
||||
on("isItemTooBig", async ({ data: { item } }) => {
|
||||
return this.isItemTooBig(item);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ const INFINITE_STREAM_SAFETY = 0.9;
|
|||
const DUD_PROMPT_LOG: PromptLog = {
|
||||
modelTitle: "",
|
||||
modelProvider: "",
|
||||
completionOptions: { model: "" },
|
||||
prompt: "",
|
||||
completion: "",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,618 +0,0 @@
|
|||
import { findSearchMatch, SearchMatchResult } from "./findSearchMatch";
|
||||
|
||||
/**
|
||||
* Helper function to perform a replacement using the match result
|
||||
* This simulates what the actual replacement tool would do
|
||||
*/
|
||||
function performReplacement(
|
||||
fileContent: string,
|
||||
match: SearchMatchResult,
|
||||
replacement: string,
|
||||
): string {
|
||||
return (
|
||||
fileContent.substring(0, match.startIndex) +
|
||||
replacement +
|
||||
fileContent.substring(match.endIndex)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to test a specific strategy by crafting inputs that
|
||||
* will fail all previous strategies
|
||||
*/
|
||||
function testSpecificStrategy(
|
||||
fileContent: string,
|
||||
searchContent: string,
|
||||
expectedStrategy: string,
|
||||
): SearchMatchResult | null {
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
if (result && result.strategyName !== expectedStrategy) {
|
||||
throw new Error(
|
||||
`Expected strategy ${expectedStrategy} but got ${result.strategyName}`,
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to verify that a match result correctly identifies
|
||||
* the intended content and replacement works properly
|
||||
*/
|
||||
function verifyMatchAndReplacement(
|
||||
fileContent: string,
|
||||
searchContent: string,
|
||||
expectedMatchedText: string,
|
||||
replacementText: string,
|
||||
expectedResult: string,
|
||||
): void {
|
||||
const match = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
if (!match) {
|
||||
throw new Error("No match found");
|
||||
}
|
||||
|
||||
// Verify the match captures the expected text
|
||||
const actualMatchedText = fileContent.substring(
|
||||
match.startIndex,
|
||||
match.endIndex,
|
||||
);
|
||||
expect(actualMatchedText).toBe(expectedMatchedText);
|
||||
|
||||
// Verify replacement works correctly
|
||||
const result = performReplacement(fileContent, match, replacementText);
|
||||
expect(result).toBe(expectedResult);
|
||||
}
|
||||
|
||||
describe("Strategy-specific tests", () => {
|
||||
describe("exactMatch strategy", () => {
|
||||
it("should handle exact match at various positions", () => {
|
||||
const testCases = [
|
||||
{
|
||||
name: "at start",
|
||||
fileContent: "abc def ghi",
|
||||
searchContent: "abc",
|
||||
expectedStart: 0,
|
||||
expectedEnd: 3,
|
||||
},
|
||||
{
|
||||
name: "in middle",
|
||||
fileContent: "abc def ghi",
|
||||
searchContent: "def",
|
||||
expectedStart: 4,
|
||||
expectedEnd: 7,
|
||||
},
|
||||
{
|
||||
name: "at end",
|
||||
fileContent: "abc def ghi",
|
||||
searchContent: "ghi",
|
||||
expectedStart: 8,
|
||||
expectedEnd: 11,
|
||||
},
|
||||
{
|
||||
name: "entire content",
|
||||
fileContent: "abc def ghi",
|
||||
searchContent: "abc def ghi",
|
||||
expectedStart: 0,
|
||||
expectedEnd: 11,
|
||||
},
|
||||
];
|
||||
|
||||
testCases.forEach(
|
||||
({ name, fileContent, searchContent, expectedStart, expectedEnd }) => {
|
||||
const result = testSpecificStrategy(
|
||||
fileContent,
|
||||
searchContent,
|
||||
"exactMatch",
|
||||
);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.startIndex).toBe(expectedStart);
|
||||
expect(result!.endIndex).toBe(expectedEnd);
|
||||
|
||||
// Verify the matched content
|
||||
const matchedContent = fileContent.substring(
|
||||
result!.startIndex,
|
||||
result!.endIndex,
|
||||
);
|
||||
expect(matchedContent).toBe(searchContent);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle multiline exact matches", () => {
|
||||
const fileContent = `line1
|
||||
line2
|
||||
line3
|
||||
line4`;
|
||||
const searchContent = `line2
|
||||
line3`;
|
||||
|
||||
const result = testSpecificStrategy(
|
||||
fileContent,
|
||||
searchContent,
|
||||
"exactMatch",
|
||||
);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.startIndex).toBe(6); // After "line1\n"
|
||||
expect(result!.endIndex).toBe(17); // End of "line3"
|
||||
|
||||
const matchedContent = fileContent.substring(
|
||||
result!.startIndex,
|
||||
result!.endIndex,
|
||||
);
|
||||
expect(matchedContent).toBe(searchContent);
|
||||
});
|
||||
|
||||
it("should handle content with special characters", () => {
|
||||
const fileContent = `const regex = /[a-z]+/gi;
|
||||
const str = "Hello, World!";
|
||||
const result = str.match(regex);`;
|
||||
const searchContent = `const str = "Hello, World!";`;
|
||||
|
||||
const result = testSpecificStrategy(
|
||||
fileContent,
|
||||
searchContent,
|
||||
"exactMatch",
|
||||
);
|
||||
expect(result).not.toBeNull();
|
||||
|
||||
const matchedContent = fileContent.substring(
|
||||
result!.startIndex,
|
||||
result!.endIndex,
|
||||
);
|
||||
expect(matchedContent).toBe(searchContent);
|
||||
});
|
||||
|
||||
it("should verify replacement works correctly for exact matches", () => {
|
||||
verifyMatchAndReplacement(
|
||||
"const a = 1;\nconst b = 2;\nconst c = 3;",
|
||||
"const b = 2;",
|
||||
"const b = 2;",
|
||||
"const b = 42;",
|
||||
"const a = 1;\nconst b = 42;\nconst c = 3;",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle Windows-style line endings", () => {
|
||||
const fileContent = "line1\r\nline2\r\nline3";
|
||||
const searchContent = "line2";
|
||||
|
||||
const result = testSpecificStrategy(
|
||||
fileContent,
|
||||
searchContent,
|
||||
"exactMatch",
|
||||
);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.startIndex).toBe(7); // After "line1\r\n"
|
||||
expect(result!.endIndex).toBe(12); // End of "line2"
|
||||
});
|
||||
|
||||
it("should handle mixed line endings", () => {
|
||||
const fileContent = "line1\nline2\r\nline3\rline4";
|
||||
const searchContent = "line2\r\nline3";
|
||||
|
||||
const result = testSpecificStrategy(
|
||||
fileContent,
|
||||
searchContent,
|
||||
"exactMatch",
|
||||
);
|
||||
expect(result).not.toBeNull();
|
||||
|
||||
const matchedContent = fileContent.substring(
|
||||
result!.startIndex,
|
||||
result!.endIndex,
|
||||
);
|
||||
expect(matchedContent).toBe(searchContent);
|
||||
});
|
||||
});
|
||||
|
||||
describe("trimmedMatch strategy", () => {
|
||||
it("should match when only whitespace differs at edges", () => {
|
||||
const testCases = [
|
||||
{
|
||||
name: "leading spaces",
|
||||
fileContent: "abc\n def\nghi",
|
||||
searchContent: " def",
|
||||
trimmedSearch: "def",
|
||||
},
|
||||
{
|
||||
name: "trailing spaces",
|
||||
fileContent: "abc\ndef \nghi",
|
||||
searchContent: "def ",
|
||||
trimmedSearch: "def",
|
||||
},
|
||||
{
|
||||
name: "both leading and trailing",
|
||||
fileContent: "abc\n def \nghi",
|
||||
searchContent: " def ",
|
||||
trimmedSearch: "def",
|
||||
},
|
||||
{
|
||||
name: "tabs and spaces",
|
||||
fileContent: "abc\n\t def \t\nghi",
|
||||
searchContent: "\t def \t",
|
||||
trimmedSearch: "def",
|
||||
},
|
||||
];
|
||||
|
||||
testCases.forEach(
|
||||
({ name, fileContent, searchContent, trimmedSearch }) => {
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
expect(result).not.toBeNull();
|
||||
|
||||
// For cases where exact match exists, it should be preferred
|
||||
if (fileContent.indexOf(searchContent) !== -1) {
|
||||
expect(result!.strategyName).toBe("exactMatch");
|
||||
const matchedContent = fileContent.substring(
|
||||
result!.startIndex,
|
||||
result!.endIndex,
|
||||
);
|
||||
expect(matchedContent).toBe(searchContent);
|
||||
} else {
|
||||
expect(result!.strategyName).toBe("trimmedMatch");
|
||||
// The match should find the trimmed content with surrounding whitespace
|
||||
const matchedContent = fileContent.substring(
|
||||
result!.startIndex,
|
||||
result!.endIndex,
|
||||
);
|
||||
expect(matchedContent).toContain(trimmedSearch);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle multiline content with edge whitespace", () => {
|
||||
const fileContent = `function test() {
|
||||
const x = 1;
|
||||
const y = 2;
|
||||
}`;
|
||||
const searchContent = ` const x = 1;
|
||||
const y = 2; `;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
expect(result).not.toBeNull();
|
||||
// Since there's no exact match (trailing spaces don't exist), trimmedMatch should be used
|
||||
expect(result!.strategyName).toBe("trimmedMatch");
|
||||
});
|
||||
|
||||
it("should verify replacement with trimmed matches", () => {
|
||||
const fileContent = "start\n targetContent \nend";
|
||||
const searchContent = " targetContent ";
|
||||
const replacement = "newContent";
|
||||
|
||||
const match = findSearchMatch(fileContent, searchContent);
|
||||
expect(match).not.toBeNull();
|
||||
expect(match!.strategyName).toBe("trimmedMatch");
|
||||
|
||||
const result = performReplacement(fileContent, match!, replacement);
|
||||
expect(result).toBe("start\nnewContent\nend");
|
||||
});
|
||||
|
||||
it("should handle edge case with only whitespace", () => {
|
||||
const fileContent = " \n \n ";
|
||||
const searchContent = " \n ";
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
expect(result).not.toBeNull();
|
||||
// Should find exact match since the content matches exactly
|
||||
expect(result!.strategyName).toBe("exactMatch");
|
||||
});
|
||||
});
|
||||
|
||||
describe("whitespaceIgnoredMatch strategy", () => {
|
||||
it("should match content with different indentation", () => {
|
||||
const fileContent = `function test() {
|
||||
const x = 1;
|
||||
if (x > 0) {
|
||||
return true;
|
||||
}
|
||||
}`;
|
||||
const searchContent = `const x=1;
|
||||
if(x>0){
|
||||
return true;
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
|
||||
|
||||
// Verify the match covers the intended code block
|
||||
const matchedContent = fileContent.substring(
|
||||
result!.startIndex,
|
||||
result!.endIndex,
|
||||
);
|
||||
expect(matchedContent).toContain("const x = 1");
|
||||
expect(matchedContent).toContain("return true");
|
||||
});
|
||||
|
||||
it("should handle complex whitespace variations", () => {
|
||||
const testCases = [
|
||||
{
|
||||
name: "spaces vs tabs",
|
||||
fileContent: "if\t(\tcondition\t)\t{\n\treturn\ttrue;\n}",
|
||||
searchContent: "if (condition) { return true; }",
|
||||
},
|
||||
{
|
||||
name: "multiple spaces collapsed",
|
||||
fileContent: "const result = calculate( x , y );",
|
||||
searchContent: "const result=calculate(x,y);",
|
||||
},
|
||||
{
|
||||
name: "newlines removed",
|
||||
fileContent: "function\ntest\n(\n)\n{\nreturn\n1\n;\n}",
|
||||
searchContent: "function test(){return 1;}",
|
||||
},
|
||||
];
|
||||
|
||||
testCases.forEach(({ name, fileContent, searchContent }) => {
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
|
||||
|
||||
// Verify the entire content is matched
|
||||
const matchedContent = fileContent.substring(
|
||||
result!.startIndex,
|
||||
result!.endIndex,
|
||||
);
|
||||
expect(matchedContent.replace(/\s/g, "")).toBe(
|
||||
searchContent.replace(/\s/g, ""),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle partial matches with whitespace differences", () => {
|
||||
const fileContent = `class Example {
|
||||
constructor(name) {
|
||||
this.name = name;
|
||||
this.items = [];
|
||||
}
|
||||
|
||||
addItem(item) {
|
||||
this.items.push(item);
|
||||
}
|
||||
}`;
|
||||
const searchContent = `constructor(name){this.name=name;this.items=[];}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
|
||||
|
||||
// The match should cover the constructor method
|
||||
const matchedContent = fileContent.substring(
|
||||
result!.startIndex,
|
||||
result!.endIndex,
|
||||
);
|
||||
expect(matchedContent).toContain("constructor");
|
||||
expect(matchedContent).toContain("this.items = []");
|
||||
});
|
||||
|
||||
it("should verify replacement with whitespace-ignored matches", () => {
|
||||
const fileContent = `function calculate ( a , b ) {
|
||||
return a + b ;
|
||||
}`;
|
||||
const searchContent = `function calculate(a,b){return a+b;}`;
|
||||
const replacement = `function calculate(x, y) {
|
||||
return x + y;
|
||||
}`;
|
||||
|
||||
const match = findSearchMatch(fileContent, searchContent);
|
||||
expect(match).not.toBeNull();
|
||||
expect(match!.strategyName).toBe("whitespaceIgnoredMatch");
|
||||
|
||||
const result = performReplacement(fileContent, match!, replacement);
|
||||
expect(result).toBe(replacement);
|
||||
});
|
||||
|
||||
it("should handle edge cases with empty content after whitespace removal", () => {
|
||||
const fileContent = " \n\t\r\n ";
|
||||
const searchContent = " \n ";
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
// Since search content doesn't exist in file but trims to empty, should return emptySearch
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.strategyName).toBe("emptySearch");
|
||||
});
|
||||
|
||||
it("should match correctly when multiple potential matches exist", () => {
|
||||
const fileContent = `const a=1;
|
||||
const a = 1 ;
|
||||
const a = 1;`;
|
||||
const searchContent = "const a = 1;";
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
expect(result).not.toBeNull();
|
||||
// Should find the exact match first (third occurrence)
|
||||
expect(result!.strategyName).toBe("exactMatch");
|
||||
expect(result!.startIndex).toBe(33); // After first two lines
|
||||
});
|
||||
});
|
||||
|
||||
describe("Empty search content", () => {
|
||||
it("should always return position 0 for empty search", () => {
|
||||
const testCases = [
|
||||
{ fileContent: "some content" },
|
||||
{ fileContent: "" },
|
||||
{ fileContent: "line1\nline2\nline3" },
|
||||
{ fileContent: " spaces " },
|
||||
];
|
||||
|
||||
testCases.forEach(({ fileContent }) => {
|
||||
const result = findSearchMatch(fileContent, "");
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: 0,
|
||||
strategyName: "emptySearch",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("should treat whitespace-only search as empty", () => {
|
||||
const searchVariants = [" ", "\n\n", "\t\t", " \n\t "];
|
||||
|
||||
searchVariants.forEach((searchContent) => {
|
||||
const result = findSearchMatch("test content", searchContent);
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: 0,
|
||||
strategyName: "emptySearch",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Strategy precedence", () => {
|
||||
it("should always prefer exact match over other strategies", () => {
|
||||
const fileContent = `exact match
|
||||
exact match with spaces
|
||||
exactmatch`;
|
||||
|
||||
// This should find exact match even though fuzzy would also work
|
||||
const result = findSearchMatch(fileContent, "exact match");
|
||||
expect(result!.strategyName).toBe("exactMatch");
|
||||
expect(result!.startIndex).toBe(0);
|
||||
});
|
||||
|
||||
it("should prefer trimmed match over whitespace-ignored", () => {
|
||||
const fileContent = " content ";
|
||||
const searchContent = " content ";
|
||||
|
||||
// Should find exact match
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
expect(result!.strategyName).toBe("exactMatch");
|
||||
});
|
||||
|
||||
it("should prefer whitespace-ignored over fuzzy", () => {
|
||||
const fileContent = "const x = 1;";
|
||||
const searchContent = "const x=1;";
|
||||
|
||||
// Should use whitespace-ignored, not fuzzy
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Replacement verification tests", () => {
|
||||
it("should correctly replace content found by each strategy", () => {
|
||||
const testCases = [
|
||||
{
|
||||
name: "exact match replacement",
|
||||
fileContent: "const a = 1;\nconst b = 2;\nconst c = 3;",
|
||||
searchContent: "const b = 2;",
|
||||
replacement: "const b = 42;",
|
||||
expectedResult: "const a = 1;\nconst b = 42;\nconst c = 3;",
|
||||
expectedStrategy: "exactMatch",
|
||||
},
|
||||
{
|
||||
name: "trimmed match replacement",
|
||||
fileContent: "start\n target \nend",
|
||||
searchContent: " target ",
|
||||
replacement: "replaced",
|
||||
expectedResult: "start\nreplaced\nend",
|
||||
expectedStrategy: "trimmedMatch",
|
||||
},
|
||||
{
|
||||
name: "whitespace-ignored replacement",
|
||||
fileContent: "if ( x > 0 ) { return true; }",
|
||||
searchContent: "if(x>0){return true;}",
|
||||
replacement: "if (x > 0) { return false; }",
|
||||
expectedResult: "if (x > 0) { return false; }",
|
||||
expectedStrategy: "whitespaceIgnoredMatch",
|
||||
},
|
||||
];
|
||||
|
||||
testCases.forEach(
|
||||
({
|
||||
name,
|
||||
fileContent,
|
||||
searchContent,
|
||||
replacement,
|
||||
expectedResult,
|
||||
expectedStrategy,
|
||||
}) => {
|
||||
const match = findSearchMatch(fileContent, searchContent);
|
||||
expect(match).not.toBeNull();
|
||||
expect(match!.strategyName).toBe(expectedStrategy);
|
||||
|
||||
const result = performReplacement(fileContent, match!, replacement);
|
||||
expect(result).toBe(expectedResult);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle edge cases in replacement", () => {
|
||||
// Empty replacement
|
||||
verifyMatchAndReplacement(
|
||||
"before target after",
|
||||
"target",
|
||||
"target",
|
||||
"",
|
||||
"before after",
|
||||
);
|
||||
|
||||
// Replacement longer than original
|
||||
verifyMatchAndReplacement(
|
||||
"short",
|
||||
"short",
|
||||
"short",
|
||||
"much longer replacement",
|
||||
"much longer replacement",
|
||||
);
|
||||
|
||||
// Multiline replacement
|
||||
verifyMatchAndReplacement(
|
||||
"single line",
|
||||
"single",
|
||||
"single",
|
||||
"multi\nline\nreplacement",
|
||||
"multi\nline\nreplacement line",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Performance and edge cases", () => {
|
||||
it("should handle very long content efficiently", () => {
|
||||
const longContent = "x".repeat(10000) + "target" + "y".repeat(10000);
|
||||
const result = findSearchMatch(longContent, "target");
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.startIndex).toBe(10000);
|
||||
expect(result!.endIndex).toBe(10006);
|
||||
});
|
||||
|
||||
it("should handle unicode and special characters", () => {
|
||||
const testCases = [
|
||||
{
|
||||
fileContent: "const emoji = '🚀🌟🎉';",
|
||||
searchContent: "🚀🌟🎉",
|
||||
},
|
||||
{
|
||||
fileContent: "const chinese = '你好世界';",
|
||||
searchContent: "你好世界",
|
||||
},
|
||||
{
|
||||
fileContent: "const regex = /\\d+/g;",
|
||||
searchContent: "/\\d+/g",
|
||||
},
|
||||
];
|
||||
|
||||
testCases.forEach(({ fileContent, searchContent }) => {
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
expect(result).not.toBeNull();
|
||||
|
||||
const matchedContent = fileContent.substring(
|
||||
result!.startIndex,
|
||||
result!.endIndex,
|
||||
);
|
||||
expect(matchedContent).toContain(searchContent);
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle null bytes and control characters", () => {
|
||||
const fileContent = "before\x00null\x01byte\x02after";
|
||||
const searchContent = "\x00null\x01byte\x02";
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.strategyName).toBe("exactMatch");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,587 +0,0 @@
|
|||
import { findSearchMatch } from "./findSearchMatch";
|
||||
|
||||
describe("Exact matches", () => {
|
||||
it("should find exact match at the beginning of file", () => {
|
||||
const fileContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
const searchContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: fileContent.length,
|
||||
strategyName: "exactMatch",
|
||||
});
|
||||
});
|
||||
|
||||
it("should find exact match in the middle of file", () => {
|
||||
const fileContent = `const a = 1;
|
||||
function hello() {
|
||||
console.log("world");
|
||||
}
|
||||
const b = 2;`;
|
||||
const searchContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 13, // After "const a = 1;\n"
|
||||
endIndex: 13 + searchContent.length,
|
||||
strategyName: "exactMatch",
|
||||
});
|
||||
});
|
||||
|
||||
it("should find exact match at the end of file", () => {
|
||||
const fileContent = `const a = 1;
|
||||
function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
const searchContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 13, // After "const a = 1;\n"
|
||||
endIndex: fileContent.length,
|
||||
strategyName: "exactMatch",
|
||||
});
|
||||
});
|
||||
|
||||
it("should find exact match with single line", () => {
|
||||
const fileContent = `const a = 1;
|
||||
const b = 2;
|
||||
const c = 3;`;
|
||||
const searchContent = `const b = 2;`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 13, // After "const a = 1;\n"
|
||||
endIndex: 13 + searchContent.length,
|
||||
strategyName: "exactMatch",
|
||||
});
|
||||
});
|
||||
|
||||
it("should find exact match with whitespace preserved", () => {
|
||||
const fileContent = `function test() {
|
||||
const x = 1;
|
||||
const y = 2;
|
||||
}`;
|
||||
const searchContent = ` const x = 1;
|
||||
const y = 2;`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
// The actual indexOf result is 18, not 17
|
||||
expect(result).toEqual({
|
||||
startIndex: 18,
|
||||
endIndex: 18 + searchContent.length,
|
||||
strategyName: "exactMatch",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Trimmed matches", () => {
|
||||
it("should find trimmed match when exact match fails due to leading newlines", () => {
|
||||
const fileContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
const searchContent = `\n\nfunction hello() {
|
||||
console.log("world");
|
||||
}\n\n`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: fileContent.length, // Uses trimmed length
|
||||
strategyName: "trimmedMatch",
|
||||
});
|
||||
});
|
||||
|
||||
it("should find trimmed match when exact match fails due to trailing newlines", () => {
|
||||
const fileContent = `const a = 1;
|
||||
function hello() {
|
||||
return "world";
|
||||
}
|
||||
const b = 2;`;
|
||||
const searchContent = `\nfunction hello() {
|
||||
return "world";
|
||||
}\n`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
// The function finds the exact match first (at index 12), not the trimmed match
|
||||
expect(result).toEqual({
|
||||
startIndex: 12,
|
||||
endIndex: 12 + searchContent.length,
|
||||
strategyName: "exactMatch",
|
||||
});
|
||||
});
|
||||
|
||||
it("should find trimmed match for single line with extra whitespace", () => {
|
||||
const fileContent = `const a = 1;
|
||||
const b = 2;
|
||||
const c = 3;`;
|
||||
const searchContent = `\n const b = 2; \n`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
const trimmedSearchContent = searchContent.trim();
|
||||
const expectedStart = fileContent.indexOf(trimmedSearchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: expectedStart,
|
||||
endIndex: expectedStart + trimmedSearchContent.length,
|
||||
strategyName: "trimmedMatch",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Empty search content", () => {
|
||||
it("should match at beginning for empty search content", () => {
|
||||
const fileContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
const searchContent = "";
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: 0,
|
||||
strategyName: "emptySearch",
|
||||
});
|
||||
});
|
||||
|
||||
it("should match at beginning for whitespace-only search content", () => {
|
||||
const fileContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
const searchContent = "\n\n \t \n";
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: 0,
|
||||
strategyName: "emptySearch",
|
||||
});
|
||||
});
|
||||
|
||||
it("should match at beginning for empty file and empty search", () => {
|
||||
const fileContent = "";
|
||||
const searchContent = "";
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: 0,
|
||||
strategyName: "emptySearch",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Edge cases", () => {
|
||||
it("should handle empty file with non-empty search", () => {
|
||||
const fileContent = "";
|
||||
const searchContent = "function hello() {}";
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should handle very large content", () => {
|
||||
const repeatedLine = "const x = 1;\n";
|
||||
const fileContent =
|
||||
repeatedLine.repeat(1000) +
|
||||
"const target = 2;\n" +
|
||||
repeatedLine.repeat(1000);
|
||||
const searchContent = "const target = 2;";
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
const expectedStart = repeatedLine.length * 1000;
|
||||
expect(result).toEqual({
|
||||
startIndex: expectedStart,
|
||||
endIndex: expectedStart + searchContent.length,
|
||||
strategyName: "exactMatch",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle special characters and symbols", () => {
|
||||
const fileContent = `const regex = /[a-zA-Z]+/g;
|
||||
const symbols = !@#$%^&*();
|
||||
const unicode = "🚀 Hello 世界";`;
|
||||
const searchContent = `const symbols = !@#$%^&*();`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
const expectedStart = fileContent.indexOf(searchContent);
|
||||
expect(result).toEqual({
|
||||
startIndex: expectedStart,
|
||||
endIndex: expectedStart + searchContent.length,
|
||||
strategyName: "exactMatch",
|
||||
});
|
||||
});
|
||||
|
||||
it("should prefer exact match over trimmed match", () => {
|
||||
const fileContent = `function test() {
|
||||
const x = 1;
|
||||
}
|
||||
|
||||
function test() {
|
||||
const x = 1;
|
||||
}`;
|
||||
const searchContent = `function test() {
|
||||
const x = 1;
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
// Should find the first exact match, not a trimmed version
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: searchContent.length,
|
||||
strategyName: "exactMatch",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle multiple occurrences and return first match", () => {
|
||||
const fileContent = `const a = 1;
|
||||
const b = 2;
|
||||
const a = 1;`;
|
||||
const searchContent = `const a = 1;`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: searchContent.length,
|
||||
strategyName: "exactMatch",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Whitespace-ignored matches", () => {
|
||||
it("should match code with different indentation", () => {
|
||||
const fileContent = `function example() {
|
||||
const x = 1;
|
||||
const y = 2;
|
||||
return x + y;
|
||||
}`;
|
||||
const searchContent = `const x=1;
|
||||
const y=2;
|
||||
return x+y;`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.startIndex).toBe(20); // After "function example() {\n"
|
||||
expect(result!.endIndex).toBe(72); // End of " return x + y;"
|
||||
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
|
||||
|
||||
// Verify the matched content contains the original whitespace
|
||||
const matchedContent = fileContent.substring(
|
||||
result!.startIndex,
|
||||
result!.endIndex,
|
||||
);
|
||||
expect(matchedContent).toBe(`
|
||||
const x = 1;
|
||||
const y = 2;
|
||||
return x + y;`);
|
||||
});
|
||||
|
||||
it("should match single line with different spacing", () => {
|
||||
const fileContent = `const a = 1;
|
||||
const b = 2;
|
||||
const c = 3;`;
|
||||
const searchContent = `const b=2;`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.startIndex).toBe(12); // After "const a = 1;"
|
||||
expect(result!.endIndex).toBe(32); // End of "const b = 2;"
|
||||
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
|
||||
|
||||
// Verify the matched content preserves original spacing
|
||||
const matchedContent = fileContent.substring(
|
||||
result!.startIndex,
|
||||
result!.endIndex,
|
||||
);
|
||||
expect(matchedContent).toBe(`
|
||||
const b = 2;`);
|
||||
});
|
||||
|
||||
it("should match with tabs vs spaces", () => {
|
||||
const fileContent = `function test() {
|
||||
\tif (condition) {
|
||||
\t\treturn true;
|
||||
\t}
|
||||
}`;
|
||||
const searchContent = `if (condition) {
|
||||
return true;
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.startIndex).toBe(17); // After "function test() {"
|
||||
expect(result!.endIndex).toBe(53); // End of "\t}"
|
||||
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
|
||||
|
||||
// Verify the matched content preserves original tabs
|
||||
const matchedContent = fileContent.substring(
|
||||
result!.startIndex,
|
||||
result!.endIndex,
|
||||
);
|
||||
expect(matchedContent).toBe(`
|
||||
\tif (condition) {
|
||||
\t\treturn true;
|
||||
\t}`);
|
||||
});
|
||||
|
||||
it("should match complex whitespace patterns", () => {
|
||||
const fileContent = `const obj = {
|
||||
key1 : 'value1',
|
||||
key2 : 'value2',
|
||||
key3 : 'value3'
|
||||
};`;
|
||||
const searchContent = `key1:'value1',
|
||||
key2:'value2',
|
||||
key3:'value3'`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.startIndex).toBe(13); // After "const obj = {"
|
||||
expect(result!.endIndex).toBe(83); // End of " key3 : 'value3'"
|
||||
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
|
||||
|
||||
// Verify the matched content preserves original formatting
|
||||
const matchedContent = fileContent.substring(
|
||||
result!.startIndex,
|
||||
result!.endIndex,
|
||||
);
|
||||
expect(matchedContent).toBe(`
|
||||
key1 : 'value1',
|
||||
key2 : 'value2',
|
||||
key3 : 'value3'`);
|
||||
});
|
||||
|
||||
it("should handle newlines and mixed whitespace", () => {
|
||||
const fileContent = `function calc() {
|
||||
|
||||
|
||||
let result = 0;
|
||||
|
||||
result += 5;
|
||||
|
||||
|
||||
return result;
|
||||
}`;
|
||||
const searchContent = `let result=0;result+=5;return result;`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.startIndex).toBe(17); // After "function calc() {\n\n"
|
||||
expect(result!.endIndex).toBe(78); // End of " return result;"
|
||||
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
|
||||
|
||||
// Verify the matched content includes all original whitespace
|
||||
const matchedContent = fileContent.substring(
|
||||
result!.startIndex,
|
||||
result!.endIndex,
|
||||
);
|
||||
expect(matchedContent).toBe(`
|
||||
|
||||
|
||||
let result = 0;
|
||||
|
||||
result += 5;
|
||||
|
||||
|
||||
return result;`);
|
||||
});
|
||||
|
||||
it("should prefer exact match over whitespace-ignored match", () => {
|
||||
const fileContent = `const x=1;
|
||||
const x = 1;`;
|
||||
const searchContent = `const x=1;`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
// Should find the exact match first (at index 0), not the whitespace-ignored match
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: 10,
|
||||
strategyName: "exactMatch",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle empty content after whitespace removal", () => {
|
||||
const fileContent = `function test() {
|
||||
return 1;
|
||||
}`;
|
||||
const searchContent = `\n\n \t \n`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
// Should match at beginning for empty/whitespace-only content
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: 0,
|
||||
strategyName: "emptySearch",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle complex code blocks with different formatting", () => {
|
||||
const fileContent = `class Example {
|
||||
constructor(name) {
|
||||
this.name = name;
|
||||
this.value = 0;
|
||||
}
|
||||
|
||||
getValue() {
|
||||
return this.value;
|
||||
}
|
||||
}`;
|
||||
const searchContent = `constructor(name){
|
||||
this.name=name;
|
||||
this.value=0;
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.startIndex).toBe(15); // After "class Example {"
|
||||
expect(result!.endIndex).toBe(95); // End of " }"
|
||||
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
|
||||
|
||||
// Verify the matched content preserves original formatting
|
||||
const matchedContent = fileContent.substring(
|
||||
result!.startIndex,
|
||||
result!.endIndex,
|
||||
);
|
||||
expect(matchedContent).toBe(`
|
||||
constructor(name) {
|
||||
this.name = name;
|
||||
this.value = 0;
|
||||
}`);
|
||||
});
|
||||
|
||||
it("should return null when no close match exists", () => {
|
||||
const fileContent = `function hello() {
|
||||
console.log("world");
|
||||
}`;
|
||||
const searchContent = `this has nothing to do with the other option`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should handle multiple potential matches and return first", () => {
|
||||
const fileContent = `const a=1;
|
||||
const a = 1;
|
||||
const a = 1;`;
|
||||
const searchContent = `const a=1;`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
// Should find the first exact match
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: 10,
|
||||
strategyName: "exactMatch",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Real-world scenarios", () => {
|
||||
it("should match typical function replacement", () => {
|
||||
const fileContent = `class Calculator {
|
||||
constructor() {
|
||||
this.result = 0;
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.result = 0;
|
||||
return this;
|
||||
}
|
||||
|
||||
add(value) {
|
||||
this.result += value;
|
||||
return this;
|
||||
}
|
||||
}`;
|
||||
const searchContent = ` reset() {
|
||||
this.result = 0;
|
||||
return this;
|
||||
}`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
const expectedStart = fileContent.indexOf(searchContent);
|
||||
expect(result).toEqual({
|
||||
startIndex: expectedStart,
|
||||
endIndex: expectedStart + searchContent.length,
|
||||
strategyName: "exactMatch",
|
||||
});
|
||||
});
|
||||
|
||||
it("should match import statement", () => {
|
||||
const fileContent = `import React from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import './App.css';
|
||||
|
||||
function App() {
|
||||
return <div>Hello World</div>;
|
||||
}`;
|
||||
const searchContent = `import { useState, useEffect } from 'react';`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
const expectedStart = fileContent.indexOf(searchContent);
|
||||
expect(result).toEqual({
|
||||
startIndex: expectedStart,
|
||||
endIndex: expectedStart + searchContent.length,
|
||||
strategyName: "exactMatch",
|
||||
});
|
||||
});
|
||||
|
||||
it("should match comment block", () => {
|
||||
const fileContent = `/**
|
||||
* This is a comment
|
||||
* that spans multiple lines
|
||||
*/
|
||||
function test() {
|
||||
// Single line comment
|
||||
return true;
|
||||
}`;
|
||||
const searchContent = `/**
|
||||
* This is a comment
|
||||
* that spans multiple lines
|
||||
*/`;
|
||||
|
||||
const result = findSearchMatch(fileContent, searchContent);
|
||||
|
||||
expect(result).toEqual({
|
||||
startIndex: 0,
|
||||
endIndex: searchContent.length,
|
||||
strategyName: "exactMatch",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,203 +0,0 @@
|
|||
/**
|
||||
* Represents a basic match result with start and end character positions
|
||||
*/
|
||||
interface BasicMatchResult {
|
||||
/** The starting character index of the match in the file content */
|
||||
startIndex: number;
|
||||
/** The ending character index of the match in the file content */
|
||||
endIndex: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a match result with start and end character positions
|
||||
*/
|
||||
export interface SearchMatchResult extends BasicMatchResult {
|
||||
/** The name of the strategy that successfully matched */
|
||||
strategyName: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strategy function type for finding matches
|
||||
*/
|
||||
type MatchStrategy = (
|
||||
fileContent: string,
|
||||
searchContent: string,
|
||||
) => BasicMatchResult | null;
|
||||
|
||||
/**
|
||||
* Exact string matching strategy
|
||||
*/
|
||||
function exactMatch(
|
||||
fileContent: string,
|
||||
searchContent: string,
|
||||
): BasicMatchResult | null {
|
||||
const exactIndex = fileContent.indexOf(searchContent);
|
||||
if (exactIndex !== -1) {
|
||||
return {
|
||||
startIndex: exactIndex,
|
||||
endIndex: exactIndex + searchContent.length,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trimmed content matching strategy
|
||||
* Finds content where the search content (when trimmed) matches content in the file,
|
||||
* and returns the span that includes the file content's whitespace
|
||||
*/
|
||||
function trimmedMatch(
|
||||
fileContent: string,
|
||||
searchContent: string,
|
||||
): BasicMatchResult | null {
|
||||
const trimmedSearchContent = searchContent.trim();
|
||||
|
||||
// Don't apply if search content has no leading/trailing whitespace to trim
|
||||
if (trimmedSearchContent === searchContent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Don't match if trimmed content is empty
|
||||
if (trimmedSearchContent === "") {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Look for the trimmed content in the file
|
||||
const trimmedContentIndex = fileContent.indexOf(trimmedSearchContent);
|
||||
if (trimmedContentIndex === -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Find the boundaries that include surrounding whitespace (but not newlines)
|
||||
// Look backwards for horizontal whitespace (spaces and tabs)
|
||||
let startIndex = trimmedContentIndex;
|
||||
while (startIndex > 0 && /[ \t]/.test(fileContent[startIndex - 1])) {
|
||||
startIndex--;
|
||||
}
|
||||
|
||||
// Look forwards for horizontal whitespace (spaces and tabs)
|
||||
let endIndex = trimmedContentIndex + trimmedSearchContent.length;
|
||||
while (endIndex < fileContent.length && /[ \t]/.test(fileContent[endIndex])) {
|
||||
endIndex++;
|
||||
}
|
||||
|
||||
return {
|
||||
startIndex,
|
||||
endIndex,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whitespace-ignored matching strategy
|
||||
* Removes all whitespace from both content and search, then finds the match
|
||||
*/
|
||||
function whitespaceIgnoredMatch(
|
||||
fileContent: string,
|
||||
searchContent: string,
|
||||
): BasicMatchResult | null {
|
||||
// Remove all whitespace (spaces, tabs, newlines, etc.)
|
||||
const strippedFileContent = fileContent.replace(/\s/g, "");
|
||||
const strippedSearchContent = searchContent.replace(/\s/g, "");
|
||||
|
||||
if (strippedSearchContent === "") {
|
||||
return null; // Empty search after stripping whitespace
|
||||
}
|
||||
|
||||
const strippedIndex = strippedFileContent.indexOf(strippedSearchContent);
|
||||
if (strippedIndex === -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Map the stripped position back to the original file content
|
||||
let originalStartIndex = 0;
|
||||
let strippedCharCount = 0;
|
||||
|
||||
// Find the original position by counting non-whitespace characters
|
||||
for (let i = 0; i < fileContent.length; i++) {
|
||||
if (strippedCharCount === strippedIndex) {
|
||||
originalStartIndex = i;
|
||||
break;
|
||||
}
|
||||
if (!/\s/.test(fileContent[i])) {
|
||||
strippedCharCount++;
|
||||
}
|
||||
}
|
||||
|
||||
// Find the end position by counting the length of the search content
|
||||
let originalEndIndex = originalStartIndex;
|
||||
let matchedChars = 0;
|
||||
|
||||
for (
|
||||
let i = originalStartIndex;
|
||||
i < fileContent.length && matchedChars < strippedSearchContent.length;
|
||||
i++
|
||||
) {
|
||||
if (!/\s/.test(fileContent[i])) {
|
||||
matchedChars++;
|
||||
}
|
||||
originalEndIndex = i + 1;
|
||||
}
|
||||
|
||||
return {
|
||||
startIndex: originalStartIndex,
|
||||
endIndex: originalEndIndex,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Ordered list of matching strategies to try with their names
|
||||
*/
|
||||
const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [
|
||||
{ strategy: exactMatch, name: "exactMatch" },
|
||||
{ strategy: trimmedMatch, name: "trimmedMatch" },
|
||||
{ strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" },
|
||||
];
|
||||
|
||||
/**
|
||||
* Find the exact match position for search content in file content.
|
||||
* Uses multiple matching strategies in order of preference.
|
||||
*
|
||||
* Matching Strategy:
|
||||
* 1. If search content is empty, matches at the beginning of file (position 0)
|
||||
* 2. Try each matching strategy in order until one succeeds
|
||||
*
|
||||
* @param fileContent - The complete content of the file to search in
|
||||
* @param searchContent - The content to search for
|
||||
* @param config - Configuration options for matching behavior
|
||||
* @returns Match result with character positions, or null if no match found
|
||||
*/
|
||||
export function findSearchMatch(
|
||||
fileContent: string,
|
||||
searchContent: string,
|
||||
): SearchMatchResult | null {
|
||||
// Handle truly empty search content
|
||||
if (searchContent === "") {
|
||||
return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
|
||||
}
|
||||
|
||||
// Handle whitespace-only search content that trims to empty
|
||||
const trimmedSearchContent = searchContent.trim();
|
||||
if (trimmedSearchContent === "") {
|
||||
// Check if the whitespace-only search content has an exact match first
|
||||
const exactIndex = fileContent.indexOf(searchContent);
|
||||
if (exactIndex !== -1) {
|
||||
return {
|
||||
startIndex: exactIndex,
|
||||
endIndex: exactIndex + searchContent.length,
|
||||
strategyName: "exactMatch",
|
||||
};
|
||||
}
|
||||
// If no exact match for whitespace-only content, treat as empty search
|
||||
return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
|
||||
}
|
||||
|
||||
// Try each matching strategy in order
|
||||
for (const { strategy, name } of matchingStrategies) {
|
||||
const result = strategy(fileContent, searchContent);
|
||||
if (result !== null) {
|
||||
return { ...result, strategyName: name };
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
|
@ -1,390 +0,0 @@
|
|||
import {
|
||||
parseAllSearchReplaceBlocks,
|
||||
parseSearchReplaceBlock,
|
||||
} from "./parseSearchReplaceBlock";
|
||||
|
||||
describe("parseSearchReplaceBlock", () => {
|
||||
describe("Complete blocks", () => {
|
||||
it("should parse a complete basic search/replace block", () => {
|
||||
const content = `------- SEARCH
|
||||
reset() {
|
||||
this.result = 0;
|
||||
return this;
|
||||
}
|
||||
=======
|
||||
// Resets the calculator result to 0 and returns the instance for method chaining
|
||||
reset() {
|
||||
this.result = 0;
|
||||
return this;
|
||||
}
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(true);
|
||||
expect(result.searchContent).toBe(`reset() {
|
||||
this.result = 0;
|
||||
return this;
|
||||
}`);
|
||||
expect(result.replaceContent)
|
||||
.toBe(`// Resets the calculator result to 0 and returns the instance for method chaining
|
||||
reset() {
|
||||
this.result = 0;
|
||||
return this;
|
||||
}`);
|
||||
expect(result.error).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should handle different marker lengths", () => {
|
||||
const content = `------- SEARCH
|
||||
old content
|
||||
=========
|
||||
new content
|
||||
+++++++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(true);
|
||||
expect(result.searchContent).toBe("old content");
|
||||
expect(result.replaceContent).toBe("new content");
|
||||
});
|
||||
|
||||
it("should handle empty search content", () => {
|
||||
const content = `------- SEARCH
|
||||
=======
|
||||
new content
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(true);
|
||||
expect(result.searchContent).toBe("");
|
||||
expect(result.replaceContent).toBe("new content");
|
||||
});
|
||||
|
||||
it("should handle empty replace content (deletion)", () => {
|
||||
const content = `------- SEARCH
|
||||
old content to delete
|
||||
=======
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(true);
|
||||
expect(result.searchContent).toBe("old content to delete");
|
||||
expect(result.replaceContent).toBe("");
|
||||
});
|
||||
|
||||
it("should handle both empty search and replace content", () => {
|
||||
const content = `------- SEARCH
|
||||
=======
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(true);
|
||||
expect(result.searchContent).toBe("");
|
||||
expect(result.replaceContent).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Incomplete blocks", () => {
|
||||
it("should handle incomplete search block", () => {
|
||||
const content = `------- SEARCH
|
||||
some content`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(false);
|
||||
expect(result.searchContent).toBe("some content");
|
||||
expect(result.replaceContent).toBe("");
|
||||
expect(result.error).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should handle incomplete replace block", () => {
|
||||
const content = `------- SEARCH
|
||||
old content
|
||||
=======
|
||||
new content`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(false);
|
||||
expect(result.searchContent).toBe("old content");
|
||||
expect(result.replaceContent).toBe("new content");
|
||||
expect(result.error).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Error cases", () => {
|
||||
it("should error on search end without start", () => {
|
||||
const content = `=======
|
||||
some content
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(false);
|
||||
expect(result.error).toBe(
|
||||
"Found search block end marker without matching start marker",
|
||||
);
|
||||
});
|
||||
|
||||
it("should error on replace end without replace start", () => {
|
||||
const content = `+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
|
||||
expect(result.isComplete).toBe(false);
|
||||
expect(result.error).toBe(
|
||||
"Found replace block end marker without matching replace start marker",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Regex pattern validation", () => {
|
||||
it("should match various search start patterns", () => {
|
||||
const patterns = ["--- SEARCH", "------- SEARCH", "------------- SEARCH"];
|
||||
|
||||
patterns.forEach((pattern) => {
|
||||
const content = `${pattern}
|
||||
content
|
||||
=======
|
||||
replacement
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
expect(result.isComplete).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("should match various search end patterns", () => {
|
||||
const patterns = ["===", "=======", "=============="];
|
||||
|
||||
patterns.forEach((pattern) => {
|
||||
const content = `------- SEARCH
|
||||
content
|
||||
${pattern}
|
||||
replacement
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
expect(result.isComplete).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("should match various replace end patterns", () => {
|
||||
const patterns = [
|
||||
"+++ REPLACE",
|
||||
"+++++++ REPLACE",
|
||||
"+++++++++++ REPLACE",
|
||||
];
|
||||
|
||||
patterns.forEach((pattern) => {
|
||||
const content = `------- SEARCH
|
||||
content
|
||||
=======
|
||||
replacement
|
||||
${pattern}`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
expect(result.isComplete).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it("should not match invalid patterns", () => {
|
||||
const invalidPatterns = [
|
||||
"-- SEARCH", // Too few dashes
|
||||
"SEARCH", // No markers
|
||||
"== SEARCH", // Wrong markers
|
||||
"=== REPLACE", // Wrong end marker
|
||||
"++++ SEARCH", // Wrong markers for search
|
||||
];
|
||||
|
||||
invalidPatterns.forEach((pattern) => {
|
||||
const content = `${pattern}
|
||||
content`;
|
||||
|
||||
const result = parseSearchReplaceBlock(content);
|
||||
expect(result.isComplete).toBe(false);
|
||||
expect(result.searchContent).toBe(""); // Should not enter search mode
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseAllSearchReplaceBlocks", () => {
|
||||
it("should parse multiple complete blocks", () => {
|
||||
const content = `------- SEARCH
|
||||
old code 1
|
||||
=======
|
||||
new code 1
|
||||
+++++++ REPLACE
|
||||
|
||||
------- SEARCH
|
||||
old code 2
|
||||
=======
|
||||
new code 2
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(2);
|
||||
expect(blocks[0].searchContent).toBe("old code 1");
|
||||
expect(blocks[0].replaceContent).toBe("new code 1");
|
||||
expect(blocks[1].searchContent).toBe("old code 2");
|
||||
expect(blocks[1].replaceContent).toBe("new code 2");
|
||||
});
|
||||
|
||||
it("should handle blocks with different content", () => {
|
||||
const content = `------- SEARCH
|
||||
function old() {
|
||||
return 1;
|
||||
}
|
||||
=======
|
||||
function new() {
|
||||
return 2;
|
||||
}
|
||||
+++++++ REPLACE
|
||||
|
||||
------- SEARCH
|
||||
const x = 'old';
|
||||
=======
|
||||
const x = 'new';
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(2);
|
||||
expect(blocks[0].searchContent).toBe(`function old() {
|
||||
return 1;
|
||||
}`);
|
||||
expect(blocks[0].replaceContent).toBe(`function new() {
|
||||
return 2;
|
||||
}`);
|
||||
expect(blocks[1].searchContent).toBe(`const x = 'old';`);
|
||||
expect(blocks[1].replaceContent).toBe(`const x = 'new';`);
|
||||
});
|
||||
|
||||
it("should handle deletion blocks (empty replace content)", () => {
|
||||
const content = `------- SEARCH
|
||||
code to keep
|
||||
=======
|
||||
modified code
|
||||
+++++++ REPLACE
|
||||
|
||||
------- SEARCH
|
||||
code to delete
|
||||
=======
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(2);
|
||||
expect(blocks[0].searchContent).toBe("code to keep");
|
||||
expect(blocks[0].replaceContent).toBe("modified code");
|
||||
expect(blocks[1].searchContent).toBe("code to delete");
|
||||
expect(blocks[1].replaceContent).toBe(""); // Deletion
|
||||
});
|
||||
|
||||
it("should handle insertion blocks (empty search content)", () => {
|
||||
const content = `------- SEARCH
|
||||
existing code
|
||||
=======
|
||||
modified existing code
|
||||
+++++++ REPLACE
|
||||
|
||||
------- SEARCH
|
||||
=======
|
||||
new code to insert
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(2);
|
||||
expect(blocks[0].searchContent).toBe("existing code");
|
||||
expect(blocks[0].replaceContent).toBe("modified existing code");
|
||||
expect(blocks[1].searchContent).toBe(""); // Insertion
|
||||
expect(blocks[1].replaceContent).toBe("new code to insert");
|
||||
});
|
||||
|
||||
it("should skip incomplete blocks", () => {
|
||||
const content = `------- SEARCH
|
||||
incomplete block
|
||||
|
||||
------- SEARCH
|
||||
complete block
|
||||
=======
|
||||
replacement
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(1);
|
||||
expect(blocks[0].searchContent).toBe("complete block");
|
||||
expect(blocks[0].replaceContent).toBe("replacement");
|
||||
});
|
||||
|
||||
it("should handle single block", () => {
|
||||
const content = `------- SEARCH
|
||||
single block
|
||||
=======
|
||||
replacement
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(1);
|
||||
expect(blocks[0].searchContent).toBe("single block");
|
||||
expect(blocks[0].replaceContent).toBe("replacement");
|
||||
});
|
||||
|
||||
it("should return empty array when no complete blocks found", () => {
|
||||
const content = `------- SEARCH
|
||||
incomplete
|
||||
=======
|
||||
missing replace marker`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("should handle blocks with extra content between them", () => {
|
||||
const content = `Some other content here
|
||||
|
||||
------- SEARCH
|
||||
block 1
|
||||
=======
|
||||
replacement 1
|
||||
+++++++ REPLACE
|
||||
|
||||
More content in between
|
||||
|
||||
------- SEARCH
|
||||
block 2
|
||||
=======
|
||||
replacement 2
|
||||
+++++++ REPLACE
|
||||
|
||||
Trailing content`;
|
||||
|
||||
const blocks = parseAllSearchReplaceBlocks(content);
|
||||
|
||||
expect(blocks).toHaveLength(2);
|
||||
expect(blocks[0].searchContent).toBe("block 1");
|
||||
expect(blocks[0].replaceContent).toBe("replacement 1");
|
||||
expect(blocks[1].searchContent).toBe("block 2");
|
||||
expect(blocks[1].replaceContent).toBe("replacement 2");
|
||||
});
|
||||
|
||||
it("should throw error for malformed blocks", () => {
|
||||
const content = `------- SEARCH
|
||||
content
|
||||
+++++++ REPLACE`; // Missing =======
|
||||
|
||||
expect(() => parseAllSearchReplaceBlocks(content)).toThrow(
|
||||
"Found replace block end marker without matching replace start marker",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,147 +0,0 @@
|
|||
// Search and replace block markers using flexible regex patterns
|
||||
const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH$/;
|
||||
const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/;
|
||||
const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE$/;
|
||||
|
||||
export interface SearchReplaceBlockResult {
|
||||
/** Whether a complete search/replace block has been parsed */
|
||||
isComplete: boolean;
|
||||
/** The content to search for in the file */
|
||||
searchContent?: string;
|
||||
/** The content to replace the search content with */
|
||||
replaceContent?: string;
|
||||
/** Error message if parsing failed */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a search and replace block from content.
|
||||
*
|
||||
* Expected format:
|
||||
* ------- SEARCH
|
||||
* [content to find]
|
||||
* =======
|
||||
* [content to replace with]
|
||||
* +++++++ REPLACE
|
||||
*
|
||||
* @param content - The content to parse
|
||||
* @returns ParseResult with completion status and extracted content
|
||||
*/
|
||||
export function parseSearchReplaceBlock(
|
||||
content: string,
|
||||
): SearchReplaceBlockResult {
|
||||
const lines = content.split("\n");
|
||||
|
||||
let currentSearchContent = "";
|
||||
let currentReplaceContent = "";
|
||||
let inSearch = false;
|
||||
let inReplace = false;
|
||||
|
||||
for (const line of lines) {
|
||||
if (SEARCH_BLOCK_START_REGEX.test(line)) {
|
||||
inSearch = true;
|
||||
inReplace = false;
|
||||
currentSearchContent = "";
|
||||
currentReplaceContent = "";
|
||||
continue;
|
||||
}
|
||||
|
||||
if (SEARCH_BLOCK_END_REGEX.test(line)) {
|
||||
if (!inSearch) {
|
||||
return {
|
||||
isComplete: false,
|
||||
error: "Found search block end marker without matching start marker",
|
||||
};
|
||||
}
|
||||
inSearch = false;
|
||||
inReplace = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (REPLACE_BLOCK_END_REGEX.test(line)) {
|
||||
if (!inReplace) {
|
||||
return {
|
||||
isComplete: false,
|
||||
error:
|
||||
"Found replace block end marker without matching replace start marker",
|
||||
};
|
||||
}
|
||||
|
||||
// Complete block found
|
||||
return {
|
||||
isComplete: true,
|
||||
searchContent: currentSearchContent.trim(),
|
||||
replaceContent: currentReplaceContent.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
// Accumulate content
|
||||
if (inSearch) {
|
||||
currentSearchContent += line + "\n";
|
||||
} else if (inReplace) {
|
||||
currentReplaceContent += line + "\n";
|
||||
}
|
||||
}
|
||||
|
||||
// Block is not yet complete
|
||||
return {
|
||||
isComplete: false,
|
||||
searchContent: currentSearchContent.trim(),
|
||||
replaceContent: currentReplaceContent.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses all complete search and replace blocks from content.
|
||||
*
|
||||
* @param content - The content containing multiple search/replace blocks
|
||||
* @returns Array of complete search/replace blocks found
|
||||
* @throws Error if any malformed blocks are encountered
|
||||
*/
|
||||
export function parseAllSearchReplaceBlocks(
|
||||
content: string,
|
||||
): SearchReplaceBlockResult[] {
|
||||
const blocks: SearchReplaceBlockResult[] = [];
|
||||
const lines = content.split("\n");
|
||||
|
||||
let currentBlockLines: string[] = [];
|
||||
let inBlock = false;
|
||||
|
||||
for (const line of lines) {
|
||||
if (SEARCH_BLOCK_START_REGEX.test(line)) {
|
||||
// Start of new block
|
||||
if (inBlock && currentBlockLines.length > 0) {
|
||||
// Process previous incomplete block if any
|
||||
const blockContent = currentBlockLines.join("\n");
|
||||
const result = parseSearchReplaceBlock(blockContent);
|
||||
if (result.isComplete) {
|
||||
blocks.push(result);
|
||||
} else if (result.error) {
|
||||
// Fail fast on any parsing error
|
||||
throw new Error(result.error);
|
||||
}
|
||||
// If incomplete but no error, it's just a partial block - continue processing
|
||||
}
|
||||
currentBlockLines = [line];
|
||||
inBlock = true;
|
||||
} else if (inBlock) {
|
||||
currentBlockLines.push(line);
|
||||
|
||||
// Check if this line completes the current block
|
||||
if (REPLACE_BLOCK_END_REGEX.test(line)) {
|
||||
const blockContent = currentBlockLines.join("\n");
|
||||
const result = parseSearchReplaceBlock(blockContent);
|
||||
if (result.isComplete) {
|
||||
blocks.push(result);
|
||||
} else if (result.error) {
|
||||
// Fail fast on any parsing error
|
||||
throw new Error(result.error);
|
||||
}
|
||||
currentBlockLines = [];
|
||||
inBlock = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return blocks;
|
||||
}
|
||||
11
core/index.d.ts
vendored
11
core/index.d.ts
vendored
|
|
@ -456,7 +456,6 @@ export type FileSymbolMap = Record<string, SymbolWithRange[]>;
|
|||
export interface PromptLog {
|
||||
modelTitle: string;
|
||||
modelProvider: string;
|
||||
completionOptions: CompletionOptions;
|
||||
prompt: string;
|
||||
completion: string;
|
||||
}
|
||||
|
|
@ -1071,11 +1070,6 @@ export interface ToolExtras {
|
|||
codeBaseIndexer?: CodebaseIndexer;
|
||||
}
|
||||
|
||||
export type ToolPolicy =
|
||||
| "allowedWithPermission"
|
||||
| "allowedWithoutPermission"
|
||||
| "disabled";
|
||||
|
||||
export interface Tool {
|
||||
type: "function";
|
||||
function: {
|
||||
|
|
@ -1100,6 +1094,10 @@ export interface Tool {
|
|||
exampleArgs?: Array<[string, string | number]>;
|
||||
};
|
||||
defaultToolPolicy?: ToolPolicy;
|
||||
evaluateToolCallPolicy?: (
|
||||
basePolicy: ToolPolicy,
|
||||
parsedArgs: Record<string, unknown>,
|
||||
) => ToolPolicy;
|
||||
}
|
||||
|
||||
interface ToolChoice {
|
||||
|
|
@ -1347,6 +1345,7 @@ export interface ContinueUIConfig {
|
|||
codeWrap?: boolean;
|
||||
showSessionTabs?: boolean;
|
||||
autoAcceptEditToolDiffs?: boolean;
|
||||
continueAfterToolRejection?: boolean;
|
||||
}
|
||||
|
||||
export interface ContextMenuConfig {
|
||||
|
|
|
|||
|
|
@ -12,7 +12,6 @@ import type { IMessenger } from "../protocol/messenger";
|
|||
import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
|
||||
import { Logger } from "../util/Logger.js";
|
||||
import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
|
||||
import { Telemetry } from "../util/posthog.js";
|
||||
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
|
||||
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
|
|
@ -667,14 +666,6 @@ export class CodebaseIndexer {
|
|||
update.desc,
|
||||
update.debugInfo,
|
||||
);
|
||||
void Telemetry.capture(
|
||||
"indexing_error",
|
||||
{
|
||||
error: update.desc,
|
||||
stack: update.debugInfo,
|
||||
},
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -858,6 +858,27 @@ export default class DocsService {
|
|||
return docs.map(this.lanceDBRowToChunk);
|
||||
}
|
||||
|
||||
async getIndexedPages(startUrl: string): Promise<Set<string>> {
|
||||
try {
|
||||
const table = await this.getOrCreateLanceTable({
|
||||
initializationVector: [],
|
||||
startUrl,
|
||||
});
|
||||
|
||||
const rows = (await table
|
||||
.filter(`starturl = '${startUrl}'`)
|
||||
.select(["path"]) // Only select path to minimize data transfer
|
||||
.limit(99999999) // Default is 10, we want to show all
|
||||
.execute()) as { path: string }[];
|
||||
|
||||
// Get unique paths (pages)
|
||||
return new Set(rows.map((row) => row.path));
|
||||
} catch (e) {
|
||||
console.warn(`Error getting page list for ${startUrl}:`, e);
|
||||
return new Set();
|
||||
}
|
||||
}
|
||||
|
||||
// SQLITE DB
|
||||
private async getOrCreateSqliteDb() {
|
||||
if (!this.sqliteDb) {
|
||||
|
|
|
|||
|
|
@ -155,9 +155,27 @@ describe("DocsCrawler", () => {
|
|||
test(
|
||||
`Default crawler common site: ${url}`,
|
||||
async () => {
|
||||
const { pages, crawler } = await runCrawl(url);
|
||||
expect(pages.length).toBeGreaterThanOrEqual(1);
|
||||
expect(crawler).toEqual("default");
|
||||
// Retry logic to handle flaky network requests to TRIAL_PROXY_URL
|
||||
let lastError;
|
||||
const maxRetries = 3;
|
||||
|
||||
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
const { pages, crawler } = await runCrawl(url);
|
||||
expect(pages.length).toBeGreaterThanOrEqual(1);
|
||||
expect(crawler).toEqual("default");
|
||||
return; // Test passed, exit retry loop
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (attempt === maxRetries) {
|
||||
throw error; // Final attempt failed, throw the error
|
||||
}
|
||||
// Wait before retrying (exponential backoff)
|
||||
await new Promise((resolve) =>
|
||||
setTimeout(resolve, 1000 * attempt),
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ import { Logger } from "../util/Logger.js";
|
|||
import mergeJson from "../util/merge.js";
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
import { isOllamaInstalled } from "../util/ollamaHelper.js";
|
||||
import { Telemetry } from "../util/posthog.js";
|
||||
import { TokensBatchingService } from "../util/TokensBatchingService.js";
|
||||
import { withExponentialBackoff } from "../util/withExponentialBackoff.js";
|
||||
|
||||
import {
|
||||
|
|
@ -346,15 +346,11 @@ export abstract class BaseLLM implements ILLM {
|
|||
let generatedTokens = this.countTokens(completion);
|
||||
let thinkingTokens = thinking ? this.countTokens(thinking) : 0;
|
||||
|
||||
void Telemetry.capture(
|
||||
"tokens_generated",
|
||||
{
|
||||
model: model,
|
||||
provider: this.providerName,
|
||||
promptTokens: promptTokens,
|
||||
generatedTokens: generatedTokens,
|
||||
},
|
||||
true,
|
||||
TokensBatchingService.getInstance().addTokens(
|
||||
model,
|
||||
this.providerName,
|
||||
promptTokens,
|
||||
generatedTokens,
|
||||
);
|
||||
|
||||
void DevDataSqliteDb.logTokensGenerated(
|
||||
|
|
@ -374,8 +370,17 @@ export abstract class BaseLLM implements ILLM {
|
|||
},
|
||||
});
|
||||
|
||||
if (error !== undefined) {
|
||||
if (error === "cancel" || error.name === "AbortError") {
|
||||
if (typeof error === "undefined") {
|
||||
interaction?.logItem({
|
||||
kind: "success",
|
||||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
usage,
|
||||
});
|
||||
return "success";
|
||||
} else {
|
||||
if (error === "cancel" || error?.name?.includes("AbortError")) {
|
||||
interaction?.logItem({
|
||||
kind: "cancel",
|
||||
promptTokens,
|
||||
|
|
@ -397,15 +402,6 @@ export abstract class BaseLLM implements ILLM {
|
|||
});
|
||||
return "error";
|
||||
}
|
||||
} else {
|
||||
interaction?.logItem({
|
||||
kind: "success",
|
||||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
usage,
|
||||
});
|
||||
return "success";
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -619,6 +615,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
kind: "chunk",
|
||||
chunk: formattedContent,
|
||||
});
|
||||
|
||||
completion += formattedContent;
|
||||
yield content;
|
||||
}
|
||||
|
|
@ -634,6 +631,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
kind: "chunk",
|
||||
chunk,
|
||||
});
|
||||
|
||||
completion += chunk;
|
||||
yield chunk;
|
||||
}
|
||||
|
|
@ -1146,7 +1144,6 @@ export abstract class BaseLLM implements ILLM {
|
|||
modelProvider: this.underlyingProviderName,
|
||||
prompt,
|
||||
completion,
|
||||
completionOptions,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -19,9 +19,6 @@ async function dudLLMCall(llm: ILLM, messages: ChatMessage[]) {
|
|||
await gen.next();
|
||||
await gen.return({
|
||||
completion: "",
|
||||
completionOptions: {
|
||||
model: "",
|
||||
},
|
||||
modelTitle: "",
|
||||
modelProvider: "",
|
||||
prompt: "",
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import {
|
|||
CompletionOptions,
|
||||
LLMOptions,
|
||||
ModelInstaller,
|
||||
ThinkingChatMessage,
|
||||
} from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { getRemoteModelInfo } from "../../util/ollamaHelper.js";
|
||||
|
|
@ -18,6 +19,7 @@ type OllamaChatMessage = {
|
|||
role: ChatMessageRole;
|
||||
content: string;
|
||||
images?: string[] | null;
|
||||
thinking?: string;
|
||||
tool_calls?: {
|
||||
function: {
|
||||
name: string;
|
||||
|
|
@ -148,7 +150,7 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
|
||||
if (options.isFromAutoDetect) {
|
||||
if (options.model === "AUTODETECT") {
|
||||
return;
|
||||
}
|
||||
const headers: Record<string, string> = {
|
||||
|
|
@ -420,24 +422,35 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
signal,
|
||||
});
|
||||
|
||||
function convertChatMessage(res: OllamaChatResponse): ChatMessage {
|
||||
function convertChatMessage(res: OllamaChatResponse): ChatMessage[] {
|
||||
if ("error" in res) {
|
||||
throw new Error(res.error);
|
||||
}
|
||||
if (res.message.role === "tool") {
|
||||
|
||||
const { role, content, thinking, tool_calls: toolCalls } = res.message;
|
||||
|
||||
if (role === "tool") {
|
||||
throw new Error(
|
||||
"Unexpected message received from ollama with role = tool",
|
||||
"Unexpected message received from Ollama with role = tool",
|
||||
);
|
||||
}
|
||||
if (res.message.role === "assistant") {
|
||||
const chatMessage: ChatMessage = {
|
||||
role: "assistant",
|
||||
content: res.message.content,
|
||||
};
|
||||
if (res.message.tool_calls) {
|
||||
|
||||
if (role === "assistant") {
|
||||
const thinkingMessage: ThinkingChatMessage | null = thinking
|
||||
? { role: "thinking", content: thinking }
|
||||
: null;
|
||||
|
||||
if (thinkingMessage && !content) {
|
||||
// When Streaming you can't have both thinking and content
|
||||
return [thinkingMessage];
|
||||
}
|
||||
// Either not thinking, or not streaming
|
||||
const chatMessage: ChatMessage = { role: "assistant", content };
|
||||
|
||||
if (toolCalls?.length) {
|
||||
// Continue handles the response as a tool call delta but
|
||||
// But ollama returns the full object in one response with no streaming
|
||||
chatMessage.toolCalls = res.message.tool_calls.map((tc) => ({
|
||||
chatMessage.toolCalls = toolCalls.map((tc) => ({
|
||||
type: "function",
|
||||
id: `tc_${uuidv4()}`, // Generate a proper UUID with a prefix
|
||||
function: {
|
||||
|
|
@ -446,13 +459,13 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
},
|
||||
}));
|
||||
}
|
||||
return chatMessage;
|
||||
} else {
|
||||
return {
|
||||
role: res.message.role,
|
||||
content: res.message.content,
|
||||
};
|
||||
|
||||
// Return both thinking and chat messages if applicable
|
||||
return thinkingMessage ? [thinkingMessage, chatMessage] : [chatMessage];
|
||||
}
|
||||
|
||||
// Fallback for all other roles
|
||||
return [{ role, content }];
|
||||
}
|
||||
|
||||
if (chatOptions.stream === false) {
|
||||
|
|
@ -460,7 +473,9 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
return; // Aborted by user
|
||||
}
|
||||
const json = (await response.json()) as OllamaChatResponse;
|
||||
yield convertChatMessage(json);
|
||||
for (const msg of convertChatMessage(json)) {
|
||||
yield msg;
|
||||
}
|
||||
} else {
|
||||
let buffer = "";
|
||||
for await (const value of streamResponse(response)) {
|
||||
|
|
@ -475,8 +490,9 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
if (chunk.trim() !== "") {
|
||||
try {
|
||||
const j = JSON.parse(chunk) as OllamaChatResponse;
|
||||
const chatMessage = convertChatMessage(j);
|
||||
yield chatMessage;
|
||||
for (const msg of convertChatMessage(j)) {
|
||||
yield msg;
|
||||
}
|
||||
} catch (e) {
|
||||
throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
|
||||
}
|
||||
|
|
|
|||
18
core/llm/llms/TARS.ts
Normal file
18
core/llm/llms/TARS.ts
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
import { LLMOptions } from "../../index.js";
|
||||
import { osModelsEditPrompt } from "../templates/edit.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class TARS extends OpenAI {
|
||||
static providerName = "tars";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.router.tetrate.ai/v1",
|
||||
model: "gpt-5-mini",
|
||||
promptTemplates: {
|
||||
edit: osModelsEditPrompt,
|
||||
},
|
||||
useLegacyCompletionsEndpoint: false,
|
||||
};
|
||||
}
|
||||
|
||||
export default TARS;
|
||||
|
|
@ -53,6 +53,7 @@ import SambaNova from "./SambaNova";
|
|||
import Scaleway from "./Scaleway";
|
||||
import SiliconFlow from "./SiliconFlow";
|
||||
import ContinueProxy from "./stubs/ContinueProxy";
|
||||
import TARS from "./TARS";
|
||||
import TestLLM from "./Test";
|
||||
import TextGenWebUI from "./TextGenWebUI";
|
||||
import Together from "./Together";
|
||||
|
|
@ -116,6 +117,7 @@ export const LLMClasses = [
|
|||
Inception,
|
||||
Voyage,
|
||||
LlamaStack,
|
||||
TARS,
|
||||
];
|
||||
|
||||
export async function llmFromDescription(
|
||||
|
|
|
|||
|
|
@ -13,6 +13,10 @@ export enum EditableRegionStrategy {
|
|||
Static = "static",
|
||||
}
|
||||
|
||||
/**
|
||||
* This was an attempt to find next edit locations deterministically.
|
||||
* I was intending to use this in tandem with the prefetching logic, but we are not using it anymore.
|
||||
*/
|
||||
export async function getNextEditableRegion(
|
||||
strategy: EditableRegionStrategy,
|
||||
ctx: any,
|
||||
|
|
|
|||
|
|
@ -11,6 +11,16 @@ export class NextEditLoggingService {
|
|||
private _abortControllers = new Map<string, AbortController>();
|
||||
private _logRejectionTimeouts = new Map<string, NodeJS.Timeout>();
|
||||
private _outcomes = new Map<string, NextEditOutcome>();
|
||||
// Track minimal data for completions that get aborted before we have full outcome.
|
||||
private _pendingCompletions = new Map<
|
||||
string,
|
||||
{
|
||||
startTime: number;
|
||||
modelName?: string;
|
||||
modelProvider?: string;
|
||||
filepath?: string;
|
||||
}
|
||||
>();
|
||||
_lastDisplayedCompletion: { id: string; displayedAt: number } | undefined =
|
||||
undefined;
|
||||
|
||||
|
|
@ -26,21 +36,54 @@ export class NextEditLoggingService {
|
|||
public createAbortController(completionId: string): AbortController {
|
||||
const abortController = new AbortController();
|
||||
this._abortControllers.set(completionId, abortController);
|
||||
this.trackPendingCompletion(completionId);
|
||||
return abortController;
|
||||
}
|
||||
|
||||
public deleteAbortController(completionId: string) {
|
||||
this._abortControllers.delete(completionId);
|
||||
this._pendingCompletions.delete(completionId);
|
||||
}
|
||||
|
||||
// Keep track of a new completion request.
|
||||
public trackPendingCompletion(completionId: string) {
|
||||
this._pendingCompletions.set(completionId, {
|
||||
startTime: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
// Update pending completion info as it becomes available.
|
||||
public updatePendingCompletion(
|
||||
completionId: string,
|
||||
data: {
|
||||
modelName?: string;
|
||||
modelProvider?: string;
|
||||
filepath?: string;
|
||||
},
|
||||
) {
|
||||
const pending = this._pendingCompletions.get(completionId);
|
||||
if (pending) {
|
||||
this._pendingCompletions.set(completionId, { ...pending, ...data });
|
||||
} else {
|
||||
// If we haven't tracked it yet, create new entry with provided data.
|
||||
this._pendingCompletions.set(completionId, {
|
||||
startTime: Date.now(),
|
||||
...data,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public cancel() {
|
||||
this._abortControllers.forEach((abortController, id) => {
|
||||
this._abortControllers.forEach((abortController, completionId) => {
|
||||
this.handleAbort(completionId);
|
||||
abortController.abort();
|
||||
});
|
||||
this._abortControllers.clear();
|
||||
}
|
||||
|
||||
public accept(completionId: string): NextEditOutcome | undefined {
|
||||
this._pendingCompletions.delete(completionId);
|
||||
|
||||
if (this._logRejectionTimeouts.has(completionId)) {
|
||||
clearTimeout(this._logRejectionTimeouts.get(completionId));
|
||||
this._logRejectionTimeouts.delete(completionId);
|
||||
|
|
@ -48,6 +91,7 @@ export class NextEditLoggingService {
|
|||
if (this._outcomes.has(completionId)) {
|
||||
const outcome = this._outcomes.get(completionId)!;
|
||||
outcome.accepted = true;
|
||||
outcome.aborted = false;
|
||||
this.logNextEditOutcome(outcome);
|
||||
this._outcomes.delete(completionId);
|
||||
return outcome;
|
||||
|
|
@ -55,6 +99,8 @@ export class NextEditLoggingService {
|
|||
}
|
||||
|
||||
public reject(completionId: string): NextEditOutcome | undefined {
|
||||
this._pendingCompletions.delete(completionId);
|
||||
|
||||
if (this._logRejectionTimeouts.has(completionId)) {
|
||||
clearTimeout(this._logRejectionTimeouts.get(completionId));
|
||||
this._logRejectionTimeouts.delete(completionId);
|
||||
|
|
@ -63,6 +109,7 @@ export class NextEditLoggingService {
|
|||
if (this._outcomes.has(completionId)) {
|
||||
const outcome = this._outcomes.get(completionId)!;
|
||||
outcome.accepted = false;
|
||||
outcome.aborted = false;
|
||||
this.logNextEditOutcome(outcome);
|
||||
this._outcomes.delete(completionId);
|
||||
return outcome;
|
||||
|
|
@ -86,12 +133,19 @@ export class NextEditLoggingService {
|
|||
}
|
||||
|
||||
public markDisplayed(completionId: string, outcome: NextEditOutcome) {
|
||||
// Remove from pending since we now have full data.
|
||||
this._pendingCompletions.delete(completionId);
|
||||
outcome.aborted = false;
|
||||
|
||||
const logRejectionTimeout = setTimeout(() => {
|
||||
// Wait 10 seconds, then assume it wasn't accepted
|
||||
outcome.accepted = false;
|
||||
outcome.aborted = false;
|
||||
this.logNextEditOutcome(outcome);
|
||||
this._logRejectionTimeouts.delete(completionId);
|
||||
this._outcomes.delete(completionId);
|
||||
}, COUNT_COMPLETION_REJECTED_AFTER);
|
||||
|
||||
this._outcomes.set(completionId, outcome);
|
||||
this._logRejectionTimeouts.set(completionId, logRejectionTimeout);
|
||||
|
||||
|
|
@ -124,7 +178,62 @@ export class NextEditLoggingService {
|
|||
};
|
||||
}
|
||||
|
||||
public handleAbort(completionId: string) {
|
||||
// Clear any pending rejection timeout.
|
||||
if (this._logRejectionTimeouts.has(completionId)) {
|
||||
clearTimeout(this._logRejectionTimeouts.get(completionId));
|
||||
this._logRejectionTimeouts.delete(completionId);
|
||||
}
|
||||
|
||||
// If we have the full outcome, log it as aborted.
|
||||
if (this._outcomes.has(completionId)) {
|
||||
const outcome = this._outcomes.get(completionId)!;
|
||||
outcome.accepted = false;
|
||||
outcome.aborted = true;
|
||||
this.logNextEditOutcome(outcome);
|
||||
this._outcomes.delete(completionId);
|
||||
} else {
|
||||
// Log minimal abort event for requests that never got displayed.
|
||||
const pendingData = this._pendingCompletions.get(completionId);
|
||||
|
||||
const minimalAbortOutcome: Partial<NextEditOutcome> = {
|
||||
completionId,
|
||||
accepted: false,
|
||||
aborted: true,
|
||||
timestamp: Date.now(),
|
||||
uniqueId: completionId,
|
||||
elapsed: pendingData ? Date.now() - pendingData.startTime : 0,
|
||||
modelName: pendingData?.modelName || "unknown",
|
||||
modelProvider: pendingData?.modelProvider || "unknown",
|
||||
fileUri: pendingData?.filepath || "unknown",
|
||||
|
||||
// Empty/default values for fields we don't have.
|
||||
completion: "",
|
||||
prompt: "",
|
||||
userEdits: "",
|
||||
userExcerpts: "",
|
||||
originalEditableRange: "",
|
||||
workspaceDirUri: "",
|
||||
cursorPosition: { line: -1, character: -1 },
|
||||
finalCursorPosition: { line: -1, character: -1 },
|
||||
editableRegionStartLine: -1,
|
||||
editableRegionEndLine: -1,
|
||||
diffLines: [],
|
||||
completionOptions: {},
|
||||
};
|
||||
|
||||
this.logNextEditOutcome(minimalAbortOutcome as NextEditOutcome);
|
||||
}
|
||||
|
||||
// Clean up.
|
||||
this._pendingCompletions.delete(completionId);
|
||||
}
|
||||
|
||||
private logNextEditOutcome(outcome: NextEditOutcome) {
|
||||
if (outcome.aborted === undefined) {
|
||||
outcome.aborted = false;
|
||||
}
|
||||
|
||||
void DataLogger.getInstance().logDevData({
|
||||
name: "nextEditOutcome",
|
||||
data: outcome,
|
||||
|
|
|
|||
|
|
@ -7,6 +7,14 @@ export interface ProcessedItem {
|
|||
outcome: NextEditOutcome; // Result from the model
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a queue of the broken down diffs from a changed editable range, as determined in core/nextEdit/diff.ts
|
||||
*/
|
||||
/**
|
||||
* This is where the chain is stored. Think of it as a regular queue, but being a singleton because we need one source of truth for the chain.
|
||||
* I originally intended this to be a separate data structure to handle prefetching next edit outcomes from the model in the background.
|
||||
* Due to subpar results, lack of satisfactory next edit location suggestion algorithms and token cost/latency issues, I scratched the idea.
|
||||
*/
|
||||
export class PrefetchQueue {
|
||||
private static instance: PrefetchQueue | null = null;
|
||||
|
||||
|
|
|
|||
|
|
@ -19,14 +19,13 @@ import { HelperVars } from "../autocomplete/util/HelperVars.js";
|
|||
import { AutocompleteInput } from "../autocomplete/util/types.js";
|
||||
import { isSecurityConcern } from "../indexing/ignore.js";
|
||||
import { modelSupportsNextEdit } from "../llm/autodetect.js";
|
||||
import { countTokens } from "../llm/countTokens.js";
|
||||
import { localPathOrUriToPath } from "../util/pathToUri.js";
|
||||
import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
|
||||
import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js";
|
||||
import { NextEditLoggingService } from "./NextEditLoggingService.js";
|
||||
import { PrefetchQueue } from "./NextEditPrefetchQueue.js";
|
||||
import { NextEditProviderFactory } from "./NextEditProviderFactory.js";
|
||||
import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js";
|
||||
import { BaseNextEditModelProvider } from "./providers/BaseNextEditProvider.js";
|
||||
import {
|
||||
ModelSpecificContext,
|
||||
NextEditOutcome,
|
||||
|
|
@ -45,6 +44,14 @@ const ERRORS_TO_IGNORE = [
|
|||
"operation was aborted",
|
||||
];
|
||||
|
||||
/**
|
||||
* This is the next edit analogue to autocomplete's CompletionProvider.
|
||||
* You will see a lot of similar if not identical methods to CompletionProvider methods.
|
||||
* All logic used to live inside this class, but that became untenable quickly.
|
||||
* I moved a lot of the model-specific logic (prompt building, pre/post processing, etc.) to the BaseNextEditProvider and the children inheriting from it.
|
||||
* Keeping this class around might be a good idea because it handles lots of delicate logic such as abort signals, chains, logging, etc.
|
||||
* There being a singleton also gives a lot of guarantees about the state of the next edit state machine.
|
||||
*/
|
||||
export class NextEditProvider {
|
||||
private static instance: NextEditProvider | null = null;
|
||||
|
||||
|
|
@ -62,10 +69,9 @@ export class NextEditProvider {
|
|||
private currentEditChainId: string | null = null;
|
||||
private previousRequest: AutocompleteInput | null = null;
|
||||
private previousCompletions: NextEditOutcome[] = [];
|
||||
// private nextEditableRegionsInTheCurrentChain: RangeInFile[] = [];
|
||||
|
||||
// Model-specific provider instance.
|
||||
private modelProvider: BaseNextEditProvider | null = null;
|
||||
private modelProvider: BaseNextEditModelProvider | null = null;
|
||||
|
||||
private constructor(
|
||||
private readonly configHandler: ConfigHandler,
|
||||
|
|
@ -223,14 +229,14 @@ export class NextEditProvider {
|
|||
|
||||
this.currentEditChainId = null;
|
||||
this.previousCompletions = [];
|
||||
// TODO: this should be cleaned up in the prefetch queue.
|
||||
// this.nextEditableRegionsInTheCurrentChain = [];
|
||||
|
||||
if (this.previousRequest) {
|
||||
const fileContent = (
|
||||
await this.ide.readFile(this.previousRequest.filepath)
|
||||
).toString();
|
||||
|
||||
const ast = await getAst(this.previousRequest.filepath, fileContent);
|
||||
|
||||
if (ast) {
|
||||
DocumentHistoryTracker.getInstance().push(
|
||||
localPathOrUriToPath(this.previousRequest.filepath),
|
||||
|
|
@ -253,6 +259,9 @@ export class NextEditProvider {
|
|||
return this.previousCompletions.length === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* This is the main entry point to this class.
|
||||
*/
|
||||
public async provideInlineCompletionItems(
|
||||
input: AutocompleteInput,
|
||||
token: AbortSignal | undefined,
|
||||
|
|
@ -311,7 +320,11 @@ export class NextEditProvider {
|
|||
input.completionId,
|
||||
);
|
||||
token = controller.signal;
|
||||
} else {
|
||||
// Token was provided externally, just track the completion.
|
||||
this.loggingService.trackPendingCompletion(input.completionId);
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
const options = await this._getAutocompleteOptions();
|
||||
|
||||
|
|
@ -325,6 +338,13 @@ export class NextEditProvider {
|
|||
return { token, startTime, helper: undefined };
|
||||
}
|
||||
|
||||
// Update pending completion with model info.
|
||||
this.loggingService.updatePendingCompletion(input.completionId, {
|
||||
modelName: llm.model,
|
||||
modelProvider: llm.providerName,
|
||||
filepath: input.filepath,
|
||||
});
|
||||
|
||||
// Check model capabilities
|
||||
if (!modelSupportsNextEdit(llm.capabilities, llm.model, llm.title)) {
|
||||
console.error(`${llm.model} is not capable of next edit.`);
|
||||
|
|
@ -359,6 +379,8 @@ export class NextEditProvider {
|
|||
throw new Error("Model provider not initialized");
|
||||
}
|
||||
|
||||
// NOTE: getAllSnippetsWithoutRace doesn't seem to incur much performance penalties when compared to getAllSnippets.
|
||||
// Use getAllSnippets if snippet gathering becomes noticably slow.
|
||||
const [snippetPayload, workspaceDirs] = await Promise.all([
|
||||
getAllSnippetsWithoutRace({
|
||||
helper,
|
||||
|
|
@ -434,6 +456,9 @@ export class NextEditProvider {
|
|||
}
|
||||
|
||||
// Send prompts to LLM (using only user prompt for fine-tuned models).
|
||||
// prompts[1] extracts the user prompt from the system-user prompt pair.
|
||||
// NOTE: Stream is currently set to false, but this should ideally be a per-model flag.
|
||||
// Mercury Coder currently does not support streaming.
|
||||
const msg: ChatMessage = await llm.chat([prompts[1]], token, {
|
||||
stream: false,
|
||||
});
|
||||
|
|
@ -473,7 +498,7 @@ export class NextEditProvider {
|
|||
}
|
||||
|
||||
if (outcome) {
|
||||
// Handle NextEditProvider-specific state
|
||||
// Handle NextEditProvider-specific state.
|
||||
this.previousCompletions.push(outcome);
|
||||
|
||||
// Mark as displayed for JetBrains
|
||||
|
|
@ -483,97 +508,6 @@ export class NextEditProvider {
|
|||
return outcome;
|
||||
}
|
||||
|
||||
private _calculateOptimalEditableRegion(
|
||||
helper: HelperVars,
|
||||
heuristic: "fourChars" | "tokenizer" = "tokenizer",
|
||||
): {
|
||||
editableRegionStartLine: number;
|
||||
editableRegionEndLine: number;
|
||||
} {
|
||||
const cursorLine = helper.pos.line;
|
||||
const fileLines = helper.fileLines;
|
||||
const MAX_TOKENS = 512;
|
||||
|
||||
// Initialize with cursor line.
|
||||
let editableRegionStartLine = cursorLine;
|
||||
let editableRegionEndLine = cursorLine;
|
||||
|
||||
// Get initial content and token count.
|
||||
let currentContent = fileLines[cursorLine];
|
||||
let totalTokens =
|
||||
heuristic === "tokenizer"
|
||||
? countTokens(currentContent, helper.modelName)
|
||||
: Math.ceil(currentContent.length / 4);
|
||||
|
||||
// Expand outward alternating between adding lines above and below.
|
||||
let addingAbove = true;
|
||||
|
||||
while (totalTokens < MAX_TOKENS) {
|
||||
let addedLine = false;
|
||||
|
||||
if (addingAbove) {
|
||||
// Try to add a line above.
|
||||
if (editableRegionStartLine > 0) {
|
||||
editableRegionStartLine--;
|
||||
const lineContent = fileLines[editableRegionStartLine];
|
||||
const lineTokens =
|
||||
heuristic === "tokenizer"
|
||||
? countTokens(lineContent, helper.modelName)
|
||||
: Math.ceil(lineContent.length / 4);
|
||||
|
||||
totalTokens += lineTokens;
|
||||
addedLine = true;
|
||||
}
|
||||
} else {
|
||||
// Try to add a line below.
|
||||
if (editableRegionEndLine < fileLines.length - 1) {
|
||||
editableRegionEndLine++;
|
||||
const lineContent = fileLines[editableRegionEndLine];
|
||||
const lineTokens =
|
||||
heuristic === "tokenizer"
|
||||
? countTokens(lineContent, helper.modelName)
|
||||
: Math.ceil(lineContent.length / 4);
|
||||
|
||||
totalTokens += lineTokens;
|
||||
addedLine = true;
|
||||
}
|
||||
}
|
||||
|
||||
// If we can't add in the current direction, try the other.
|
||||
if (!addedLine) {
|
||||
// If we're already at both file boundaries, we're done.
|
||||
if (
|
||||
editableRegionStartLine === 0 &&
|
||||
editableRegionEndLine === fileLines.length - 1
|
||||
) {
|
||||
break;
|
||||
}
|
||||
|
||||
// If we couldn't add in one direction, force the next attempt in the other direction.
|
||||
addingAbove = !addingAbove;
|
||||
continue;
|
||||
}
|
||||
|
||||
// If we exceeded the token limit, revert the last addition.
|
||||
if (totalTokens > MAX_TOKENS) {
|
||||
if (addingAbove) {
|
||||
editableRegionStartLine++;
|
||||
} else {
|
||||
editableRegionEndLine--;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// Alternate between adding above and below for balanced context.
|
||||
addingAbove = !addingAbove;
|
||||
}
|
||||
|
||||
return {
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
};
|
||||
}
|
||||
|
||||
private async _markDisplayedIfJetBrains(
|
||||
completionId: string,
|
||||
outcome: NextEditOutcome,
|
||||
|
|
@ -584,6 +518,12 @@ export class NextEditProvider {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is a wrapper around provideInlineCompletionItems.
|
||||
* This is invoked when we call the model in the background using prefetch.
|
||||
* It's not currently used anywhere (references are not used either), but I decided to keep it in case we actually need to use prefetch.
|
||||
* You will see that calls to this method is made from NextEditPrefetchQueue.proecss(), which is wrapped in `if (!this.usingFullFileDiff)`.
|
||||
*/
|
||||
public async provideInlineCompletionItemsWithChain(
|
||||
ctx: {
|
||||
completionId: string;
|
||||
|
|
|
|||
|
|
@ -1,259 +0,0 @@
|
|||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
|
||||
import { HelperVars } from "../autocomplete/util/HelperVars.js";
|
||||
import { ConfigHandler } from "../config/ConfigHandler.js";
|
||||
import { IDE, ILLM } from "../index.js";
|
||||
import { NextEditProvider } from "./NextEditProvider.js";
|
||||
|
||||
// Mock the countTokens function
|
||||
vi.mock("../llm/countTokens.js", () => ({
|
||||
countTokens: (text: string) => {
|
||||
// Simple mock that counts 1 token per character for predictable tests
|
||||
return text.length;
|
||||
},
|
||||
}));
|
||||
|
||||
// Create a helper function to set up the test context
|
||||
function createMockHelper(
|
||||
fileContents: string,
|
||||
cursorLine: number,
|
||||
): HelperVars {
|
||||
const fileLines = fileContents.split("\n");
|
||||
|
||||
return {
|
||||
fileLines,
|
||||
fileContents,
|
||||
pos: { line: cursorLine, character: 0 },
|
||||
modelName: "gpt-4",
|
||||
lang: { name: "typescript" },
|
||||
filepath: "test/file.ts",
|
||||
workspaceUris: ["test/workspace"],
|
||||
options: {},
|
||||
input: { completionId: "test-completion-id" },
|
||||
} as unknown as HelperVars;
|
||||
}
|
||||
|
||||
// TODO: Add more tests for other methods.
|
||||
describe("_calculateOptimalEditableRegion", () => {
|
||||
let nextEditProvider: NextEditProvider;
|
||||
let mockConfigHandler: ConfigHandler;
|
||||
let mockIde: IDE;
|
||||
let mockGetLlm: () => Promise<ILLM | undefined>;
|
||||
let mockOnError: (e: any) => void;
|
||||
let mockGetDefinitionsFromLsp: GetLspDefinitionsFunction;
|
||||
|
||||
beforeEach(() => {
|
||||
// Create comprehensive mocks for all dependencies
|
||||
mockConfigHandler = {
|
||||
loadConfig: vi.fn().mockResolvedValue({ config: {} }),
|
||||
} as unknown as ConfigHandler;
|
||||
|
||||
mockIde = {
|
||||
readFile: vi.fn().mockResolvedValue(""),
|
||||
getWorkspaceDirs: vi.fn().mockResolvedValue([]),
|
||||
getRepoName: vi.fn().mockResolvedValue("test-repo"),
|
||||
getUniqueId: vi.fn().mockResolvedValue("test-id"),
|
||||
getIdeInfo: vi.fn().mockResolvedValue({ ideType: "vscode" }),
|
||||
onDidChangeActiveTextEditor: vi.fn().mockImplementation((callback) => {
|
||||
// Return a disposable object that does nothing when disposed
|
||||
return {
|
||||
dispose: () => {},
|
||||
};
|
||||
}),
|
||||
} as unknown as IDE;
|
||||
|
||||
mockGetLlm = vi.fn().mockResolvedValue({
|
||||
model: "gpt-4",
|
||||
providerName: "openai",
|
||||
underlyingProviderName: "openai",
|
||||
completionOptions: {},
|
||||
chat: vi.fn(),
|
||||
});
|
||||
|
||||
mockOnError = vi.fn();
|
||||
mockGetDefinitionsFromLsp = vi.fn();
|
||||
|
||||
// Initialize NextEditProvider with mocked dependencies
|
||||
nextEditProvider = NextEditProvider.initialize(
|
||||
mockConfigHandler,
|
||||
mockIde,
|
||||
mockGetLlm,
|
||||
mockOnError,
|
||||
mockGetDefinitionsFromLsp,
|
||||
"default",
|
||||
);
|
||||
|
||||
// Expose the private method for testing
|
||||
// This is a bit of a hack, but necessary for testing private methods
|
||||
(nextEditProvider as any)._calculateOptimalEditableRegion = (
|
||||
NextEditProvider.prototype as any
|
||||
)._calculateOptimalEditableRegion.bind(nextEditProvider);
|
||||
});
|
||||
|
||||
// Test cases remain the same as before...
|
||||
it("should include only the cursor line when it already exceeds token limit", () => {
|
||||
// Create a mock helper with a very long cursor line (>500 characters)
|
||||
const longLine = "X".repeat(600);
|
||||
const helper = createMockHelper(longLine, 0);
|
||||
|
||||
//@ts-ignore
|
||||
const result = nextEditProvider._calculateOptimalEditableRegion(
|
||||
helper,
|
||||
"tokenizer",
|
||||
);
|
||||
|
||||
expect(result.editableRegionStartLine).toBe(0);
|
||||
expect(result.editableRegionEndLine).toBe(0);
|
||||
});
|
||||
|
||||
it("should expand symmetrically when possible", () => {
|
||||
// Create content with identical lines and cursor in the middle
|
||||
const lines = Array(11).fill("A".repeat(40)).join("\n"); // 11 lines of 40 chars each
|
||||
const helper = createMockHelper(lines, 5); // Cursor in the middle (line 5)
|
||||
|
||||
//@ts-ignore
|
||||
const result = nextEditProvider._calculateOptimalEditableRegion(
|
||||
helper,
|
||||
"tokenizer",
|
||||
);
|
||||
|
||||
// Should expand 5 lines in each direction (total 11 lines) for symmetry
|
||||
expect(result.editableRegionStartLine).toBe(0);
|
||||
expect(result.editableRegionEndLine).toBe(10);
|
||||
});
|
||||
|
||||
it("should expand asymmetrically when hitting a file boundary", () => {
|
||||
// Create content with cursor near the top
|
||||
const lines = Array(20).fill("B".repeat(20)).join("\n"); // 20 lines of 20 chars each
|
||||
const helper = createMockHelper(lines, 1); // Cursor near the top (line 1)
|
||||
|
||||
//@ts-ignore
|
||||
const result = nextEditProvider._calculateOptimalEditableRegion(
|
||||
helper,
|
||||
"tokenizer",
|
||||
);
|
||||
|
||||
// Should include more lines below since it can't expand much above
|
||||
expect(result.editableRegionStartLine).toBe(0);
|
||||
// Should include many more lines below to reach token limit
|
||||
expect(result.editableRegionEndLine).toBeGreaterThan(10);
|
||||
});
|
||||
|
||||
it("should handle files with varying line lengths", () => {
|
||||
// Create content with varying line lengths
|
||||
const fileContents = [
|
||||
"Short line", // 10 chars
|
||||
"A".repeat(100), // 100 chars
|
||||
"Medium length line here", // 24 chars
|
||||
"B".repeat(200), // 200 chars
|
||||
"Another typical line of code", // 28 chars
|
||||
].join("\n");
|
||||
|
||||
const helper = createMockHelper(fileContents, 2); // Cursor on the medium line
|
||||
|
||||
//@ts-ignore
|
||||
const result = nextEditProvider._calculateOptimalEditableRegion(
|
||||
helper,
|
||||
"tokenizer",
|
||||
);
|
||||
|
||||
// Should include all lines since total tokens < 500
|
||||
expect(result.editableRegionStartLine).toBe(0);
|
||||
expect(result.editableRegionEndLine).toBe(4);
|
||||
});
|
||||
|
||||
it("should respect the token limit and not include too many lines", () => {
|
||||
// Create content with many small lines (10 chars each)
|
||||
const lines = Array(600).fill("C".repeat(10)).join("\n");
|
||||
const helper = createMockHelper(lines, 300); // Cursor in the middle
|
||||
|
||||
//@ts-ignore
|
||||
const result = nextEditProvider._calculateOptimalEditableRegion(
|
||||
helper,
|
||||
"tokenizer",
|
||||
);
|
||||
|
||||
// Each line is 10 chars = 10 tokens per line with our mock.
|
||||
// So with 500 token limit, we should get 50 lines total.
|
||||
// 25 above, 25 below, +1 current
|
||||
const totalLines =
|
||||
result.editableRegionEndLine - result.editableRegionStartLine + 1;
|
||||
expect(totalLines).toBe(51); // Not more than 51 lines (25 above, 25 below, +1 for current line)
|
||||
});
|
||||
|
||||
it("should use character approximation when using fourChars heuristic", () => {
|
||||
// In this test, we're setting up a situation where tiktoken and fourChars would give different results
|
||||
// Creating 5 lines, each 100 characters
|
||||
const lines = Array(10).fill("D".repeat(100)).join("\n");
|
||||
const helper = createMockHelper(lines, 2); // Cursor in the middle
|
||||
|
||||
// Mock for tiktoken counting (1 char = 1 token)
|
||||
//@ts-ignore
|
||||
const tokenizerResult = nextEditProvider._calculateOptimalEditableRegion(
|
||||
helper,
|
||||
"tokenizer",
|
||||
);
|
||||
|
||||
// Mock for fourChars counting (1 token = 4 chars)
|
||||
// This should include more lines since each line is counted as 25 tokens instead of 100
|
||||
//@ts-ignore
|
||||
const fourCharsResult = nextEditProvider._calculateOptimalEditableRegion(
|
||||
helper,
|
||||
"fourChars",
|
||||
);
|
||||
|
||||
// The fourChars approach should include more lines since it estimates fewer tokens per line
|
||||
expect(
|
||||
fourCharsResult.editableRegionEndLine -
|
||||
fourCharsResult.editableRegionStartLine,
|
||||
).toBeGreaterThan(
|
||||
tokenizerResult.editableRegionEndLine -
|
||||
tokenizerResult.editableRegionStartLine,
|
||||
);
|
||||
});
|
||||
|
||||
it("should include the entire file if it's within token limit", () => {
|
||||
// Create a small file
|
||||
const smallFile = "Small file\nwith just\na few lines\nof text";
|
||||
const helper = createMockHelper(smallFile, 1);
|
||||
|
||||
//@ts-ignore
|
||||
const result = nextEditProvider._calculateOptimalEditableRegion(
|
||||
helper,
|
||||
"tokenizer",
|
||||
);
|
||||
|
||||
// Should include all lines
|
||||
expect(result.editableRegionStartLine).toBe(0);
|
||||
expect(result.editableRegionEndLine).toBe(3);
|
||||
});
|
||||
|
||||
it("should prioritize balanced context when token limit allows", () => {
|
||||
// Create content with alternating long and short lines
|
||||
const fileContents = [
|
||||
"Short", // 5 chars
|
||||
"E".repeat(80), // 80 chars
|
||||
"Also short", // 10 chars
|
||||
"F".repeat(80), // 80 chars
|
||||
"Another short one", // 17 chars
|
||||
"G".repeat(80), // 80 chars
|
||||
"Final short line", // 16 chars
|
||||
].join("\n");
|
||||
|
||||
const helper = createMockHelper(fileContents, 3); // Cursor on the long line (index 3)
|
||||
|
||||
//@ts-ignore
|
||||
const result = nextEditProvider._calculateOptimalEditableRegion(
|
||||
helper,
|
||||
"tokenizer",
|
||||
);
|
||||
|
||||
// Should try to include equal number of lines above and below cursor
|
||||
const linesAbove = result.editableRegionStartLine;
|
||||
const linesBelow =
|
||||
helper.fileLines.length - 1 - result.editableRegionEndLine;
|
||||
|
||||
// Difference between lines above and below should be minimal
|
||||
expect(Math.abs(linesAbove - linesBelow)).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,10 +1,10 @@
|
|||
import { NEXT_EDIT_MODELS } from "../llm/constants.js";
|
||||
import { BaseNextEditProvider } from "./providers/BaseNextEditProvider.js";
|
||||
import { BaseNextEditModelProvider } from "./providers/BaseNextEditProvider.js";
|
||||
import { InstinctProvider } from "./providers/InstinctNextEditProvider.js";
|
||||
import { MercuryCoderProvider } from "./providers/MercuryCoderNextEditProvider.js";
|
||||
|
||||
export class NextEditProviderFactory {
|
||||
static createProvider(modelName: string): BaseNextEditProvider {
|
||||
static createProvider(modelName: string): BaseNextEditModelProvider {
|
||||
if (modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER)) {
|
||||
return new MercuryCoderProvider();
|
||||
} else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) {
|
||||
|
|
|
|||
|
|
@ -19,7 +19,12 @@ import {
|
|||
} from "../types.js";
|
||||
import { isWhitespaceOnlyDeletion } from "../utils.js";
|
||||
|
||||
export abstract class BaseNextEditProvider {
|
||||
/**
|
||||
* This class is used as an abstract base class for model-specific providers.
|
||||
* This and its children are responsible for pre/post processing of prompts and outcomes.
|
||||
* Different next edit models have very different requirements.
|
||||
*/
|
||||
export abstract class BaseNextEditModelProvider {
|
||||
protected readonly modelName: string;
|
||||
|
||||
constructor(modelName: string) {
|
||||
|
|
@ -298,7 +303,7 @@ export abstract class BaseNextEditProvider {
|
|||
return {
|
||||
elapsed: Date.now() - outcomeCtx.startTime,
|
||||
modelProvider: outcomeCtx.llm.underlyingProviderName,
|
||||
modelName: outcomeCtx.llm.model + ":zetaDataset",
|
||||
modelName: outcomeCtx.llm.model,
|
||||
completionOptions: null,
|
||||
completionId:
|
||||
outcomeCtx.completionId || outcomeCtx.helper.input.completionId,
|
||||
|
|
|
|||
|
|
@ -11,9 +11,9 @@ import {
|
|||
PromptTemplateRenderer,
|
||||
} from "../templating/NextEditPromptEngine.js";
|
||||
import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js";
|
||||
import { BaseNextEditProvider } from "./BaseNextEditProvider.js";
|
||||
import { BaseNextEditModelProvider } from "./BaseNextEditProvider.js";
|
||||
|
||||
export class InstinctProvider extends BaseNextEditProvider {
|
||||
export class InstinctProvider extends BaseNextEditModelProvider {
|
||||
private templateRenderer: PromptTemplateRenderer;
|
||||
|
||||
constructor() {
|
||||
|
|
|
|||
|
|
@ -11,9 +11,9 @@ import {
|
|||
PromptTemplateRenderer,
|
||||
} from "../templating/NextEditPromptEngine.js";
|
||||
import { ModelSpecificContext, Prompt, PromptMetadata } from "../types.js";
|
||||
import { BaseNextEditProvider } from "./BaseNextEditProvider.js";
|
||||
import { BaseNextEditModelProvider } from "./BaseNextEditProvider.js";
|
||||
|
||||
export class MercuryCoderProvider extends BaseNextEditProvider {
|
||||
export class MercuryCoderProvider extends BaseNextEditModelProvider {
|
||||
private templateRenderer: PromptTemplateRenderer;
|
||||
|
||||
constructor() {
|
||||
|
|
|
|||
|
|
@ -63,6 +63,7 @@ export interface NextEditOutcome extends TabAutocompleteOptions {
|
|||
cursorPosition: { line: number; character: number };
|
||||
finalCursorPosition: { line: number; character: number };
|
||||
accepted?: boolean;
|
||||
aborted?: boolean;
|
||||
editableRegionStartLine: number;
|
||||
editableRegionEndLine: number;
|
||||
diffLines: DiffLine[];
|
||||
|
|
|
|||
40
core/package-lock.json
generated
40
core/package-lock.json
generated
|
|
@ -17,6 +17,7 @@
|
|||
"@continuedev/fetch": "file:../packages/fetch",
|
||||
"@continuedev/llm-info": "file:../packages/llm-info",
|
||||
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
|
||||
"@continuedev/terminal-security": "file:../packages/terminal-security",
|
||||
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.1.1",
|
||||
|
|
@ -67,6 +68,7 @@
|
|||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
"request": "^2.88.2",
|
||||
"shell-quote": "^1.8.3",
|
||||
"socket.io-client": "^4.7.3",
|
||||
"sqlite": "^5.1.1",
|
||||
"sqlite3": "^5.1.7",
|
||||
|
|
@ -101,6 +103,7 @@
|
|||
"@types/pg": "^8.11.6",
|
||||
"@types/plist": "^3.0.5",
|
||||
"@types/request": "^2.48.12",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"@types/tar": "^6.1.13",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/win-ca": "^3.5.4",
|
||||
|
|
@ -236,6 +239,20 @@
|
|||
"vitest": "^3.2.4"
|
||||
}
|
||||
},
|
||||
"../packages/terminal-security": {
|
||||
"name": "@continuedev/terminal-security",
|
||||
"version": "1.0.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"shell-quote": "^1.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.19",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"typescript": "^5.5.2",
|
||||
"vitest": "^1.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@75lb/deep-merge": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.2.tgz",
|
||||
|
|
@ -2955,6 +2972,10 @@
|
|||
"resolved": "../packages/openai-adapters",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@continuedev/terminal-security": {
|
||||
"resolved": "../packages/terminal-security",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@dabh/diagnostics": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.3.tgz",
|
||||
|
|
@ -6892,6 +6913,13 @@
|
|||
"node": ">= 0.12"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/shell-quote": {
|
||||
"version": "1.7.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/shell-quote/-/shell-quote-1.7.5.tgz",
|
||||
"integrity": "sha512-+UE8GAGRPbJVQDdxi16dgadcBfQ+KG2vgZhV1+3A1XmHbmwcdwhCUwIdy+d3pAGrbvgRoVSjeI9vOWyq376Yzw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/shimmer": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/shimmer/-/shimmer-1.2.0.tgz",
|
||||
|
|
@ -17459,6 +17487,18 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/shell-quote": {
|
||||
"version": "1.8.3",
|
||||
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz",
|
||||
"integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/shiki": {
|
||||
"version": "3.7.0",
|
||||
"resolved": "https://registry.npmjs.org/shiki/-/shiki-3.7.0.tgz",
|
||||
|
|
|
|||
|
|
@ -7,7 +7,8 @@
|
|||
"vitest": "vitest run",
|
||||
"test:coverage": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --coverage && open ./coverage/lcov-report/index.html",
|
||||
"tsc:check": "tsc -p ./ --noEmit",
|
||||
"build:npm": "tsc -p ./tsconfig.npm.json && npm run sentry:sourcemaps",
|
||||
"build": "tsc -p ./tsconfig.npm.json",
|
||||
"build:npm": "npm run build && npm run sentry:sourcemaps",
|
||||
"lint": "eslint . --ext ts",
|
||||
"lint:fix": "eslint . --ext ts --fix",
|
||||
"sentry:sourcemaps": "sentry-cli sourcemaps inject --org continue-xd --project continue ./dist && sentry-cli sourcemaps upload --org continue-xd --project continue ./dist"
|
||||
|
|
@ -33,6 +34,7 @@
|
|||
"@types/pg": "^8.11.6",
|
||||
"@types/plist": "^3.0.5",
|
||||
"@types/request": "^2.48.12",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"@types/tar": "^6.1.13",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/win-ca": "^3.5.4",
|
||||
|
|
@ -60,6 +62,7 @@
|
|||
"@continuedev/fetch": "file:../packages/fetch",
|
||||
"@continuedev/llm-info": "file:../packages/llm-info",
|
||||
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
|
||||
"@continuedev/terminal-security": "file:../packages/terminal-security",
|
||||
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.1.1",
|
||||
|
|
@ -110,6 +113,7 @@
|
|||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
"request": "^2.88.2",
|
||||
"shell-quote": "^1.8.3",
|
||||
"socket.io-client": "^4.7.3",
|
||||
"sqlite": "^5.1.1",
|
||||
"sqlite3": "^5.1.7",
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import {
|
|||
DevDataLogEvent,
|
||||
ModelRole,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { ToolPolicy } from "@continuedev/terminal-security";
|
||||
|
||||
import {
|
||||
AutocompleteInput,
|
||||
|
|
@ -285,6 +286,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
"docs/getSuggestedDocs": [undefined, void];
|
||||
"docs/initStatuses": [undefined, void];
|
||||
"docs/getDetails": [{ startUrl: string }, DocsIndexingDetails];
|
||||
"docs/getIndexedPages": [{ startUrl: string }, string[]];
|
||||
addAutocompleteModel: [{ model: ModelDescription }, void];
|
||||
|
||||
"auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }];
|
||||
|
|
@ -292,6 +294,10 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
{ toolCall: ToolCall },
|
||||
{ contextItems: ContextItem[]; errorMessage?: string },
|
||||
];
|
||||
"tools/evaluatePolicy": [
|
||||
{ toolName: string; basePolicy: ToolPolicy; args: Record<string, unknown> },
|
||||
{ policy: ToolPolicy; displayValue?: string },
|
||||
];
|
||||
"clipboardCache/add": [{ content: string }, void];
|
||||
"controlPlane/openUrl": [{ path: string; orgSlug?: string }, void];
|
||||
"controlPlane/getEnvironment": [undefined, ControlPlaneEnv];
|
||||
|
|
|
|||
|
|
@ -71,12 +71,14 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"indexing/setPaused",
|
||||
"docs/initStatuses",
|
||||
"docs/getDetails",
|
||||
"docs/getIndexedPages",
|
||||
//
|
||||
"onboarding/complete",
|
||||
"addAutocompleteModel",
|
||||
"didChangeSelectedProfile",
|
||||
"didChangeSelectedOrg",
|
||||
"tools/call",
|
||||
"tools/evaluatePolicy",
|
||||
"controlPlane/getEnvironment",
|
||||
"controlPlane/getFreeTrialStatus",
|
||||
"controlPlane/getModelsAddOnUpgradeUrl",
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
export enum BuiltInToolNames {
|
||||
ReadFile = "read_file",
|
||||
ReadFileRange = "read_file_range",
|
||||
EditExistingFile = "edit_existing_file",
|
||||
SearchAndReplaceInFile = "search_and_replace_in_file",
|
||||
SingleFindAndReplace = "single_find_and_replace",
|
||||
MultiEdit = "multi_edit",
|
||||
ReadCurrentlyOpenFile = "read_currently_open_file",
|
||||
|
|
@ -26,7 +26,6 @@ export const BUILT_IN_GROUP_NAME = "Built-In";
|
|||
|
||||
export const CLIENT_TOOLS_IMPLS = [
|
||||
BuiltInToolNames.EditExistingFile,
|
||||
BuiltInToolNames.SearchAndReplaceInFile,
|
||||
BuiltInToolNames.SingleFindAndReplace,
|
||||
BuiltInToolNames.MultiEdit,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -12,6 +12,8 @@ import { grepSearchImpl } from "./implementations/grepSearch";
|
|||
import { lsToolImpl } from "./implementations/lsTool";
|
||||
import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile";
|
||||
import { readFileImpl } from "./implementations/readFile";
|
||||
|
||||
import { readFileRangeImpl } from "./implementations/readFileRange";
|
||||
import { requestRuleImpl } from "./implementations/requestRule";
|
||||
import { runTerminalCommandImpl } from "./implementations/runTerminalCommand";
|
||||
import { searchWebImpl } from "./implementations/searchWeb";
|
||||
|
|
@ -145,6 +147,8 @@ export async function callBuiltInTool(
|
|||
switch (functionName) {
|
||||
case BuiltInToolNames.ReadFile:
|
||||
return await readFileImpl(args, extras);
|
||||
case BuiltInToolNames.ReadFileRange:
|
||||
return await readFileRangeImpl(args, extras);
|
||||
case BuiltInToolNames.CreateNewFile:
|
||||
return await createNewFileImpl(args, extras);
|
||||
case BuiltInToolNames.GrepSearch:
|
||||
|
|
|
|||
|
|
@ -1,13 +1,15 @@
|
|||
import { Tool } from "../..";
|
||||
import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { NO_PARALLEL_TOOL_CALLING_INSRUCTION } from "./searchAndReplaceInFile";
|
||||
|
||||
export interface EditToolArgs {
|
||||
filepath: string;
|
||||
changes: string;
|
||||
}
|
||||
|
||||
export const NO_PARALLEL_TOOL_CALLING_INTSRUCTION =
|
||||
"This tool CANNOT be called in parallel with other tools.";
|
||||
|
||||
const CHANGES_DESCRIPTION =
|
||||
"Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock or write anything besides the code changes. In larger files, use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... existing code ...'";
|
||||
|
||||
|
|
@ -22,7 +24,7 @@ export const editFileTool: Tool = {
|
|||
isInstant: false,
|
||||
function: {
|
||||
name: BuiltInToolNames.EditExistingFile,
|
||||
description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}\n${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`,
|
||||
description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}\n${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}`,
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "changes"],
|
||||
|
|
|
|||
|
|
@ -9,9 +9,10 @@ export { lsTool } from "./ls";
|
|||
export { multiEditTool } from "./multiEdit";
|
||||
export { readCurrentlyOpenFileTool } from "./readCurrentlyOpenFile";
|
||||
export { readFileTool } from "./readFile";
|
||||
|
||||
export { readFileRangeTool } from "./readFileRange";
|
||||
export { requestRuleTool } from "./requestRule";
|
||||
export { runTerminalCommandTool } from "./runTerminalCommand";
|
||||
export { searchAndReplaceInFileTool } from "./searchAndReplaceInFile";
|
||||
export { searchWebTool } from "./searchWeb";
|
||||
export { singleFindAndReplaceTool } from "./singleFindAndReplace";
|
||||
export { viewDiffTool } from "./viewDiff";
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { NO_PARALLEL_TOOL_CALLING_INTSRUCTION } from "./editFile";
|
||||
import { singleFindAndReplaceTool } from "./singleFindAndReplace";
|
||||
|
||||
export interface EditOperation {
|
||||
old_string: string;
|
||||
|
|
@ -23,59 +25,41 @@ export const multiEditTool: Tool = {
|
|||
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.
|
||||
description: `This is a tool for making multiple edits to a single file in one operation. It is built on top of the ${singleFindAndReplaceTool.function.name} and allows you to perform multiple find-and-replace operations efficiently.
|
||||
Prefer this tool over the ${singleFindAndReplaceTool.function.name} 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)
|
||||
To make multiple edits to a file, provide the following:
|
||||
1. filepath: The path to the file to modify, RELATIVE to the project/workspace root (verify the directory path is correct)
|
||||
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)
|
||||
- old_string: The text to replace (must match the old file contents exactly, including all whitespace/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
|
||||
- Each edit operates on the result of the previous edit, so plan your edits carefully to avoid conflicts between sequential operations
|
||||
- Edits are atomic - 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:
|
||||
|
||||
1. ALWAYS use the ${BuiltInToolNames.ReadFile} tool just before making edits, to understand the file's up-to-date contents and context. The user can also edit the file while you are working with it.
|
||||
2. ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}
|
||||
3. 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.
|
||||
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked
|
||||
- Use replace_all for replacing and renaming all matches for a string across the file. This parameter is useful if you want to rename a variable, for instance
|
||||
|
||||
If you want to create a new file, use:
|
||||
- A new file path
|
||||
- A new file path, including new directory if needed
|
||||
- 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`,
|
||||
- Subsequent edits are not allowed - there is no need since you are creating
|
||||
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required
|
||||
|
||||
WARNINGS:
|
||||
- If earlier edits affect the text that later edits are trying to find, files can become mangled
|
||||
- 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 - they MUST be different`,
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "edits"],
|
||||
|
|
@ -95,16 +79,18 @@ If you want to create a new file, use:
|
|||
properties: {
|
||||
old_string: {
|
||||
type: "string",
|
||||
description: "The text to replace",
|
||||
description:
|
||||
"The text to replace (exact match including whitespace/indentation)",
|
||||
},
|
||||
new_string: {
|
||||
type: "string",
|
||||
description: "The text to replace it with",
|
||||
description:
|
||||
"The text to replace it with. MUST be different than old_string.",
|
||||
},
|
||||
replace_all: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"Replace all occurrences of old_string (default false)",
|
||||
"Replace all occurrences of old_string (default false) in the file",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
|
|||
51
core/tools/definitions/readFileRange.ts
Normal file
51
core/tools/definitions/readFileRange.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export const readFileRangeTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Read File Range",
|
||||
wouldLikeTo:
|
||||
"read lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
|
||||
isCurrently:
|
||||
"reading lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
|
||||
hasAlready:
|
||||
"viewed lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
|
||||
readonly: true,
|
||||
isInstant: true,
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
name: BuiltInToolNames.ReadFileRange,
|
||||
description:
|
||||
"Use this tool to read a specific range of lines from an existing file. Only supports positive line numbers (1-based from start). For reading from the end of a file, use the terminal tool with 'tail' command instead.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "startLine", "endLine"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path of the file to read, relative to the root of the workspace (NOT uri or absolute path)",
|
||||
},
|
||||
startLine: {
|
||||
type: "number",
|
||||
description:
|
||||
"The starting line number (1-based from start). Must be a positive integer. Example: 1 = first line, 10 = tenth line",
|
||||
},
|
||||
endLine: {
|
||||
type: "number",
|
||||
description:
|
||||
"The ending line number (1-based from start). Must be a positive integer greater than or equal to startLine. Example: 10 = tenth line, 20 = twentieth line",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: {
|
||||
prefix: `To read a specific range of lines from a file, use the ${BuiltInToolNames.ReadFileRange} tool. Only supports positive line numbers (1-based from start). For reading from the end of files, use the terminal tool with 'tail' command instead:`,
|
||||
exampleArgs: [
|
||||
["filepath", "path/to/the_file.txt"],
|
||||
["startLine", 10],
|
||||
["endLine", 20],
|
||||
],
|
||||
},
|
||||
defaultToolPolicy: "allowedWithoutPermission",
|
||||
};
|
||||
|
|
@ -1,6 +1,10 @@
|
|||
import os from "os";
|
||||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import {
|
||||
evaluateTerminalCommandSecurity,
|
||||
ToolPolicy,
|
||||
} from "@continuedev/terminal-security";
|
||||
|
||||
/**
|
||||
* Get the preferred shell for the current platform
|
||||
|
|
@ -56,6 +60,15 @@ export const runTerminalCommandTool: Tool = {
|
|||
},
|
||||
},
|
||||
defaultToolPolicy: "allowedWithPermission",
|
||||
evaluateToolCallPolicy: (
|
||||
basePolicy: ToolPolicy,
|
||||
parsedArgs: Record<string, unknown>,
|
||||
): ToolPolicy => {
|
||||
return evaluateTerminalCommandSecurity(
|
||||
basePolicy,
|
||||
parsedArgs.command as string,
|
||||
);
|
||||
},
|
||||
systemMessageDescription: {
|
||||
prefix: `To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool
|
||||
${RUN_COMMAND_NOTES}
|
||||
|
|
|
|||
|
|
@ -1,112 +0,0 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
export interface SearchAndReplaceInFileArgs {
|
||||
filepath: string;
|
||||
diffs: string[];
|
||||
}
|
||||
|
||||
// Currently unsupported and filtered out in `gui/src/redux/slices/sessionSlice.ts`
|
||||
export const NO_PARALLEL_TOOL_CALLING_INSRUCTION =
|
||||
"Note this tool CANNOT be called in parallel.";
|
||||
|
||||
const SEARCH_AND_REPLACE_EXAMPLE_BLOCK = `------- SEARCH
|
||||
[exact content to find]
|
||||
=======
|
||||
[new content to replace with]
|
||||
+++++++ REPLACE`;
|
||||
|
||||
const SEARCH_AND_REPLACE_RULES = `Critical rules:
|
||||
1. SEARCH content must match the associated file section to find EXACTLY:
|
||||
* Match character-for-character including whitespace, indentation, line endings
|
||||
* Include all comments, docstrings, etc.
|
||||
2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence.
|
||||
* Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes.
|
||||
* Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change.
|
||||
* When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file.
|
||||
3. **Order matters**: DIFFs in the array should be ordered from top to bottom of the file to ensure correct application.
|
||||
4. Keep SEARCH/REPLACE blocks concise:
|
||||
* Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file.
|
||||
* Include just the changing lines, and a few surrounding lines if needed for uniqueness.
|
||||
* Do not include long runs of unchanging lines in SEARCH/REPLACE blocks.
|
||||
* Each line must be complete. Never truncate lines mid-way through as this can cause matching failures.
|
||||
5. Splitting up tool calls:
|
||||
* When making multiple closely related edits to the same file, you should try to use multiple SEARCH/REPLACE blocks in a single tool call, rather than making multiple separate tool calls
|
||||
* If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls
|
||||
* DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call]
|
||||
6. Special operations:
|
||||
* To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
|
||||
* To delete code: Use empty REPLACE section
|
||||
7. You should always read the file before trying to edit it, to ensure you know the up-to-date file contents`;
|
||||
|
||||
const SEARCH_AND_REPLACE_DIFFS_DESCRIPTION = `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format:
|
||||
\`\`\`
|
||||
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
|
||||
\`\`\`
|
||||
|
||||
${SEARCH_AND_REPLACE_RULES}
|
||||
|
||||
Usage:
|
||||
\`\`\`
|
||||
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
|
||||
|
||||
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
|
||||
\`\`\`
|
||||
|
||||
Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`;
|
||||
|
||||
/**
|
||||
* This tool is in an experimental state.
|
||||
* Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121
|
||||
*/
|
||||
export const searchAndReplaceInFileTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "Edit File",
|
||||
wouldLikeTo: "edit {{{ filepath }}}",
|
||||
isCurrently: "editing {{{ filepath }}}",
|
||||
hasAlready: "edited {{{ filepath }}}",
|
||||
group: BUILT_IN_GROUP_NAME,
|
||||
readonly: false,
|
||||
isInstant: false,
|
||||
function: {
|
||||
name: BuiltInToolNames.SearchAndReplaceInFile,
|
||||
description: `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`,
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "diffs"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description: `The path of the file to modify, relative to the root of the workspace.`,
|
||||
},
|
||||
diffs: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "string",
|
||||
},
|
||||
description: SEARCH_AND_REPLACE_DIFFS_DESCRIPTION,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
systemMessageDescription: {
|
||||
prefix: `To make targeted edits by replacing sections of content in an existing file, use the ${BuiltInToolNames.SearchAndReplaceInFile} tool with a filepath (relative to the root of the workspace) and a "diffs" argument containing an array of SEARCH/REPLACE blocks that define exact changes to specific parts of the file.
|
||||
Each block should follow this format:
|
||||
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
|
||||
|
||||
${SEARCH_AND_REPLACE_RULES}
|
||||
|
||||
For example, you could respond with:`,
|
||||
exampleArgs: [
|
||||
["filepath", "path/to/file.ts"],
|
||||
[
|
||||
"diffs",
|
||||
`[
|
||||
"${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}",
|
||||
"${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}"
|
||||
]`,
|
||||
],
|
||||
],
|
||||
},
|
||||
defaultToolPolicy: "allowedWithPermission",
|
||||
};
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { NO_PARALLEL_TOOL_CALLING_INTSRUCTION } from "./editFile";
|
||||
|
||||
export interface SingleFindAndReplaceArgs {
|
||||
filepath: string;
|
||||
|
|
@ -19,31 +20,18 @@ export const singleFindAndReplaceTool: Tool = {
|
|||
isInstant: false,
|
||||
function: {
|
||||
name: BuiltInToolNames.SingleFindAndReplace,
|
||||
description: `Performs exact string replacements in files.
|
||||
description: `Performs exact string replacements in a file.
|
||||
|
||||
Usage:
|
||||
IMPORTANT:
|
||||
- ALWAYS use the \`${BuiltInToolNames.ReadFile}\` tool just before making edits, to understand the file's up-to-date contents and context. The user can also edit the file while you are working with it.
|
||||
- ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}
|
||||
- When editing text from \`${BuiltInToolNames.ReadFile}\` tool output, ensure you preserve exact whitespace/indentation.
|
||||
- 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.
|
||||
|
||||
- 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.`,
|
||||
WARNINGS:
|
||||
- When not using \`replace_all\`, the edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`.
|
||||
- The edit will likely fail if you have not recently used the \`${BuiltInToolNames.ReadFile}\` tool to view up-to-date file contents.`,
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "old_string", "new_string"],
|
||||
|
|
@ -55,12 +43,13 @@ parameter is useful if you want to rename a variable for instance.`,
|
|||
},
|
||||
old_string: {
|
||||
type: "string",
|
||||
description: "The text to replace",
|
||||
description:
|
||||
"The text to replace - must be exact including whitespace/indentation",
|
||||
},
|
||||
new_string: {
|
||||
type: "string",
|
||||
description:
|
||||
"The text to replace it with (must be different from old_string)",
|
||||
"The text to replace it with (MUST be different from old_string)",
|
||||
},
|
||||
replace_all: {
|
||||
type: "boolean",
|
||||
|
|
|
|||
204
core/tools/implementations/readFileRange.integration.vitest.ts
Normal file
204
core/tools/implementations/readFileRange.integration.vitest.ts
Normal file
|
|
@ -0,0 +1,204 @@
|
|||
import { expect, test, vi } from "vitest";
|
||||
import { ToolExtras } from "../..";
|
||||
import { readFileRangeImpl } from "./readFileRange";
|
||||
|
||||
// Mock the dependencies
|
||||
vi.mock("../../util/ideUtils", () => ({
|
||||
resolveRelativePathInDir: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../util/uri", () => ({
|
||||
getUriPathBasename: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./readFileLimit", () => ({
|
||||
throwIfFileExceedsHalfOfContext: vi.fn(),
|
||||
}));
|
||||
|
||||
test("readFileRangeImpl handles out-of-bounds ranges gracefully", async () => {
|
||||
const { resolveRelativePathInDir } = await import("../../util/ideUtils");
|
||||
const { getUriPathBasename } = await import("../../util/uri");
|
||||
const { throwIfFileExceedsHalfOfContext } = await import("./readFileLimit");
|
||||
|
||||
// Mock the utility functions
|
||||
vi.mocked(resolveRelativePathInDir).mockResolvedValue("file:///test.txt");
|
||||
vi.mocked(getUriPathBasename).mockReturnValue("test.txt");
|
||||
vi.mocked(throwIfFileExceedsHalfOfContext).mockResolvedValue(undefined);
|
||||
|
||||
// Test case 1: Start line beyond end of file
|
||||
const mockIdeOutOfBounds = {
|
||||
readRangeInFile: vi.fn().mockResolvedValue(""), // IDE returns empty string
|
||||
};
|
||||
|
||||
const mockExtras1 = {
|
||||
ide: mockIdeOutOfBounds,
|
||||
config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
|
||||
} as unknown as ToolExtras;
|
||||
|
||||
const result1 = await readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: 100, // Beyond end of file
|
||||
endLine: 105,
|
||||
},
|
||||
mockExtras1,
|
||||
);
|
||||
|
||||
expect(result1).toHaveLength(1);
|
||||
expect(result1[0].content).toBe("");
|
||||
expect(result1[0].description).toBe("test.txt (lines 100-105)");
|
||||
|
||||
// Test case 2: End line beyond end of file
|
||||
const mockIdePartialRange = {
|
||||
readRangeInFile: vi.fn().mockResolvedValue("line5\nline6"), // IDE returns available content
|
||||
};
|
||||
|
||||
const mockExtras2 = {
|
||||
ide: mockIdePartialRange,
|
||||
config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
|
||||
} as unknown as ToolExtras;
|
||||
|
||||
const result2 = await readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: 5,
|
||||
endLine: 100, // Beyond end of file
|
||||
},
|
||||
mockExtras2,
|
||||
);
|
||||
|
||||
expect(result2).toHaveLength(1);
|
||||
expect(result2[0].content).toBe("line5\nline6");
|
||||
expect(result2[0].description).toBe("test.txt (lines 5-100)");
|
||||
|
||||
// Verify that IDE methods were called with correct 0-based ranges
|
||||
expect(mockIdeOutOfBounds.readRangeInFile).toHaveBeenCalledWith(
|
||||
"file:///test.txt",
|
||||
{
|
||||
start: { line: 99, character: 0 }, // 100 - 1
|
||||
end: { line: 104, character: Number.MAX_SAFE_INTEGER }, // 105 - 1
|
||||
},
|
||||
);
|
||||
|
||||
expect(mockIdePartialRange.readRangeInFile).toHaveBeenCalledWith(
|
||||
"file:///test.txt",
|
||||
{
|
||||
start: { line: 4, character: 0 }, // 5 - 1
|
||||
end: { line: 99, character: Number.MAX_SAFE_INTEGER }, // 100 - 1
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("readFileRangeImpl validates line number constraints", async () => {
|
||||
const mockExtras = {
|
||||
ide: { readRangeInFile: vi.fn(), readFile: vi.fn() },
|
||||
config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
|
||||
} as unknown as ToolExtras;
|
||||
|
||||
// Test startLine < 1 (invalid)
|
||||
await expect(
|
||||
readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: 0,
|
||||
endLine: 5,
|
||||
},
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("startLine must be 1 or greater");
|
||||
|
||||
// Test negative startLine (no longer supported)
|
||||
await expect(
|
||||
readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: -1,
|
||||
endLine: 5,
|
||||
},
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("Negative line numbers are not supported");
|
||||
|
||||
// Test endLine < 1 (invalid)
|
||||
await expect(
|
||||
readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: 1,
|
||||
endLine: 0,
|
||||
},
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("endLine must be 1 or greater");
|
||||
|
||||
// Test negative endLine (no longer supported)
|
||||
await expect(
|
||||
readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: 1,
|
||||
endLine: -1,
|
||||
},
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow("Negative line numbers are not supported");
|
||||
|
||||
// Test endLine < startLine
|
||||
await expect(
|
||||
readFileRangeImpl(
|
||||
{
|
||||
filepath: "test.txt",
|
||||
startLine: 10,
|
||||
endLine: 5,
|
||||
},
|
||||
mockExtras,
|
||||
),
|
||||
).rejects.toThrow(
|
||||
"endLine (5) must be greater than or equal to startLine (10)",
|
||||
);
|
||||
});
|
||||
|
||||
test("readFileRangeImpl handles normal ranges correctly", async () => {
|
||||
const { resolveRelativePathInDir } = await import("../../util/ideUtils");
|
||||
const { getUriPathBasename } = await import("../../util/uri");
|
||||
const { throwIfFileExceedsHalfOfContext } = await import("./readFileLimit");
|
||||
|
||||
vi.mocked(resolveRelativePathInDir).mockResolvedValue("file:///test.txt");
|
||||
vi.mocked(getUriPathBasename).mockReturnValue("test.txt");
|
||||
vi.mocked(throwIfFileExceedsHalfOfContext).mockResolvedValue(undefined);
|
||||
|
||||
const mockIde = {
|
||||
readRangeInFile: vi.fn().mockResolvedValue("line2\nline3\nline4"),
|
||||
};
|
||||
|
||||
const mockExtras = {
|
||||
ide: mockIde,
|
||||
config: { selectedModelByRole: { chat: { contextLength: 8192 } } },
|
||||
} as unknown as ToolExtras;
|
||||
|
||||
const result = await readFileRangeImpl(
|
||||
{
|
||||
filepath: "src/test.py",
|
||||
startLine: 2,
|
||||
endLine: 4,
|
||||
},
|
||||
mockExtras,
|
||||
);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toEqual({
|
||||
name: "test.txt",
|
||||
description: "src/test.py (lines 2-4)",
|
||||
content: "line2\nline3\nline4",
|
||||
uri: {
|
||||
type: "file",
|
||||
value: "file:///test.txt",
|
||||
},
|
||||
});
|
||||
|
||||
// Verify correct 0-based conversion
|
||||
expect(mockIde.readRangeInFile).toHaveBeenCalledWith("file:///test.txt", {
|
||||
start: { line: 1, character: 0 }, // 2 - 1
|
||||
end: { line: 3, character: Number.MAX_SAFE_INTEGER }, // 4 - 1
|
||||
});
|
||||
});
|
||||
68
core/tools/implementations/readFileRange.ts
Normal file
68
core/tools/implementations/readFileRange.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import { resolveRelativePathInDir } from "../../util/ideUtils";
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
import { getNumberArg, getStringArg } from "../parseArgs";
|
||||
import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
|
||||
|
||||
export const readFileRangeImpl: ToolImpl = async (args, extras) => {
|
||||
const filepath = getStringArg(args, "filepath");
|
||||
const startLine = getNumberArg(args, "startLine");
|
||||
const endLine = getNumberArg(args, "endLine");
|
||||
|
||||
// Validate that line numbers are positive integers
|
||||
if (startLine < 1) {
|
||||
throw new Error(
|
||||
"startLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.",
|
||||
);
|
||||
}
|
||||
if (endLine < 1) {
|
||||
throw new Error(
|
||||
"endLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.",
|
||||
);
|
||||
}
|
||||
if (endLine < startLine) {
|
||||
throw new Error(
|
||||
`endLine (${endLine}) must be greater than or equal to startLine (${startLine})`,
|
||||
);
|
||||
}
|
||||
|
||||
const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide);
|
||||
if (!firstUriMatch) {
|
||||
throw new Error(
|
||||
`File "${filepath}" does not exist. You might want to check the path and try again.`,
|
||||
);
|
||||
}
|
||||
|
||||
// Use the IDE's readRangeInFile method with 0-based range (IDE expects 0-based internally)
|
||||
const content = await extras.ide.readRangeInFile(firstUriMatch, {
|
||||
start: {
|
||||
line: startLine - 1, // Convert from 1-based to 0-based
|
||||
character: 0,
|
||||
},
|
||||
end: {
|
||||
line: endLine - 1, // Convert from 1-based to 0-based
|
||||
character: Number.MAX_SAFE_INTEGER, // Read to end of line
|
||||
},
|
||||
});
|
||||
|
||||
await throwIfFileExceedsHalfOfContext(
|
||||
filepath,
|
||||
content,
|
||||
extras.config.selectedModelByRole.chat,
|
||||
);
|
||||
|
||||
const rangeDescription = `${filepath} (lines ${startLine}-${endLine})`;
|
||||
|
||||
return [
|
||||
{
|
||||
name: getUriPathBasename(firstUriMatch),
|
||||
description: rangeDescription,
|
||||
content,
|
||||
uri: {
|
||||
type: "file",
|
||||
value: firstUriMatch,
|
||||
},
|
||||
},
|
||||
];
|
||||
};
|
||||
60
core/tools/implementations/readFileRange.vitest.ts
Normal file
60
core/tools/implementations/readFileRange.vitest.ts
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import { expect, test } from "vitest";
|
||||
import { getNumberArg } from "../parseArgs";
|
||||
|
||||
test("readFileRange should validate positive line number arguments", () => {
|
||||
// Test positive startLine validation
|
||||
expect(() => getNumberArg({ startLine: 1 }, "startLine")).not.toThrow();
|
||||
expect(() => getNumberArg({ startLine: "1" }, "startLine")).not.toThrow();
|
||||
expect(() => getNumberArg({ startLine: 100 }, "startLine")).not.toThrow();
|
||||
|
||||
// Test positive endLine validation
|
||||
expect(() => getNumberArg({ endLine: 5 }, "endLine")).not.toThrow();
|
||||
expect(() => getNumberArg({ endLine: "10" }, "endLine")).not.toThrow();
|
||||
expect(() => getNumberArg({ endLine: 1000 }, "endLine")).not.toThrow();
|
||||
|
||||
// Test missing arguments
|
||||
expect(() => getNumberArg({}, "startLine")).toThrow(
|
||||
"Argument `startLine` is required (type number)",
|
||||
);
|
||||
expect(() => getNumberArg({}, "endLine")).toThrow(
|
||||
"Argument `endLine` is required (type number)",
|
||||
);
|
||||
|
||||
// Test invalid arguments
|
||||
expect(() =>
|
||||
getNumberArg({ startLine: "not-a-number" }, "startLine"),
|
||||
).toThrow("Argument `startLine` must be a valid number");
|
||||
expect(() => getNumberArg({ endLine: true }, "endLine")).toThrow(
|
||||
"Argument `endLine` must be a valid number",
|
||||
);
|
||||
});
|
||||
|
||||
test("readFileRange should handle line number conversion", () => {
|
||||
// Test that our parsing function converts correctly
|
||||
expect(getNumberArg({ line: 1 }, "line")).toBe(1);
|
||||
expect(getNumberArg({ line: "5" }, "line")).toBe(5);
|
||||
expect(getNumberArg({ line: 10.7 }, "line")).toBe(10); // Should floor
|
||||
expect(getNumberArg({ line: "15.9" }, "line")).toBe(15); // Should floor
|
||||
});
|
||||
|
||||
test("readFileRange parses negative numbers (validation happens in implementation)", () => {
|
||||
// The parseArgs function should parse negative numbers correctly
|
||||
// but the implementation will reject them with helpful error messages
|
||||
expect(getNumberArg({ line: -1 }, "line")).toBe(-1);
|
||||
expect(getNumberArg({ line: -10 }, "line")).toBe(-10);
|
||||
expect(getNumberArg({ line: "-5" }, "line")).toBe(-5);
|
||||
});
|
||||
|
||||
test("readFileRange handles out-of-bounds ranges gracefully", () => {
|
||||
// IDE implementations handle out-of-bounds gracefully:
|
||||
// - VS Code: Uses array.slice() which handles out-of-bounds gracefully
|
||||
// - IntelliJ: Uses lines.getOrNull() which returns null for out-of-bounds
|
||||
// Both return empty content or available content without throwing errors
|
||||
|
||||
expect(() => {
|
||||
const startLine = getNumberArg({ startLine: 1000 }, "startLine");
|
||||
const endLine = getNumberArg({ endLine: 2000 }, "endLine");
|
||||
expect(startLine).toBe(1000);
|
||||
expect(endLine).toBe(2000);
|
||||
}).not.toThrow();
|
||||
});
|
||||
|
|
@ -1,4 +1,12 @@
|
|||
import { jest } from "@jest/globals";
|
||||
import {
|
||||
describe,
|
||||
it,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
afterAll,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import * as childProcess from "node:child_process";
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
|
|
@ -6,17 +14,18 @@ import * as path from "node:path";
|
|||
import { IDE, ToolExtras } from "../..";
|
||||
import * as processBackgroundStates from "../../util/processTerminalBackgroundStates";
|
||||
import { runTerminalCommandImpl } from "./runTerminalCommand";
|
||||
import { runTerminalCommandTool } from "../definitions/runTerminalCommand";
|
||||
|
||||
// We're using real child processes, so ensure these aren't mocked
|
||||
jest.unmock("node:child_process");
|
||||
jest.unmock("node:util");
|
||||
vi.unmock("node:child_process");
|
||||
vi.unmock("node:util");
|
||||
|
||||
describe("runTerminalCommandImpl", () => {
|
||||
// Setup mocks and spies
|
||||
const mockGetIdeInfo = jest.fn();
|
||||
const mockGetWorkspaceDirs = jest.fn();
|
||||
const mockOnPartialOutput = jest.fn();
|
||||
const mockRunCommand = jest.fn();
|
||||
const mockGetIdeInfo = vi.fn();
|
||||
const mockGetWorkspaceDirs = vi.fn();
|
||||
const mockOnPartialOutput = vi.fn();
|
||||
const mockRunCommand = vi.fn();
|
||||
|
||||
// Use a simple approach to ensure background processes are terminated
|
||||
let testPid: number | null = null;
|
||||
|
|
@ -27,7 +36,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
);
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
vi.resetAllMocks();
|
||||
|
||||
// Setup backgrounded processes handling - don't mock, just make sure it's empty
|
||||
// Get any processes that might be already tracked and clear them
|
||||
|
|
@ -73,7 +82,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
// Helper function to create a ToolExtras object
|
||||
const createMockExtras = (
|
||||
overrides: Partial<{
|
||||
onPartialOutput?: jest.Mock;
|
||||
onPartialOutput?: any;
|
||||
remoteName?: string;
|
||||
}> = {},
|
||||
): ToolExtras => {
|
||||
|
|
@ -90,16 +99,16 @@ describe("runTerminalCommandImpl", () => {
|
|||
getWorkspaceDirs: mockGetWorkspaceDirs,
|
||||
runCommand: mockRunCommand,
|
||||
// Add stubs for other required IDE methods
|
||||
getIdeSettings: jest.fn(),
|
||||
getDiff: jest.fn(),
|
||||
getClipboardContent: jest.fn(),
|
||||
isTelemetryEnabled: jest.fn(),
|
||||
readFile: jest.fn(),
|
||||
writeFile: jest.fn(),
|
||||
renameFile: jest.fn(),
|
||||
deleteFile: jest.fn(),
|
||||
globFiles: jest.fn(),
|
||||
ls: jest.fn(),
|
||||
getIdeSettings: vi.fn(),
|
||||
getDiff: vi.fn(),
|
||||
getClipboardContent: vi.fn(),
|
||||
isTelemetryEnabled: vi.fn(),
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
renameFile: vi.fn(),
|
||||
deleteFile: vi.fn(),
|
||||
globFiles: vi.fn(),
|
||||
ls: vi.fn(),
|
||||
};
|
||||
|
||||
// Create a base ToolExtras object with required properties
|
||||
|
|
@ -147,7 +156,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
"`;
|
||||
|
||||
const args = { command, waitForCompletion: true };
|
||||
const mockOutputFn = jest.fn();
|
||||
const mockOutputFn = vi.fn();
|
||||
const extras = createMockExtras({ onPartialOutput: mockOutputFn });
|
||||
|
||||
// Execute the command with streaming
|
||||
|
|
@ -191,7 +200,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
"`;
|
||||
|
||||
const args = { command, waitForCompletion: false };
|
||||
const mockOutputFn = jest.fn();
|
||||
const mockOutputFn = vi.fn();
|
||||
const extras = createMockExtras({ onPartialOutput: mockOutputFn });
|
||||
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
|
@ -355,25 +364,25 @@ describe("runTerminalCommandImpl", () => {
|
|||
|
||||
it("should handle missing workspace directory gracefully", async () => {
|
||||
// Mock IDE to return empty workspace directories
|
||||
const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([]));
|
||||
const mockEmptyWorkspace = vi.fn().mockReturnValue(Promise.resolve([]));
|
||||
|
||||
// Create IDE mock with empty workspace
|
||||
const mockIde = {
|
||||
getIdeInfo: jest
|
||||
getIdeInfo: vi
|
||||
.fn()
|
||||
.mockReturnValue(Promise.resolve({ remoteName: "local" })),
|
||||
getWorkspaceDirs: mockEmptyWorkspace,
|
||||
runCommand: jest.fn(),
|
||||
getIdeSettings: jest.fn(),
|
||||
getDiff: jest.fn(),
|
||||
getClipboardContent: jest.fn(),
|
||||
isTelemetryEnabled: jest.fn(),
|
||||
readFile: jest.fn(),
|
||||
writeFile: jest.fn(),
|
||||
renameFile: jest.fn(),
|
||||
deleteFile: jest.fn(),
|
||||
globFiles: jest.fn(),
|
||||
ls: jest.fn(),
|
||||
runCommand: vi.fn(),
|
||||
getIdeSettings: vi.fn(),
|
||||
getDiff: vi.fn(),
|
||||
getClipboardContent: vi.fn(),
|
||||
isTelemetryEnabled: vi.fn(),
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
renameFile: vi.fn(),
|
||||
deleteFile: vi.fn(),
|
||||
globFiles: vi.fn(),
|
||||
ls: vi.fn(),
|
||||
};
|
||||
|
||||
const extras = {
|
||||
|
|
@ -402,7 +411,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
|
||||
it("should handle case where cwd fallbacks all fail", async () => {
|
||||
// Mock IDE to return empty workspace directories
|
||||
const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([]));
|
||||
const mockEmptyWorkspace = vi.fn().mockReturnValue(Promise.resolve([]));
|
||||
|
||||
// Save original environment variables and process.cwd
|
||||
const originalHome = process.env.HOME;
|
||||
|
|
@ -413,27 +422,27 @@ describe("runTerminalCommandImpl", () => {
|
|||
// Mock all fallbacks to fail
|
||||
delete process.env.HOME;
|
||||
delete process.env.USERPROFILE;
|
||||
process.cwd = jest.fn().mockImplementation(() => {
|
||||
process.cwd = vi.fn().mockImplementation(() => {
|
||||
throw new Error("Current directory unavailable");
|
||||
}) as jest.MockedFunction<() => string>;
|
||||
}) as any;
|
||||
|
||||
// Create IDE mock with empty workspace
|
||||
const mockIde = {
|
||||
getIdeInfo: jest
|
||||
getIdeInfo: vi
|
||||
.fn()
|
||||
.mockReturnValue(Promise.resolve({ remoteName: "local" })),
|
||||
getWorkspaceDirs: mockEmptyWorkspace,
|
||||
runCommand: jest.fn(),
|
||||
getIdeSettings: jest.fn(),
|
||||
getDiff: jest.fn(),
|
||||
getClipboardContent: jest.fn(),
|
||||
isTelemetryEnabled: jest.fn(),
|
||||
readFile: jest.fn(),
|
||||
writeFile: jest.fn(),
|
||||
renameFile: jest.fn(),
|
||||
deleteFile: jest.fn(),
|
||||
globFiles: jest.fn(),
|
||||
ls: jest.fn(),
|
||||
runCommand: vi.fn(),
|
||||
getIdeSettings: vi.fn(),
|
||||
getDiff: vi.fn(),
|
||||
getClipboardContent: vi.fn(),
|
||||
isTelemetryEnabled: vi.fn(),
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
renameFile: vi.fn(),
|
||||
deleteFile: vi.fn(),
|
||||
globFiles: vi.fn(),
|
||||
ls: vi.fn(),
|
||||
};
|
||||
|
||||
const extras = {
|
||||
|
|
@ -472,3 +481,125 @@ describe("runTerminalCommandImpl", () => {
|
|||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTerminalCommandTool.evaluateToolCallPolicy", () => {
|
||||
it("should return base policy for safe commands like echo", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "echo hello world" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithoutPermission");
|
||||
});
|
||||
|
||||
it("should respect disabled policy even for non-echo commands", () => {
|
||||
const basePolicy = "disabled";
|
||||
const args = { command: "ls -la" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("disabled");
|
||||
});
|
||||
|
||||
it("should respect disabled policy even for safe commands", () => {
|
||||
const basePolicy = "disabled";
|
||||
const args = { command: "echo test" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("disabled");
|
||||
});
|
||||
|
||||
it("should return base policy for non-echo commands", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "ls -la" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithoutPermission");
|
||||
});
|
||||
|
||||
it("should return base policy for git commands", () => {
|
||||
const basePolicy = "allowedWithPermission";
|
||||
const args = { command: "git status" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithPermission");
|
||||
});
|
||||
|
||||
it("should handle undefined command gracefully", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: undefined };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithoutPermission");
|
||||
});
|
||||
|
||||
it("should handle null command gracefully", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: null };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithoutPermission");
|
||||
});
|
||||
|
||||
it("should handle empty command string", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithoutPermission");
|
||||
});
|
||||
|
||||
it("should disable dangerous commands like rm -rf /", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "rm -rf /" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("disabled");
|
||||
});
|
||||
|
||||
it("should require permission for high-risk network commands", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "curl http://example.com" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithPermission");
|
||||
});
|
||||
});
|
||||
|
|
@ -4,6 +4,7 @@ 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.
|
||||
export const getBaseToolDefinitions = () => [
|
||||
toolDefinitions.readFileTool,
|
||||
|
||||
toolDefinitions.createNewFileTool,
|
||||
toolDefinitions.runTerminalCommandTool,
|
||||
toolDefinitions.globSearchTool,
|
||||
|
|
@ -33,11 +34,10 @@ export const getConfigDependentToolDefinitions = (
|
|||
toolDefinitions.viewRepoMapTool,
|
||||
toolDefinitions.viewSubdirectoryTool,
|
||||
toolDefinitions.codebaseTool,
|
||||
toolDefinitions.readFileRangeTool,
|
||||
);
|
||||
}
|
||||
|
||||
// OLD SEARCH AND REPLACE IS CURRENTLY NOT USED
|
||||
// toolDefinitions.searchAndReplaceInFileTool
|
||||
if (modelName?.includes("claude") || modelName?.includes("gpt-5")) {
|
||||
tools.push(toolDefinitions.multiEditTool);
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,12 @@
|
|||
import { MCPServerStatus, MCPTool } from "..";
|
||||
|
||||
export function getMCPToolName(server: MCPServerStatus, tool: MCPTool) {
|
||||
const serverPrefix = server.name.split(" ").join("_").toLowerCase();
|
||||
// Replace any sequence of non-alphanumeric characters with a single underscore
|
||||
const serverPrefix = server.name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "_")
|
||||
.replace(/^_+|_+$/g, "") // Remove leading/trailing underscores
|
||||
.replace(/_+/g, "_"); // Replace multiple sequential underscores with single underscore
|
||||
|
||||
if (tool.name.startsWith(serverPrefix)) {
|
||||
return tool.name;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -56,3 +56,54 @@ test("getMCPToolName - handles mixed case in server names", () => {
|
|||
const result = getMCPToolName(server, tool);
|
||||
expect(result).toBe("gitlab_create_merge_request");
|
||||
});
|
||||
|
||||
test("getMCPToolName - handles server names with special characters (parentheses)", () => {
|
||||
const server = createMcpServer("Linear MCP (SSE)");
|
||||
const tool = createMCPTool("create_issue");
|
||||
|
||||
const result = getMCPToolName(server, tool);
|
||||
// Should only contain alphanumeric characters and underscores
|
||||
expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
|
||||
expect(result).toBe("linear_mcp_sse_create_issue");
|
||||
});
|
||||
|
||||
test("getMCPToolName - handles server names with dots and other special characters", () => {
|
||||
const server = createMcpServer("My.Server@Test!");
|
||||
const tool = createMCPTool("test_action");
|
||||
|
||||
const result = getMCPToolName(server, tool);
|
||||
// Should only contain alphanumeric characters and underscores
|
||||
expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
|
||||
expect(result).toBe("my_server_test_test_action");
|
||||
});
|
||||
|
||||
test("getMCPToolName - handles server names with multiple consecutive special characters", () => {
|
||||
const server = createMcpServer("Server@@##Name");
|
||||
const tool = createMCPTool("action");
|
||||
|
||||
const result = getMCPToolName(server, tool);
|
||||
// Should only contain alphanumeric characters and underscores (no hyphens or multiple underscores)
|
||||
expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
|
||||
expect(result).toBe("server_name_action");
|
||||
});
|
||||
|
||||
test("getMCPToolName - handles server names with hyphens", () => {
|
||||
const server = createMcpServer("My-Server-Name");
|
||||
const tool = createMCPTool("test_action");
|
||||
|
||||
const result = getMCPToolName(server, tool);
|
||||
// Should only contain alphanumeric characters and underscores
|
||||
expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
|
||||
expect(result).toBe("my_server_name_test_action");
|
||||
});
|
||||
|
||||
test("getMCPToolName - handles multiple consecutive underscores in server name", () => {
|
||||
const server = createMcpServer("Linear__MCP");
|
||||
const tool = createMCPTool("create_issue");
|
||||
|
||||
const result = getMCPToolName(server, tool);
|
||||
// Should only contain alphanumeric characters and single underscores
|
||||
expect(result).toMatch(/^[a-zA-Z0-9_]+$/);
|
||||
expect(result).not.toMatch(/__/);
|
||||
expect(result).toBe("linear_mcp_create_issue");
|
||||
});
|
||||
|
|
|
|||
|
|
@ -40,6 +40,24 @@ export function getOptionalStringArg(
|
|||
return getStringArg(args, argName, allowEmpty);
|
||||
}
|
||||
|
||||
export function getNumberArg(args: any, argName: string): number {
|
||||
if (!args || !(argName in args)) {
|
||||
throw new Error(`Argument \`${argName}\` is required (type number)`);
|
||||
}
|
||||
const value = args[argName];
|
||||
if (typeof value === "string") {
|
||||
const parsed = parseInt(value, 10);
|
||||
if (isNaN(parsed)) {
|
||||
throw new Error(`Argument \`${argName}\` must be a valid number`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
if (typeof value !== "number" || isNaN(value)) {
|
||||
throw new Error(`Argument \`${argName}\` must be a valid number`);
|
||||
}
|
||||
return Math.floor(value); // Ensure integer for line numbers (supports negative numbers)
|
||||
}
|
||||
|
||||
export function getBooleanArg(args: any, argName: string, required = false) {
|
||||
if (!args || !(argName in args)) {
|
||||
if (required) {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
|||
import { ToolCallDelta } from "..";
|
||||
import {
|
||||
getBooleanArg,
|
||||
getNumberArg,
|
||||
getOptionalStringArg,
|
||||
getStringArg,
|
||||
safeParseToolCallArgs,
|
||||
|
|
@ -246,3 +247,86 @@ describe("getBooleanArg", () => {
|
|||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getNumberArg", () => {
|
||||
it("should return number argument when valid", () => {
|
||||
const args = { count: 42 };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(42);
|
||||
});
|
||||
|
||||
it("should parse string numbers", () => {
|
||||
const args = { count: "42" };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(42);
|
||||
});
|
||||
|
||||
it("should floor decimal numbers", () => {
|
||||
const args = { count: 42.7 };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(42);
|
||||
});
|
||||
|
||||
it("should parse and floor string decimal numbers", () => {
|
||||
const args = { count: "42.7" };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(42);
|
||||
});
|
||||
|
||||
it("should throw error when argument is missing", () => {
|
||||
const args = { otherArg: 42 };
|
||||
expect(() => getNumberArg(args, "count")).toThrowError(
|
||||
"Argument `count` is required (type number)",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error when argument is not a number", () => {
|
||||
const argsString = { count: "not-a-number" };
|
||||
const argsBoolean = { count: true };
|
||||
const argsObject = { count: {} };
|
||||
|
||||
expect(() => getNumberArg(argsString, "count")).toThrowError(
|
||||
"Argument `count` must be a valid number",
|
||||
);
|
||||
expect(() => getNumberArg(argsBoolean, "count")).toThrowError(
|
||||
"Argument `count` must be a valid number",
|
||||
);
|
||||
expect(() => getNumberArg(argsObject, "count")).toThrowError(
|
||||
"Argument `count` must be a valid number",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error when argument is NaN", () => {
|
||||
const args = { count: NaN };
|
||||
expect(() => getNumberArg(args, "count")).toThrowError(
|
||||
"Argument `count` must be a valid number",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle negative numbers", () => {
|
||||
const args = { count: -5 };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(-5);
|
||||
});
|
||||
|
||||
it("should handle negative string numbers", () => {
|
||||
const args = { count: "-10" };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(-10);
|
||||
});
|
||||
|
||||
it("should handle zero", () => {
|
||||
const args = { count: 0 };
|
||||
const result = getNumberArg(args, "count");
|
||||
expect(result).toBe(0);
|
||||
});
|
||||
|
||||
it("should handle null or undefined args", () => {
|
||||
expect(() => getNumberArg(null, "count")).toThrowError(
|
||||
"Argument `count` is required (type number)",
|
||||
);
|
||||
expect(() => getNumberArg(undefined, "count")).toThrowError(
|
||||
"Argument `count` is required (type number)",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
106
core/util/TokensBatchingService.ts
Normal file
106
core/util/TokensBatchingService.ts
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
import { Telemetry } from "./posthog.js";
|
||||
|
||||
interface TokenBatch {
|
||||
model: string;
|
||||
provider: string;
|
||||
count: number;
|
||||
totalPromptTokens: number;
|
||||
totalGeneratedTokens: number;
|
||||
lastEventTime: number;
|
||||
}
|
||||
|
||||
export class TokensBatchingService {
|
||||
private static instance: TokensBatchingService;
|
||||
private batches = new Map<string, TokenBatch>();
|
||||
private flushTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
private readonly BATCH_SIZE_LIMIT = 25;
|
||||
private readonly FLUSH_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes
|
||||
|
||||
static getInstance(): TokensBatchingService {
|
||||
if (!TokensBatchingService.instance) {
|
||||
TokensBatchingService.instance = new TokensBatchingService();
|
||||
}
|
||||
return TokensBatchingService.instance;
|
||||
}
|
||||
|
||||
private constructor() {
|
||||
this.startFlushTimer();
|
||||
}
|
||||
|
||||
addTokens(
|
||||
model: string,
|
||||
provider: string,
|
||||
promptTokens: number,
|
||||
generatedTokens: number,
|
||||
): void {
|
||||
const key = `${provider}:${model}`;
|
||||
|
||||
if (!this.batches.has(key)) {
|
||||
this.batches.set(key, {
|
||||
model,
|
||||
provider,
|
||||
count: 0,
|
||||
totalPromptTokens: 0,
|
||||
totalGeneratedTokens: 0,
|
||||
lastEventTime: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
const batch = this.batches.get(key)!;
|
||||
batch.count++;
|
||||
batch.totalPromptTokens += promptTokens;
|
||||
batch.totalGeneratedTokens += generatedTokens;
|
||||
batch.lastEventTime = Date.now();
|
||||
|
||||
// Flush if batch is full
|
||||
if (batch.count >= this.BATCH_SIZE_LIMIT) {
|
||||
this.flushBatch(key, batch);
|
||||
}
|
||||
}
|
||||
|
||||
private flushBatch(key: string, batch: TokenBatch): void {
|
||||
if (batch.count === 0) return;
|
||||
|
||||
void Telemetry.capture(
|
||||
"tokens_generated_batch",
|
||||
{
|
||||
model: batch.model,
|
||||
provider: batch.provider,
|
||||
eventCount: batch.count,
|
||||
totalPromptTokens: batch.totalPromptTokens,
|
||||
totalGeneratedTokens: batch.totalGeneratedTokens,
|
||||
avgPromptTokens: Math.round(batch.totalPromptTokens / batch.count),
|
||||
avgGeneratedTokens: Math.round(
|
||||
batch.totalGeneratedTokens / batch.count,
|
||||
),
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
this.batches.delete(key);
|
||||
}
|
||||
|
||||
private startFlushTimer(): void {
|
||||
this.flushTimer = setInterval(() => {
|
||||
this.flushAllBatches();
|
||||
}, this.FLUSH_INTERVAL_MS);
|
||||
// Allow the process to exit if this timer is the only thing keeping it alive
|
||||
// This prevents test hangs and allows graceful shutdown
|
||||
this.flushTimer.unref();
|
||||
}
|
||||
|
||||
private flushAllBatches(): void {
|
||||
for (const [key, batch] of this.batches.entries()) {
|
||||
this.flushBatch(key, batch);
|
||||
}
|
||||
}
|
||||
|
||||
shutdown(): void {
|
||||
if (this.flushTimer) {
|
||||
clearInterval(this.flushTimer);
|
||||
this.flushTimer = null;
|
||||
}
|
||||
this.flushAllBatches();
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ import { removeCodeBlocksAndTrim, removeQuotesAndEscapes } from ".";
|
|||
import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
|
||||
import type { IMessenger } from "../protocol/messenger";
|
||||
import { renderChatMessage } from "./messageContent";
|
||||
import { convertFromUnifiedHistory } from "./messageConversion";
|
||||
|
||||
export class ChatDescriber {
|
||||
static maxTokens = 12;
|
||||
|
|
@ -46,6 +47,66 @@ export class ChatDescriber {
|
|||
return removeQuotesAndEscapes(renderChatMessage(titleResponse));
|
||||
}
|
||||
|
||||
// CLI-specific method that works with BaseLlmApi
|
||||
static async describeWithBaseLlmApi(
|
||||
llmApi: any, // BaseLlmApi - using any to avoid import issues
|
||||
modelConfig: any, // ModelConfig - using any to avoid import issues
|
||||
message: string,
|
||||
): Promise<string | undefined> {
|
||||
if (!ChatDescriber.prompt) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clean up and distill the message we want to send to the LLM
|
||||
message = removeCodeBlocksAndTrim(message);
|
||||
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Create the chat message in the unified format
|
||||
const chatMessage = {
|
||||
role: "user" as const,
|
||||
content: ChatDescriber.prompt + message,
|
||||
};
|
||||
|
||||
// Convert to OpenAI format - use a simple fallback to avoid import issues
|
||||
const openaiMessages = convertFromUnifiedHistory([
|
||||
{
|
||||
message: chatMessage,
|
||||
contextItems: [],
|
||||
},
|
||||
]);
|
||||
|
||||
// Set up completion options for non-streaming
|
||||
const completionOptions = {
|
||||
model: modelConfig.model,
|
||||
messages: openaiMessages,
|
||||
max_tokens: ChatDescriber.maxTokens,
|
||||
stream: false as const,
|
||||
};
|
||||
|
||||
// Call the LLM
|
||||
const titleResponse = await llmApi.chatCompletionNonStream(
|
||||
completionOptions,
|
||||
new AbortController().signal,
|
||||
);
|
||||
|
||||
// Extract and clean up the response
|
||||
if (titleResponse.choices && titleResponse.choices.length > 0) {
|
||||
const content = titleResponse.choices[0].message.content;
|
||||
if (content) {
|
||||
return removeQuotesAndEscapes(content);
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
} catch (error) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// // TODO: Allow the user to manually set specific/tailored prompts to generate their titles
|
||||
// static async setup() {
|
||||
// if(config?.prompt) {
|
||||
|
|
|
|||
|
|
@ -93,8 +93,9 @@ describe("Many sessions created", () => {
|
|||
const offset = 10;
|
||||
|
||||
const sessions = historyManager.list({ offset: offset, limit: limit });
|
||||
// Sessions are now reversed, so newest (99) comes first
|
||||
const sessionIds = Array.from({ length: limit }, (_, i) =>
|
||||
(i + offset).toString(),
|
||||
(99 - offset - i).toString(),
|
||||
);
|
||||
const isSessionIdInList = (sessionId: string) =>
|
||||
sessions.some((session) => session.sessionId === sessionId);
|
||||
|
|
@ -105,7 +106,10 @@ describe("Many sessions created", () => {
|
|||
const limit = 25;
|
||||
|
||||
const sessions = historyManager.list({ limit: limit });
|
||||
const sessionIds = Array.from({ length: limit }, (_, i) => i.toString());
|
||||
// Sessions are now reversed, so newest (99) comes first
|
||||
const sessionIds = Array.from({ length: limit }, (_, i) =>
|
||||
(99 - i).toString(),
|
||||
);
|
||||
|
||||
const isSessionIdInList = (sessionId: string) =>
|
||||
sessions.some((session) => session.sessionId === sessionId);
|
||||
|
|
|
|||
|
|
@ -30,10 +30,13 @@ export class HistoryManager {
|
|||
const content = fs.readFileSync(filepath, "utf8");
|
||||
|
||||
let sessions = safeParseArray<SessionMetadata>(content) ?? [];
|
||||
sessions = sessions.filter((session: any) => {
|
||||
// Filter out old format
|
||||
return typeof session.session_id !== "string";
|
||||
});
|
||||
sessions = sessions
|
||||
.filter((session: any) => {
|
||||
// Filter out old format
|
||||
return typeof session.session_id !== "string";
|
||||
// Reverse to show newest first; sessions.json is chronological by creation
|
||||
})
|
||||
.reverse();
|
||||
|
||||
// Apply limit and offset
|
||||
if (options.limit) {
|
||||
|
|
|
|||
399
core/util/messageConversion.ts
Normal file
399
core/util/messageConversion.ts
Normal file
|
|
@ -0,0 +1,399 @@
|
|||
/**
|
||||
* Message conversion utilities for transitioning to unified ChatHistoryItem type.
|
||||
*
|
||||
* This module provides conversion functions between the OpenAI ChatCompletionMessageParam
|
||||
* format and the unified ChatHistoryItem format from the core package.
|
||||
*/
|
||||
|
||||
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import type {
|
||||
AssistantChatMessage,
|
||||
ChatHistoryItem,
|
||||
ChatMessage,
|
||||
ContextItemWithId,
|
||||
MessageContent,
|
||||
ToolCall,
|
||||
ToolCallState,
|
||||
ToolStatus,
|
||||
} from "../index.js";
|
||||
|
||||
/**
|
||||
* Convert ChatCompletionMessageParam to ChatMessage
|
||||
*/
|
||||
export function convertToUnifiedMessage(
|
||||
message: ChatCompletionMessageParam,
|
||||
): ChatMessage {
|
||||
switch (message.role) {
|
||||
case "system":
|
||||
return {
|
||||
role: "system",
|
||||
content: typeof message.content === "string" ? message.content : "",
|
||||
};
|
||||
|
||||
case "user":
|
||||
return {
|
||||
role: "user",
|
||||
content: convertMessageContent(message.content),
|
||||
};
|
||||
|
||||
case "assistant": {
|
||||
const assistantMessage: AssistantChatMessage = {
|
||||
role: "assistant",
|
||||
content: convertMessageContent(message.content || ""),
|
||||
};
|
||||
|
||||
// Convert tool calls if present
|
||||
if ("tool_calls" in message && message.tool_calls) {
|
||||
assistantMessage.toolCalls = message.tool_calls.map((tc: any) => ({
|
||||
id: tc.id,
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: tc.function?.name || "",
|
||||
arguments: tc.function?.arguments || "",
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
return assistantMessage;
|
||||
}
|
||||
|
||||
case "tool":
|
||||
return {
|
||||
role: "tool",
|
||||
content: typeof message.content === "string" ? message.content : "",
|
||||
toolCallId: message.tool_call_id,
|
||||
};
|
||||
|
||||
default:
|
||||
throw new Error(`Unsupported message role: ${(message as any).role}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert ChatMessage to ChatCompletionMessageParam
|
||||
*/
|
||||
export function convertFromUnifiedMessage(
|
||||
message: ChatMessage,
|
||||
): ChatCompletionMessageParam {
|
||||
switch (message.role) {
|
||||
case "system":
|
||||
return {
|
||||
role: "system",
|
||||
content: message.content,
|
||||
};
|
||||
|
||||
case "user":
|
||||
return {
|
||||
role: "user",
|
||||
content: convertFromMessageContent(message.content),
|
||||
};
|
||||
|
||||
case "assistant": {
|
||||
const assistantMessage: ChatCompletionMessageParam = {
|
||||
role: "assistant",
|
||||
content: convertFromMessageContent(message.content),
|
||||
};
|
||||
|
||||
// Convert tool calls if present
|
||||
if (message.toolCalls && message.toolCalls.length > 0) {
|
||||
(assistantMessage as any).tool_calls = message.toolCalls.map(
|
||||
(tc: any) => ({
|
||||
id: tc.id,
|
||||
type: "function",
|
||||
function: {
|
||||
name: tc.function?.name || "",
|
||||
arguments: tc.function?.arguments || "",
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return assistantMessage;
|
||||
}
|
||||
|
||||
case "tool":
|
||||
return {
|
||||
role: "tool",
|
||||
content: message.content,
|
||||
tool_call_id: message.toolCallId,
|
||||
};
|
||||
|
||||
case "thinking":
|
||||
// Thinking messages don't have a direct equivalent in OpenAI format
|
||||
// Convert to assistant message with content
|
||||
return {
|
||||
role: "assistant",
|
||||
content: convertFromMessageContent(message.content),
|
||||
};
|
||||
|
||||
default:
|
||||
throw new Error(`Unsupported message role: ${(message as any).role}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert OpenAI message content to unified MessageContent format
|
||||
*/
|
||||
function convertMessageContent(
|
||||
content: string | null | Array<any>,
|
||||
): MessageContent {
|
||||
if (content === null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (typeof content === "string") {
|
||||
return content;
|
||||
}
|
||||
|
||||
if (Array.isArray(content)) {
|
||||
return content.map((part: any) => {
|
||||
if (part.type === "text") {
|
||||
return {
|
||||
type: "text" as const,
|
||||
text: part.text,
|
||||
};
|
||||
} else if (part.type === "image_url") {
|
||||
return {
|
||||
type: "imageUrl" as const,
|
||||
imageUrl: { url: part.image_url.url },
|
||||
};
|
||||
}
|
||||
throw new Error(`Unsupported content part type: ${part.type}`);
|
||||
});
|
||||
}
|
||||
|
||||
throw new Error(`Unsupported content type: ${typeof content}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert unified MessageContent to OpenAI format
|
||||
*/
|
||||
function convertFromMessageContent(
|
||||
content: MessageContent,
|
||||
): string | Array<any> {
|
||||
if (typeof content === "string") {
|
||||
return content;
|
||||
}
|
||||
|
||||
if (Array.isArray(content)) {
|
||||
return content.map((part: any) => {
|
||||
if (part.type === "text") {
|
||||
return {
|
||||
type: "text",
|
||||
text: part.text,
|
||||
};
|
||||
} else if (part.type === "imageUrl") {
|
||||
return {
|
||||
type: "image_url",
|
||||
image_url: { url: part.imageUrl.url },
|
||||
};
|
||||
}
|
||||
throw new Error(`Unsupported content part type: ${part.type}`);
|
||||
});
|
||||
}
|
||||
|
||||
throw new Error(`Unsupported content type: ${typeof content}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a ChatHistoryItem from a ChatMessage
|
||||
*/
|
||||
export function createHistoryItem(
|
||||
message: ChatMessage,
|
||||
contextItems: ContextItemWithId[] = [],
|
||||
toolCallStates?: ToolCallState[],
|
||||
): ChatHistoryItem {
|
||||
return {
|
||||
message,
|
||||
contextItems,
|
||||
...(toolCallStates && { toolCallStates }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle tool result message by updating the corresponding tool call state
|
||||
*/
|
||||
function handleToolResult(
|
||||
unifiedMessage: ChatMessage & { role: "tool" },
|
||||
pendingToolCalls: Map<string, ToolCall>,
|
||||
historyItems: ChatHistoryItem[],
|
||||
): void {
|
||||
const toolCall = pendingToolCalls.get(unifiedMessage.toolCallId);
|
||||
if (!toolCall) return;
|
||||
|
||||
// Add tool result as context to the previous assistant message
|
||||
let lastAssistantIndex = -1;
|
||||
for (let i = historyItems.length - 1; i >= 0; i--) {
|
||||
if (historyItems[i].message.role === "assistant") {
|
||||
lastAssistantIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (lastAssistantIndex < 0) return;
|
||||
if (!historyItems[lastAssistantIndex].toolCallStates) return;
|
||||
|
||||
const toolState = historyItems[lastAssistantIndex].toolCallStates?.find(
|
||||
(ts: ToolCallState) => ts.toolCallId === unifiedMessage.toolCallId,
|
||||
);
|
||||
|
||||
if (toolState) {
|
||||
toolState.output = [
|
||||
{
|
||||
content: unifiedMessage.content as string,
|
||||
name: `Tool Result: ${toolCall.function.name}`,
|
||||
description: "Tool execution result",
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert array of ChatCompletionMessageParam to ChatHistoryItem array
|
||||
*/
|
||||
export function convertToUnifiedHistory(
|
||||
messages: ChatCompletionMessageParam[],
|
||||
): ChatHistoryItem[] {
|
||||
const historyItems: ChatHistoryItem[] = [];
|
||||
const pendingToolCalls: Map<string, ToolCall> = new Map();
|
||||
|
||||
for (const message of messages) {
|
||||
const unifiedMessage = convertToUnifiedMessage(message);
|
||||
|
||||
if (unifiedMessage.role === "assistant" && unifiedMessage.toolCalls) {
|
||||
// Store tool calls for matching with results
|
||||
const toolCallStates: ToolCallState[] = unifiedMessage.toolCalls.map(
|
||||
(tc: any) => {
|
||||
const toolCall: ToolCall = {
|
||||
id: tc.id || "",
|
||||
type: "function",
|
||||
function: {
|
||||
name: tc.function?.name || "",
|
||||
arguments: tc.function?.arguments || "",
|
||||
},
|
||||
};
|
||||
pendingToolCalls.set(toolCall.id, toolCall);
|
||||
|
||||
return {
|
||||
toolCallId: toolCall.id,
|
||||
toolCall,
|
||||
status: "done" as ToolStatus, // Historical calls are complete
|
||||
parsedArgs: tryParseJson(toolCall.function.arguments),
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
historyItems.push(createHistoryItem(unifiedMessage, [], toolCallStates));
|
||||
} else if (unifiedMessage.role === "tool") {
|
||||
// Tool result - handle separately to reduce nesting
|
||||
handleToolResult(unifiedMessage, pendingToolCalls, historyItems);
|
||||
// Don't add tool messages as separate history items
|
||||
} else {
|
||||
historyItems.push(createHistoryItem(unifiedMessage));
|
||||
}
|
||||
}
|
||||
|
||||
return historyItems;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert ChatHistoryItem array to ChatCompletionMessageParam array
|
||||
*/
|
||||
export function convertFromUnifiedHistory(
|
||||
historyItems: ChatHistoryItem[],
|
||||
): ChatCompletionMessageParam[] {
|
||||
const messages: ChatCompletionMessageParam[] = [];
|
||||
|
||||
for (const item of historyItems) {
|
||||
const baseMessage = convertFromUnifiedMessage(item.message);
|
||||
|
||||
// If this is a user message with context items, expand the content
|
||||
if (
|
||||
item.message.role === "user" &&
|
||||
item.contextItems &&
|
||||
item.contextItems.length > 0
|
||||
) {
|
||||
const contextContent = item.contextItems
|
||||
.map(
|
||||
(contextItem: ContextItemWithId) =>
|
||||
`<context name="${contextItem.name}">\n${contextItem.content}\n</context>\n\n`,
|
||||
)
|
||||
.join("");
|
||||
|
||||
baseMessage.content =
|
||||
typeof baseMessage.content === "string"
|
||||
? contextContent + baseMessage.content
|
||||
: baseMessage.content; // Keep array format if it's already an array
|
||||
}
|
||||
|
||||
messages.push(baseMessage);
|
||||
|
||||
// Add tool result messages if there are completed tool calls
|
||||
if (item.toolCallStates) {
|
||||
for (const toolState of item.toolCallStates) {
|
||||
if (toolState.output && toolState.output.length > 0) {
|
||||
messages.push({
|
||||
role: "tool",
|
||||
content: toolState.output.map((o: any) => o.content).join("\n"),
|
||||
tool_call_id: toolState.toolCallId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return messages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert ChatHistoryItem array to ChatCompletionMessageParam array with injected system message
|
||||
* @param historyItems - The chat history items
|
||||
* @param systemMessage - The system message to inject at the beginning
|
||||
*/
|
||||
export function convertFromUnifiedHistoryWithSystemMessage(
|
||||
historyItems: ChatHistoryItem[],
|
||||
systemMessage: string,
|
||||
): ChatCompletionMessageParam[] {
|
||||
const messages: ChatCompletionMessageParam[] = [];
|
||||
|
||||
// Inject system message at the beginning
|
||||
messages.push({
|
||||
role: "system",
|
||||
content: systemMessage,
|
||||
});
|
||||
|
||||
// Convert the rest of the history
|
||||
const convertedMessages = convertFromUnifiedHistory(historyItems);
|
||||
messages.push(...convertedMessages);
|
||||
|
||||
return messages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract tool call information from a ChatHistoryItem
|
||||
*/
|
||||
export function extractToolCallInfo(historyItem: ChatHistoryItem): {
|
||||
hasToolCalls: boolean;
|
||||
toolCalls?: ToolCall[];
|
||||
toolStates?: ToolCallState[];
|
||||
} {
|
||||
const hasToolCalls = !!(
|
||||
historyItem.toolCallStates && historyItem.toolCallStates.length > 0
|
||||
);
|
||||
|
||||
return {
|
||||
hasToolCalls,
|
||||
toolCalls: historyItem.toolCallStates?.map((ts: any) => ts.toolCall),
|
||||
toolStates: historyItem.toolCallStates,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to safely parse JSON
|
||||
*/
|
||||
function tryParseJson(str: string): any {
|
||||
try {
|
||||
return JSON.parse(str);
|
||||
} catch {
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ import { IdeInfo } from "../index.js";
|
|||
|
||||
import type { PostHog as PostHogType } from "posthog-node";
|
||||
import { extractMinimalStackTraceInfo } from "./extractMinimalStackTraceInfo.js";
|
||||
import { TokensBatchingService } from "./TokensBatchingService.js";
|
||||
|
||||
export enum PosthogFeatureFlag {
|
||||
AutocompleteTimeout = "autocomplete-timeout",
|
||||
|
|
@ -99,6 +100,7 @@ export class Telemetry {
|
|||
}
|
||||
|
||||
static shutdownPosthogClient() {
|
||||
TokensBatchingService.getInstance().shutdown();
|
||||
Telemetry.client?.shutdown();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
---
|
||||
title: "MCP Blocks"
|
||||
title: "MCP servers"
|
||||
description: "Learn how to use Model Context Protocol (MCP) blocks in Continue to integrate external tools, connect databases, and extend your development environment."
|
||||
---
|
||||
|
||||
Model Context Protocol (MCP) blocks let Continue connect to external tools, systems, and databases by running MCP servers.
|
||||
Model Context Protocol (MCP) servers let Continue connect to external tools, systems, and databases by running MCP servers.
|
||||
|
||||
These blocks make it possible to:
|
||||
These servers make it possible to:
|
||||
|
||||
- **Enable integration** with external tools and systems
|
||||
- **Create extensible interfaces** for custom capabilities
|
||||
|
|
@ -13,8 +13,8 @@ These blocks make it possible to:
|
|||
- **Allow partners** to contribute specialized functionality
|
||||
- **Connect to databases** to understand schema and data models during development
|
||||
|
||||

|
||||

|
||||
|
||||
## Learn More About MCP Blocks
|
||||
## Learn More About MCP servers
|
||||
|
||||
Learn more in the [MCP deep dive](/customize/deep-dives/mcp), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details.
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
---
|
||||
title: "Model Blocks"
|
||||
description: "These blocks form the foundation of the entire assistant experience, offering different specialized capabilities:"
|
||||
title: "Models"
|
||||
description: "Models form the foundation of the entire agent experience, offering different specialized capabilities:"
|
||||
---
|
||||
|
||||
import { ModelRecommendations } from "/snippets/ModelRecommendations.jsx";
|
||||
|
||||
- **[Chat](/customize/model-roles/chat)**: Power conversational interactions about code and provide detailed guidance
|
||||
- **[Edit](/customize/model-roles/edit)**: Handle complex code transformations and refactoring tasks
|
||||
- **[Apply](/customize/model-roles/apply)**: Execute targeted code modifications with high accuracy
|
||||
|
|
@ -10,24 +12,118 @@ description: "These blocks form the foundation of the entire assistant experienc
|
|||
- **[Embedding](/customize/model-roles/embeddings)**: Transform code into vector representations for semantic search
|
||||
- **[Reranker](/customize/model-roles/reranking)**: Improve search relevance by ordering results based on semantic meaning
|
||||
|
||||

|
||||

|
||||
|
||||
## Recommended Models
|
||||
|
||||
### Best Models by Role
|
||||
|
||||
| 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 |
|
||||
<ModelRecommendations role="all" />
|
||||
|
||||
## Learn More About Model Blocks
|
||||
## Learn More About Models
|
||||
|
||||
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.
|
||||
Read more about [model roles](/customize/model-roles), [model capabilities](/customize/deep-dives/model-capabilities) and view [`models`](/reference#models) in the YAML Reference.
|
||||
|
||||
### Example Model Setup Instructions
|
||||
|
||||
# Frontier Models
|
||||
|
||||
[Claude 4 Sonnet](https://hub.continue.dev/anthropic/claude-4-sonnet) from Anthropic
|
||||
|
||||
1. Get your API key from [Anthropic](https://console.anthropic.com/)
|
||||
2. Add [Claude 4 Sonnet](https://hub.continue.dev/anthropic/claude-4-sonnet) to an agent 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 agent selector in the Continue IDE extension
|
||||
|
||||
[Qwen Coder 3 480B](https://hub.continue.dev/openrouter/qwen3-coder) from Qwen
|
||||
|
||||
1. Get your API key from [OpenRouter](https://openrouter.ai/settings/keys)
|
||||
2. Add [Qwen Coder 3 480B](https://hub.continue.dev/openrouter/qwen3-coder) to an agent on Continue Hub
|
||||
3. Add `OPENROUTER_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the agent selector in the Continue IDE extension
|
||||
|
||||
[GPT-5](https://hub.continue.dev/openai/gpt-5) from OpenAI
|
||||
|
||||
1. Get your API key from [OpenAI](https://platform.openai.com)
|
||||
2. Add [GPT-5](https://hub.continue.dev/openai/gpt-5) to an agent on Continue Hub
|
||||
3. Add `OPENAI_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the agent selector in the Continue IDE extension
|
||||
|
||||
[Kimi K2](https://hub.continue.dev/openrouter/kimi-k2) from Moonshot AI
|
||||
|
||||
1. Get your API key from [OpenRouter](https://openrouter.ai/settings/keys)
|
||||
2. Add [Kimi K2](https://hub.continue.dev/openrouter/kimi-k2) to an agent on Continue Hub
|
||||
3. Add `OPENROUTER_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the agent selector in the Continue IDE extension
|
||||
|
||||
[Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) from Google
|
||||
|
||||
1. Get your API key from [Google AI Studio](https://aistudio.google.com)
|
||||
2. Add [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) to an agent on Continue Hub
|
||||
3. Add `GEMINI_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the agent selector in the Continue IDE extension
|
||||
|
||||
[Grok 4](https://hub.continue.dev/xai/grok-4) from xAI
|
||||
|
||||
1. Get your API key from [xAI](https://console.x.ai/)
|
||||
2. Add [Grok 4](https://hub.continue.dev/xai/grok-4) to an agent on Continue Hub
|
||||
3. Add `XAI_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the agent selector in the Continue IDE extension
|
||||
|
||||
[Devstral Medium](https://hub.continue.dev/mistral/devstral-medium) from Mistral AI
|
||||
|
||||
1. Get your API key from [Mistral AI](https://console.mistral.ai/)
|
||||
2. Add [Devstral Medium](https://hub.continue.dev/mistral/devstral-medium) to an agent 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 agent selector in the Continue IDE extension
|
||||
|
||||
[gpt-oss-120b](https://hub.continue.dev/openrouter/gpt-oss-120b) from OpenAI
|
||||
|
||||
1. Get your API key from [OpenRouter](https://openrouter.ai/settings/keys)
|
||||
2. Add [gpt-oss-120b](https://hub.continue.dev/openrouter/gpt-oss-120b) to an agent on Continue Hub
|
||||
3. Add `OPENROUTER_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the agent selector in the Continue IDE extension
|
||||
|
||||
### Local Models
|
||||
|
||||
These models can be run on your computer if you have enough VRAM.
|
||||
|
||||
Their limited tool calling and reasoning capabilities will make it challenging to use Agent mode.
|
||||
|
||||
[Qwen3 Coder 30B](https://hub.continue.dev/ollama/qwen3-coder-30b)
|
||||
|
||||
1. Add [Qwen3 Coder 30B](https://hub.continue.dev/ollama/qwen3-coder-30b) to an agent on Continue Hub
|
||||
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
|
||||
3. Click `Reload config` in the agent selector in the Continue IDE extension
|
||||
|
||||
[gpt-oss-20b](https://hub.continue.dev/ollama/gpt-oss-20b)
|
||||
|
||||
1. Add [gpt-oss-20b](ttps://hub.continue.dev/ollama/gpt-oss-20b) to an agent on Continue Hub
|
||||
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
|
||||
3. Click `Reload config` in the agent selector in the Continue IDE extension
|
||||
|
||||
[Devstral Small 27B](https://hub.continue.dev/ollama/devstral)
|
||||
|
||||
1. Add [Devstral Small](https://hub.continue.dev/ollama/devstral) to an agent on Continue Hub
|
||||
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
|
||||
3. Click `Reload config` in the agent selector in the Continue IDE extension
|
||||
|
||||
[Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) from Qwen
|
||||
|
||||
1. Add [Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) to an agent on Continue Hub
|
||||
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
|
||||
3. Click `Reload config` in the agent selector in the Continue IDE extension
|
||||
|
||||
[Gemma 3 4B](https://hub.continue.dev/ollama/gemma3-4b) from Google
|
||||
|
||||
1. Add [Gemma 3 4B](https://hub.continue.dev/ollama/gemma3-4b) to an agent on Continue Hub
|
||||
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
|
||||
3. Click `Reload config` in the agent selector in the Continue IDE extension
|
||||
|
||||
[Qwen2.5-Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b) from Qwen
|
||||
|
||||
1. Add [Qwen2.5-Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b) to an agent on Continue Hub
|
||||
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
|
||||
3. Click `Reload config` in the agent selector in the Continue IDE extension
|
||||
|
|
|
|||
|
|
@ -13,10 +13,6 @@ Continue allows you to choose your favorite or even add multiple model providers
|
|||
|
||||
Different Continue features can use different models. We call these _model roles_. For example, you can use a different model for chat than you do for autocomplete. Learn more about [model roles](/customize/model-roles).
|
||||
|
||||
## Add a Context Provider
|
||||
|
||||
Context providers allow you to add information to your prompts, giving your LLM additional context to work with. Context providers allow you to reference snippets from your codebase, or lookup relevant documentation, or use a search engine to find information and much more. Learn more about [context providers](/customize/custom-providers).
|
||||
|
||||
## Create a Slash Command
|
||||
|
||||
Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](/customize/deep-dives/slash-commands).
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
---
|
||||
title: "Prompt Blocks"
|
||||
title: "Prompts"
|
||||
description: "These are the specialized instructions that shape how models respond:"
|
||||
---
|
||||
|
||||
|
|
@ -9,8 +9,8 @@ description: "These are the specialized instructions that shape how models respo
|
|||
- **Can be shared and reused** across multiple assistants
|
||||
- **Act as automated code reviewers** that ensure consistency across teams
|
||||
|
||||

|
||||

|
||||
|
||||
## Learn More
|
||||
|
||||
Prompt blocks have the same syntax as [prompt files](/customization/prompts). The `config.yaml` spec for `prompts` can be found [here](/reference#prompts).
|
||||
Prompts have the same syntax as [prompt files](/customization/prompts). The `config.yaml` spec for `prompts` can be found [here](/reference#prompts).
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
---
|
||||
title: "Rules Blocks"
|
||||
title: "Rules"
|
||||
description: "Rules allow you to provide specific instructions that guide how the AI assistant behaves when working with your code. Instead of the AI making assumptions about your coding standards, architecture patterns, or project-specific requirements, you can explicitly define guidelines that ensure consistent, contextually appropriate responses."
|
||||
---
|
||||
|
||||
|
|
@ -13,6 +13,6 @@ By implementing rules, you transform the AI from a generic coding assistant into
|
|||
|
||||
## How Rules Work
|
||||
|
||||
Your assistant detects rule blocks and applies the specified rules while in [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) modes.
|
||||
Your assistant detects rules and applies the specified rules while in [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) modes.
|
||||
|
||||
Learn more in the [rules deep dive](/customize/deep-dives/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details.
|
||||
Learn more in the [rules deep dive](/customize/deep-dives/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details.
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue