Merge branch 'main' into tingwai/con-3668
This commit is contained in:
commit
e7e9d08d5d
329 changed files with 17881 additions and 9244 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
|
||||
2
.github/workflows/cli-pr-checks.yml
vendored
2
.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
|
||||
|
||||
|
|
|
|||
|
|
@ -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/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 }}
|
||||
|
|
|
|||
239
.github/workflows/respond-to-cubic.yaml
vendored
Normal file
239
.github/workflows/respond-to-cubic.yaml
vendored
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
name: Respond to @continuedev Comments
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_review_comment:
|
||||
types: [created]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
respond-to-comment:
|
||||
# Only run on pull request comments
|
||||
if: github.event_name == 'issue_comment' && github.event.issue.pull_request
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Check if comment contains @continuedev
|
||||
id: check-mention
|
||||
run: |
|
||||
if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
|
||||
echo "contains_mention=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "contains_mention=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Add eyes reaction to comment
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
await github.rest.reactions.createForIssueComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: ${{ github.event.comment.id }},
|
||||
content: 'eyes'
|
||||
});
|
||||
|
||||
- name: Checkout PR branch
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Get PR information
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
id: pr-info
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const { data: pr } = await github.rest.pulls.get({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
pull_number: context.issue.number
|
||||
});
|
||||
|
||||
core.setOutput('head_ref', pr.head.ref);
|
||||
core.setOutput('head_sha', pr.head.sha);
|
||||
return pr;
|
||||
|
||||
- name: Checkout PR branch
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
run: |
|
||||
git checkout ${{ steps.pr-info.outputs.head_ref }}
|
||||
|
||||
- name: Setup Node.js
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
|
||||
- name: Install Continue CLI globally
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
run: npm i -g @continuedev/cli
|
||||
|
||||
- name: Start remote session
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
id: remote-session
|
||||
env:
|
||||
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
|
||||
run: |
|
||||
# Create the prompt for remote session
|
||||
PROMPT="Please help with the following request from @${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}:
|
||||
|
||||
${{ github.event.comment.body }}
|
||||
|
||||
Please analyze the current PR, understand the request, implement the necessary changes, and commit them to this branch."
|
||||
|
||||
# Start remote session and capture JSON output
|
||||
SESSION_OUTPUT=$(echo "$PROMPT" | cn remote -s --branch ${{ steps.pr-info.outputs.head_ref }})
|
||||
echo "Raw session output: $SESSION_OUTPUT"
|
||||
|
||||
# Extract URL from JSON output
|
||||
SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty')
|
||||
|
||||
if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then
|
||||
echo "Failed to extract session URL from output: $SESSION_OUTPUT"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT
|
||||
echo "✅ Started remote session: $SESSION_URL"
|
||||
|
||||
- name: Comment with session URL
|
||||
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
|
||||
> ${{ github.event.comment.body }}`;
|
||||
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
body: commentBody
|
||||
});
|
||||
|
||||
- name: Log session details
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
run: |
|
||||
echo "✅ Successfully started remote session for comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}"
|
||||
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
|
||||
echo "Original comment: ${{ github.event.comment.body }}"
|
||||
|
||||
respond-to-review-comment:
|
||||
# Only run on pull request review comments
|
||||
if: github.event_name == 'pull_request_review_comment'
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Check if comment contains @continuedev
|
||||
id: check-mention
|
||||
run: |
|
||||
if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
|
||||
echo "contains_mention=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "contains_mention=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Add eyes reaction to comment
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
await github.rest.reactions.createForPullRequestReviewComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: ${{ github.event.comment.id }},
|
||||
content: 'eyes'
|
||||
});
|
||||
|
||||
- name: Checkout PR branch
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.event.pull_request.head.ref }}
|
||||
|
||||
- name: Setup Node.js
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
|
||||
- name: Install Continue CLI globally
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
run: npm i -g @continuedev/cli
|
||||
|
||||
- name: Start remote session
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
id: remote-session
|
||||
env:
|
||||
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
|
||||
run: |
|
||||
# Create a temporary file for the prompt to handle special characters and newlines properly
|
||||
cat > /tmp/prompt.txt << 'PROMPT_EOF'
|
||||
Please help with the following code review comment from @${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}:
|
||||
|
||||
**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.
|
||||
PROMPT_EOF
|
||||
|
||||
# Debug output
|
||||
echo "PROMPT content:"
|
||||
cat /tmp/prompt.txt
|
||||
|
||||
# Start remote session and capture JSON output
|
||||
echo "Starting cn with prompt..."
|
||||
SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --branch ${{ github.event.pull_request.head.ref }})
|
||||
echo "Raw session output: $SESSION_OUTPUT"
|
||||
|
||||
# Extract URL from JSON output
|
||||
SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty')
|
||||
|
||||
if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then
|
||||
echo "Failed to extract session URL from output: $SESSION_OUTPUT"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT
|
||||
echo "✅ Started remote session: $SESSION_URL"
|
||||
|
||||
- name: Comment with session URL
|
||||
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
|
||||
> ${{ github.event.comment.body }}`;
|
||||
|
||||
const commentParams = {
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
pull_number: ${{ github.event.pull_request.number }},
|
||||
body: commentBody,
|
||||
commit_id: '${{ github.event.pull_request.head.sha }}',
|
||||
path: '${{ github.event.comment.path }}',
|
||||
in_reply_to: ${{ github.event.comment.id }}
|
||||
};
|
||||
|
||||
await github.rest.pulls.createReviewComment(commentParams);
|
||||
|
||||
- name: Log session details
|
||||
if: steps.check-mention.outputs.contains_mention == 'true'
|
||||
run: |
|
||||
echo "✅ Successfully started remote session for review comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}"
|
||||
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
|
||||
echo "File: ${{ github.event.comment.path }}"
|
||||
echo "Line: ${{ github.event.comment.line }}"
|
||||
echo "Original comment: ${{ github.event.comment.body }}"
|
||||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
33
core/core.ts
33
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;
|
||||
|
|
@ -1007,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);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
9
core/index.d.ts
vendored
9
core/index.d.ts
vendored
|
|
@ -1070,11 +1070,6 @@ export interface ToolExtras {
|
|||
codeBaseIndexer?: CodebaseIndexer;
|
||||
}
|
||||
|
||||
export type ToolPolicy =
|
||||
| "allowedWithPermission"
|
||||
| "allowedWithoutPermission"
|
||||
| "disabled";
|
||||
|
||||
export interface Tool {
|
||||
type: "function";
|
||||
function: {
|
||||
|
|
@ -1099,6 +1094,10 @@ export interface Tool {
|
|||
exampleArgs?: Array<[string, string | number]>;
|
||||
};
|
||||
defaultToolPolicy?: ToolPolicy;
|
||||
evaluateToolCallPolicy?: (
|
||||
basePolicy: ToolPolicy,
|
||||
parsedArgs: Record<string, unknown>,
|
||||
) => ToolPolicy;
|
||||
}
|
||||
|
||||
interface ToolChoice {
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
);
|
||||
|
|
|
|||
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,
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
@ -370,6 +379,8 @@ export class NextEditProvider {
|
|||
throw new Error("Model provider not initialized");
|
||||
}
|
||||
|
||||
// NOTE: getAllSnippetsWithoutRace doesn't seem to incur much performance penalties when compared to getAllSnippets.
|
||||
// Use getAllSnippets if snippet gathering becomes noticably slow.
|
||||
const [snippetPayload, workspaceDirs] = await Promise.all([
|
||||
getAllSnippetsWithoutRace({
|
||||
helper,
|
||||
|
|
@ -445,6 +456,9 @@ export class NextEditProvider {
|
|||
}
|
||||
|
||||
// Send prompts to LLM (using only user prompt for fine-tuned models).
|
||||
// prompts[1] extracts the user prompt from the system-user prompt pair.
|
||||
// NOTE: Stream is currently set to false, but this should ideally be a per-model flag.
|
||||
// Mercury Coder currently does not support streaming.
|
||||
const msg: ChatMessage = await llm.chat([prompts[1]], token, {
|
||||
stream: false,
|
||||
});
|
||||
|
|
@ -484,7 +498,7 @@ export class NextEditProvider {
|
|||
}
|
||||
|
||||
if (outcome) {
|
||||
// Handle NextEditProvider-specific state
|
||||
// Handle NextEditProvider-specific state.
|
||||
this.previousCompletions.push(outcome);
|
||||
|
||||
// Mark as displayed for JetBrains
|
||||
|
|
@ -494,97 +508,6 @@ export class NextEditProvider {
|
|||
return outcome;
|
||||
}
|
||||
|
||||
private _calculateOptimalEditableRegion(
|
||||
helper: HelperVars,
|
||||
heuristic: "fourChars" | "tokenizer" = "tokenizer",
|
||||
): {
|
||||
editableRegionStartLine: number;
|
||||
editableRegionEndLine: number;
|
||||
} {
|
||||
const cursorLine = helper.pos.line;
|
||||
const fileLines = helper.fileLines;
|
||||
const MAX_TOKENS = 512;
|
||||
|
||||
// Initialize with cursor line.
|
||||
let editableRegionStartLine = cursorLine;
|
||||
let editableRegionEndLine = cursorLine;
|
||||
|
||||
// Get initial content and token count.
|
||||
let currentContent = fileLines[cursorLine];
|
||||
let totalTokens =
|
||||
heuristic === "tokenizer"
|
||||
? countTokens(currentContent, helper.modelName)
|
||||
: Math.ceil(currentContent.length / 4);
|
||||
|
||||
// Expand outward alternating between adding lines above and below.
|
||||
let addingAbove = true;
|
||||
|
||||
while (totalTokens < MAX_TOKENS) {
|
||||
let addedLine = false;
|
||||
|
||||
if (addingAbove) {
|
||||
// Try to add a line above.
|
||||
if (editableRegionStartLine > 0) {
|
||||
editableRegionStartLine--;
|
||||
const lineContent = fileLines[editableRegionStartLine];
|
||||
const lineTokens =
|
||||
heuristic === "tokenizer"
|
||||
? countTokens(lineContent, helper.modelName)
|
||||
: Math.ceil(lineContent.length / 4);
|
||||
|
||||
totalTokens += lineTokens;
|
||||
addedLine = true;
|
||||
}
|
||||
} else {
|
||||
// Try to add a line below.
|
||||
if (editableRegionEndLine < fileLines.length - 1) {
|
||||
editableRegionEndLine++;
|
||||
const lineContent = fileLines[editableRegionEndLine];
|
||||
const lineTokens =
|
||||
heuristic === "tokenizer"
|
||||
? countTokens(lineContent, helper.modelName)
|
||||
: Math.ceil(lineContent.length / 4);
|
||||
|
||||
totalTokens += lineTokens;
|
||||
addedLine = true;
|
||||
}
|
||||
}
|
||||
|
||||
// If we can't add in the current direction, try the other.
|
||||
if (!addedLine) {
|
||||
// If we're already at both file boundaries, we're done.
|
||||
if (
|
||||
editableRegionStartLine === 0 &&
|
||||
editableRegionEndLine === fileLines.length - 1
|
||||
) {
|
||||
break;
|
||||
}
|
||||
|
||||
// If we couldn't add in one direction, force the next attempt in the other direction.
|
||||
addingAbove = !addingAbove;
|
||||
continue;
|
||||
}
|
||||
|
||||
// If we exceeded the token limit, revert the last addition.
|
||||
if (totalTokens > MAX_TOKENS) {
|
||||
if (addingAbove) {
|
||||
editableRegionStartLine++;
|
||||
} else {
|
||||
editableRegionEndLine--;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// Alternate between adding above and below for balanced context.
|
||||
addingAbove = !addingAbove;
|
||||
}
|
||||
|
||||
return {
|
||||
editableRegionStartLine,
|
||||
editableRegionEndLine,
|
||||
};
|
||||
}
|
||||
|
||||
private async _markDisplayedIfJetBrains(
|
||||
completionId: string,
|
||||
outcome: NextEditOutcome,
|
||||
|
|
@ -595,6 +518,12 @@ export class NextEditProvider {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is a wrapper around provideInlineCompletionItems.
|
||||
* This is invoked when we call the model in the background using prefetch.
|
||||
* It's not currently used anywhere (references are not used either), but I decided to keep it in case we actually need to use prefetch.
|
||||
* You will see that calls to this method is made from NextEditPrefetchQueue.proecss(), which is wrapped in `if (!this.usingFullFileDiff)`.
|
||||
*/
|
||||
public async provideInlineCompletionItemsWithChain(
|
||||
ctx: {
|
||||
completionId: string;
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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() {
|
||||
|
|
|
|||
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",
|
||||
|
|
|
|||
|
|
@ -34,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",
|
||||
|
|
@ -61,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",
|
||||
|
|
@ -111,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,
|
||||
|
|
@ -293,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];
|
||||
|
|
|
|||
|
|
@ -78,6 +78,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"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 =
|
||||
"Note 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,6 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { NO_PARALLEL_TOOL_CALLING_INTSRUCTION } from "./editFile";
|
||||
|
||||
export interface EditOperation {
|
||||
old_string: string;
|
||||
|
|
@ -54,6 +55,7 @@ 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
|
||||
4. ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}
|
||||
|
||||
WARNING:
|
||||
|
||||
|
|
|
|||
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;
|
||||
|
|
@ -38,6 +39,8 @@ unless explicitly required.
|
|||
- Only use emojis if the user explicitly requests it. Avoid adding emojis to
|
||||
files unless asked.
|
||||
|
||||
- ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}
|
||||
|
||||
- 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\`.
|
||||
|
|
|
|||
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)",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -103,7 +103,6 @@ export class ChatDescriber {
|
|||
|
||||
return undefined;
|
||||
} catch (error) {
|
||||
console.debug("Error generating chat title:", error);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 | Qwen3 Coder (480B), Qwen3 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 | Qwen3 Coder (480B), Qwen3 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](https://hub.continue.dev/ollama/nomic-embed-text-latest), Qwen3 Embedding | [Voyage Code 3](https://hub.continue.dev/voyageai/voyage-code-3), [Morph Embeddings](https://hub.continue.dev/morphllm/morph-embedding-v2), Codestral Embed | Closed models are slightly better than open models |
|
||||
| Rerank | zerank-1, zerank-1-small, Qwen3 Reranker | [Voyage Rerank 2.5](https://hub.continue.dev/voyageai/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.
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
{
|
||||
"label": "Context",
|
||||
"position": 2
|
||||
}
|
||||
|
|
@ -437,432 +437,6 @@ config.json
|
|||
|
||||
You'll then be able to type "@" and see "MCP" in the context providers dropdown.
|
||||
|
||||
### @Issue Context Provider – Reference GitHub Issue Conversations
|
||||
|
||||
Reference the conversation in a GitHub issue.
|
||||
|
||||
- YAML
|
||||
- JSON
|
||||
|
||||
config.yaml
|
||||
|
||||
```
|
||||
context:
|
||||
- provider: issue
|
||||
params:
|
||||
repos:
|
||||
- owner: continuedev
|
||||
repo: continue
|
||||
githubToken: ghp_xxx
|
||||
```
|
||||
|
||||
config.json
|
||||
|
||||
```json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "issue",
|
||||
"params": {
|
||||
"repos": [{ "owner": "continuedev", "repo": "continue" }],
|
||||
"githubToken": "ghp_xxx"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Make sure to include your own [GitHub personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token) to avoid being rate-limited.
|
||||
|
||||
### @Database Context Provider – Reference Database Table Schemas
|
||||
|
||||
Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases.
|
||||
|
||||
- YAML
|
||||
- JSON
|
||||
|
||||
config.yaml
|
||||
|
||||
```
|
||||
context:
|
||||
- provider: database
|
||||
params:
|
||||
connections:
|
||||
- name: examplePostgres
|
||||
connection_type: postgres
|
||||
connection:
|
||||
user: username
|
||||
host: localhost
|
||||
database: exampleDB
|
||||
password: yourPassword
|
||||
port: 5432
|
||||
- name: exampleMssql
|
||||
connection_type: mssql
|
||||
connection:
|
||||
user: username
|
||||
server: localhost
|
||||
database: exampleDB
|
||||
password: yourPassword
|
||||
- name: exampleSqlite
|
||||
connection_type: sqlite
|
||||
connection:
|
||||
filename: /path/to/your/sqlite/database.db
|
||||
```
|
||||
|
||||
config.json
|
||||
|
||||
```json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "database",
|
||||
"params": {
|
||||
"connections": [
|
||||
{
|
||||
"name": "examplePostgres",
|
||||
"connection_type": "postgres",
|
||||
"connection": {
|
||||
"user": "username",
|
||||
"host": "localhost",
|
||||
"database": "exampleDB",
|
||||
"password": "yourPassword",
|
||||
"port": 5432
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "exampleMssql",
|
||||
"connection_type": "mssql",
|
||||
"connection": {
|
||||
"user": "username",
|
||||
"server": "localhost",
|
||||
"database": "exampleDB",
|
||||
"password": "yourPassword"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "exampleSqlite",
|
||||
"connection_type": "sqlite",
|
||||
"connection": { "filename": "/path/to/your/sqlite/database.db" }
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Each connection should include a unique name, the `connection_type`, and the necessary connection parameters specific to each database type.
|
||||
|
||||
Available connection types:
|
||||
|
||||
- `postgres`
|
||||
- `mysql`
|
||||
- `sqlite`
|
||||
|
||||
### @Google Context Provider – Reference Google Search Results
|
||||
|
||||
Reference the results of a Google search.
|
||||
|
||||
- YAML
|
||||
- JSON
|
||||
|
||||
config.yaml
|
||||
|
||||
```
|
||||
context:
|
||||
- provider: google
|
||||
params:
|
||||
serperApiKey: <YOUR_SERPER.DEV_API_KEY>
|
||||
```
|
||||
|
||||
config.json
|
||||
|
||||
```json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "google",
|
||||
"params": { "serperApiKey": "<YOUR_SERPER.DEV_API_KEY>" }
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
For example, type "@Google python tutorial" if you want to search and discuss ways of learning Python.
|
||||
|
||||
Note: You can get an API key for free at [serper.dev](https://serper.dev).
|
||||
|
||||
### @Gitlab Merge Request Context Provider – Reference GitLab Merge Requests
|
||||
|
||||
Reference an open MR for this branch on GitLab.
|
||||
|
||||
- YAML
|
||||
- JSON
|
||||
|
||||
config.yaml
|
||||
|
||||
```
|
||||
context:
|
||||
- provider: gitlab-mr
|
||||
params:
|
||||
token: "..."
|
||||
```
|
||||
|
||||
config.json
|
||||
|
||||
```json
|
||||
{ "contextProviders": [{ "name": "gitlab-mr", "params": { "token": "..." } }] }
|
||||
```
|
||||
|
||||
You will need to create a [personal access token](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html) with the `read_api` scope.
|
||||
|
||||
#### How to Use Self-Hosted GitLab
|
||||
|
||||
You can specify the domain to communicate with by setting the `domain` parameter in your configurtion. By default this is set to `gitlab.com`.
|
||||
|
||||
- YAML
|
||||
- JSON
|
||||
|
||||
config.yaml
|
||||
|
||||
```
|
||||
context:
|
||||
- provider: gitlab-mr
|
||||
params:
|
||||
token: "..."
|
||||
domain: "gitlab.example.com"
|
||||
```
|
||||
|
||||
config.json
|
||||
|
||||
```json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "gitlab-mr",
|
||||
"params": { "token": "...", "domain": "gitlab.example.com" }
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### How to Provide Context by Filtering Comments
|
||||
|
||||
If you select some code to be edited, you can have the context provider filter out comments for other files. To enable this feature, set `filterComments` to `true`.
|
||||
|
||||
### @Jira Context Provider – Reference Jira Issues
|
||||
|
||||
Reference the conversation in a Jira issue.
|
||||
|
||||
- YAML
|
||||
- JSON
|
||||
|
||||
config.yaml
|
||||
|
||||
```
|
||||
context:
|
||||
- provider: jira
|
||||
params:
|
||||
domain: company.atlassian.net
|
||||
token: ATATT...
|
||||
```
|
||||
|
||||
config.json
|
||||
|
||||
```json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "jira",
|
||||
"params": { "domain": "company.atlassian.net", "token": "ATATT..." }
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Make sure to include your own [Atlassian API Token](https://id.atlassian.com/manage-profile/security/api-tokens), or use your `email` and `token`, with token set to your password for basic authentication. If you use your own Atlassian API Token, don't configure your email.
|
||||
|
||||
#### Jira Datacenter Support
|
||||
|
||||
This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property.
|
||||
|
||||
- YAML
|
||||
- JSON
|
||||
|
||||
config.yaml
|
||||
|
||||
```
|
||||
context:
|
||||
- provider: jira
|
||||
params:
|
||||
apiVersion: "2"
|
||||
```
|
||||
|
||||
config.json
|
||||
|
||||
```json
|
||||
{ "contextProviders": [{ "name": "jira", "params": { "apiVersion": "2" } }] }
|
||||
```
|
||||
|
||||
#### Issue Query
|
||||
|
||||
By default, the following query will be used to find issues:
|
||||
|
||||
```
|
||||
assignee = currentUser() AND resolution = Unresolved order by updated DESC
|
||||
```
|
||||
|
||||
You can override this query by setting the `issueQuery` parameter.
|
||||
|
||||
#### Max results
|
||||
|
||||
You can set the `maxResults` parameter to limit the number of results returned. The default is `50`.
|
||||
|
||||
### @Discord Context Provider – Reference Messages in Discord Channels
|
||||
|
||||
Reference the messages in a Discord channel.
|
||||
|
||||
- YAML
|
||||
- JSON
|
||||
|
||||
config.yaml
|
||||
|
||||
```
|
||||
context:
|
||||
- provider: discord
|
||||
params:
|
||||
discordKey: "bot token"
|
||||
guildId: "1234567890"
|
||||
channels:
|
||||
- id: "123456"
|
||||
name: "example-channel"
|
||||
- id: "678901"
|
||||
name: "example-channel-2"
|
||||
```
|
||||
|
||||
config.json
|
||||
|
||||
```json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "discord",
|
||||
"params": {
|
||||
"discordKey": "bot token",
|
||||
"guildId": "1234567890",
|
||||
"channels": [
|
||||
{ "id": "123456", "name": "example-channel" },
|
||||
{ "id": "678901", "name": "example-channel-2" }
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Make sure to include your own [Bot Token](https://discord.com/developers/applications), and join it to your related server . If you want more granular control over which channels are searched, you can specify a list of channel IDs to search in. If you don't want to specify any channels, just include the guild id(Server ID) and all channels will be included. The provider only reads text channels.
|
||||
|
||||
### @HTTP Context Provider – Reference Data from an HTTP Request
|
||||
|
||||
The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems.
|
||||
|
||||
- YAML
|
||||
- JSON
|
||||
|
||||
config.yaml
|
||||
|
||||
```
|
||||
context:
|
||||
- provider: http
|
||||
params:
|
||||
url: "https://api.example.com/v1/users"
|
||||
```
|
||||
|
||||
config.json
|
||||
|
||||
```json
|
||||
{
|
||||
"contextProviders": [
|
||||
{ "name": "http", "params": { "url": "https://api.example.com/v1/users" } }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The receiving URL should expect to receive the following parameters:
|
||||
|
||||
POST parameters
|
||||
|
||||
```json
|
||||
{ query: string, fullInput: string}
|
||||
```
|
||||
|
||||
The response 200 OK should be a JSON object with the following structure:
|
||||
|
||||
Response
|
||||
|
||||
```
|
||||
[ { "name": "", "description": "", "content": "" }]// OR{ "name": "", "description": "", "content": ""}
|
||||
```
|
||||
|
||||
### @Commits Context Provider – Reference Git Commit Metadata and Diffs
|
||||
|
||||
Reference specific git commit metadata and diff or all of the recent commits.
|
||||
|
||||
- YAML
|
||||
- JSON
|
||||
|
||||
config.yaml
|
||||
|
||||
```
|
||||
context:
|
||||
- provider: commit
|
||||
params:
|
||||
Depth: 50
|
||||
LastXCommitsDepth: 10
|
||||
```
|
||||
|
||||
config.json
|
||||
|
||||
```json
|
||||
{
|
||||
"contextProviders": [
|
||||
{ "name": "commit", "params": { "Depth": 50, "LastXCommitsDepth": 10 } }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The depth is how many commits will be loaded into the submenu, defaults to 50. The LastXCommitsDepth is how many recent commits will be included, defaults to 10.
|
||||
|
||||
### @Greptile Context Provider – Query Greptile Index of Repo/Branch
|
||||
|
||||
Query a [Greptile](https://www.greptile.com/) index of the current repo/branch.
|
||||
|
||||
- YAML
|
||||
- JSON
|
||||
|
||||
config.yaml
|
||||
|
||||
```
|
||||
context:
|
||||
- provider: greptile
|
||||
params:
|
||||
greptileToken: "..."
|
||||
githubToken: "..."
|
||||
```
|
||||
|
||||
config.json
|
||||
|
||||
```json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "greptile",
|
||||
"params": { "GreptileToken": "...", "GithubToken": "..." }
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### How to Request a New Context Provider in Continue
|
||||
|
||||
Not seeing what you want? Create an issue [here](https://github.com/continuedev/continue/issues/new?assignees=TyDunn&labels=enhancement&projects=&template=feature-request-%F0%9F%92%AA.md&title=) to request a new Context Provider.
|
||||
|
|
|
|||
|
|
@ -5,9 +5,11 @@ keywords: [autocomplete]
|
|||
sidebarTitle: Autocomplete
|
||||
---
|
||||
|
||||
<Info>
|
||||
For a comprehensive comparison of all autocomplete models, see our [model recommendations table](/customization/models#recommended-models).
|
||||
</Info>
|
||||
import { ModelRecommendations } from "/snippets/ModelRecommendations.jsx";
|
||||
|
||||
## Model Recommendations for Autocomplete
|
||||
|
||||
<ModelRecommendations role="autocomplete" />
|
||||
|
||||
## How to Set Up Autocomplete in Continue with Codestral (Recommended)
|
||||
|
||||
|
|
@ -127,7 +129,7 @@ Explore autocomplete model configurations on [the hub](https://hub.continue.dev/
|
|||
### Customize Autocomplete User Settings in the Continue Extension
|
||||
|
||||
{/* - `Use autocomplete cache`: If on, caches completions */}
|
||||
The following settings can be configured for autocompletion in the IDE extension [User Settings Page](../settings.md):
|
||||
The following settings can be configured for autocompletion in the IDE extension User Settings Page:
|
||||
|
||||
- `Multiline Autocompletions`: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto`
|
||||
- `Disable autocomplete in files`: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., "\_/.md, \*/.txt"
|
||||
|
|
|
|||
433
docs/customize/deep-dives/custom-providers.mdx
Normal file
433
docs/customize/deep-dives/custom-providers.mdx
Normal file
|
|
@ -0,0 +1,433 @@
|
|||
---
|
||||
title: "Context Providers"
|
||||
description: "Context Providers allow you to type '@' and see a dropdown of content that can all be provided to the model as context."
|
||||
---
|
||||
|
||||
Context Providers allow you to type '@' and see a dropdown of content that can all be provided to the model as context.
|
||||
|
||||

|
||||
|
||||
## Built-in Context Providers
|
||||
|
||||
You can add any built-in context-providers in your config file as shown below:
|
||||
|
||||
### `@File`
|
||||
|
||||
Reference any file in your current workspace.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml config.yaml
|
||||
context:
|
||||
- provider: file
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json config.json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "file"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### `@Code`
|
||||
|
||||
Reference specific functions or classes from throughout your project.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml config.yaml
|
||||
context:
|
||||
- provider: code
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json config.json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "code"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### `@Git Diff`
|
||||
|
||||
Reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml config.yaml
|
||||
context:
|
||||
- provider: diff
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json config.json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "diff"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### `@Current File`
|
||||
|
||||
Reference the currently open file.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml config.yaml
|
||||
context:
|
||||
- provider: currentFile
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json config.json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "currentFile"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### `@Terminal`
|
||||
|
||||
Reference the last command you ran in your IDE's terminal and its output.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml config.yaml
|
||||
context:
|
||||
- provider: terminal
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json config.json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "terminal"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### `@Open`
|
||||
|
||||
Reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml config.yaml
|
||||
context:
|
||||
- provider: open
|
||||
params:
|
||||
onlyPinned: true
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json config.json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "open",
|
||||
"params": {
|
||||
"onlyPinned": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### `@Clipboard`
|
||||
|
||||
Reference recent clipboard items
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml config.yaml
|
||||
context:
|
||||
- provider: clipboard
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json config.json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "clipboard"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### `@Tree`
|
||||
|
||||
Reference the structure of your current workspace.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml config.yaml
|
||||
context:
|
||||
- provider: tree
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json config.json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "tree"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### `@Problems`
|
||||
|
||||
Get Problems from the current file.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml config.yaml
|
||||
context:
|
||||
- provider: problems
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json config.json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "problems"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### `@Debugger`
|
||||
|
||||
Reference the contents of the local variables in the debugger. Currently only available in VS Code.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml config.yaml
|
||||
context:
|
||||
- provider: debugger
|
||||
params:
|
||||
stackDepth: 3
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json config.json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "debugger",
|
||||
"params": {
|
||||
"stackDepth": 3
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Uses the top _n_ levels (defaulting to 3) of the call stack for that thread.
|
||||
|
||||
### `@Repository Map`
|
||||
|
||||
Reference the outline of your codebase. By default, signatures are included along with file in the repo map.
|
||||
|
||||
`includeSignatures` params can be set to false to exclude signatures. This could be necessary for large codebases and/or to reduce context size significantly. Signatures will not be included if indexing is disabled.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml config.yaml
|
||||
context:
|
||||
- provider: repo-map
|
||||
params:
|
||||
includeSignatures: false # default true
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json config.json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "repo-map",
|
||||
"params": {
|
||||
"includeSignatures": false // default true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase.
|
||||
|
||||
In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repostiory map from.
|
||||
|
||||
This context provider is inpsired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html).
|
||||
|
||||
### `@Operating System`
|
||||
|
||||
Reference the architecture and platform of your current operating system.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml config.yaml
|
||||
context:
|
||||
- provider: os
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json config.json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "os"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### `@HTTP`
|
||||
|
||||
The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml config.yaml
|
||||
context:
|
||||
- provider: http
|
||||
params:
|
||||
url: "https://api.example.com/v1/users"
|
||||
headers:
|
||||
- Authorization: "Bearer <token>"
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json config.json
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "http",
|
||||
"params": {
|
||||
"url": "https://api.example.com/v1/users"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
The receiving URL should expect to receive the following parameters:
|
||||
|
||||
POST parameters
|
||||
|
||||
```json
|
||||
{ query: string, fullInput: string}
|
||||
```
|
||||
|
||||
The response 200 OK should be a JSON object with the following structure:
|
||||
|
||||
Response
|
||||
|
||||
```
|
||||
[ { "name": "", "description": "", "content": "" }]// OR{ "name": "", "description": "", "content": ""}
|
||||
```
|
||||
|
||||
### Model Context Protocol
|
||||
|
||||
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then set up your configuration like this:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml config.yaml
|
||||
mcpServers:
|
||||
- name: My MCP Server
|
||||
command: uvx
|
||||
args:
|
||||
- mcp-server-sqlite
|
||||
- --db-path
|
||||
- /Users/NAME/test.db
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json config.json
|
||||
{
|
||||
"experimental": {
|
||||
"modelContextProtocolServers": [
|
||||
{
|
||||
"transport": {
|
||||
"type": "stdio",
|
||||
"command": "uvx",
|
||||
"args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
You'll then be able to type "@" and see "MCP" in the context providers dropdown.
|
||||
|
||||
## Deprecated Context Providers
|
||||
|
||||
<Note>
|
||||
To provide conext beyond the built-in context providers, we now recommend
|
||||
using [MCP Servers](/customization/mcp-tools)
|
||||
</Note>
|
||||
|
||||
View the [deprecated context providers](/reference/deprecated-context-providers) for documentation on:
|
||||
|
||||
- [`@Codebase`](/reference/deprecated-codebase) - Use the [codebase awareness guide](/guides/codebase-documentation-awareness) instead
|
||||
- [`@Folder`](/reference/deprecated-codebase) - Use the [codebase awareness guide](/guides/codebase-documentation-awareness) instead
|
||||
- [`@Docs`](/reference/deprecated-docs) - Use the [documentation awareness guide](/guides/codebase-documentation-awareness) instead
|
||||
- `@Greptile` - Query Greptile index
|
||||
- `@Commits` - Reference git commits
|
||||
- `@Discord` - Reference Discord messages
|
||||
- `@Jira` - Reference Jira issues
|
||||
- `@Gitlab Merge Request` - Reference GitLab MRs
|
||||
- `@Google` - Google search results
|
||||
- `@Database` - Database schemas
|
||||
- `@Issue` - GitHub issues
|
||||
- `@Url` - URL content
|
||||
- `@Search` - Codebase search
|
||||
- `@Web` - Web search results
|
||||
|
|
@ -13,8 +13,6 @@ You can read more about how development data is generated as a byproduct of LLM-
|
|||
|
||||
You can also configure custom destinations for your data, including remote HTTP endpoints and local file directories.
|
||||
|
||||
For hub assistants, data destinations are configured in `data` blocks. Visit the hub to [explore example data blocks](https://hub.continue.dev/explore/data) or [create your own](https://hub.continue.dev/new?type=block&blockType=data).
|
||||
|
||||
See more details about adding `data` blocks to your configuration files in the [YAML specification](/reference#data)
|
||||
Data destinations should be configured directly in the `data` section of your `config.yaml` file. See more details about adding `data` configuration in the [YAML specification](/reference#data).
|
||||
|
||||
When sending development data to your own HTTP endpoint, it will receive an event JSON blob at the given `schema` version. You can view event names, schema versions, and fields [here in the source code](https://github.com/continuedev/continue/tree/main/packages/config-yaml/src/schemas/data).
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ sidebarTitle: "Slash Commands"
|
|||
Slash commands are shortcuts that can be activated by typing '/' in a chat session (press <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains)), and selecting from the dropdown.
|
||||

|
||||
|
||||
Slash commands can be combined with additional instructions, including [context providers](../custom-providers) or highlighted code.
|
||||
Slash commands can be combined with additional instructions, including highlighted code.
|
||||
|
||||
<Note>
|
||||
**Recommended approach**: Use prompt files to create slash commands instead of
|
||||
|
|
|
|||
|
|
@ -1,44 +0,0 @@
|
|||
---
|
||||
title: "How to Use Continue's VS Code Actions and Quick Features"
|
||||
keywords: [vscode, quick actions, quick, actions]
|
||||
description: "Learn about Continue's VS Code-specific actions including quick actions buttons, right-click context menu options, debug shortcuts, and quick fixes for errors in your code"
|
||||
sidebarTitle: "VS Code Actions"
|
||||
---
|
||||
|
||||
<Info>Currently all of these are only available in VS Code</Info>
|
||||
|
||||
To make common use cases even more accessible, we provide a handful of other ways to invoke actions in VS Code.
|
||||
|
||||
## How to Use Quick Actions
|
||||
|
||||
Quick Actions are displayed as buttons above top-level classes and functions in your source code, letting you invoke actions with one click. They will edit that class or function, but nothing outside of it. They can also be customized with [.prompt files](./prompts.md) to perform custom actions.
|
||||
|
||||

|
||||
|
||||
By default, quick actions are disabled, but can be enabled with the “Continue: Enable Quick Actions” in VS Code settings.
|
||||
|
||||
## How to Use Right Click Actions
|
||||
|
||||
Right click actions let you highlight a desired region of code, right click, and then select an action from the dropdown menu.
|
||||
|
||||
The highlighted code you’ve selected will be included in your prompt alongside a pre-written set of instructions depending on the selected action. This is the only section of code that the model will attempt to edit.
|
||||
|
||||
Right click actions that generate inline diffs use the same prompt and response processing logic as [Edit](../../features/edit/how-it-works).
|
||||
|
||||

|
||||
|
||||
## How to Use the Debug Action Shortcut
|
||||
|
||||
The debug action is a special built-in keyboard shortcut in the VS Code extension. Use <kbd>cmd/ctrl</kbd> + <kbd>shift</kbd> + <kbd>R</kbd> to instantly copy the contents of the most recent terminal output into the chat sidebar and get debugging advice. There is no additional, non-visible information sent to the language model.
|
||||
|
||||
```
|
||||
I got the following error, can you please help explain how to fix it?
|
||||
|
||||
[ERROR_MESSAGE]
|
||||
```
|
||||
|
||||
## How to Use Quick Fixes for Code Errors
|
||||
|
||||
Whenever you see red/yellow underlines in your code indicating errors, you can place your cursor nearby and VS Code will display a lightbulb icon. Either clicking the lightbulb or using the keyboard shortcut <kbd>cmd/ctrl</kbd> + <kbd>.</kbd> will show a dropdown menu of quick fixes. One of these will be the “Ask Continue” action. Either click or use <kbd>cmd/ctrl</kbd> + <kbd>.</kbd> again and Continue will attempt to help solve the problem.
|
||||
|
||||
Similarly to the debug action, quick actions transparently inject a prompt into the chat window. When you select “Ask Continue”, the 3 lines above and below the error are sent to the chat followed by the question “How do I fix the following problem in the above code?: [ERROR_MESSAGE]”.
|
||||
|
|
@ -3,27 +3,35 @@ title: "DeepInfra"
|
|||
description: "Configure DeepInfra with Continue to access low-cost inference for open-source models like Mixtral-8x7B-Instruct, including API setup instructions"
|
||||
---
|
||||
|
||||
[DeepInfra](https://deepinfra.com) provides inference for open-source models at very low cost. To get started with DeepInfra, obtain your API key [here](https://deepinfra.com/dash). Then, find the model you want to use [here](https://deepinfra.com/models?type=text-generation) and copy the name of the model. Continue can then be configured to use the `DeepInfra` LLM class, like the example here:
|
||||
<Tip>
|
||||
**Discover Deep Infra models [here](https://hub.continue.dev/deepinfra)**
|
||||
</Tip>
|
||||
|
||||
<Info>
|
||||
Get an API key from the [Deep Infra](https://deepinfra.com/)
|
||||
</Info>
|
||||
|
||||
## Configuration
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: DeepInfra
|
||||
- name: <MODEL_NAME>
|
||||
provider: deepinfra
|
||||
model: mistralai/Mixtral-8x7B-Instruct-v0.1
|
||||
apiKey: <YOUR_DEEP_INFRA_API_KEY>
|
||||
model: <MODEL_ID>
|
||||
apiKey: <YOUR_DEEPINFRA_API_KEY>
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "<MODEL_NAME>",
|
||||
"provider": "deepinfra",
|
||||
"title": "DeepInfra",
|
||||
"model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
||||
"apiKey": "<YOUR_DEEP_INFRA_API_KEY>"
|
||||
"model": "<MODEL_ID>",
|
||||
"apiKey": "<YOUR_DEEPINFRA_API_KEY>"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -31,4 +39,6 @@ description: "Configure DeepInfra with Continue to access low-cost inference for
|
|||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/DeepInfra.ts)
|
||||
<Info>
|
||||
**Check out a more advanced configuration [here](https://hub.continue.dev/deepinfra/qwen-qwen2.5-coder-32b-instruct?view=config)**
|
||||
</Info>
|
||||
40
docs/customize/model-providers/more/deepseek.mdx
Normal file
40
docs/customize/model-providers/more/deepseek.mdx
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
---
|
||||
title: DeepSeek
|
||||
slug: ../deepseek
|
||||
---
|
||||
|
||||
<Tip>
|
||||
**Discover DeepSeek models [here](https://hub.continue.dev/?q=DeepSeek)**
|
||||
</Tip>
|
||||
|
||||
<Info>
|
||||
You can get an API key from the [DeepSeek Console](https://www.deepseek.com/).
|
||||
</Info>
|
||||
|
||||
## Confiugration
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: <MODEL_NAME>
|
||||
provider: deepseek
|
||||
model: <MODEL_ID>
|
||||
apiKey: <YOUR_DEEPSEEK_API_KEY>
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "<MODEL_NAME>",
|
||||
"provider": "deepseek",
|
||||
"model": "<MODEL_ID>",
|
||||
"apiKey": "<YOUR_DEEPSEEK_API_KEY>"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
|
@ -1,44 +1,36 @@
|
|||
---
|
||||
title: "How to Configure Groq with Continue"
|
||||
description: "Configure Groq with Continue to access their ultra-fast inference platform for open-source language models, including the entire Llama 3.1 and 3.3 family with industry-leading speeds"
|
||||
sidebarTitle: "Groq"
|
||||
---
|
||||
|
||||
<Info>
|
||||
Check if your chosen model is still supported by referring to the [model
|
||||
documentation](https://console.groq.com/docs/models). If a model has been
|
||||
deprecated, you may encounter a 404 error when attempting to use it.
|
||||
Get your API key from the [Groq Console](https://console.groq.com/docs/models)
|
||||
</Info>
|
||||
|
||||
Groq provides the fastest available inference for open-source language models, including the entire Llama 3.1 family.
|
||||
|
||||
1. Obtain an API key [here](https://console.groq.com/keys)
|
||||
2. Update your Continue config file like this:
|
||||
## Configuration
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Llama 3.3 70b Versatile
|
||||
- name: <MODEL_NAME>
|
||||
provider: groq
|
||||
model: llama-3.3-70b-versatile
|
||||
apiKey: <YOUR_GROQ_API_KEY>
|
||||
roles:
|
||||
- chat
|
||||
model: <MODEL_ID>
|
||||
apiKey: <YOUR_GROQ_API_KEY>"
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Llama 3.3 70b Versatile",
|
||||
"title": "<MODEL_NAME>",
|
||||
"provider": "groq",
|
||||
"model": "llama-3.3-70b-versatile",
|
||||
"apiKey": "<YOUR_GROQ_API_KEY>"
|
||||
"model": "<MODEL_ID>",
|
||||
"apiKey": "<YOUR_GROQ_API_KEY>"",
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
</Tabs>
|
||||
|
|
@ -1,36 +1,37 @@
|
|||
---
|
||||
title: "HuggingFace Inference Endpoints"
|
||||
description: "Configure HuggingFace Inference Endpoints with Continue to deploy and access open-source language models on any cloud, including setup instructions for models like WizardCoder"
|
||||
title: "Hugging Face"
|
||||
---
|
||||
|
||||
Hugging Face Inference Endpoints are an easy way to setup instances of open-source language models on any cloud. Sign up for an account and add billing [here](https://huggingface.co/settings/billing), access the Inference Endpoints [here](https://ui.endpoints.huggingface.co), click on “New endpoint”, and fill out the form (e.g. select a model like [WizardCoder-Python-34B-V1.0](https://huggingface.co/WizardLM/WizardCoder-Python-34B-V1.0)), and then deploy your model by clicking “Create Endpoint”. Change `~/.continue/config.json` to look like this:
|
||||
<Info>
|
||||
Get started with [Hugging Face Inference Endpoints](https://endpoints.huggingface.co/)
|
||||
</Info>
|
||||
|
||||
## Configuration
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Hugging Face Inference API
|
||||
provider: huggingface-inference-api
|
||||
model: MODEL_NAME
|
||||
apiKey: <YOUR_HF_TOKEN>
|
||||
apiBase: <YOUR_HF_INFERENCE_API_ENDPOINT_URL>
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Hugging Face Inference API",
|
||||
"provider": "huggingface-inference-api",
|
||||
"model": "MODEL_NAME",
|
||||
"apiKey": "<YOUR_HF_TOKEN>",
|
||||
"apiBase": "<YOUR_HF_INFERENCE_API_ENDPOINT_URL>"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/HuggingFaceInferenceAPI.ts)
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: <MODEL_NAME>
|
||||
provider: huggingface-inference-api
|
||||
model: <MODEL_ID>
|
||||
apiKey: <YOUR_HF_TOKEN>
|
||||
apiBase: <YOUR_HF_INFERENCE_API_ENDPOINT_URL>
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "<MODEL_NAME>",
|
||||
"provider": "huggingface-inference-api",
|
||||
"model": "<MODEL_ID>",
|
||||
"apiKey": "<YOUR_HF_TOKEN>",
|
||||
"apiBase": "<YOUR_HF_INFERENCE_API_ENDPOINT_URL>"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
|
@ -1,40 +1,35 @@
|
|||
---
|
||||
title: "Llama.cpp"
|
||||
description: "Configure Llama.cpp with Continue to run local language models using high-performance C++ inference, including setup instructions for the server and client configuration"
|
||||
---
|
||||
|
||||
Run the llama.cpp server binary to start the API server. If running on a remote server, be sure to set host to 0.0.0.0:
|
||||
<Info>
|
||||
Get started with [Llama.cpp](https://github.com/ggml-org/llama.cpp?tab=readme-ov-file#quick-start)
|
||||
</Info>
|
||||
|
||||
```bash
|
||||
.\server.exe -c 4096 --host 0.0.0.0 -t 16 --mlock -m models\meta\llama\codellama-7b-instruct.Q8_0.gguf
|
||||
```
|
||||
|
||||
After it's up and running, change `~/.continue/config.json` to look like this:
|
||||
## Configuration
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Llama CPP
|
||||
provider: llama.cpp
|
||||
model: MODEL_NAME
|
||||
apiBase: http://localhost:8080
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Llama CPP",
|
||||
"provider": "llama.cpp",
|
||||
"model": "MODEL_NAME",
|
||||
"apiBase": "http://localhost:8080"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/LlamaCpp.ts)
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: <MODEL_NAME>
|
||||
provider: llama.cpp
|
||||
model: <MODEL_ID>
|
||||
apiBase: http://localhost:8080
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "<MODEL_NAME>",
|
||||
"provider": "llama.cpp",
|
||||
"model": "<MODEL_ID>"
|
||||
"apiBase": "http://localhost:8080"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
|
@ -1,114 +1,34 @@
|
|||
---
|
||||
title: "Llama Stack"
|
||||
description: "Configure Llama Stack with Continue"
|
||||
keywords: [llama, stack, local, api, inference]
|
||||
---
|
||||
|
||||
[Llama Stack](https://llama-stack.readthedocs.io/en/latest/index.html) is an open-source library that standardizes the core building blocks that simplify AI application development. It codifies best practices across the Llama ecosystem. More specifically, it provides
|
||||
|
||||
- **Unified API layer** for Inference, RAG, Agents, Tools, Safety, Evals, and Telemetry.
|
||||
- **Plugin architecture** to support the rich ecosystem of different API implementations in various environments, including local development, on-premises, cloud, and mobile.
|
||||
- **Prepackaged verified distributions** which offer a one-stop solution for developers to get started quickly and reliably in any environment.
|
||||
- **Multiple developer interfaces** like CLI and SDKs for Python, Typescript, iOS, and Android.
|
||||
- **Standalone applications** as examples for how to build production-grade AI applications with Llama Stack.
|
||||
|
||||
To try Llama Stack locally, run:
|
||||
|
||||
```shell
|
||||
curl -LsSf https://github.com/meta-llama/llama-stack/raw/main/install.sh | bash
|
||||
```
|
||||
|
||||
Learn more about how to get started with llama stack in this [guide](https://llama-stack.readthedocs.io/en/latest/getting_started/index.html)
|
||||
|
||||
## Chat model
|
||||
|
||||
We recommend configuring **Llama 4 Maverick** as your chat model.
|
||||
<Info>
|
||||
Get started with [Lllama Stack](https://llama-stack.readthedocs.io/en/latest/getting_started/index.html)
|
||||
</Info>
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Llama4 Maverick
|
||||
provider: llamastack
|
||||
model: meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8
|
||||
apiBase: http://<llama stack endpoint>/v1/openai/v1/
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Llama4 Maverick",
|
||||
"provider": "llamastack",
|
||||
"model": "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",
|
||||
"apiBase": "http://<llama stack endpoint>/v1/openai/v1/"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Autocomplete model
|
||||
|
||||
We recommend configuring **CodeLlama 7B** as your autocomplete model.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: CodeLlama 7B
|
||||
provider: llamastack
|
||||
model: codellama:7b
|
||||
apiBase: http://<llama stack endpoint>/v1/openai/v1/
|
||||
roles:
|
||||
- autocomplete
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"tabAutocompleteModel": {
|
||||
"title": "CodeLlama 7B",
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: <MODEL_NAME>
|
||||
provider: llamastack
|
||||
model: <MODEL_ID>
|
||||
apiBase: http://<LLAMA_STACK_ENDPOINT>/v1/openai/v1/
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "<MODEL_NAME>",
|
||||
"provider": "llamastack",
|
||||
"model": "codellama:7b",
|
||||
"apiBase": "http://<llama stack endpoint>/v1/openai/v1/"
|
||||
}
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Embeddings model
|
||||
|
||||
By default, Llama Stack uses **all-MiniLM-L6-v2** as the embeddings model.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: all-MiniLM-L6-v2
|
||||
provider: llamastack
|
||||
model: all-MiniLM-L6-v2
|
||||
apiBase: http://<llama stack endpoint>/v1/openai/v1/
|
||||
roles:
|
||||
- embed
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"embeddingsProvider": {
|
||||
"provider": "llamastack",
|
||||
"model": "all-MiniLM-L6-v2",
|
||||
"apiBase": "http://<llama stack endpoint>/v1/openai/v1/"
|
||||
}
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Reranking model
|
||||
|
||||
Llama Stack currently did not support Reranking API yet.
|
||||
"model": "<MODEL_ID>",
|
||||
"apiBase": "http://<LLAMA_STACK_ENDPOINT>/v1/openai/v1/"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
|
@ -1,95 +0,0 @@
|
|||
---
|
||||
title: "LM Studio"
|
||||
description: "Configure LM Studio with Continue to run open-source models locally, including setup for Llama3.1 8B for chat, embedding models, and instructions for connecting to remote instances"
|
||||
---
|
||||
|
||||
[LM Studio](https://lmstudio.ai) is an application for Mac, Windows, and Linux that makes it easy to locally run open-source models and comes with a great UI. To get started with LM Studio, download from the website, use the UI to download a model, and then start the local inference server. Continue can then be configured to use the `LMStudio` LLM class:
|
||||
|
||||
## Chat model
|
||||
|
||||
We recommend configuring **Llama3.1 8B** as your chat model.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Llama3.1 8B Instruct
|
||||
provider: lmstudio
|
||||
model: meta-llama-3.1-8b-instruct
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Llama3.1 8B Instruct",
|
||||
"provider": "lmstudio",
|
||||
"model": "meta-llama-3.1-8b-instruct"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Embeddings model
|
||||
|
||||
LMStudio supports embeddings endpoints, and comes with the `nomic-ai/nomic-embed-text-v1.5-GGUF` model (as of Nov 2024, check your models)
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Nomic Embed Text
|
||||
provider: lmstudio
|
||||
model: nomic-ai/nomic-embed-text-v1.5-GGUF
|
||||
roles:
|
||||
- embed
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"embeddingsProvider": {
|
||||
"provider": "lmstudio",
|
||||
"model": "nomic-ai/nomic-embed-text-v1.5-GGUF"
|
||||
}
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Setting up a remote instance
|
||||
|
||||
To configure a remote instance of LM Studio, add the `"apiBase"` property to your model in config.json:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Llama3.1 8B Instruct
|
||||
provider: lmstudio
|
||||
model: meta-llama-3.1-8b-instruct
|
||||
apiBase: http://<MY ENDPOINT>/v1
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Llama3.1 8B Instruct",
|
||||
"provider": "lmstudio",
|
||||
"model": "meta-llama-3.1-8b-instruct",
|
||||
"apiBase": "http://<MY ENDPOINT>/v1"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
This `apiBase` will now be used instead of the default `http://localhost:1234/v1`.
|
||||
|
||||
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/LMStudio.ts)
|
||||
50
docs/customize/model-providers/more/mistral.mdx
Normal file
50
docs/customize/model-providers/more/mistral.mdx
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
---
|
||||
title: Mistral
|
||||
slug: ../mistral
|
||||
---
|
||||
|
||||
<Tip>
|
||||
**Discover Mistral models [here](https://hub.continue.dev/mistral)**
|
||||
</Tip>
|
||||
|
||||
<Info>
|
||||
Get an API key from the [Mistral Dashboard](https://console.mistral.ai)
|
||||
</Info>
|
||||
|
||||
## Configuration
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: <MODEL_NAME>
|
||||
provider: mistral
|
||||
model: <MODEL_ID>
|
||||
apiKey: <YOUR_MISTRAL_API_KEY>
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "<MODEL_NAME>",
|
||||
"provider": "mistral",
|
||||
"model": "<MODEL_ID>",
|
||||
"apiKey": "<YOUR_MISTRAL_API_KEY>"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Info>
|
||||
**Check out a more advanced configuration [here](https://hub.continue.dev/mistral/codestral?view=config)**
|
||||
</Info>
|
||||
|
||||
<Note>
|
||||
The API key for `codestral.mistral.ai` is different from `api.mistral.ai`.
|
||||
If you are using a Codestral API key, you should set the `apiBase` to `https://codestral.mistral.ai/v1`.
|
||||
Otherwise, we will default to using `https://api.mistral.ai/v1`.
|
||||
</Note>
|
||||
|
|
@ -1,36 +1,31 @@
|
|||
---
|
||||
title: "NVIDIA"
|
||||
description: "Configure NVIDIA AI models with Continue, including setup for Nemotron-4-340B-Instruct for chat and NVIDIA Retrieval QA Mistral 7B for embeddings"
|
||||
---
|
||||
|
||||
<Info>
|
||||
[View the
|
||||
docs](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog)
|
||||
to learn how to get an API key.
|
||||
Get an API key from the [NVIDIA](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog)
|
||||
</Info>
|
||||
|
||||
## Chat model
|
||||
|
||||
We recommend configuring **Nemotron-4-340B-Instruct** as your chat model.
|
||||
## Configuration
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Nemotron-4-340B-Instruct
|
||||
- name: <MODEL_NAME>
|
||||
provider: nvidia
|
||||
model: nvidia-nemotron-4-340b-instruct
|
||||
model: <MODEL_ID>
|
||||
apiKey: <YOUR_NVIDIA_API_KEY>
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Nemotron-4-340B-Instruct",
|
||||
"title": "<MODEL_NAME>",
|
||||
"provider": "nvidia",
|
||||
"model": "nvidia-nemotron-4-340b-instruct",
|
||||
"model": "<MODEL_ID>",
|
||||
"apiKey": "<YOUR_NVIDIA_API_KEY>"
|
||||
}
|
||||
]
|
||||
|
|
@ -38,44 +33,3 @@ We recommend configuring **Nemotron-4-340B-Instruct** as your chat model.
|
|||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Autocomplete model
|
||||
|
||||
NVIDIA currently does not offer any autocomplete models.
|
||||
|
||||
[Click here](../../model-roles/autocomplete) to see a list of autocomplete model providers.
|
||||
|
||||
## Embeddings model
|
||||
|
||||
We recommend configuring **NVIDIA Retrieval QA Mistral 7B** as your embeddings model.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Nvidia Embedder
|
||||
provider: nvidia
|
||||
model: nvidia/nv-embedqa-mistral-7b-v2
|
||||
apiKey: <YOUR_NVIDIA_API_KEY>
|
||||
roles:
|
||||
- embed
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"embeddingsProvider": {
|
||||
"provider": "nvidia",
|
||||
"model": "nvidia/nv-embedqa-mistral-7b-v2",
|
||||
"apiKey": "<YOUR_NVIDIA_API_KEY>"
|
||||
}
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Reranking model
|
||||
|
||||
NVIDIA currently does not offer any reranking models.
|
||||
|
||||
[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers.
|
||||
|
|
|
|||
|
|
@ -1,157 +0,0 @@
|
|||
---
|
||||
title: "How to Configure OpenRouter with Continue"
|
||||
sidebarTitle: "OpenRouter"
|
||||
description: "Configure OpenRouter with Continue to access various commercial and open-source models through a unified interface, including model capability configuration and advanced request options"
|
||||
---
|
||||
|
||||
OpenRouter is a unified interface for commercial and open-source models, giving you access to the best models at the best prices. You can sign up [here](https://openrouter.ai/signup), create your API key on the [keys page](https://openrouter.ai/keys), and then choose a model from the [list of supported models](https://openrouter.ai/models).
|
||||
|
||||
Change `~/.continue/config.yaml` to look like the following.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: OpenRouter LLaMA 70 8B
|
||||
provider: openrouter
|
||||
model: meta-llama/llama-3-70b-instruct
|
||||
apiBase: https://openrouter.ai/api/v1
|
||||
apiKey: <YOUR_OPEN_ROUTER_API_KEY>
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "OpenRouter LLaMA 70 8B",
|
||||
"provider": "openrouter",
|
||||
"model": "meta-llama/llama-3-70b-instruct",
|
||||
"apiBase": "https://openrouter.ai/api/v1",
|
||||
"apiKey": "<YOUR_OPEN_ROUTER_API_KEY>"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Using Custom Models
|
||||
|
||||
To use a model that is not in the dropdown list, you can simply enter the model name in the `model` field. For example, to use Qwen3Coder, you would update your configuration to look like this:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Qwen3Coder
|
||||
provider: openrouter
|
||||
model: qwen/qwen-coder
|
||||
apiBase: https://openrouter.ai/api/v1
|
||||
apiKey: <YOUR_OPEN_ROUTER_API_KEY>
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Qwen3Coder",
|
||||
"provider": "openrouter",
|
||||
"model": "qwen/qwen-coder",
|
||||
"apiBase": "https://openrouter.ai/api/v1",
|
||||
"apiKey": "<YOUR_OPEN_ROUTER_API_KEY>"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
To utilize features such as provider preferences or model routing configuration, include these parameters inside the `models[].requestsOptions.extraBodyProperties` field of your plugin config.
|
||||
|
||||
For example, to prevent extra long prompts from being compressed, you can explicitly turn off the feature like so:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Example Model
|
||||
provider: exampleProvider
|
||||
model: example-model
|
||||
requestOptions:
|
||||
extraBodyProperties:
|
||||
transforms: []
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Example Model",
|
||||
"provider": "exampleProvider",
|
||||
"model": "example-model",
|
||||
"requestOptions": {
|
||||
"extraBodyProperties": {
|
||||
"transforms": []
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Learn more about available settings [here](https://openrouter.ai/docs).
|
||||
|
||||
## Model Capabilities
|
||||
|
||||
OpenRouter models may require explicit capability configuration because the proxy doesn't always preserve the original model's function calling support.
|
||||
|
||||
<Info>
|
||||
Continue automatically uses system message tools for models that don't support
|
||||
native function calling, so Agent mode should work even without explicit
|
||||
capability configuration. However, you can still override capabilities if
|
||||
needed.
|
||||
</Info>
|
||||
|
||||
If you're experiencing issues with Agent mode or tools not working, you can add the capabilities field:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Claude via OpenRouter
|
||||
provider: openrouter
|
||||
model: anthropic/claude-3.5-sonnet
|
||||
apiBase: https://openrouter.ai/api/v1
|
||||
apiKey: <YOUR_OPEN_ROUTER_API_KEY>
|
||||
capabilities:
|
||||
- tool_use # Enable function calling for Agent mode
|
||||
- image_input # Enable image upload support
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Claude via OpenRouter",
|
||||
"provider": "openrouter",
|
||||
"model": "anthropic/claude-3.5-sonnet",
|
||||
"apiBase": "https://openrouter.ai/api/v1",
|
||||
"apiKey": "<YOUR_OPEN_ROUTER_API_KEY>",
|
||||
"capabilities": {
|
||||
"tools": true,
|
||||
"uploadImage": true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Note: Not all models support function calling. Check the [OpenRouter models page](https://openrouter.ai/models) for specific model capabilities.
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
---
|
||||
title: "Tetrate Agent Router Service"
|
||||
---
|
||||
|
||||
The Tetrate Agent Router Service (TARS) provides a unified API gateway for accessing various AI models with fast inference capabilities. TARS acts as an intelligent router that can distribute requests across multiple model providers, offering enterprise-grade reliability and performance optimization.
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. Obtain an API key from the [Tetrate Agent Router Service portal](https://api.router.tetrate.ai/)
|
||||
2. Configure Continue to use TARS as your model provider
|
||||
|
||||
## Configuration
|
||||
|
||||
Update your Continue configuration file (`~/.continue/config.json` or `~/.continue/config.yaml`) with your TARS API key:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: TARS GPT-5 Mini
|
||||
provider: tars
|
||||
model: gpt-5-mini
|
||||
apiKey: <YOUR_TARS_API_KEY>
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "TARS GPT-5 Mini",
|
||||
"provider": "tars",
|
||||
"model": "gpt-5-mini",
|
||||
"apiKey": "<YOUR_TARS_API_KEY>"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Available Models
|
||||
|
||||
TARS supports routing to various models. Go to the [Tetrate Agent Router Service model catalog](https://router.tetrate.ai/models) for a full list of supported models.
|
||||
|
|
@ -1,35 +1,44 @@
|
|||
---
|
||||
title: "How to Configure Together AI with Continue"
|
||||
description: "Configure the Together AI cloud platform for running large language models with Continue, including setup instructions and sample configuration for Qwen2.5 Coder"
|
||||
title: "Together AI"
|
||||
sidebarTitle: "Together AI"
|
||||
---
|
||||
|
||||
The Together API is a cloud platform for running large AI models. You can sign up [here](https://api.together.xyz/signup), copy your API key on the initial welcome screen, and then hit the play button on any model from the [Together Models list](https://docs.together.ai/docs/serverless-models). Change `~/.continue/config.json` to look like this:
|
||||
<Tip>
|
||||
**Discover Together AI models [here](https://hub.continue.dev/togetherai)**
|
||||
</Tip>
|
||||
|
||||
<Info>
|
||||
Get an API key from the [Together AI](https://api.together.ai)
|
||||
</Info>
|
||||
|
||||
## Configuration
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Together Qwen2.5 Coder
|
||||
provider: together
|
||||
model: Qwen/Qwen2.5-Coder-32B-Instruct
|
||||
apiKey: <YOUR_TOGETHER_API_KEY>
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Together Qwen2.5 Coder",
|
||||
"provider": "together",
|
||||
"model": "Qwen/Qwen2.5-Coder-32B-Instruct",
|
||||
"apiKey": "<YOUR_TOGETHER_API_KEY>"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: <MODEL_NAME>
|
||||
provider: together
|
||||
model: <MODEL_ID>
|
||||
apiKey: <YOUR_TOGETHER_API_KEY>
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "<MODEL_NAME>",
|
||||
"provider": "together",
|
||||
"model": "<MODEL_ID>",
|
||||
"apiKey": "<YOUR_TOGETHER_API_KEY>"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Together.ts)
|
||||
<Info>
|
||||
**Check out a more advanced configuration [here](https://hub.continue.dev/togetherai/qwen3-coder-480b-a35b-instruct-fp8?view=config)**
|
||||
</Info>
|
||||
44
docs/customize/model-providers/more/xAI.mdx
Normal file
44
docs/customize/model-providers/more/xAI.mdx
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
---
|
||||
title: xAI
|
||||
slug: ../xai
|
||||
---
|
||||
|
||||
<Tip>
|
||||
**Discover xAI models [here](https://hub.continue.dev/xai)**
|
||||
</Tip>
|
||||
|
||||
<Info>
|
||||
Get an API key from the [xAI Console](https://console.x.ai/)
|
||||
</Info>
|
||||
|
||||
## Configuration
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: <MODEL_NAME>
|
||||
provider: xai
|
||||
model: <MODEL_ID>
|
||||
apiKey: <YOUR_XAI_API_KEY>
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "<MODEL_NAME>",
|
||||
"provider": "anthropic",
|
||||
"model": "<MODEL_ID>",
|
||||
"apiKey": "<YOUR_XAI_API_KEY>"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Info>
|
||||
**Check out a more advanced configuration [here](https://hub.continue.dev/xai/grok-4?view=config)**
|
||||
</Info>
|
||||
|
|
@ -15,9 +15,9 @@ These are the most commonly used model providers that offer a wide range of capa
|
|||
| [Amazon Bedrock](/customize/model-providers/top-level/bedrock) | AWS service offering access to various foundation models | Chat, Edit, Apply, Embeddings |
|
||||
| [Ollama](/customize/model-providers/top-level/ollama) | Run open-source models locally with a simple interface | Chat, Edit, Apply, Embeddings, Autocomplete |
|
||||
| [Google Gemini](/customize/model-providers/top-level/gemini) | Google's multimodal AI models | Chat, Edit, Apply, Embeddings |
|
||||
| [DeepSeek](/customize/model-providers/top-level/deepseek) | Specialized code models with strong performance | Chat, Edit, Apply |
|
||||
| [Mistral](/customize/model-providers/top-level/mistral) | High-performance open models with commercial offerings | Chat, Edit, Apply, Embeddings |
|
||||
| [xAI](/customize/model-providers/top-level/xAI) | Grok models from xAI | Chat, Edit, Apply |
|
||||
| [DeepSeek](/customize/model-providers/more/deepseek) | Specialized code models with strong performance | Chat, Edit, Apply |
|
||||
| [Mistral](/customize/model-providers/more/mistral) | High-performance open models with commercial offerings | Chat, Edit, Apply, Embeddings |
|
||||
| [xAI](/customize/model-providers/more/xAI) | Grok models from xAI | Chat, Edit, Apply |
|
||||
| [Vertex AI](/customize/model-providers/top-level/vertexai) | Google Cloud's machine learning platform | Chat, Edit, Apply, Embeddings |
|
||||
| [Inception](/customize/model-providers/top-level/inception) | On-premises open-source model runners | Chat, Edit, Apply |
|
||||
|
||||
|
|
@ -32,7 +32,7 @@ Beyond the top-level providers, Continue supports many other options:
|
|||
| [Groq](/customize/model-providers/more/groq) | Ultra-fast inference for various open models |
|
||||
| [Together AI](/customize/model-providers/more/together) | Platform for running a variety of open models |
|
||||
| [DeepInfra](/customize/model-providers/more/deepinfra) | Hosting for various open source models |
|
||||
| [OpenRouter](/customize/model-providers/more/openrouter) | Gateway to multiple model providers |
|
||||
| [OpenRouter](/customize/model-providers/top-level/openrouter) | Gateway to multiple model providers |
|
||||
| [Cohere](/customize/model-providers/more/cohere) | Models specialized for semantic search and text generation |
|
||||
| [NVIDIA](/customize/model-providers/more/nvidia) | GPU-accelerated model hosting |
|
||||
| [Cloudflare](/customize/model-providers/more/cloudflare) | Edge-based AI inference services |
|
||||
|
|
@ -42,7 +42,7 @@ Beyond the top-level providers, Continue supports many other options:
|
|||
|
||||
| Provider | Description |
|
||||
| :------------------------------------------------------- | :-------------------------------------------- |
|
||||
| [LM Studio](/customize/model-providers/more/lmstudio) | Desktop app for running models locally |
|
||||
| [LM Studio](/customize/model-providers/top-level/lmstudio) | Desktop app for running models locally |
|
||||
| [llama.cpp](/customize/model-providers/more/llamacpp) | Optimized C++ implementation for running LLMs |
|
||||
| [LlamaStack](/customize/model-providers/more/llamastack) | Stack for running Llama models locally |
|
||||
| [llamafile](/customize/model-providers/more/llamafile) | Self-contained executable model files |
|
||||
|
|
@ -72,9 +72,9 @@ You can add models to your `config.yaml` file like this:
|
|||
|
||||
```yaml
|
||||
models:
|
||||
- name: My Model
|
||||
provider: openai # Choose provider from the lists above
|
||||
model: gpt-4o # Specific model name
|
||||
- name: Claude 4 Sonnet
|
||||
provider: anthropic # Choose provider from the lists above
|
||||
model: claude-sonnet-4-20250514 # Specific model name
|
||||
apiKey: ${{ secrets.OPENAI_API_KEY }}
|
||||
roles:
|
||||
- chat
|
||||
|
|
|
|||
|
|
@ -1,37 +1,37 @@
|
|||
---
|
||||
title: "How to Configure Anthropic Claude Models with Continue"
|
||||
slug: ../anthropic
|
||||
description: "Configure Anthropic's Claude models with Continue, including Claude 4 Sonnet with prompt caching capabilities to improve performance and reduce costs for chat applications"
|
||||
sidebarTitle: "Anthropic"
|
||||
---
|
||||
|
||||
<Tip>
|
||||
**Discover Anthropic models [here](https://hub.continue.dev/anthropic)**
|
||||
</Tip>
|
||||
|
||||
<Info>
|
||||
You can get an API key from the [Anthropic
|
||||
console](https://console.anthropic.com/account/keys).
|
||||
Get an API key from the [Anthropic Console](https://console.anthropic.com/account/keys)
|
||||
</Info>
|
||||
|
||||
## How to Set Up Anthropic Chat Models
|
||||
|
||||
We recommend configuring **Claude 4 Sonnet** as your chat model.
|
||||
## Configuration
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Claude 4 Sonnet
|
||||
- name: <MODEL_NAME>
|
||||
provider: anthropic
|
||||
model: claude-sonnet-4-20250514
|
||||
model: <MODEL_ID>
|
||||
apiKey: <YOUR_ANTHROPIC_API_KEY>
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Claude 4 Sonnet",
|
||||
"title": "<MODEL_NAME>",
|
||||
"provider": "anthropic",
|
||||
"model": "claude-sonnet-4-latest",
|
||||
"model": "<MODEL_ID>",
|
||||
"apiKey": "<YOUR_ANTHROPIC_API_KEY>"
|
||||
}
|
||||
]
|
||||
|
|
@ -40,44 +40,23 @@ We recommend configuring **Claude 4 Sonnet** as your chat model.
|
|||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Anthropic Autocomplete Model Availability
|
||||
|
||||
Anthropic currently does not offer any autocomplete models.
|
||||
|
||||
[Click here](../../model-roles/autocomplete) to see a list of autocomplete model providers.
|
||||
|
||||
## Anthropic Embeddings Model Availability
|
||||
|
||||
Anthropic currently does not offer any embeddings models.
|
||||
|
||||
[Click here](../../model-roles/embeddings.mdx) to see a list of embeddings model providers.
|
||||
|
||||
## Anthropic Reranking Model Availability
|
||||
|
||||
Anthropic currently does not offer any reranking models.
|
||||
|
||||
[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers.
|
||||
<Info>
|
||||
**Check out a more advanced configuration [here](https://hub.continue.dev/anthropic/claude-4-sonnet?view=config)**
|
||||
</Info>
|
||||
|
||||
## How to Enable Prompt Caching with Claude
|
||||
|
||||
Anthropic supports [prompt caching with Claude](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching), which allows Claude models to cache system messages and conversation history between requests to improve performance and reduce costs.
|
||||
|
||||
Prompt caching is generally available for:
|
||||
|
||||
- Claude 4 Sonnet
|
||||
- Claude 3.7 Sonnet
|
||||
- Claude 3.5 Sonnet
|
||||
- Claude 3.5 Haiku
|
||||
|
||||
To enable caching of the system message and the turn-by-turn conversation, update your model configuration as follows:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Anthropic
|
||||
- name: <MODEL_NAME>
|
||||
provider: anthropic
|
||||
model: claude-sonnet-4-20250514
|
||||
model: <MODEL_ID>
|
||||
apiKey: <YOUR_ANTHROPIC_API_KEY>
|
||||
roles:
|
||||
- chat
|
||||
|
|
@ -85,7 +64,7 @@ To enable caching of the system message and the turn-by-turn conversation, updat
|
|||
promptCaching: true
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
|
|
@ -94,9 +73,9 @@ To enable caching of the system message and the turn-by-turn conversation, updat
|
|||
"cacheSystemMessage": true,
|
||||
"cacheConversation": true
|
||||
},
|
||||
"title": "Anthropic",
|
||||
"title": "<MODEL_NAME>",
|
||||
"provider": "anthropic",
|
||||
"model": "claude-sonnet-4-latest",
|
||||
"model": "<MODEL_ID>",
|
||||
"defaultCompletionOptions": {
|
||||
"promptCaching": true
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,29 +1,20 @@
|
|||
---
|
||||
title: "How to Configure Azure AI Foundry with Continue"
|
||||
slug: ../azure
|
||||
description: "Configure Azure AI Foundry with Continue to access models from OpenAI and Mistral with Microsoft's enterprise security features, including setup for GPT-4o, Codestral, and embedding models"
|
||||
sidebarTitle: "Azure AI Foundry"
|
||||
---
|
||||
|
||||
Azure AI Foundry is a cloud-based service that provides access to models from OpenAI, Mistral AI, and others, integrated with the security and enterprise features of the Microsoft Azure platform. To get started, create an Azure AI Foundry resource in the [Azure portal](https://portal.azure.com).
|
||||
|
||||
<Info>
|
||||
|
||||
For details on OpenAI model setup, see [Azure OpenAI Service configuration](#how-to-configure-azure-openai-service).
|
||||
|
||||
Create an Azure AI Foundry resource in the [Azure Portal](https://portal.azure.com)
|
||||
</Info>
|
||||
|
||||
## How to Set Up Azure AI Foundry Chat Models
|
||||
|
||||
We recommend configuring **GPT-4o** as your chat model.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: GPT-4o
|
||||
- name: <Model_NAME>
|
||||
provider: azure
|
||||
model: gpt-4o
|
||||
model: <MODEL_ID>
|
||||
apiBase: <YOUR_DEPLOYMENT_BASE>
|
||||
apiKey: <YOUR_AZURE_API_KEY> # If you use subscription key, try using Azure gateway to rename it apiKey
|
||||
env:
|
||||
|
|
@ -32,13 +23,13 @@ We recommend configuring **GPT-4o** as your chat model.
|
|||
apiVersion: 2023-07-01-preview # Azure API version
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [{
|
||||
"title": "GPT-4o",
|
||||
"title": "<MODEL_NAME>",
|
||||
"provider": "azure",
|
||||
"model": "gpt-4o",
|
||||
"model": "<MODEL_ID>",
|
||||
"apiBase": "<YOUR_DEPLOYMENT_BASE>",
|
||||
"deployment": "<YOUR_DEPLOYMENT_NAME>",
|
||||
"apiKey": "<YOUR_AZURE_API_KEY>", // If you use subscription key, try using Azure gateway to rename it apiKey
|
||||
|
|
@ -49,101 +40,12 @@ We recommend configuring **GPT-4o** as your chat model.
|
|||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## How to Set Up Azure AI Foundry Autocomplete Models
|
||||
|
||||
We recommend configuring **Codestral** as your autocomplete model.
|
||||
## Azure OpenAI Service (Alternative)
|
||||
|
||||
<Info>
|
||||
**Note:** Azure AI Foundry does not provide the FIM (Fill-in-Middle) endpoint
|
||||
required for autocomplete functionality. To use Codestral for autocomplete,
|
||||
deploy it through **Azure Machine Learning Studio** instead, which provides
|
||||
the necessary `/v1/fim/completions` endpoint.
|
||||
Get access to the Azure OpenAI service [here](https://azure.microsoft.com/en-us/products/ai-services/openai-service)
|
||||
</Info>
|
||||
|
||||
If you use Azure Machine Learning Studio to deploy Codestral:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Codestral
|
||||
provider: mistral
|
||||
model: codestral-latest
|
||||
apiBase: https://<YOUR_MODEL_NAME>.<YOUR_REGION>.models.ai.azure.com/v1
|
||||
apiKey: <YOUR_AZURE_API_KEY>
|
||||
roles:
|
||||
- autocomplete
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"tabAutocompleteModel": {
|
||||
"title": "Codestral",
|
||||
"provider": "mistral",
|
||||
"model": "codestral-latest",
|
||||
"apiBase": "https://<YOUR_MODEL_NAME>.<YOUR_REGION>.models.ai.azure.com/v1",
|
||||
"apiKey": "<YOUR_AZURE_API_KEY>"
|
||||
}
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## How to Configure Azure AI Foundry Embeddings Models
|
||||
|
||||
For recommended embeddings models, please refer to our [Model Recommendations page](/customization/models).
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Text Embedding-3 Large
|
||||
provider: azure
|
||||
model: text-embedding-3-large
|
||||
apiBase: <YOUR_DEPLOYMENT_BASE>
|
||||
apiKey: <YOUR_AZURE_API_KEY>
|
||||
env:
|
||||
deployment: <YOUR_DEPLOYMENT_NAME>
|
||||
apiType: azure
|
||||
apiVersion: 2023-07-01-preview
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"embeddingsProvider": {
|
||||
"provider": "azure",
|
||||
"model": "text-embedding-3-large",
|
||||
"apiBase": "<YOUR_DEPLOYMENT_BASE>",
|
||||
"deployment": "<YOUR_DEPLOYMENT_NAME>",
|
||||
"apiKey": "<YOUR_AZURE_API_KEY>",
|
||||
"apiType": "azure-foundry" // Or "azure-openai" if using OpenAI models
|
||||
}
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Reranking model
|
||||
|
||||
Azure OpenAI currently does not offer any reranking models.
|
||||
|
||||
[Click here](../../model-roles/reranking.mdx) to see a list of reranking models.
|
||||
|
||||
## Privacy
|
||||
|
||||
If you'd like to use OpenAI models but are concerned about privacy, you can use the Azure OpenAI service, which is GDPR and HIPAA compliant.
|
||||
|
||||
<Info>
|
||||
**Getting access:** [Click
|
||||
here](https://azure.microsoft.com/en-us/products/ai-services/openai-service)
|
||||
to apply for access to the Azure OpenAI service. Response times are typically
|
||||
within a few days.
|
||||
</Info>
|
||||
|
||||
## Azure OpenAI Service configuration
|
||||
|
||||
Azure OpenAI Service requires a handful of additional parameters to be configured, such as a deployment name and API base URL.
|
||||
|
||||
To find this information in _Azure AI Foundry_, first select the model that you would like to connect. Then visit _Endpoint_ > _Target URI_.
|
||||
|
|
@ -154,29 +56,29 @@ For example, a Target URI of `https://just-an-example.openai.azure.com/openai/de
|
|||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: GPT-4o Azure
|
||||
model: gpt-4o
|
||||
- name: <MODEL_NAME>
|
||||
model: <MODEL_ID>
|
||||
provider: azure
|
||||
apiBase: https://just-an-example.openai.azure.com
|
||||
apiKey: <YOUR_AZURE_API_KEY>
|
||||
env:
|
||||
apiVersion: 2023-03-15-preview
|
||||
deployment: gpt-4o-july
|
||||
apiVersion: <API_VERSION>
|
||||
deployment: <MODEL_DEPLOYMENT>
|
||||
apiType: azure-openai
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json title="config.json"
|
||||
{
|
||||
"title": "GPT-4o Azure",
|
||||
"model": "gpt-4o",
|
||||
"title": "<MODEL_NAME>",
|
||||
"model": "<MODEL_ID>",
|
||||
"provider": "azure",
|
||||
"apiBase": "https://just-an-example.openai.azure.com",
|
||||
"deployment": "gpt-4o-july",
|
||||
"apiVersion": "2023-03-15-preview",
|
||||
"deployment": "<MODEL_DEPLOYMENT>",
|
||||
"apiVersion": "<API_VERSION>",
|
||||
"apiKey": "<YOUR_AZURE_API_KEY>",
|
||||
"apiType": "azure-openai"
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
</Tabs>
|
||||
|
|
@ -1,23 +1,26 @@
|
|||
---
|
||||
title: "How to Configure Amazon Bedrock with Continue"
|
||||
slug: ../bedrock
|
||||
description: "Configure Amazon Bedrock with Continue to access foundation models like Claude 3.7 Sonnet for chat, Titan for embeddings, and Cohere for reranking, with AWS credential authentication"
|
||||
sidebarTitle: "Amazon Bedrock"
|
||||
---
|
||||
|
||||
Amazon Bedrock is a fully managed service on AWS that provides access to foundation models from various AI companies through a single API.
|
||||
<Tip>
|
||||
**Discover Amazon Bedrock models [here](https://hub.continue.dev/amazon)**
|
||||
</Tip>
|
||||
|
||||
## How to Set Up Amazon Bedrock Chat Models
|
||||
<Info>
|
||||
Get started with [Amazon Bedrock](https://aws.amazon.com/bedrock/)
|
||||
</Info>
|
||||
|
||||
We recommend configuring **Claude 3.7 Sonnet** as your chat model.
|
||||
## Configuration
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Claude 3.7 Sonnet
|
||||
- name: <MODEL_NAME>
|
||||
provider: bedrock
|
||||
model: us.anthropic.claude-3-7-sonnet-20250219-v1:0
|
||||
model: <MODEL_ID>
|
||||
env:
|
||||
region: us-east-1
|
||||
profile: bedrock
|
||||
|
|
@ -25,14 +28,14 @@ We recommend configuring **Claude 3.7 Sonnet** as your chat model.
|
|||
- chat
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Claude 3.7 Sonnet",
|
||||
"title": "<MODEL_NAME>",
|
||||
"provider": "bedrock",
|
||||
"model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
|
||||
"model": "<MODEL_ID>",
|
||||
"region": "us-east-1",
|
||||
"profile": "bedrock"
|
||||
}
|
||||
|
|
@ -42,109 +45,9 @@ We recommend configuring **Claude 3.7 Sonnet** as your chat model.
|
|||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
> If you run into the following error when connecting to the new Claude 3.5 Sonnet 2 models from AWS - `400 Invocation of model ID anthropic.claude-3-5-sonnet-20241022-v2:0 with on-demand throughput isn't supported. Retry your request with the ID or ARN of an inference profile that contains this model.`
|
||||
|
||||
> You can fix this using the following config:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Claude 3.5 Sonnet
|
||||
provider: bedrock
|
||||
model: us.anthropic.claude-3-5-sonnet-20241022-v2:0
|
||||
env:
|
||||
region: us-east-1
|
||||
profile: bedrock
|
||||
roles:
|
||||
- chat
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Claude 3.5 Sonnet",
|
||||
"provider": "bedrock",
|
||||
"model": "us.anthropic.claude-3-5-sonnet-20241022-v2:0",
|
||||
"region": "us-east-1",
|
||||
"profile": "bedrock"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## How to Set Up Amazon Bedrock Autocomplete Models
|
||||
|
||||
Bedrock currently does not offer any autocomplete models. However, [Codestral from Mistral](https://mistral.ai/news/codestral-2501/) and [Point from Poolside](https://aws.amazon.com/bedrock/poolside/) will be supported in the near future.
|
||||
|
||||
In the meantime, you can view a list of autocomplete model providers [here](../../model-roles/autocomplete).
|
||||
|
||||
## How to Configure Amazon Bedrock Embeddings Models
|
||||
|
||||
We recommend configuring [`amazon.titan-embed-text-v2:0`](https://docs.aws.amazon.com/bedrock/latest/devguide/models.html#amazon.titan-embed-text-v2-0) as your embeddings model.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Embeddings Model
|
||||
provider: bedrock
|
||||
model: amazon.titan-embed-text-v2:0
|
||||
env:
|
||||
region: us-west-2
|
||||
roles:
|
||||
- embed
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"embeddingsProvider": {
|
||||
"title": "Embeddings Model",
|
||||
"provider": "bedrock",
|
||||
"model": "amazon.titan-embed-text-v2:0",
|
||||
"region": "us-west-2"
|
||||
}
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## How to Configure Amazon Bedrock Reranking Models
|
||||
|
||||
We recommend configuring `cohere.rerank-v3-5:0` as your reranking model, you may also use `amazon.rerank-v1:0`.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Bedrock Reranker
|
||||
provider: bedrock
|
||||
model: cohere.rerank-v3-5:0
|
||||
env:
|
||||
region: us-west-2
|
||||
roles:
|
||||
- rerank
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"reranker": {
|
||||
"name": "bedrock",
|
||||
"params": {
|
||||
"model": "cohere.rerank-v3-5:0",
|
||||
"region": "us-west-2"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
<Info>
|
||||
**Check out a more advanced configuration [here](https://hub.continue.dev/amazon/us-anthropic-claude-sonnet-4-20250514-v1?view=config)**
|
||||
</Info>
|
||||
|
||||
## How to Enable Prompt Caching with Amazon Bedrock
|
||||
|
||||
|
|
@ -153,23 +56,11 @@ messages between requests. Enable this behavior by adding
|
|||
`promptCaching: true` under `defaultCompletionOptions` in your model
|
||||
configuration.
|
||||
|
||||
Prompt caching is generally available for:
|
||||
|
||||
- Claude 3.7 Sonnet
|
||||
- Claude 3.5 Haiku
|
||||
- Amazon Nova Micro
|
||||
- Amazon Nova Lite
|
||||
- Amazon Nova Pro
|
||||
|
||||
Customers who were granted access to Claude 3.5 Sonnet v2 during the prompt
|
||||
caching preview will retain that access, but it cannot be enabled for new users
|
||||
on that model.
|
||||
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Claude 3.7 Sonnet
|
||||
- name: <MODEL_NAME>
|
||||
provider: bedrock
|
||||
model: us.anthropic.claude-3-7-sonnet-20250219-v1:0
|
||||
model: <MODEL_ID>
|
||||
defaultCompletionOptions:
|
||||
promptCaching: true
|
||||
```
|
||||
|
|
@ -194,9 +85,9 @@ You can also use an AWS `accessKeyId` and `secretAccessKey` for authentication i
|
|||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Claude 3.7 Sonnet
|
||||
- name: <MODEL_NAME>
|
||||
provider: bedrock
|
||||
model: us.anthropic.claude-3-7-sonnet-20250219-v1:0
|
||||
model: <MODEL_ID>
|
||||
env:
|
||||
region: us-east-1
|
||||
accessKeyId: ${{ secrets.AWS_ACCESS_KEY_ID }} # can also enter key inline here for local assistants
|
||||
|
|
@ -205,17 +96,17 @@ You can also use an AWS `accessKeyId` and `secretAccessKey` for authentication i
|
|||
- chat
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Claude 3.7 Sonnet",
|
||||
"title": "<MODEL_NAME>",
|
||||
"provider": "bedrock",
|
||||
"model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
|
||||
"model": "<MODEL_ID>",
|
||||
"region": "us-east-1",
|
||||
"accessKeyId": "[YOUR_ACCESS_KEY_ID]",
|
||||
"secretAccessKey": "[YOUR_SECRET_ACCESS_KEY]"
|
||||
"accessKeyId": "<YOUR_ACCESS_KEY_ID>",
|
||||
"secretAccessKey": "<YOUR_SECRET_ACCESS_KEY>"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -231,23 +122,23 @@ To setup Bedrock using custom imported models, add the following to your config
|
|||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: AWS Bedrock deepseek-coder-6.7b-instruct
|
||||
- name: <MODEL_NAME>
|
||||
provider: bedrockimport
|
||||
model: deepseek-coder-6.7b-instruct
|
||||
model: <MODEL_ID>
|
||||
env:
|
||||
region: us-west-2
|
||||
profile: bedrock
|
||||
modelArn: arn:aws:bedrock:us-west-2:XXXXX:imported-model/XXXXXX
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
<Tab title="JSON (Deprecated)">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "AWS Bedrock deepseek-coder-6.7b-instruct",
|
||||
"title": "<MODEL_NAME>",
|
||||
"provider": "bedrockimport",
|
||||
"model": "deepseek-coder-6.7b-instruct",
|
||||
"model": "<MODEL_ID>",
|
||||
"modelArn": "arn:aws:bedrock:us-west-2:XXXXX:imported-model/XXXXXX",
|
||||
"region": "us-west-2",
|
||||
"profile": "bedrock"
|
||||
|
|
|
|||
|
|
@ -1,82 +0,0 @@
|
|||
---
|
||||
title: "How to Configure DeepSeek with Continue"
|
||||
slug: ../deepseek
|
||||
description: "Configure DeepSeek models with Continue, including DeepSeek Chat for general conversations and DeepSeek Coder specifically optimized for code autocomplete and programming tasks"
|
||||
sidebarTitle: "DeepSeek"
|
||||
---
|
||||
|
||||
<Info>
|
||||
You can get an API key from the [DeepSeek console](https://www.deepseek.com/).
|
||||
</Info>
|
||||
|
||||
## How to Set Up DeepSeek Chat Models
|
||||
|
||||
We recommend configuring **DeepSeek Chat** as your chat model.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: DeepSeek Chat
|
||||
provider: deepseek
|
||||
model: deepseek-chat
|
||||
apiKey: <YOUR_DEEPSEEK_API_KEY>
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "DeepSeek Chat",
|
||||
"provider": "deepseek",
|
||||
"model": "deepseek-chat",
|
||||
"apiKey": "<YOUR_DEEPSEEK_API_KEY>"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## How to Set Up DeepSeek Autocomplete Models
|
||||
|
||||
For recommended autocomplete models, please refer to our [Model Recommendations page](/customization/models).
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: DeepSeek Coder
|
||||
provider: deepseek
|
||||
model: deepseek-coder
|
||||
apiKey: <YOUR_DEEPSEEK_API_KEY>
|
||||
roles:
|
||||
- autocomplete
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"tabAutocompleteModel": {
|
||||
"title": "DeepSeek Coder",
|
||||
"provider": "deepseek",
|
||||
"model": "deepseek-coder",
|
||||
"apiKey": "<YOUR_DEEPSEEK_API_KEY>"
|
||||
}
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## How to Configure DeepSeek Embeddings Models
|
||||
|
||||
DeepSeek currently does not offer any embeddings models.
|
||||
|
||||
[Click here](../../model-roles/embeddings.mdx) to see a list of embeddings model providers.
|
||||
|
||||
## How to Configure DeepSeek Reranking Models
|
||||
|
||||
DeepSeek currently does not offer any reranking models.
|
||||
|
||||
[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers.
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue