Merge branch 'fix-added-folders-not-triggering-reindex' of https://github.com/mq200/continue into fix-added-folders-not-triggering-reindex

This commit is contained in:
mq200 2025-09-25 10:12:16 -07:00
commit d6a5129fdb
426 changed files with 39190 additions and 10222 deletions

View file

@ -0,0 +1,100 @@
# Mintlify Documentation Formatting Rules
## Component Formatting
When working with Mintlify documentation components (Card, Info, Tip, Note, Warning, etc.), follow these formatting guidelines:
### Bullet Points and Lists
1. **Always add a blank line** after the opening component tag and before the closing tag
2. **Indent content** by 2 spaces within components
3. **Use proper list formatting** with each item on its own line:
- Start lists on a new line after introductory text
- Use `-` for unordered lists
- Maintain consistent indentation
### Examples
#### ✅ Correct Formatting:
```mdx
<Card title="Example" icon="icon-name">
This is the content with proper formatting:
- First bullet point
- Second bullet point
- Third bullet point
</Card>
```
```mdx
<Info>
Important information here:
- Point one
- Point two
- Point three
</Info>
```
#### ❌ Incorrect Formatting:
```mdx
<Card title="Example" icon="icon-name">
This is wrong: - All bullets - On one line - Bad formatting
</Card>
```
### Component-Specific Rules
1. **Card Components**: Always include blank lines and proper indentation
2. **Info/Tip/Note/Warning**: Format lists as bullet points, not inline
3. **CardGroup**: Each Card within should follow the same formatting rules
4. **Code Blocks**: Within components, maintain proper indentation
### Links in Lists
When including links in bullet points:
```mdx
- [Link Text](url): Description of the link
```
### Nested Components
For nested components, maintain proper indentation levels:
```mdx
<CardGroup>
<Card title="First Card">
Content here:
- Bullet one
- Bullet two
</Card>
<Card title="Second Card">
More content:
- Another bullet
- Final bullet
</Card>
</CardGroup>
```
## Application
These rules apply to all `.mdx` files in the `docs/` directory, particularly:
- Guide documents
- Cookbook documents
- Reference documentation
- Any Mintlify-powered documentation
## Automation Note
When using Continue or other AI assistants to generate or modify documentation:
- Always format Mintlify components according to these rules
- Review generated content for proper formatting
- Apply these rules consistently across all documentation

View file

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

View file

@ -0,0 +1,6 @@
---
name: Personality Rules
description: Conversational and personality guidelines
---
When the user challenges your output or asks a question, don't be overly-amiable (e.g. responding "You're right" all the time). Focus on correctness and be willing to tell the user they are wrong.

View file

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

View file

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

View file

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

View file

@ -26,8 +26,24 @@ jobs:
echo "should_run=false" >> $GITHUB_OUTPUT
fi
check-version:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v5
with:
fetch-depth: 0 # This ensures all tags are fetched
- name: Checkout tag
run: git checkout ${GITHUB_REF#refs/tags/}
- name: Make sure version isn't odd
run: |
cd extensions/vscode
node scripts/versionCheck.js
build:
needs: check_release_name
needs: [check_release_name, check-version]
if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch'
runs-on: ${{ matrix.os }}
strategy:
@ -88,22 +104,6 @@ jobs:
name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix
path: "extensions/vscode/*.vsix"
check-version:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v5
with:
fetch-depth: 0 # This ensures all tags are fetched
- name: Checkout tag
run: git checkout ${GITHUB_REF#refs/tags/}
- name: Make sure version isn't odd
run: |
cd extensions/vscode
node scripts/versionCheck.js
release:
permissions:
contents: write

View file

@ -84,6 +84,9 @@ jobs:
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
gui-checks:
runs-on: ubuntu-latest
@ -217,6 +220,8 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
vscode-get-test-file-matrix:
runs-on: ubuntu-latest

View file

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

View file

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

View file

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

View file

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

View file

@ -21,7 +21,12 @@ jobs:
- name: Check if comment contains @continuedev
id: check-mention
run: |
if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
# Create a temporary file to safely handle comment body with special characters
cat > /tmp/comment.txt << 'COMMENT_EOF'
${{ github.event.comment.body }}
COMMENT_EOF
if grep -q "@continuedev" /tmp/comment.txt; then
echo "contains_mention=true" >> $GITHUB_OUTPUT
else
echo "contains_mention=false" >> $GITHUB_OUTPUT
@ -83,15 +88,22 @@ jobs:
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 }}:
# 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 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."
Please analyze the current PR, understand the request, 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
SESSION_OUTPUT=$(echo "$PROMPT" | cn remote -s --branch ${{ steps.pr-info.outputs.head_ref }})
echo "Starting cn with prompt..."
SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --config continuedev/address-code-review --branch ${{ steps.pr-info.outputs.head_ref }})
echo "Raw session output: $SESSION_OUTPUT"
# Extract URL from JSON output
@ -108,10 +120,13 @@ jobs:
- name: Comment with session URL
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
uses: actions/github-script@v8
env:
ORIGINAL_COMMENT: ${{ github.event.comment.body }}
with:
script: |
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
> ${{ github.event.comment.body }}`;
const sessionUrl = '${{ steps.remote-session.outputs.session_url }}';
const originalComment = process.env.ORIGINAL_COMMENT;
const commentBody = "I've started [a remote session](" + sessionUrl + ") to help with your request:\n> " + originalComment;
await github.rest.issues.createComment({
owner: context.repo.owner,
@ -125,7 +140,8 @@ jobs:
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 }}"
echo "Original comment:"
cat /tmp/comment.txt
respond-to-review-comment:
# Only run on pull request review comments
@ -136,7 +152,12 @@ jobs:
- name: Check if comment contains @continuedev
id: check-mention
run: |
if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
# Create a temporary file to safely handle comment body with special characters
cat > /tmp/review_comment.txt << 'COMMENT_EOF'
${{ github.event.comment.body }}
COMMENT_EOF
if grep -q "@continuedev" /tmp/review_comment.txt; then
echo "contains_mention=true" >> $GITHUB_OUTPUT
else
echo "contains_mention=false" >> $GITHUB_OUTPUT
@ -233,7 +254,7 @@ jobs:
# Start remote session and capture JSON output
echo "Starting cn with prompt..."
SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --branch ${{ github.event.pull_request.head.ref }})
SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --config continuedev/address-code-review --branch ${{ github.event.pull_request.head.ref }})
echo "Raw session output: $SESSION_OUTPUT"
# Extract URL from JSON output
@ -250,10 +271,13 @@ jobs:
- name: Comment with session URL
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
uses: actions/github-script@v8
env:
ORIGINAL_COMMENT: ${{ github.event.comment.body }}
with:
script: |
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
> ${{ github.event.comment.body }}`;
const sessionUrl = '${{ steps.remote-session.outputs.session_url }}';
const originalComment = process.env.ORIGINAL_COMMENT;
const commentBody = "I've started [a remote session](" + sessionUrl + ") to help with your request:\n> " + originalComment;
const commentParams = {
owner: context.repo.owner,
@ -274,4 +298,5 @@ jobs:
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
echo "File: ${{ github.event.comment.path }}"
echo "Line: ${{ github.event.comment.line }}"
echo "Original comment: ${{ github.event.comment.body }}"
echo "Original comment:"
cat /tmp/review_comment.txt

View file

@ -32,6 +32,10 @@ on:
required: false
VOYAGE_API_KEY:
required: false
RELACE_API_KEY:
required: false
INCEPTION_API_KEY:
required: false
permissions:
contents: write
@ -77,6 +81,8 @@ jobs:
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
- name: Release
env:

View file

@ -4,6 +4,7 @@ binary/out
binary/tmp
core/.continue-test
docs/.docusaurus
docs/**/*.mdx
extensions/.continue-debug
extensions/vscode/continue_rc_schema.json
extensions/vscode/.vscode-test
@ -17,6 +18,7 @@ extensions/vscode/models
extensions/intellij/src/main/resources
gui/dist
**/.continueignore
.continue/rules/mintlify-formatting.md
CHANGELOG.md
**/continue_tutorial.py
**/node_modules

11
.vscode/launch.json vendored
View file

@ -136,8 +136,9 @@
"name": "Debug CLI",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/extensions/cli/src/index.ts",
"program": "${workspaceFolder}/extensions/cli/dist/cn.js",
"args": [],
"runtimeArgs": ["--enable-source-maps"],
"env": {
"NODE_ENV": "development"
// "CONTINUE_API_BASE": "http://localhost:3001/",
@ -147,13 +148,17 @@
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"skipFiles": ["<node_internals>/**"],
"runtimeArgs": ["--loader", "ts-node/esm"],
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/extensions/cli/dist/**/*.js"],
"sourceMapPathOverrides": {
"../src/*": "${workspaceFolder}/extensions/cli/src/*",
"../../core/*": "${workspaceFolder}/core/*"
},
"resolveSourceMapLocations": [
"${workspaceFolder}/**",
"!**/node_modules/**"
],
"preLaunchTask": "watch-logs",
"preLaunchTask": "cli:build-and-watch-logs",
"cwd": "${workspaceFolder}/extensions/cli"
},
{

35
.vscode/tasks.json vendored
View file

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

View file

@ -1,20 +1,20 @@
name: 'Continue PR Review'
description: 'Automated code review for pull requests using Continue CLI'
author: 'Continue Dev, Inc.'
name: "Continue PR Review"
description: "Automated code review for pull requests using Continue CLI"
author: "Continue Dev, Inc."
inputs:
continue-api-key:
description: 'API key for Continue service'
description: "API key for Continue service"
required: true
continue-org:
description: 'Organization for Continue config'
description: "Organization for Continue config"
required: true
continue-config:
description: 'Config path to use (e.g., "myorg/review-bot")'
required: true
runs:
using: 'composite'
using: "composite"
steps:
- name: Checkout Repository
uses: actions/checkout@v4
@ -27,7 +27,7 @@ runs:
run: |
# Check if this action should run based on event type and user permissions
SHOULD_RUN="false"
if [ "${{ github.event_name }}" = "pull_request" ]; then
# Check if PR is a draft
if [ "${{ github.event.pull_request.draft }}" = "true" ]; then
@ -56,7 +56,7 @@ runs:
else
echo "::notice::Skipping review - Unsupported event type: ${{ github.event_name }}"
fi
echo "SHOULD_RUN=$SHOULD_RUN" >> $GITHUB_ENV
- name: Setup Node.js
@ -162,14 +162,14 @@ runs:
echo "Warning: CONTINUE_API_KEY environment variable is not set"
# Create fallback review and continue
cat > code_review.md << 'EOF'
## Code Review Summary
## Code Review Summary
⚠️ AI review skipped: CONTINUE_API_KEY not configured.
⚠️ 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
### 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
@ -180,7 +180,7 @@ EOF
echo "Error: Invalid organization name. Must contain only alphanumeric characters, hyphens, and underscores."
exit 1
fi
if [[ ! "$CONTINUE_CONFIG" =~ ^[a-zA-Z0-9_/-]+$ ]]; then
echo "Error: Invalid config path. Must contain only alphanumeric characters, hyphens, underscores, and forward slashes."
exit 1
@ -192,14 +192,14 @@ EOF
if ! cn --version; then
echo "Warning: Continue CLI not found or not working"
cat > code_review.md << 'EOF'
## Code Review Summary
## Code Review Summary
⚠️ AI review skipped: Continue CLI installation failed.
⚠️ AI review skipped: Continue CLI installation failed.
### Troubleshooting
- Check that npm installation succeeded
- Verify @continuedev/cli package is available
EOF
### 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)"
@ -222,15 +222,15 @@ EOF
# Create fallback review
cat > code_review.md << 'EOF'
## Code Review Summary
## Code Review Summary
⚠️ AI review failed due to service initialization issues. Please check the Continue API key and configuration.
⚠️ 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
### 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
@ -294,5 +294,5 @@ EOF
}
branding:
icon: 'code'
color: 'blue'
icon: "code"
color: "blue"

View file

@ -56,6 +56,7 @@
"@continuedev/fetch": "file:../packages/fetch",
"@continuedev/llm-info": "file:../packages/llm-info",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@continuedev/terminal-security": "file:../packages/terminal-security",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",

View file

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

View file

@ -1,99 +1,17 @@
import fs from "fs";
import { homedir } from "node:os";
import { fileURLToPath, pathToFileURL } from "node:url";
import { fileURLToPath } from "node:url";
import path from "path";
import { languageForFilepath } from "../../../autocomplete/constants/AutocompleteLanguageInfo.js";
import { SlashCommand } from "../../../index.js";
import { renderChatMessage } from "../../../util/messageContent.js";
import { getContinueGlobalPath } from "../../../util/paths.js";
// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
function getOffsetDatetime(date: Date): Date {
const offset = date.getTimezoneOffset();
const offsetHours = Math.floor(offset / 60);
const offsetMinutes = offset % 60;
date.setHours(date.getHours() - offsetHours);
date.setMinutes(date.getMinutes() - offsetMinutes);
return date;
}
function asBasicISOString(date: Date): string {
const isoString = date.toISOString();
return isoString.replace(/[-:]|(\.\d+Z)/g, "");
}
function reformatCodeBlocks(msgText: string): string {
const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g;
msgText = msgText.replace(
codeBlockFenceRegex,
(match, metadata, filename, extension) => {
const lang = languageForFilepath(filename);
return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`;
},
);
// Appease the markdown linter
return msgText.replace(/```\n```/g, "```\n\n```");
}
import { shareSession } from "../../../util/historyUtils.js";
const ShareSlashCommand: SlashCommand = {
name: "share",
description: "Export the current chat session to markdown",
run: async function* ({ ide, history, params }) {
const now = new Date();
let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${now.toLocaleString()}`;
// As currently implemented, the /share command is by definition the last
// message in the chat history, this will omit it
for (const msg of history.slice(0, history.length - 1)) {
let msgText = msg.content;
msgText = renderChatMessage(msg);
if (msg.role === "user" && msgText.search("```") > -1) {
msgText = reformatCodeBlocks(msgText);
}
// format messages as blockquotes
msgText = msgText.replace(/^/gm, "> ");
content += `\n\n#### ${
msg.role === "user" ? "_User_" : "_Assistant_"
}\n\n${msgText}`;
}
let outputDir: string = params?.outputDir ?? getContinueGlobalPath();
if (outputDir.startsWith("~")) {
outputDir = outputDir.replace(/^~/, homedir);
} else if (
outputDir.startsWith("./") ||
outputDir.startsWith(".\\") ||
outputDir === "."
) {
const workspaceDirs = await ide.getWorkspaceDirs();
// Although the most common situation is to have one directory open in a
// workspace it's also possible to have just a file open without an
// associated directory or to use multi-root workspaces in which multiple
// folders are included. We default to using the first item in the list, if
// it exists.
const workspaceDirectory = workspaceDirs?.[0] || "";
outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory));
}
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
const dtString = asBasicISOString(getOffsetDatetime(now));
const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming?
const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^
await ide.writeFile(fileUrl, content);
await ide.openFile(fileUrl);
const fileUrl = await shareSession(ide, history, params?.outputDir);
const filePath = fileURLToPath(fileUrl);
// output path is the parent directory of the filePath
const outPath = path.dirname(filePath);
yield `The session transcript has been saved to a markdown file at \`${outPath}\`.`;
},
};

View file

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

View file

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

View file

@ -215,8 +215,8 @@ function applyRequestOptionsToModels(
// Prepare models
for (const model of models) {
model.requestOptions = {
...model.requestOptions,
...config.requestOptions,
...model.requestOptions,
};
if (roles !== undefined) {
model.roles = model.roles ?? roles;
@ -545,6 +545,7 @@ async function intermediateToFinalConfig({
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
const orgPolicy = PolicySingleton.getInstance().policy;
if (orgPolicy?.policy?.allowMcpServers === false) {
await mcpManager.shutdown();
@ -555,6 +556,7 @@ async function intermediateToFinalConfig({
id: `continue-mcp-server-${index + 1}`,
name: `MCP Server`,
...server,
requestOptions: config.requestOptions,
}),
),
false,

View file

@ -3,11 +3,13 @@ import {
markdownToRule,
} from "@continuedev/config-yaml";
import { IDE, RuleWithSource } from "../..";
import { findUriInDirs } from "../../util/uri";
import { findUriInDirs, joinPathsToUri } from "../../util/uri";
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
export const SUPPORTED_AGENT_FILES = ["AGENTS.md", "AGENT.md", "CLAUDE.md"];
/**
* Loads rules from markdown files in the .continue/rules directory
* and agent files (AGENTS.md, AGENT.md, CLAUDE.md) at workspace root
*/
export async function loadMarkdownRules(ide: IDE): Promise<{
rules: RuleWithSource[];
@ -16,6 +18,38 @@ export async function loadMarkdownRules(ide: IDE): Promise<{
const errors: ConfigValidationError[] = [];
const rules: RuleWithSource[] = [];
// First, try to load agent files from workspace root
const workspaceDirs = await ide.getWorkspaceDirs();
for (const workspaceDir of workspaceDirs) {
let agentFileFound = false;
for (const fileName of SUPPORTED_AGENT_FILES) {
try {
const agentFilePath = joinPathsToUri(workspaceDir, fileName);
const agentContent = await ide.readFile(agentFilePath);
const rule = markdownToRule(agentContent, {
uriType: "file",
fileUri: agentFilePath,
});
rules.push({
...rule,
source: "agent-file",
ruleFile: agentFilePath,
alwaysApply: true,
});
agentFileFound = true;
break; // Use the first found agent file in this workspace
} catch (e) {
// File doesn't exist or can't be read, continue to next file
}
}
if (agentFileFound) {
break; // Use agent file from first workspace that has one
}
}
try {
// Get all .md files from .continue/rules
const markdownFiles = await getAllDotContinueDefinitionFiles(

View file

@ -18,6 +18,7 @@ import {
Tool,
} from "../../";
import { stringifyMcpPrompt } from "../../commands/slash/mcpSlashCommand";
import { convertRuleBlockToSlashCommand } from "../../commands/slash/ruleBlockSlashCommand";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import ContinueProxyContextProvider from "../../context/providers/ContinueProxyContextProvider";
import MCPContextProvider from "../../context/providers/MCPContextProvider";
@ -155,6 +156,21 @@ export default async function doLoadConfig(options: {
errors.push(...rulesErrors);
newConfig.rules.unshift(...rules);
// Convert invokable rules to slash commands
for (const rule of newConfig.rules) {
if (rule.invokable) {
try {
const slashCommand = convertRuleBlockToSlashCommand(rule);
(newConfig.slashCommands ??= []).push(slashCommand);
} catch (e) {
errors.push({
message: `Error converting invokable rule ${rule.name} to slash command: ${e instanceof Error ? e.message : e}`,
fatal: false,
});
}
}
}
const proxyContextProvider = newConfig.contextProviders?.find(
(cp) => cp.description.title === "continue-proxy",
);
@ -187,7 +203,6 @@ export default async function doLoadConfig(options: {
const mcpManager = MCPManagerSingleton.getInstance();
const mcpServerStatuses = mcpManager.getStatuses();
// Slightly hacky just need connection's client to make slash command for now
const serializableStatuses = mcpServerStatuses.map((server) => {
const { client, ...rest } = server;
return rest;

View file

@ -280,11 +280,6 @@ declare global {
replacement: string;
}
export interface ContinueError {
title: string;
message: string;
}
export interface CompletionOptions extends BaseCompletionOptions {
model: string;
}
@ -692,6 +687,8 @@ declare global {
openUrl(url: string): Promise<void>;
getExternalUri?(uri: string): Promise<string>;
runCommand(command: string): Promise<void>;
saveFile(filepath: string): Promise<void>;
@ -1061,6 +1058,7 @@ declare global {
filepath?: string;
fileContent?: string;
originalFileContent?: string;
autoFormattingDiff?: string;
}
export interface RangeInFileWithContents {

View file

@ -4,6 +4,7 @@ import {
ConfigResult,
ConfigValidationError,
isAssistantUnrolledNonNullable,
mergeConfigYamlRequestOptions,
mergeUnrolledAssistants,
ModelRole,
PackageIdentifier,
@ -33,10 +34,7 @@ import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks";
import { LocalPlatformClient } from "./LocalPlatformClient";
import { llmsFromModelConfig } from "./models";
import {
convertYamlMcpToContinueMcp,
convertYamlRuleToContinueRule,
} from "./yamlToContinueConfig";
import { convertYamlRuleToContinueRule } from "./yamlToContinueConfig";
async function loadConfigYaml(options: {
overrideConfigYaml: AssistantUnrolled | undefined;
@ -154,16 +152,15 @@ async function loadConfigYaml(options: {
};
}
async function configYamlToContinueConfig(options: {
export async function configYamlToContinueConfig(options: {
config: AssistantUnrolled;
ide: IDE;
ideSettings: IdeSettings;
ideInfo: IdeInfo;
uniqueId: string;
llmLogger: ILLMLogger;
workOsAccessToken: string | undefined;
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
let { config, ide, ideSettings, ideInfo, uniqueId, llmLogger } = options;
let { config, ide, ideInfo, uniqueId, llmLogger } = options;
const localErrors: ConfigValidationError[] = [];
@ -191,6 +188,7 @@ async function configYamlToContinueConfig(options: {
summarize: null,
},
rules: [],
requestOptions: { ...config.requestOptions },
};
// Right now, if there are any missing packages in the config, then we will just throw an error
@ -208,10 +206,17 @@ async function configYamlToContinueConfig(options: {
}
for (const rule of config.rules ?? []) {
continueConfig.rules.push(convertYamlRuleToContinueRule(rule));
const convertedRule = convertYamlRuleToContinueRule(rule);
continueConfig.rules.push(convertedRule);
}
continueConfig.data = config.data;
continueConfig.data = config.data?.map((d) => ({
...d,
requestOptions: mergeConfigYamlRequestOptions(
d.requestOptions,
continueConfig.requestOptions,
),
}));
continueConfig.docs = config.docs?.map((doc) => ({
title: doc.name,
startUrl: doc.startUrl,
@ -235,12 +240,6 @@ async function configYamlToContinueConfig(options: {
});
});
continueConfig.experimental = {
modelContextProtocolServers: config.mcpServers?.map(
convertYamlMcpToContinueMcp,
),
};
// Prompt files -
try {
const promptFiles = await getAllPromptFiles(ide, undefined, true);
@ -292,9 +291,7 @@ async function configYamlToContinueConfig(options: {
try {
const llms = await llmsFromModelConfig({
model,
ide,
uniqueId,
ideSettings,
llmLogger,
config: continueConfig,
});
@ -379,6 +376,7 @@ async function configYamlToContinueConfig(options: {
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
const orgPolicy = PolicySingleton.getInstance().policy;
if (orgPolicy?.policy?.allowMcpServers === false) {
await mcpManager.shutdown();
@ -391,6 +389,10 @@ async function configYamlToContinueConfig(options: {
transport: {
type: "stdio",
args: [],
requestOptions: mergeConfigYamlRequestOptions(
server.requestOptions,
config.requestOptions,
),
...(server as any), // TODO: fix the types on mcpServers in config-yaml
},
timeout: server.connectionTimeout,
@ -449,7 +451,6 @@ export async function loadContinueConfigFromYaml(options: {
await configYamlToContinueConfig({
config: configYamlResult.config,
ide,
ideSettings,
ideInfo,
uniqueId,
llmLogger,

View file

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

View file

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

View file

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

View file

@ -52,6 +52,7 @@ class MCPConnection {
public status: MCPConnectionStatus = "not-connected";
public isProtectedResource = false;
public errors: string[] = [];
public infos: string[] = [];
public prompts: MCPPrompt[] = [];
public tools: MCPTool[] = [];
public resources: MCPResource[] = [];
@ -84,6 +85,7 @@ class MCPConnection {
}
async disconnect() {
this.status = "not-connected";
this.abortController.abort();
await this.client.close();
await this.transport.close();
@ -93,6 +95,7 @@ class MCPConnection {
return {
...this.options,
errors: this.errors,
infos: this.infos,
prompts: this.prompts,
resources: this.resources,
resourceTemplates: this.resourceTemplates,
@ -122,6 +125,7 @@ class MCPConnection {
this.resources = [];
this.resourceTemplates = [];
this.errors = [];
this.infos = [];
this.stdioOutput = { stdout: "", stderr: "" };
this.abortController.abort();
@ -280,6 +284,16 @@ class MCPConnection {
if (msg.includes("spawn") && msg.includes("enoent")) {
const command = msg.split(" ")[1];
errorMessage += `Error: command "${command}" not found. To use this MCP server, install the ${command} CLI.`;
if (["uv", "uvx"].includes(command)) {
this.infos.push(
'Please install uv by following the installation guide: <a href="https://docs.astral.sh/uv/getting-started/installation/">https://docs.astral.sh/uv/getting-started/installation/</a>',
);
}
if (["node", "npx"].includes(command)) {
this.infos.push(
'Please install npx by following the installation guide: <a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm">https://docs.npmjs.com/downloading-and-installing-node-js-and-npm</a>',
);
}
} else {
errorMessage += "Error: " + error.message;
}

View file

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

View file

@ -13,6 +13,7 @@ export class MCPManagerSingleton {
public onConnectionsRefreshed?: () => void;
public connections: Map<string, MCPConnection> = new Map();
private disconnectedServers: string[] = [];
private abortController: AbortController = new AbortController();
@ -25,6 +26,18 @@ export class MCPManagerSingleton {
return MCPManagerSingleton.instance;
}
addDisconnectedServer(serverId: string) {
this.disconnectedServers.push(serverId);
}
removeDisconnectedServer(serverId: string) {
this.disconnectedServers = this.disconnectedServers.filter(
(server) => server !== serverId,
);
}
getDisconnectedServers() {
return this.disconnectedServers;
}
createConnection(id: string, options: MCPOptions): MCPConnection {
if (this.connections.has(id)) {
return this.connections.get(id)!;
@ -163,9 +176,19 @@ export class MCPManagerSingleton {
}),
(async () => {
await Promise.all(
Array.from(this.connections.values()).map(async (connection) => {
await connection.connectClient(force, this.abortController.signal);
}),
Array.from(this.connections.values())
.filter(
(connection) =>
!this.disconnectedServers.some(
(s) => s === connection.options.id,
),
)
.map(async (connection) => {
await connection.connectClient(
force,
this.abortController.signal,
);
}),
);
if (this.onConnectionsRefreshed) {
this.onConnectionsRefreshed();

View file

@ -12,65 +12,121 @@ import { IDE, MCPServerStatus, SSEOptions } from "../..";
import http from "http";
import url from "url";
import crypto from "crypto";
import { GlobalContext, GlobalContextType } from "../../util/GlobalContext";
let authenticatingMCPContext = null as {
authenticatingServer: MCPServerStatus;
ide: IDE;
} | null;
// Use a Map to support concurrent authentications for different servers
const authenticatingContexts = new Map<
string,
{
authenticatingServer: MCPServerStatus;
ide: IDE;
state?: string;
}
>();
// Map state parameters to server URLs for OAuth callback matching
const stateToServerUrl = new Map<string, string>();
const PORT = 3000;
const server = http.createServer((req, res) => {
try {
if (!req.url) {
throw new Error("no url found");
}
let serverInstance: http.Server | null = null;
const parsedUrl = url.parse(req.url, true);
if (!parsedUrl.query["code"]) {
throw new Error("no query params found");
}
const createServerForOAuth = () =>
http.createServer((req, res) => {
try {
if (!req.url) {
throw new Error("no url found");
}
void handleMCPOauthCode(parsedUrl.query["code"] as string);
const parsedUrl = url.parse(req.url, true);
if (!parsedUrl.query["code"]) {
throw new Error("no query params found");
}
const html = `
const code = parsedUrl.query["code"] as string;
const state = parsedUrl.query["state"] as string | undefined;
void handleMCPOauthCode(code, state);
const html = `
<!DOCTYPE html>
<html>
<head><title>Authentication Complete</title></head>
<body>Authentication Complete. You can close this page now.</body>
</html>`;
res.writeHead(200, {
"Content-Type": "text/html",
});
res.end(html);
} catch (error) {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end(`Unexpected redirect error: ${(error as Error).message}`);
}
});
res.writeHead(200, {
"Content-Type": "text/html",
});
res.end(html);
} catch (error) {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end(`Unexpected redirect error: ${(error as Error).message}`);
}
});
type MCPOauthStorage = GlobalContextType["mcpOauthStorage"][string];
type MCPOauthStorageKey = keyof MCPOauthStorage;
class MCPConnectionOauthProvider implements OAuthClientProvider {
private globalContext: GlobalContext;
private _redirectUrl: string;
private _redirectUrlInitialized: Promise<void>;
constructor(
public oauthServerUrl: string,
private ide: IDE,
) {
this.globalContext = new GlobalContext();
// Set default redirect URL immediately for synchronous access
this._redirectUrl = `http://localhost:${PORT}`;
// Initialize actual redirect URL asynchronously
this._redirectUrlInitialized = this._initializeRedirectUrl();
}
private async _initializeRedirectUrl(): Promise<void> {
try {
// If IDE supports getExternalUri (VS Code extension), use it for dynamic redirect URI
if (this.ide.getExternalUri) {
const localUri = `http://localhost:${PORT}`;
const externalUri = await this.ide.getExternalUri(localUri);
this._redirectUrl = externalUri;
}
// Otherwise keep the default localhost URL
} catch (error) {
console.error("Failed to initialize redirect URL:", error);
// Keep default URL on error
}
}
get redirectUrl() {
return `http://localhost:${PORT}`; // TODO: this has to be a hub url or should we spin up a server?
// Always return a valid URL, even if initialization is pending
return this._redirectUrl;
}
getRedirectUrlWithState(state: string): string {
// Add state parameter to redirect URL
const urlObj = new URL(this._redirectUrl);
urlObj.searchParams.set("state", state);
return urlObj.toString();
}
async ensureRedirectUrl(): Promise<string> {
// Wait for initialization to complete before returning
await this._redirectUrlInitialized;
return this._redirectUrl;
}
get clientMetadata() {
// Generate state parameter if needed
const state = authenticatingContexts.get(this.oauthServerUrl)?.state;
const redirectUri = state
? this.getRedirectUrlWithState(state)
: this.redirectUrl;
return {
redirect_uris: [this.redirectUrl],
redirect_uris: [redirectUri],
token_endpoint_auth_method: "none",
grant_types: ["authorization_code", "refresh_token"],
response_types: ["code"],
@ -151,14 +207,28 @@ class MCPConnectionOauthProvider implements OAuthClientProvider {
}
async redirectToAuthorization(authorizationUrl: URL) {
if (!server.listening) {
server.listen(PORT, () => {
console.debug(
`Server started for MCP Oauth process at http://localhost:${PORT}/`,
);
});
// Ensure redirect URL is initialized before proceeding
await this.ensureRedirectUrl();
// Only create and start local server if using localhost redirect
// For web-based VS Code, the redirect will be handled by VS Code's built-in mechanism
if (!this.ide.getExternalUri || this._redirectUrl.includes("localhost")) {
if (!serverInstance) {
serverInstance = createServerForOAuth();
}
if (!serverInstance.listening) {
await new Promise<void>((resolve, reject) => {
serverInstance!.listen(PORT, () => {
console.debug(
`Server started for MCP Oauth process at http://localhost:${PORT}/`,
);
resolve();
});
serverInstance!.on("error", reject);
});
}
}
void this.ide.openUrl(authorizationUrl.toString());
await this.ide.openUrl(authorizationUrl.toString());
}
}
@ -175,49 +245,109 @@ export async function getOauthToken(mcpServerUrl: string, ide: IDE) {
export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) {
const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
authenticatingMCPContext = {
// Ensure redirect URL is ready before starting auth
await authProvider.ensureRedirectUrl();
// Generate a unique state parameter for this auth flow
const state = crypto.randomUUID();
// Store context for this specific server with state
authenticatingContexts.set(mcpServerUrl, {
authenticatingServer: mcpServer,
ide,
};
return await auth(authProvider, {
serverUrl: mcpServerUrl,
state,
});
// Map state to server URL for callback matching
stateToServerUrl.set(state, mcpServerUrl);
try {
return await auth(authProvider, {
serverUrl: mcpServerUrl,
});
} catch (error) {
// Clean up on error
authenticatingContexts.delete(mcpServerUrl);
stateToServerUrl.delete(state);
throw error;
}
}
/**
* handle the authentication code received from the oauth redirect
*/
async function handleMCPOauthCode(authorizationCode: string) {
if (!authenticatingMCPContext) {
return;
}
const { ide, authenticatingServer } = authenticatingMCPContext;
const serverUrl = (authenticatingServer.transport as SSEOptions).url;
async function handleMCPOauthCode(authorizationCode: string, state?: string) {
let serverUrl: string | undefined;
let context:
| { authenticatingServer: MCPServerStatus; ide: IDE; state?: string }
| undefined;
if (!serverUrl) {
void ide.showToast("error", "No MCP server url found for authentication");
if (state) {
// Use state parameter to find the correct server
serverUrl = stateToServerUrl.get(state);
if (serverUrl) {
context = authenticatingContexts.get(serverUrl);
}
} else {
// Fallback: if no state or single context, use the first one
const contexts = Array.from(authenticatingContexts.entries());
if (contexts.length === 1) {
[serverUrl, context] = contexts[0];
}
}
if (!context || !serverUrl) {
console.error("No matching authenticating context found for state:", state);
return;
}
if (!authorizationCode) {
void ide.showToast(
"error",
`No MCP authorization code found for ${serverUrl}`,
);
return;
const { ide, authenticatingServer } = context;
try {
if (!serverUrl) {
throw new Error("No MCP server url found for authentication");
}
if (!authorizationCode) {
throw new Error(`No MCP authorization code found for ${serverUrl}`);
}
// Close the server before processing auth
if (serverInstance) {
await new Promise<void>((resolve) => {
serverInstance!.close(() => {
console.debug("Server for MCP Oauth process was closed");
serverInstance = null;
resolve();
});
});
}
const authProvider = new MCPConnectionOauthProvider(serverUrl, ide);
await authProvider.ensureRedirectUrl();
const authStatus = await auth(authProvider, {
serverUrl,
authorizationCode,
});
if (authStatus === "AUTHORIZED") {
const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports
await MCPManagerSingleton.getInstance().refreshConnection(
authenticatingServer.id,
);
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error("OAuth authorization failed:", errorMessage);
if (context?.ide) {
await context.ide.showToast("error", `OAuth failed: ${errorMessage}`);
}
} finally {
// Always clean up the context and state mapping
authenticatingContexts.delete(serverUrl);
if (state) {
stateToServerUrl.delete(state);
}
}
server.close(() => console.debug("Server for MCP Oauth process was closed"));
const authProvider = new MCPConnectionOauthProvider(serverUrl, ide);
const authStatus = await auth(authProvider, {
serverUrl,
authorizationCode,
});
if (authStatus === "AUTHORIZED") {
const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports
await MCPManagerSingleton.getInstance().refreshConnection(
authenticatingServer.id,
);
}
authenticatingMCPContext = null;
}
export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) {

View file

@ -33,6 +33,7 @@ describe("MCPOauth", () => {
mockIde = {
openUrl: vi.fn(),
showToast: vi.fn(),
getExternalUri: vi.fn((uri) => Promise.resolve(uri)),
};
mockMcpServer = {
@ -178,4 +179,155 @@ describe("MCPOauth", () => {
});
});
});
describe("redirect URL handling", () => {
test("should use getExternalUri when available for VS Code", async () => {
const vscodeIde = {
...mockIde,
getExternalUri: vi.fn((uri) =>
Promise.resolve("https://vscode.dev/redirect"),
),
};
const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
const mockAuth = vi.mocked(auth);
mockAuth.mockResolvedValue("AUTHORIZED");
await performAuth(mockMcpServer, vscodeIde);
expect(vscodeIde.getExternalUri).toHaveBeenCalledWith(
"http://localhost:3000",
);
});
test("should fallback to localhost when getExternalUri is not available", async () => {
const ideWithoutExternalUri = {
openUrl: vi.fn(() => Promise.resolve()),
showToast: vi.fn(() => Promise.resolve()),
};
const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
const mockAuth = vi.mocked(auth);
mockAuth.mockResolvedValue("AUTHORIZED");
await performAuth(mockMcpServer, ideWithoutExternalUri as any);
// Should still work without getExternalUri
expect(mockAuth).toHaveBeenCalled();
});
test("should handle getExternalUri errors gracefully", async () => {
const errorIde = {
...mockIde,
getExternalUri: vi.fn(() => Promise.reject(new Error("Network error"))),
};
const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
const mockAuth = vi.mocked(auth);
mockAuth.mockResolvedValue("AUTHORIZED");
// Should not throw, should fallback to localhost
await performAuth(mockMcpServer, errorIde);
expect(mockAuth).toHaveBeenCalled();
});
});
describe("concurrent authentication", () => {
test("should handle multiple concurrent auth flows", async () => {
const server1 = {
id: "server-1",
transport: { type: "sse" as const, url: "https://server1.com" },
status: "connected" as const,
errors: [],
infos: [],
isProtectedResource: false,
prompts: [],
tools: [],
resources: [],
resourceTemplates: [],
name: "server-1",
};
const server2 = {
id: "server-2",
transport: { type: "sse" as const, url: "https://server2.com" },
status: "connected" as const,
errors: [],
infos: [],
isProtectedResource: false,
prompts: [],
tools: [],
resources: [],
resourceTemplates: [],
name: "server-2",
};
const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
const mockAuth = vi.mocked(auth);
mockAuth.mockResolvedValue("AUTHORIZED");
// Start two auth flows concurrently
const [result1, result2] = await Promise.all([
performAuth(server1, mockIde),
performAuth(server2, mockIde),
]);
expect(result1).toBe("AUTHORIZED");
expect(result2).toBe("AUTHORIZED");
expect(mockAuth).toHaveBeenCalledTimes(2);
});
});
describe("error handling", () => {
test("should clean up context on auth failure", async () => {
const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
const mockAuth = vi.mocked(auth);
// First successful call to set up the context
mockAuth.mockResolvedValueOnce("AUTHORIZED");
await performAuth(mockMcpServer, mockIde);
// Reset mock for the failure test
mockAuth.mockRejectedValueOnce(new Error("Auth failed"));
// Second call that should fail and clean up
await expect(performAuth(mockMcpServer, mockIde)).rejects.toThrow(
"Auth failed",
);
// Verify auth was called twice
expect(mockAuth).toHaveBeenCalledTimes(2);
// The context cleanup happens internally in performAuth's catch block
// We can verify it indirectly by checking that a subsequent auth call works
mockAuth.mockResolvedValueOnce("AUTHORIZED");
const result = await performAuth(mockMcpServer, mockIde);
expect(result).toBe("AUTHORIZED");
});
test("should handle missing server URL", async () => {
const invalidServer = {
id: "invalid",
transport: { type: "sse" as const, url: "" },
status: "connected" as const,
errors: [],
infos: [],
isProtectedResource: false,
prompts: [],
tools: [],
resources: [],
resourceTemplates: [],
name: "invalid",
};
const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
const mockAuth = vi.mocked(auth);
mockAuth.mockResolvedValue("AUTHORIZED");
await performAuth(invalidServer, mockIde);
// Should still attempt auth with empty URL
expect(mockAuth).toHaveBeenCalled();
});
});
});

View file

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

View file

@ -17,6 +17,7 @@ import { DataLogger } from "./data/log";
import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { countTokens } from "./llm/countTokens";
import Lemonade from "./llm/llms/Lemonade";
import Ollama from "./llm/llms/Ollama";
import { EditAggregator } from "./nextEdit/context/aggregateEdits";
import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
@ -29,8 +30,9 @@ import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
import { Telemetry } from "./util/posthog";
import {
isProcessBackgrounded,
killTerminalProcess,
markProcessAsBackgrounded,
} from "./util/processTerminalBackgroundStates";
} from "./util/processTerminalStates";
import { getSymbolsForManyFiles } from "./util/treeSitter";
import { TTS } from "./util/tts";
@ -76,6 +78,7 @@ import { NextEditProvider } from "./nextEdit/NextEditProvider";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import { OnboardingModes } from "./protocol/core";
import type { IMessenger, Message } from "./protocol/messenger";
import { shareSession } from "./util/historyUtils";
import { Logger } from "./util/Logger.js";
import { getUriPathBasename } from "./util/uri";
@ -230,6 +233,17 @@ export class Core {
return;
}
// Check for disableIndexing to prevent race condition
const { config } = await this.configHandler.loadConfig();
if (!config || config.disableIndexing) {
void this.messenger.request("indexProgress", {
progress: 0,
desc: "Indexing is disabled",
status: "disabled",
});
return;
}
void this.codeBaseIndexer.refreshCodebaseIndex(dirs);
});
});
@ -312,8 +326,27 @@ export class Core {
});
// History
on("history/list", (msg) => {
return historyManager.list(msg.data);
on("history/list", async (msg) => {
const localSessions = historyManager.list(msg.data);
// Check if remote sessions should be enabled based on feature flags
const shouldFetchRemote =
await this.configHandler.controlPlaneClient.shouldEnableRemoteSessions();
// Get remote sessions from control plane if feature is enabled
const remoteSessions = shouldFetchRemote
? await this.configHandler.controlPlaneClient.listRemoteSessions()
: [];
// Combine and sort by date (most recent first)
const allSessions = [...localSessions, ...remoteSessions].sort(
(a, b) =>
new Date(b.dateCreated).getTime() - new Date(a.dateCreated).getTime(),
);
// Apply limit if specified
const limit = msg.data?.limit ?? 100;
return allSessions.slice(0, limit);
});
on("history/delete", (msg) => {
@ -324,10 +357,23 @@ export class Core {
return historyManager.load(msg.data.id);
});
on("history/loadRemote", async (msg) => {
return this.configHandler.controlPlaneClient.loadRemoteSession(
msg.data.remoteId,
);
});
on("history/save", (msg) => {
historyManager.save(msg.data);
});
on("history/share", async (msg) => {
const session = historyManager.load(msg.data.id);
const outputDir = msg.data.outputDir;
const history = session.history.map((msg) => msg.message);
await shareSession(this.ide, history, outputDir);
});
on("history/clear", (msg) => {
historyManager.clearAll();
});
@ -446,6 +492,20 @@ export class Core {
on("mcp/reloadServer", async (msg) => {
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
MCPManagerSingleton.getInstance().removeDisconnectedServer(msg.data.id);
});
on("mcp/disconnectServer", async (msg) => {
const mcpConnection = MCPManagerSingleton.getInstance().getConnection(
msg.data.id,
);
if (!mcpConnection)
throw new Error(`MCP connection with id ${msg.data.id} not found`);
MCPManagerSingleton.getInstance().addDisconnectedServer(msg.data.id);
await mcpConnection.disconnect();
await this.configHandler.refreshAll("MCP Servers disconnected");
});
on("mcp/getDisconnectedServers", async (_msg) => {
return MCPManagerSingleton.getInstance().getDisconnectedServers();
});
on("mcp/getPrompt", async (msg) => {
const { serverName, promptName, args } = msg.data;
@ -727,20 +787,13 @@ export class Core {
data.fileUri ?? "current-file-stream",
); // not super important since currently cancelling apply will cancel all streams it's one file at a time
return streamDiffLines({
highlighted: data.highlighted,
prefix: data.prefix,
suffix: data.suffix,
return streamDiffLines(
data,
llm,
// rules included for edit, NOT apply
rulesToInclude: data.includeRulesInSystemMessage
? config.rules
: undefined,
input: data.input,
language: data.language,
overridePrompt: undefined,
abortController,
});
undefined,
data.includeRulesInSystemMessage ? config.rules : undefined,
);
});
on("cancelApply", async (msg) => {
@ -1061,6 +1114,10 @@ export class Core {
},
);
on("process/killTerminalProcess", async ({ data: { toolCallId } }) => {
await killTerminalProcess(toolCallId);
});
on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
const isValid = setMdmLicenseKey(licenseKey);
return isValid;
@ -1195,6 +1252,9 @@ export class Core {
if (
uri.endsWith(".continuerc.json") ||
uri.endsWith(".prompt") ||
uri.endsWith("AGENTS.md") ||
uri.endsWith("AGENT.md") ||
uri.endsWith("CLAUDE.md") ||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
(uri.includes(".continue") &&
(uri.endsWith(".yaml") || uri.endsWith("yml"))) ||
@ -1257,6 +1317,9 @@ export class Core {
if (msg.data.title === "Ollama") {
const models = await new Ollama({ model: "" }).listModels();
return models;
} else if (msg.data.title === "Lemonade") {
const models = await new Lemonade({ model: "" }).listModels();
return models;
} else {
return undefined;
}
@ -1342,6 +1405,8 @@ export class Core {
selectedCode,
reranker: config.selectedModelByRole.rerank,
fetch: (url, init) =>
// Important note: context providers fetch uses global request options not LLM request options
// Because LLM calls are handled separately
fetchwithRequestOptions(url, init, config.requestOptions),
isInAgentMode: msg.data.isInAgentMode,
});

View file

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

View file

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

View file

@ -0,0 +1,252 @@
import { describe, expect, it } from "vitest";
import { ContinueErrorReason } from "../../util/errors";
import { executeFindAndReplace } from "./performReplace";
describe("executeFindAndReplace", () => {
describe("normal cases", () => {
it("should replace single occurrence by default", () => {
const content = "Hello world\nThis is a test file\nGoodbye";
const result = executeFindAndReplace(content, "Hello", "Hi", false);
expect(result).toBe("Hi world\nThis is a test file\nGoodbye");
});
it("should replace single occurrence when replaceAll is false", () => {
const content = "Hello world\nHello again";
const result = executeFindAndReplace(
content,
"Hello world",
"Hi world",
false,
);
expect(result).toBe("Hi world\nHello again");
});
it("should replace all occurrences when replaceAll is true", () => {
const content = "Hello world\nHello again\nHello there";
const result = executeFindAndReplace(content, "Hello", "Hi", true);
expect(result).toBe("Hi world\nHi again\nHi there");
});
it("should handle empty new string (deletion)", () => {
const content = "Hello world";
const result = executeFindAndReplace(content, "Hello ", "", false);
expect(result).toBe("world");
});
it("should handle empty old string replacement (insertion at start)", () => {
const content = "";
const result = executeFindAndReplace(content, "", "Hello world", false);
expect(result).toBe("Hello world");
});
it("should preserve whitespace and indentation", () => {
const content =
"function test() {\n const value = 'old';\n return value;\n}";
const result = executeFindAndReplace(
content,
" const value = 'old';",
" const value = 'new';",
false,
);
expect(result).toBe(
"function test() {\n const value = 'new';\n return value;\n}",
);
});
it("should handle multiline strings", () => {
const content = "line1\nline2\nline3";
const result = executeFindAndReplace(
content,
"line1\nline2",
"newline1\nnewline2",
false,
);
expect(result).toBe("newline1\nnewline2\nline3");
});
});
describe("special character handling", () => {
it("should handle regex special characters in old string", () => {
const content = "const regex = /[a-z]+/g;";
const result = executeFindAndReplace(
content,
"/[a-z]+/g",
"/[A-Z]+/g",
false,
);
expect(result).toBe("const regex = /[A-Z]+/g;");
});
it("should handle dollar signs in strings", () => {
const content = 'const text = "Hello $world"';
const result = executeFindAndReplace(
content,
'"Hello $world"',
'"Hi $universe"',
false,
);
expect(result).toBe('const text = "Hi $universe"');
});
it("should handle backslashes", () => {
const content = 'const path = "C:\\Users\\test"';
const result = executeFindAndReplace(
content,
"C:\\Users\\test",
"D:\\Users\\test",
false,
);
expect(result).toBe('const path = "D:\\Users\\test"');
});
it("should handle parentheses", () => {
const content = "function test() { return 'old'; }";
const result = executeFindAndReplace(
content,
"() { return 'old'; }",
"() { return 'new'; }",
false,
);
expect(result).toBe("function test() { return 'new'; }");
});
it("should handle square brackets", () => {
const content = "const arr = [1, 2, 3];";
const result = executeFindAndReplace(
content,
"[1, 2, 3]",
"[4, 5, 6]",
false,
);
expect(result).toBe("const arr = [4, 5, 6];");
});
});
describe("replaceAll behavior", () => {
it("should replace all occurrences including partial matches", () => {
const content = "test testing tested test";
const result = executeFindAndReplace(content, "test", "exam", true);
expect(result).toBe("exam examing examed exam");
});
it("should replace all occurrences with empty string", () => {
const content = "remove this remove that remove everything";
const result = executeFindAndReplace(content, "remove ", "", true);
expect(result).toBe("this that everything");
});
it("should handle overlapping patterns correctly", () => {
const content = "aaaa";
const result = executeFindAndReplace(content, "aa", "b", true);
expect(result).toBe("bb");
});
});
describe("error cases", () => {
it("should throw error when string not found", () => {
const content = "Hello world";
expect(() => {
executeFindAndReplace(content, "xyz", "abc", false);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceOldStringNotFound,
}),
);
});
it("should throw error with edit context when string not found", () => {
const content = "Hello world";
expect(() => {
executeFindAndReplace(content, "xyz", "abc", false, 2);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceOldStringNotFound,
}),
);
});
it("should throw error when multiple occurrences exist and replaceAll is false", () => {
const content = "Hello world\nHello again\nHello there";
expect(() => {
executeFindAndReplace(content, "Hello", "Hi", false);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences,
}),
);
});
it("should throw error with edit context for multiple occurrences", () => {
const content = "test test test";
expect(() => {
executeFindAndReplace(content, "test", "exam", false, 1);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences,
}),
);
});
});
describe("edge cases", () => {
it("should handle single character replacement", () => {
const content = "a b c";
const result = executeFindAndReplace(content, "b", "x", false);
expect(result).toBe("a x c");
});
it("should handle very long strings", () => {
const longString = "a".repeat(10000);
const content = `start${longString}end`;
const result = executeFindAndReplace(content, longString, "short", false);
expect(result).toBe("startshortend");
});
it("should handle strings at beginning of content", () => {
const content = "start middle end";
const result = executeFindAndReplace(content, "start", "begin", false);
expect(result).toBe("begin middle end");
});
it("should handle strings at end of content", () => {
const content = "start middle end";
const result = executeFindAndReplace(content, "end", "finish", false);
expect(result).toBe("start middle finish");
});
it("should handle entire content replacement", () => {
const content = "replace everything";
const result = executeFindAndReplace(
content,
"replace everything",
"new content",
false,
);
expect(result).toBe("new content");
});
});
});

View file

@ -0,0 +1,53 @@
import { ContinueError, ContinueErrorReason } from "../../util/errors";
export const FOUND_MULTIPLE_FIND_STRINGS_ERROR =
"Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.";
/**
* Validates a single edit operation
*/
export function validateSingleEdit(
oldString: string,
newString: string,
index?: number,
): void {
const context = index !== undefined ? `edit at index ${index}: ` : "";
if (!oldString && oldString !== "") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingOldString,
`${context}old_string is required`,
);
}
if (newString === undefined) {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingNewString,
`${context}new_string is required`,
);
}
if (oldString === newString) {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
`${context}old_string and new_string must be different`,
);
}
}
export function trimEmptyLines({
lines,
fromEnd,
}: {
lines: string[];
fromEnd: boolean;
}): string[] {
lines = fromEnd ? lines.slice().reverse() : lines.slice();
const newLines: string[] = [];
let shouldContinueRemoving = true;
for (let index = 0; index < lines.length; index++) {
const line = lines[index];
if (shouldContinueRemoving && line.trim() === "") continue;
shouldContinueRemoving = false;
newLines.push(line);
}
return fromEnd ? newLines.reverse() : newLines;
}

View file

@ -0,0 +1,151 @@
import { describe, expect, it } from "vitest";
import { ContinueErrorReason } from "../../util/errors";
import { trimEmptyLines, validateSingleEdit } from "./findAndReplaceUtils";
describe("validateSingleEdit", () => {
describe("valid inputs", () => {
it("should not throw for valid non-empty strings", () => {
expect(() => {
validateSingleEdit("old", "new");
}).not.toThrow();
});
it("should allow empty old_string for file creation", () => {
expect(() => {
validateSingleEdit("", "new content");
}).not.toThrow();
});
it("should allow empty new_string for deletion", () => {
expect(() => {
validateSingleEdit("delete me", "");
}).not.toThrow();
});
it("should allow multiline strings", () => {
expect(() => {
validateSingleEdit("line1\nline2", "newline1\nnewline2");
}).not.toThrow();
});
it("should allow special characters", () => {
expect(() => {
validateSingleEdit("/[a-z]+/g", "/[A-Z]+/g");
}).not.toThrow();
});
});
describe("invalid inputs", () => {
it("should throw error when old_string is null", () => {
expect(() => {
validateSingleEdit(null as any, "new");
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingOldString,
}),
);
});
it("should throw error when old_string is undefined", () => {
expect(() => {
validateSingleEdit(undefined as any, "new");
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingOldString,
}),
);
});
it("should throw error when new_string is undefined", () => {
expect(() => {
validateSingleEdit("old", undefined as any);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingNewString,
}),
);
});
it("should throw error when old_string and new_string are identical", () => {
expect(() => {
validateSingleEdit("same", "same");
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
}),
);
});
it("should throw error when both are empty strings", () => {
expect(() => {
validateSingleEdit("", "");
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
}),
);
});
});
describe("error messages with context", () => {
it("should include edit number in error messages when index provided", () => {
expect(() => {
validateSingleEdit(null as any, "new", 2);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingOldString,
}),
);
});
it("should include edit number for new_string errors", () => {
expect(() => {
validateSingleEdit("old", undefined as any, 0);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingNewString,
}),
);
});
it("should include edit number for identical strings error", () => {
expect(() => {
validateSingleEdit("same", "same", 4);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
}),
);
});
it("should not include context when index not provided", () => {
expect(() => {
validateSingleEdit("same", "same");
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
}),
);
});
});
});
describe("trimEmptyLines", () => {
it("trims leading empty lines from start", () => {
const input = ["", "", "a", "", "b"];
const result = trimEmptyLines({ lines: input, fromEnd: false });
expect(result).toEqual(["a", "", "b"]);
});
it("trims trailing empty lines from end", () => {
const input = ["a", "", "b", "", ""];
const result = trimEmptyLines({ lines: input, fromEnd: true });
expect(result).toEqual(["a", "", "b"]);
});
it("returns empty array when all lines are empty", () => {
const input = ["", "", ""];
const result = trimEmptyLines({ lines: input, fromEnd: false });
expect(result).toEqual([]);
});
});

View file

@ -4,7 +4,7 @@
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 */
/** The ending character index of the match in the file content (NOT inclusive - e.g. like slice)*/
endIndex: number;
}
@ -81,32 +81,38 @@ function whitespaceIgnoredMatch(
}
// Map the stripped position back to the original file content
let originalStartIndex = 0;
let originalStartIndex = -1;
let strippedCharCount = 0;
// Find the original position by counting non-whitespace characters
// Find the original start 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])) {
if (strippedCharCount === strippedIndex) {
originalStartIndex = i;
break;
}
strippedCharCount++;
}
}
// Find the end position by counting the length of the search content
let originalEndIndex = originalStartIndex;
let matchedChars = 0;
if (originalStartIndex === -1) {
return null; // Should not happen if strippedIndex was valid
}
for (
let i = originalStartIndex;
i < fileContent.length && matchedChars < strippedSearchContent.length;
i++
) {
// Find the end position by counting through all characters (including whitespace)
// that correspond to the stripped search content length
let originalEndIndex = originalStartIndex;
let matchedNonWhitespaceChars = 0;
for (let i = originalStartIndex; i < fileContent.length; i++) {
if (!/\s/.test(fileContent[i])) {
matchedChars++;
matchedNonWhitespaceChars++;
if (matchedNonWhitespaceChars === strippedSearchContent.length) {
originalEndIndex = i + 1;
break;
}
}
// Always update end index to include current position (whether whitespace or not)
originalEndIndex = i + 1;
}
@ -118,6 +124,7 @@ function whitespaceIgnoredMatch(
/**
* Calculate the Jaro similarity between two strings
* TODO Restore this functionality - current implementation has some kind of bug where it only returns one line for the match
*/
function jaroSimilarity(s1: string, s2: string): number {
if (s1 === s2) return 1.0;
@ -278,7 +285,7 @@ const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [
{ strategy: exactMatch, name: "exactMatch" },
{ strategy: trimmedMatch, name: "trimmedMatch" },
{ strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" },
{ strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" },
// { strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" },
];
/**
@ -315,3 +322,58 @@ export function findSearchMatch(
return null;
}
/**
* Find all matches for search content in file content.
* Uses the same matching strategies as findSearchMatch, applied iteratively.
*
* @param fileContent - The complete content of the file to search in
* @param searchContent - The content to search for
* @returns Array of match results with character positions, empty array if no matches found
*/
export function findSearchMatches(
fileContent: string,
searchContent: string,
): SearchMatchResult[] {
const matches: SearchMatchResult[] = [];
// Special case: empty search string always matches at position 0
if (searchContent.trim() === "") {
return [{ startIndex: 0, endIndex: 0, strategyName: "emptySearch" }];
}
let remainingContent = fileContent;
let currentOffset = 0;
while (remainingContent.length > 0) {
const match = findSearchMatch(remainingContent, searchContent);
if (match === null) {
break;
}
// Adjust match positions to account for the current offset
const adjustedMatch: SearchMatchResult = {
startIndex: match.startIndex + currentOffset,
endIndex: match.endIndex + currentOffset,
strategyName: match.strategyName,
};
// Prevent infinite loops by ensuring we're making progress
// If the new match starts at or before the last match's start position, break
if (
matches.length > 0 &&
adjustedMatch.startIndex <= matches[matches.length - 1].startIndex
) {
break;
}
matches.push(adjustedMatch);
// Update offset and truncate content after the current match
currentOffset = adjustedMatch.endIndex;
remainingContent = fileContent.slice(currentOffset);
}
return matches;
}

View file

@ -0,0 +1,571 @@
import { describe, expect, it } from "vitest";
import { findSearchMatch } from "./findSearchMatch";
describe("findSearchMatch", () => {
describe("Empty search content", () => {
it("should return position 0 for empty string", () => {
const result = findSearchMatch("some file content", "");
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should return position 0 for whitespace-only string", () => {
const result = findSearchMatch("some file content", " \n\t ");
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should handle empty file content with empty search", () => {
const result = findSearchMatch("", "");
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
});
describe("Exact match strategy", () => {
it("should find exact match at beginning of file", () => {
const fileContent = "hello world";
const searchContent = "hello";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 5,
strategyName: "exactMatch",
});
});
it("should find exact match in middle of file", () => {
const fileContent = "hello world test";
const searchContent = "world";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 6,
endIndex: 11,
strategyName: "exactMatch",
});
});
it("should find exact match at end of file", () => {
const fileContent = "hello world";
const searchContent = "world";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 6,
endIndex: 11,
strategyName: "exactMatch",
});
});
it("should find multi-line exact match", () => {
const fileContent = "line1\nline2\nline3";
const searchContent = "line2\nline3";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 6,
endIndex: 17,
strategyName: "exactMatch",
});
});
it("should handle exact match with special characters", () => {
const fileContent = 'function test() { return "hello"; }';
const searchContent = '{ return "hello"; }';
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 16,
endIndex: 35,
strategyName: "exactMatch",
});
});
it("should find first occurrence when multiple matches exist", () => {
const fileContent = "test test test";
const searchContent = "test";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 4,
strategyName: "exactMatch",
});
});
it("should handle case-sensitive matching", () => {
const fileContent = "Hello World";
const searchContent = "hello";
const result = findSearchMatch(fileContent, searchContent);
// Should not match due to case sensitivity, will fall through to other strategies
expect(result).toBeNull();
});
});
describe("Trimmed match strategy fallback", () => {
it("should find match when search content has leading/trailing whitespace", () => {
const fileContent = "hello world";
const searchContent = " hello ";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 5,
strategyName: "trimmedMatch",
});
});
it("should find match when search content has tabs and newlines", () => {
const fileContent = "function test() {}";
const searchContent = "\t\nfunction test()\n\t";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 15,
strategyName: "trimmedMatch",
});
});
it("should handle complex whitespace trimming", () => {
const fileContent = "const x = 5;";
const searchContent = " \n\t const x = 5; \t\n ";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 12,
strategyName: "trimmedMatch",
});
});
});
describe("Whitespace ignored strategy fallback", () => {
it("should match content with different whitespace formatting", () => {
const fileContent = "function test() {\n return true;\n}";
const searchContent = "function test(){return true;}";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 34,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should handle mixed whitespace differences", () => {
const fileContent = "if (condition) {\n doSomething();\n}";
const searchContent = "if(condition){doSomething();}";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 37,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should match with tabs vs spaces differences", () => {
const fileContent = "function test() {\n\treturn 42;\n}";
const searchContent = "function test() {\n return 42;\n}";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 31,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should handle partial matches within larger content", () => {
const fileContent = "before\nfunction test() {\n return true;\n}\nafter";
const searchContent = "function test(){return true;}";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 7,
endIndex: 41,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should recognize empty search", () => {
const fileContent = "some content";
const searchContent = " \t\n ";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should handle complex nested structures with whitespace differences", () => {
const fileContent = `{
"key": "value",
"nested": {
"prop": 123
}
}`;
const searchContent = '{"key":"value","nested":{"prop":123}}';
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 55,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should match content in middle of file with complex indentation", () => {
const fileContent = `import React from 'react';
function MyComponent() {
const handleClick = () => {
console.log('clicked');
};
return <button onClick={handleClick}>Click me</button>;
}
export default MyComponent;`;
const searchContent = `const handleClick=()=>{console.log('clicked');};`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 55,
endIndex: 115,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should handle matches with mixed line endings and special characters", () => {
const fileContent = `<!DOCTYPE html>\r\n<html>\r\n <body>\r\n <div id="app">\r\n <p>Hello & goodbye</p>\r\n </div>\r\n </body>\r\n</html>`;
const searchContent = `<divid="app"><p>Hello&goodbye</p></div>`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 39,
endIndex: 95,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should match content surrounded by different types of whitespace", () => {
const fileContent = `\tconst data = {\n\t\tname: "John",\n\t\tage: 30,\n\t\taddress: {\n\t\t\tstreet: "Main St",\n\t\t\tcity: "NYC"\n\t\t}\n\t};`;
const searchContent = `address:{street:"MainSt",city:"NYC"}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 45,
endIndex: 96,
strategyName: "whitespaceIgnoredMatch",
});
});
// IMPORTANT string.length and string.slice both count UTF-16 units so emojis will count as 2 in both
it("should handle unicode characters with whitespace differences", () => {
const fileContent = `const message = {\n greeting: "Hello 👋",\n emoji: "🚀",\n unicode: "café",\n symbol: "∑"\n};`;
const searchContent = `emoji:"🚀",unicode:"café",symbol:"∑"`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 44,
endIndex: 89,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should match across multiple nested blocks with varying indentation", () => {
const fileContent = `class Calculator {\n add(a, b) {\n if (typeof a === 'number' && typeof b === 'number') {\n return a + b;\n }\n throw new Error('Invalid input');\n }\n\n multiply(x, y) {\n return x * y;\n }\n}`;
const searchContent = `if(typeofa==='number'&&typeofb==='number'){returna+b;}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 43,
endIndex: 132,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should handle regex-like patterns with escaped characters", () => {
const fileContent = `const pattern = /\\d+\\.\\d+/g;\nconst test = \"123.456\";\nif (pattern.test(test)) {\n console.log(\"Match found\");\n}`;
const searchContent = `consttest="123.456";if(pattern.test(test)){console.log("Matchfound");}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 29,
endIndex: 110,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should match SQL-like content with varying whitespace", () => {
const fileContent = `SELECT users.name,\n users.email,\n profiles.bio\nFROM users\nINNER JOIN profiles ON users.id = profiles.user_id\nWHERE users.active = true\nORDER BY users.name;`;
const searchContent = `SELECTusers.name,users.email,profiles.bioFROMusersINNERJOINprofiles`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 89,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should handle content with form feeds, vertical tabs, and other rare whitespace", () => {
const fileContent = `function\fprocess\vdata(input)\u0020{\u00A0\n\treturn\u2000input.trim();\u2009\n}`;
const searchContent = `functionprocessdata(input){returninput.trim();}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 56,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should match content with Windows-style CRLF line endings", () => {
const fileContent = `@echo off\r\nset PATH=%PATH%;C:\\tools\r\nif \"%1\"==\"\" (\r\n echo Usage: script.bat filename\r\n exit /b 1\r\n)\r\necho Processing %1...\r\necho Done.`;
const searchContent = `if\"%1\"==\"\"(echo Usage: script.bat filename exit/b 1)`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 37,
endIndex: 105,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should handle deeply nested JSON with mixed formatting", () => {
const fileContent = `{\n \"config\": {\n \"database\": {\n \"host\": \"localhost\",\n \"port\": 5432,\n \"credentials\": {\n \"username\": \"admin\",\n \"password\": \"secret\"\n },\n \"options\": {\n \"ssl\": true,\n \"timeout\": 30000\n }\n }\n }\n}`;
const searchContent = `\"credentials\":{\"username\":\"admin\",\"password\":\"secret\"},\"options\":{\"ssl\":true,\"timeout\":30000}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 87,
endIndex: 243,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should match XML content with attribute spacing differences", () => {
const fileContent = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n <item id = \"1\" type= \"primary\" >\n <name>Test Item</name>\n <value unit=\"px\" >100</value>\n </item>\n</root>`;
const searchContent = `<itemid=\"1\"type=\"primary\"><name>TestItem</name><valueunit=\"px\">100</value></item>`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 48,
endIndex: 155,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should handle mathematical expressions with varying spacing", () => {
const fileContent = `const result = (a + b) * c - d / e;\nconst complex = Math.sqrt( x ** 2 + y ** 2 );\nconst formula = ( ( a + b ) * ( c - d ) ) / ( e + f );`;
const searchContent = `constcomplex=Math.sqrt(x**2+y**2);constformula=((a+b)*(c-d))/(e+f);`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 36,
endIndex: 142,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should match across comments and code with whitespace variations", () => {
const fileContent = `/* Multi-line comment\n with varying indentation */\nfunction processData(input) {\n // Single line comment\n const cleaned = input.trim();\n /* Another comment */\n return cleaned.toLowerCase();\n}`;
const searchContent = `/*Multi-linecommentwithvaryingindentation*/functionprocessData(input){//Singlelinecommentconstcleaned=input.trim();/*Anothercomment*/returncleaned.toLowerCase();}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 205,
strategyName: "whitespaceIgnoredMatch",
});
});
});
describe("No match scenarios", () => {
it("should return null when no strategy finds a match", () => {
const fileContent = "hello world";
const searchContent = "goodbye";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should return null for completely different content", () => {
const fileContent = "function test() { return true; }";
const searchContent = "class MyClass { }";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should return null when search content is longer than file content", () => {
const fileContent = "short";
const searchContent = "this is much longer than the file content";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
});
describe("Edge cases", () => {
it("should handle empty file content with non-empty search", () => {
const fileContent = "";
const searchContent = "something";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should handle single character matches", () => {
const fileContent = "a";
const searchContent = "a";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 1,
strategyName: "exactMatch",
});
});
it("should handle unicode characters", () => {
const fileContent = "Hello 🌍 World";
const searchContent = "🌍";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 6,
endIndex: 8, // Unicode emoji takes 2 character positions
strategyName: "exactMatch",
});
});
it("should handle newlines and carriage returns", () => {
const fileContent = "line1\r\nline2\nline3";
const searchContent = "\r\nline2";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 5,
endIndex: 12,
strategyName: "exactMatch",
});
});
it("should handle very long content efficiently", () => {
const longContent = "a".repeat(10000) + "target" + "b".repeat(10000);
const searchContent = "target";
const result = findSearchMatch(longContent, searchContent);
expect(result).toEqual({
startIndex: 10000,
endIndex: 10006,
strategyName: "exactMatch",
});
});
});
describe("Strategy precedence", () => {
it("should prefer exact match over trimmed match", () => {
const fileContent = "hello world hello";
const searchContent = "hello"; // This exists exactly, so should use exactMatch
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 5,
strategyName: "exactMatch",
});
});
it("should prefer trimmed match over whitespace ignored match", () => {
// Set up content where trimmed match would work but whitespace ignored would also work
const fileContent = "hello world";
const searchContent = " hello "; // Has whitespace but trimmed version exists
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 5,
strategyName: "trimmedMatch",
});
});
it("should fall back through strategies in correct order", () => {
const fileContent = "function test() {\n return true;\n}";
const searchContent = " function test(){return true;} "; // Needs whitespace ignored
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 34,
strategyName: "whitespaceIgnoredMatch",
});
});
});
describe("Real-world code examples", () => {
it("should handle JavaScript function matching", () => {
const fileContent = `function calculateSum(a, b) {
const result = a + b;
return result;
}`;
const searchContent = `function calculateSum(a, b) {
const result = a + b;
return result;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 72,
strategyName: "exactMatch",
});
});
it("should handle HTML tag matching with different formatting", () => {
const fileContent = `<div class="container">
<p>Hello World</p>
</div>`;
const searchContent = `<div class="container"><p>Hello World</p></div>`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 51,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should handle CSS rule matching", () => {
const fileContent = `.button {
background-color: blue;
color: white;
}`;
const searchContent = `.button{background-color:blue;color:white;}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 53,
strategyName: "whitespaceIgnoredMatch",
});
});
});
});

View file

@ -0,0 +1,368 @@
import { findSearchMatches } from "./findSearchMatch";
describe("findSearchMatches", () => {
describe("exact match strategy", () => {
it("should find single occurrence", () => {
const content = "const foo = 'bar';";
const search = "foo";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 6,
endIndex: 9,
strategyName: "exactMatch",
});
});
it("should find multiple occurrences", () => {
const content = "const foo = 'foo';";
const search = "foo";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(2);
expect(matches[0]).toEqual({
startIndex: 6,
endIndex: 9,
strategyName: "exactMatch",
});
expect(matches[1]).toEqual({
startIndex: 13,
endIndex: 16,
strategyName: "exactMatch",
});
});
it("should find overlapping pattern occurrences correctly", () => {
const content = "aaaa";
const search = "aa";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(2);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 2,
strategyName: "exactMatch",
});
expect(matches[1]).toEqual({
startIndex: 2,
endIndex: 4,
strategyName: "exactMatch",
});
});
it("should return empty array when no matches found", () => {
const content = "const bar = 'baz';";
const search = "foo";
const matches = findSearchMatches(content, search);
expect(matches).toEqual([]);
});
it("should handle multi-line content", () => {
const content = `line 1 foo
line 2 bar
line 3 foo`;
const search = "foo";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(2);
expect(matches[0]).toEqual({
startIndex: 7,
endIndex: 10,
strategyName: "exactMatch",
});
expect(matches[1]).toEqual({
startIndex: 29,
endIndex: 32,
strategyName: "exactMatch",
});
});
});
describe("trimmed match strategy", () => {
it("should find trimmed occurrences when exact match fails", () => {
const content = "const foo = 'bar';";
const search = " foo ";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 6,
endIndex: 9,
strategyName: "trimmedMatch",
});
});
it("should find multiple trimmed occurrences", () => {
const content = "const foo = 'foo';";
const search = " foo ";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(2);
expect(matches[0]).toEqual({
startIndex: 6,
endIndex: 9,
strategyName: "trimmedMatch",
});
expect(matches[1]).toEqual({
startIndex: 13,
endIndex: 16,
strategyName: "trimmedMatch",
});
});
});
describe("whitespace ignored match strategy", () => {
it("should find matches ignoring internal whitespace", () => {
const content = "const foo = bar;";
const search = "const foo=bar";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 15,
strategyName: "whitespaceIgnoredMatch",
});
});
it("should find multiple matches ignoring whitespace", () => {
const content = `const foo = bar;
const baz = foo;`;
const search = "const foo";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 9,
strategyName: "exactMatch",
});
});
it("should handle complex whitespace patterns", () => {
const content = `function test() {
return true;
}`;
const search = "function test(){return true;}";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 34,
strategyName: "whitespaceIgnoredMatch",
});
});
});
describe("empty search content", () => {
it("should return single match at position 0 for empty string", () => {
const content = "const foo = 'bar';";
const search = "";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should return single match at position 0 for whitespace-only string", () => {
const content = "const foo = 'bar';";
const search = " \n\t ";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
});
describe("edge cases", () => {
it("should handle searching in empty content", () => {
const content = "";
const search = "foo";
const matches = findSearchMatches(content, search);
expect(matches).toEqual([]);
});
it("should handle searching for content at the beginning", () => {
const content = "foo bar baz";
const search = "foo";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 3,
strategyName: "exactMatch",
});
});
it("should handle searching for content at the end", () => {
const content = "foo bar baz";
const search = "baz";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 8,
endIndex: 11,
strategyName: "exactMatch",
});
});
it("should handle searching for the entire content", () => {
const content = "foo bar baz";
const search = "foo bar baz";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 11,
strategyName: "exactMatch",
});
});
it("should handle special characters", () => {
const content = "const regex = /[a-z]+/g;";
const search = "/[a-z]+/g";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 14,
endIndex: 23,
strategyName: "exactMatch",
});
});
it("should handle Unicode characters", () => {
const content = "const emoji = '🚀 Hello 🌍';";
const search = "🚀 Hello 🌍";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 15,
endIndex: 26,
strategyName: "exactMatch",
});
});
});
describe("performance considerations", () => {
it("should handle long content with multiple matches", () => {
const repeatedContent = "foo bar ".repeat(1000);
const search = "foo";
const matches = findSearchMatches(repeatedContent, search);
expect(matches).toHaveLength(1000);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 3,
strategyName: "exactMatch",
});
expect(matches[999]).toEqual({
startIndex: 7992,
endIndex: 7995,
strategyName: "exactMatch",
});
});
it("should prevent infinite loops on edge cases", () => {
const content = "aaaa";
const search = "";
const matches = findSearchMatches(content, search);
// Should only return one match for empty search
expect(matches).toHaveLength(1);
expect(matches[0]).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
});
describe("strategy selection", () => {
it("should use exact match strategy when possible", () => {
const content = "const foo = bar;";
const search = "foo";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0].strategyName).toBe("exactMatch");
});
it("should fallback to trimmed match when exact fails", () => {
const content = "const foo = bar;";
const search = " foo ";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0].strategyName).toBe("trimmedMatch");
});
it("should fallback to whitespace ignored when others fail", () => {
const content = "const foo = bar;";
const search = "const foo=bar";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0].strategyName).toBe("whitespaceIgnoredMatch");
});
});
describe("complex patterns", () => {
it("should handle multiple matches with different line endings", () => {
const content = "foo\r\nbar\r\nfoo\nfoo";
const search = "foo";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(3);
expect(matches[0].startIndex).toBe(0);
expect(matches[1].startIndex).toBe(10);
expect(matches[2].startIndex).toBe(14);
});
it("should handle matches across different strategies", () => {
const content = "const foo = 'bar';\n const foo='baz';";
const search = "foo";
const matches = findSearchMatches(content, search);
// Both occurrences of "foo" should be found with exact match
expect(matches).toHaveLength(2);
expect(matches[0]).toEqual({
startIndex: 6,
endIndex: 9,
strategyName: "exactMatch",
});
expect(matches[1]).toEqual({
startIndex: 29,
endIndex: 32,
strategyName: "exactMatch",
});
});
it("should handle code with mixed indentation", () => {
const content = `\tfunction test() {
return true;
\t}`;
const search = "function test(){return true;}";
const matches = findSearchMatches(content, search);
expect(matches).toHaveLength(1);
expect(matches[0].strategyName).toBe("whitespaceIgnoredMatch");
});
});
});

View file

@ -0,0 +1,341 @@
import { describe, expect, it } from "vitest";
import { EditOperation } from "../../tools/definitions/multiEdit";
import { ContinueErrorReason } from "../../util/errors";
import { validateMultiEdit } from "./multiEditValidation";
import { executeMultiFindAndReplace } from "./performReplace";
describe("multiEdit shared validation", () => {
describe("validateMultiEdit", () => {
it("should throw error if edits is not an array", () => {
expect(() => validateMultiEdit({ edits: "not an array" })).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.MultiEditEditsArrayRequired,
}),
);
});
it("should throw error if edits is missing", () => {
expect(() => validateMultiEdit({})).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.MultiEditEditsArrayRequired,
}),
);
});
it("should throw error if edits array is empty", () => {
expect(() => validateMultiEdit({ edits: [] })).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.MultiEditEditsArrayEmpty,
}),
);
});
it("should return valid edits", () => {
const edits: EditOperation[] = [
{ old_string: "hello", new_string: "world" },
];
const result = validateMultiEdit({ edits });
expect(result.edits).toEqual(edits);
});
});
describe("validateMultiEdit - individual edit validation", () => {
it("should throw error if edit has missing old_string", () => {
const args = {
edits: [
{
old_string: undefined as any,
new_string: "Hi there",
},
],
};
expect(() => validateMultiEdit(args)).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingOldString,
}),
);
});
it("should throw error if edit has missing new_string", () => {
const args = {
edits: [
{
old_string: "Hello world",
new_string: undefined as any,
},
],
};
expect(() => validateMultiEdit(args)).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingNewString,
}),
);
});
it("should throw error if old_string and new_string are the same", () => {
const args = {
edits: [
{
old_string: "Hello world",
new_string: "Hello world",
},
],
};
expect(() => validateMultiEdit(args)).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
}),
);
});
it("should throw error if non-first edit has empty old_string", () => {
const args = {
edits: [
{
old_string: "Hello world",
new_string: "Hi there",
},
{
old_string: "",
new_string: "Invalid insertion",
},
],
};
expect(() => validateMultiEdit(args)).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceNonFirstEmptyOldString,
}),
);
});
it("should allow first edit to have empty old_string", () => {
const args = {
edits: [
{
old_string: "",
new_string: "New content",
},
],
};
expect(() => validateMultiEdit(args)).not.toThrow();
});
});
describe("executeMultiFindAndReplace", () => {
const originalContent = "Hello world\nThis is a test file\nGoodbye world";
it("should handle single edit", () => {
const edits = [
{
old_string: "Hello world",
new_string: "Hi there",
},
];
const result = executeMultiFindAndReplace(originalContent, edits);
expect(result).toBe("Hi there\nThis is a test file\nGoodbye world");
});
it("should handle multiple edits", () => {
const edits = [
{
old_string: "Hello world",
new_string: "Hi there",
},
{
old_string: "Goodbye world",
new_string: "See you later",
},
];
const result = executeMultiFindAndReplace(originalContent, edits);
expect(result).toBe("Hi there\nThis is a test file\nSee you later");
});
it("should handle replace_all", () => {
const edits = [
{
old_string: "world",
new_string: "universe",
replace_all: true,
},
];
const result = executeMultiFindAndReplace(originalContent, edits);
expect(result).toBe(
"Hello universe\nThis is a test file\nGoodbye universe",
);
});
it("should handle empty old_string as insertion at beginning", () => {
const edits = [
{
old_string: "",
new_string: "New first line\n",
},
];
const result = executeMultiFindAndReplace(originalContent, edits);
expect(result).toBe(
"New first line\nHello world\nThis is a test file\nGoodbye world",
);
});
it("should handle empty string in empty file", () => {
const edits = [
{
old_string: "",
new_string: "Content for empty file",
},
];
// Empty old_string matches at position 0 (beginning of file)
const result = executeMultiFindAndReplace("", edits);
expect(result).toBe("Content for empty file");
});
it("should apply edits sequentially", () => {
const edits = [
{
old_string: "Hello world",
new_string: "Hi universe",
},
{
old_string: "Hi universe",
new_string: "Greetings cosmos",
},
];
const result = executeMultiFindAndReplace(originalContent, edits);
expect(result).toBe(
"Greetings cosmos\nThis is a test file\nGoodbye world",
);
});
it("should throw error if old_string is not found", () => {
const edits = [
{
old_string: "Not found",
new_string: "Hi there",
},
];
expect(() =>
executeMultiFindAndReplace(originalContent, edits),
).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceOldStringNotFound,
}),
);
});
it("should throw error if old_string appears multiple times and replace_all is false", () => {
const edits = [
{
old_string: "world",
new_string: "universe",
replace_all: false,
},
];
expect(() =>
executeMultiFindAndReplace(originalContent, edits),
).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences,
}),
);
});
it("should throw if string not found in edit sequence", () => {
const content = "Hello world";
const edits = [
{ old_string: "Hello", new_string: "Hi" },
{ old_string: "not found", new_string: "test" },
];
expect(() => executeMultiFindAndReplace(content, edits)).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceOldStringNotFound,
}),
);
});
it("should handle whitespace differences using findSearchMatch", () => {
const content = "function test() {\n return true;\n}";
const edits = [
{
old_string: "function test(){return true;}",
new_string: "function test() { return false; }",
},
];
const result = executeMultiFindAndReplace(content, edits);
expect(result).toBe("function test() { return false; }");
});
it("should handle mixed replace_all settings", () => {
const content = "x y x z x";
const edits = [
{ old_string: "x", new_string: "a", replace_all: true },
{ old_string: "y", new_string: "b" },
];
const result = executeMultiFindAndReplace(content, edits);
expect(result).toBe("a b a z a");
});
});
describe("preprocessing logic", () => {
const originalContent = "Hello world\nThis is a test file\nGoodbye world";
it("should handle single edit preprocessing", () => {
const edits = [
{
old_string: "Hello world",
new_string: "Hi there",
},
];
const newContent = executeMultiFindAndReplace(originalContent, edits);
expect(newContent).toBe("Hi there\nThis is a test file\nGoodbye world");
});
it("should handle multiple edits preprocessing", () => {
const edits = [
{
old_string: "Hello world",
new_string: "Hi there",
},
{
old_string: "Goodbye world",
new_string: "See you later",
},
];
const newContent = executeMultiFindAndReplace(originalContent, edits);
expect(newContent).toBe("Hi there\nThis is a test file\nSee you later");
});
it("should count edits correctly", () => {
const edits = [
{ old_string: "Hello", new_string: "Hi" },
{ old_string: "world", new_string: "universe", replace_all: true },
];
const newContent = executeMultiFindAndReplace(originalContent, edits);
expect(newContent).toBe(
"Hi universe\nThis is a test file\nGoodbye universe",
);
expect(edits.length).toBe(2);
});
});
});

View file

@ -0,0 +1,50 @@
import { EditOperation } from "../../tools/definitions/multiEdit";
import { ContinueError, ContinueErrorReason } from "../../util/errors";
import { validateSingleEdit } from "./findAndReplaceUtils";
export interface MultiEditValidationResult {
edits: EditOperation[];
}
/**
* Validates multi-edit arguments and all edits in a single pass
* @param args - The arguments object containing the edits array
* @returns Validated edits array
* @throws ContinueError if validation fails
*/
export function validateMultiEdit(args: any): MultiEditValidationResult {
const { edits } = args;
// Validate that edits is a non-empty array
if (!edits || !Array.isArray(edits)) {
throw new ContinueError(
ContinueErrorReason.MultiEditEditsArrayRequired,
"edits array is required",
);
}
if (edits.length === 0) {
throw new ContinueError(
ContinueErrorReason.MultiEditEditsArrayEmpty,
"edits array must contain at least one edit",
);
}
// Validate each individual edit
for (let i = 0; i < edits.length; i++) {
const edit = edits[i];
// Use existing single edit validation
validateSingleEdit(edit.old_string, edit.new_string, i);
// Only the first edit can have empty old_string (for insertion at beginning)
if (i > 0 && edit.old_string === "") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceNonFirstEmptyOldString,
`Edit at index ${i}: old_string cannot be empty. Only the first edit can have an empty old_string for insertion at the beginning of the file.`,
);
}
}
return { edits };
}

View file

@ -0,0 +1,70 @@
import { EditOperation } from "../../tools/definitions/multiEdit";
import { ContinueError, ContinueErrorReason } from "../../util/errors";
import { findSearchMatches } from "./findSearchMatch";
export function executeFindAndReplace(
fileContent: string,
oldString: string,
newString: string,
replaceAll: boolean,
editIndex = 0,
): string {
const matches = findSearchMatches(fileContent, oldString);
if (matches.length === 0) {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceOldStringNotFound,
`Edit at index ${editIndex}: string not found in file: "${oldString}"`,
);
}
if (replaceAll) {
// Apply replacements in reverse order to maintain correct positions
let result = fileContent;
for (let i = matches.length - 1; i >= 0; i--) {
const match = matches[i];
result =
result.substring(0, match.startIndex) +
newString +
result.substring(match.endIndex);
}
return result;
} else {
// For single replacement, check for multiple matches first
if (matches.length > 1) {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMultipleOccurrences,
`Edit at index ${editIndex}: String "${oldString}" appears ${matches.length} times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.`,
);
}
// Apply single replacement
const match = matches[0];
return (
fileContent.substring(0, match.startIndex) +
newString +
fileContent.substring(match.endIndex)
);
}
}
export function executeMultiFindAndReplace(
fileContent: string,
edits: EditOperation[],
): string {
let result = fileContent;
// Apply edits in sequence
for (let editIndex = 0; editIndex < edits.length; editIndex++) {
const edit = edits[editIndex];
result = executeFindAndReplace(
result,
edit.old_string,
edit.new_string,
edit.replace_all ?? false,
editIndex,
);
}
return result;
}

View file

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

34
core/index.d.ts vendored
View file

@ -272,7 +272,7 @@ export interface Session {
history: ChatHistoryItem[];
}
export interface SessionMetadata {
export interface BaseSessionMetadata {
sessionId: string;
title: string;
dateCreated: string;
@ -310,11 +310,6 @@ export interface FileEdit {
replacement: string;
}
export interface ContinueError {
title: string;
message: string;
}
export interface CompletionOptions extends BaseCompletionOptions {
model: string;
}
@ -824,6 +819,8 @@ export interface IDE {
openUrl(url: string): Promise<void>;
getExternalUri?(uri: string): Promise<string>;
runCommand(command: string, options?: TerminalOptions): Promise<void>;
saveFile(fileUri: string): Promise<void>;
@ -1099,6 +1096,7 @@ export interface Tool {
exampleArgs?: Array<[string, string | number]>;
};
defaultToolPolicy?: ToolPolicy;
toolCallIcon?: string;
evaluateToolCallPolicy?: (
basePolicy: ToolPolicy,
parsedArgs: Record<string, unknown>,
@ -1281,6 +1279,7 @@ export interface MCPOptions {
transport: TransportOptions;
faviconUrl?: string;
timeout?: number;
requestOptions?: RequestOptions;
}
export type MCPConnectionStatus =
@ -1333,6 +1332,7 @@ export interface MCPTool {
export interface MCPServerStatus extends MCPOptions {
status: MCPConnectionStatus;
errors: string[];
infos: string[];
isProtectedResource: boolean;
prompts: MCPPrompt[];
@ -1387,9 +1387,12 @@ export interface ApplyState {
fileContent?: string;
originalFileContent?: string;
toolCallId?: string;
autoFormattingDiff?: string;
}
export interface StreamDiffLinesPayload {
export type StreamDiffLinesType = "edit" | "apply";
interface StreamDiffLinesOptionsBase {
type: StreamDiffLinesType;
prefix: string;
highlighted: string;
suffix: string;
@ -1400,6 +1403,19 @@ export interface StreamDiffLinesPayload {
fileUri?: string;
}
interface StreamDiffLinesOptionsEdit extends StreamDiffLinesOptionsBase {
type: "edit";
}
interface StreamDiffLinesOptionsApply extends StreamDiffLinesOptionsBase {
type: "apply";
newCode: string;
}
type StreamDiffLinesPayload =
| StreamDiffLinesOptionsApply
| StreamDiffLinesOptionsEdit;
export interface HighlightedCodePayload {
rangeInFileWithContents: RangeInFileWithContents;
prompt?: string;
@ -1795,7 +1811,8 @@ export type RuleSource =
| "rules-block"
| "colocated-markdown"
| "json-systemMessage"
| ".continuerules";
| ".continuerules"
| "agent-file";
export interface RuleWithSource {
name?: string;
@ -1807,6 +1824,7 @@ export interface RuleWithSource {
description?: string;
ruleFile?: string;
alwaysApply?: boolean;
invokable?: boolean;
}
export interface CompleteOnboardingPayload {
mode: OnboardingModes;

View file

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

View file

@ -2,6 +2,7 @@ import ignore from "ignore";
import path from "path";
import { fileURLToPath } from "url";
import { ContinueError, ContinueErrorReason } from "../util/errors";
// Security-focused ignore patterns - these should always be excluded for security reasons
export const DEFAULT_SECURITY_IGNORE_FILETYPES = [
@ -203,6 +204,13 @@ export const DEFAULT_IGNORE_DIRS = [
...ADDITIONAL_INDEXING_IGNORE_DIRS,
];
export const DEFAULT_IGNORES = [
...DEFAULT_IGNORE_FILETYPES,
...DEFAULT_IGNORE_DIRS,
];
export const defaultIgnoresGlob = `!{${DEFAULT_IGNORES.join(",")}}`;
// Create ignore instances
export const defaultSecurityIgnoreFile = ignore().add(
DEFAULT_SECURITY_IGNORE_FILETYPES,
@ -252,7 +260,8 @@ export function isSecurityConcern(filePathOrUri: string) {
export function throwIfFileIsSecurityConcern(filepath: string) {
if (isSecurityConcern(filepath)) {
throw new Error(
throw new ContinueError(
ContinueErrorReason.FileIsSecurityConcern,
`Reading or Editing ${filepath} is not allowed because it is a security concern. Do not attempt to read or edit this file in any way.`,
);
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,13 +1,19 @@
import {
BedrockRuntimeClient,
ContentBlock,
ContentBlockDelta,
ContentBlockStart,
ContentBlockStartEvent,
ConversationRole,
ConverseStreamCommand,
ConverseStreamCommandOutput,
ImageFormat,
InvokeModelCommand,
Message,
ReasoningContentBlockDelta,
ToolConfiguration,
ToolUseBlock,
ToolUseBlockDelta,
} from "@aws-sdk/client-bedrock-runtime";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
@ -25,15 +31,6 @@ interface ModelConfig {
extractEmbeddings: (responseBody: any) => number[][];
}
/**
* Interface for tool use state tracking
*/
interface ToolUseState {
toolUseId: string;
name: string;
input: string;
}
/**
* Interface for prompt caching metrics
*/
@ -50,7 +47,6 @@ class Bedrock extends BaseLLM {
profile: "bedrock",
};
private _currentToolResponse: Partial<ToolUseState> | null = null;
private _promptCachingMetrics: PromptCachingMetrics = {
cacheReadInputTokens: 0,
cacheWriteInputTokens: 0,
@ -149,108 +145,99 @@ class Bedrock extends BaseLLM {
console.log(`${JSON.stringify(chunk.metadata.usage)}`);
}
if (chunk.contentBlockDelta?.delta) {
const delta: any = chunk.contentBlockDelta.delta;
const contentBlockDelta: ContentBlockDelta | undefined =
chunk.contentBlockDelta?.delta;
if (contentBlockDelta) {
// Handle text content
if (chunk.contentBlockDelta.delta.text) {
if (contentBlockDelta.text) {
yield {
role: "assistant",
content: chunk.contentBlockDelta.delta.text,
content: contentBlockDelta.text,
};
continue;
}
// Handle text content
if ((chunk.contentBlockDelta.delta as any).reasoningContent?.text) {
if (contentBlockDelta.reasoningContent?.text) {
yield {
role: "thinking",
content: (chunk.contentBlockDelta.delta as any).reasoningContent
.text,
content: contentBlockDelta.reasoningContent.text,
};
continue;
}
// Handle signature for thinking
if (delta.reasoningContent?.signature) {
if (contentBlockDelta.reasoningContent?.signature) {
yield {
role: "thinking",
content: "",
signature: delta.reasoningContent.signature,
signature: contentBlockDelta.reasoningContent.signature,
};
continue;
}
// Handle redacted thinking
if (delta.redactedReasoning?.data) {
yield {
role: "thinking",
content: "",
redactedThinking: delta.redactedReasoning.data,
};
continue;
}
if (
chunk.contentBlockDelta.delta.toolUse?.input &&
this._currentToolResponse
) {
// Append the new input to the existing string
if (this._currentToolResponse.input === undefined) {
this._currentToolResponse.input = "";
}
this._currentToolResponse.input +=
chunk.contentBlockDelta.delta.toolUse.input;
continue;
}
}
if (chunk.contentBlockStart?.start) {
const start: any = chunk.contentBlockStart.start;
if (start.redactedReasoning) {
const reasoningDelta: ReasoningContentBlockDelta | undefined = chunk
.contentBlockDelta?.delta as ReasoningContentBlockDelta;
if (reasoningDelta) {
if (reasoningDelta.redactedContent) {
yield {
role: "thinking",
content: "",
redactedThinking: start.redactedReasoning.data,
redactedThinking: reasoningDelta.text,
};
continue;
}
const toolUse = chunk.contentBlockStart.start.toolUse;
if (toolUse?.toolUseId && toolUse?.name) {
this._currentToolResponse = {
toolUseId: toolUse.toolUseId,
name: toolUse.name,
input: "",
};
}
continue;
}
if (chunk.contentBlockStop) {
if (this._currentToolResponse) {
yield {
role: "assistant",
content: "",
toolCalls: [
{
id: this._currentToolResponse.toolUseId,
type: "function",
function: {
name: this._currentToolResponse.name,
arguments: this._currentToolResponse.input,
},
const toolUseBlockDelta: ToolUseBlockDelta | undefined = chunk
.contentBlockDelta?.delta?.toolUse as ToolUseBlockDelta;
const toolUseBlock: ToolUseBlock | undefined = chunk.contentBlockDelta
?.delta?.toolUse as ToolUseBlock;
if (toolUseBlockDelta && toolUseBlock) {
yield {
role: "assistant",
content: "",
toolCalls: [
{
id: toolUseBlock.toolUseId,
type: "function",
function: {
name: toolUseBlock.name,
arguments: toolUseBlockDelta.input,
},
],
};
this._currentToolResponse = null;
}
},
],
};
continue;
}
const contentBlockStart: ContentBlockStartEvent | undefined =
chunk.contentBlockStart as ContentBlockStartEvent;
if (contentBlockStart) {
const start: ContentBlockStart | undefined = chunk.contentBlockStart
?.start as ContentBlockStart;
if (start) {
const toolUseBlock: ToolUseBlock | undefined =
start.toolUse as ToolUseBlock;
if (toolUseBlock?.toolUseId && toolUseBlock?.name) {
yield {
role: "assistant",
content: "",
toolCalls: [
{
id: toolUseBlock.toolUseId,
type: "function",
function: {
name: toolUseBlock.name,
arguments: "",
},
},
],
};
continue;
}
}
}
}
} catch (error: unknown) {
// Clean up state and let the original error bubble up to the retry decorator
this._currentToolResponse = null;
throw error;
}
}
@ -348,6 +335,9 @@ class Bedrock extends BaseLLM {
budget_tokens: options.reasoningBudgetTokens,
}
: undefined,
anthropic_beta: options.model.includes("claude")
? ["fine-grained-tool-streaming-2025-05-14"]
: undefined,
},
};
}

View file

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

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

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

View file

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

View file

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

View file

@ -1,3 +1,5 @@
import { ChatCompletionCreateParams } from "openai/resources/index";
import { LLMOptions } from "../../index.js";
import { osModelsEditPrompt } from "../templates/edit.js";
@ -13,6 +15,127 @@ class OpenRouter extends OpenAI {
},
useLegacyCompletionsEndpoint: false,
};
/**
* Detect if the model is an Anthropic/Claude model
*/
private isAnthropicModel(model?: string): boolean {
if (!model) return false;
const modelLower = model.toLowerCase();
return modelLower.includes("claude");
}
/**
* Add cache_control to message content for Anthropic models
*/
private addCacheControlToContent(content: any, addCaching: boolean): any {
if (!addCaching) return content;
if (typeof content === "string") {
return [
{
type: "text",
text: content,
cache_control: { type: "ephemeral" },
},
];
}
if (Array.isArray(content)) {
// For array content, add cache_control to the last text item
return content.map((part, idx) => {
if (part.type === "text" && idx === content.length - 1) {
return {
...part,
cache_control: { type: "ephemeral" },
};
}
return part;
});
}
return content;
}
/**
* Override modifyChatBody to add Anthropic caching when appropriate
*/
protected modifyChatBody(
body: ChatCompletionCreateParams,
): ChatCompletionCreateParams {
// First apply parent modifications
body = super.modifyChatBody(body);
// Check if we should apply Anthropic caching
if (
!this.isAnthropicModel(body.model) ||
(!this.cacheBehavior && !this.completionOptions.promptCaching)
) {
return body;
}
const shouldCacheConversation =
this.cacheBehavior?.cacheConversation ||
this.completionOptions.promptCaching;
const shouldCacheSystemMessage =
this.cacheBehavior?.cacheSystemMessage ||
this.completionOptions.promptCaching;
if (!shouldCacheConversation && !shouldCacheSystemMessage) {
return body;
}
// Follow the same logic as Anthropic.ts: filter out system messages first
const filteredMessages = body.messages.filter(
(m: any) => m.role !== "system" && !!m.content,
);
// Find the last two user message indices from the filtered array
const lastTwoUserMsgIndices = filteredMessages
.map((msg: any, index: number) => (msg.role === "user" ? index : -1))
.filter((index: number) => index !== -1)
.slice(-2);
// Create a mapping from filtered indices to original indices
let filteredIndex = 0;
const filteredToOriginalIndexMap: number[] = [];
body.messages.forEach((msg: any, originalIndex: number) => {
if (msg.role !== "system" && !!msg.content) {
filteredToOriginalIndexMap[filteredIndex] = originalIndex;
filteredIndex++;
}
});
// Modify messages to add cache_control
body.messages = body.messages.map((message: any, idx) => {
// Handle system message caching
if (message.role === "system" && shouldCacheSystemMessage) {
return {
...message,
content: this.addCacheControlToContent(message.content, true),
};
}
// Handle conversation caching for last two user messages
// Check if this message's index (in filtered array) is one of the last two user messages
const filteredIdx = filteredToOriginalIndexMap.indexOf(idx);
if (
message.role === "user" &&
shouldCacheConversation &&
filteredIdx !== -1 &&
lastTwoUserMsgIndices.includes(filteredIdx)
) {
return {
...message,
content: this.addCacheControlToContent(message.content, true),
};
}
return message;
});
return body;
}
}
export default OpenRouter;

View file

@ -0,0 +1,236 @@
import { ChatCompletionCreateParams } from "openai/resources/index";
import { describe, expect, it } from "vitest";
import OpenRouter from "./OpenRouter";
describe("OpenRouter Anthropic Caching", () => {
it("should detect Anthropic models correctly", () => {
const openRouter = new OpenRouter({
model: "claude-3-5-sonnet-latest",
apiKey: "test-key",
});
// Test private method through modifyChatBody
const body: ChatCompletionCreateParams = {
model: "claude-3-5-sonnet-latest",
messages: [],
};
// Should not throw
openRouter["modifyChatBody"](body);
});
it("should add cache_control to user messages when caching is enabled", () => {
const openRouter = new OpenRouter({
model: "anthropic/claude-3.5-sonnet",
apiKey: "test-key",
cacheBehavior: {
cacheConversation: true,
cacheSystemMessage: false,
},
});
const body: ChatCompletionCreateParams = {
model: "anthropic/claude-3.5-sonnet",
messages: [
{ role: "user", content: "First message" },
{ role: "assistant", content: "Response" },
{ role: "user", content: "Second message" },
{ role: "assistant", content: "Another response" },
{ role: "user", content: "Third message" },
],
};
const modifiedBody = openRouter["modifyChatBody"](body);
// Check that the last two user messages have cache_control
const userMessages = modifiedBody.messages.filter(
(msg: any) => msg.role === "user",
);
// First user message should not have cache_control
expect(userMessages[0].content).toBe("First message");
// Last two user messages should have cache_control
expect(userMessages[1].content).toEqual([
{
type: "text",
text: "Second message",
cache_control: { type: "ephemeral" },
},
]);
expect(userMessages[2].content).toEqual([
{
type: "text",
text: "Third message",
cache_control: { type: "ephemeral" },
},
]);
});
it("should correctly handle cache_control with system messages present", () => {
const openRouter = new OpenRouter({
model: "claude-3-5-sonnet-latest",
apiKey: "test-key",
cacheBehavior: {
cacheConversation: true,
cacheSystemMessage: true,
},
});
const body: ChatCompletionCreateParams = {
model: "claude-3-5-sonnet-latest",
messages: [
{ role: "system", content: "You are a helpful assistant" },
{ role: "user", content: "First user message" },
{ role: "assistant", content: "First assistant response" },
{ role: "user", content: "Second user message" },
{ role: "assistant", content: "Second assistant response" },
{ role: "user", content: "Third user message" },
],
};
const modifiedBody = openRouter["modifyChatBody"](body);
// System message should have cache_control
expect(modifiedBody.messages[0]).toEqual({
role: "system",
content: [
{
type: "text",
text: "You are a helpful assistant",
cache_control: { type: "ephemeral" },
},
],
});
// Check user messages - should follow Anthropic filtering logic
const userMessages = modifiedBody.messages.filter(
(msg: any) => msg.role === "user",
);
// First user message should NOT have cache_control (only last 2)
expect(userMessages[0].content).toBe("First user message");
// Last two user messages should have cache_control
expect(userMessages[1].content).toEqual([
{
type: "text",
text: "Second user message",
cache_control: { type: "ephemeral" },
},
]);
expect(userMessages[2].content).toEqual([
{
type: "text",
text: "Third user message",
cache_control: { type: "ephemeral" },
},
]);
// Assistant messages should remain unchanged
expect(modifiedBody.messages[2].content).toBe("First assistant response");
expect(modifiedBody.messages[4].content).toBe("Second assistant response");
});
it("should add cache_control to system message when caching is enabled", () => {
const openRouter = new OpenRouter({
model: "claude-3-5-sonnet-latest",
apiKey: "test-key",
cacheBehavior: {
cacheConversation: false,
cacheSystemMessage: true,
},
});
const body: ChatCompletionCreateParams = {
model: "claude-3-5-sonnet-latest",
messages: [
{ role: "system", content: "You are a helpful assistant" },
{ role: "user", content: "Hello" },
],
};
const modifiedBody = openRouter["modifyChatBody"](body);
// System message should have cache_control
expect(modifiedBody.messages[0]).toEqual({
role: "system",
content: [
{
type: "text",
text: "You are a helpful assistant",
cache_control: { type: "ephemeral" },
},
],
});
// User message should remain unchanged
expect(modifiedBody.messages[1]).toEqual({
role: "user",
content: "Hello",
});
});
it("should handle array content correctly", () => {
const openRouter = new OpenRouter({
model: "claude-3-5-sonnet-latest",
apiKey: "test-key",
cacheBehavior: {
cacheConversation: true,
cacheSystemMessage: false,
},
});
const body: ChatCompletionCreateParams = {
model: "claude-3-5-sonnet-latest",
messages: [
{
role: "user",
content: [
{ type: "text", text: "First part" },
{ type: "text", text: "Second part" },
],
},
],
};
const modifiedBody = openRouter["modifyChatBody"](body);
// Only the last text part should have cache_control
expect(modifiedBody.messages[0].content).toEqual([
{ type: "text", text: "First part" },
{
type: "text",
text: "Second part",
cache_control: { type: "ephemeral" },
},
]);
});
it("should not modify messages for non-Anthropic models", () => {
const openRouter = new OpenRouter({
model: "gpt-4o",
apiKey: "test-key",
cacheBehavior: {
cacheConversation: true,
cacheSystemMessage: true,
},
});
const body: ChatCompletionCreateParams = {
model: "gpt-4o",
messages: [
{ role: "system", content: "System message" },
{ role: "user", content: "User message" },
],
};
const modifiedBody = openRouter["modifyChatBody"](body);
// Messages should remain unchanged
expect(modifiedBody.messages).toEqual(body.messages);
});
});

View file

@ -9,17 +9,16 @@ class SambaNova extends OpenAI {
};
private static MODEL_IDS: { [name: string]: string } = {
"llama4-scout": "Llama-4-Scout-17B-16E-Instruct",
"llama4-maverick": "Llama-4-Maverick-17B-128E-Instruct",
"llama3.3-70b": "Meta-Llama-3.3-70B-Instruct",
"llama3.3-swalllow-70b": "Llama-3.3-Swallow-70B-Instruct-v0.4",
"llama3.1-8b": "Meta-Llama-3.1-8B-Instruct",
"llama3.1-405b": "Meta-Llama-3.1-405B-Instruct",
"llama3.2-1b": "Meta-Llama-3.2-1B-Instruct",
"llama3.2-3b": "Meta-Llama-3.2-3B-Instruct",
"qwq-32b": "QwQ-32B",
"deepseek-r1-distill-llama-70b": "DeepSeek-R1-Distill-Llama-70B",
"deepseek-r1": "DeepSeek-R1",
"deepseek-v3": "DeepSeek-V3-0324",
"deepseek-v3.1": "DeepSeek-V3-0324",
"gpt-oss-120b": "gpt-oss-120b",
"qwen3-32b": "Qwen3-32B",
};
protected _convertModelName(model: string) {

View file

@ -33,6 +33,7 @@ import Kindo from "./Kindo";
import LlamaCpp from "./LlamaCpp";
import Llamafile from "./Llamafile";
import LlamaStack from "./LlamaStack";
import Lemonade from "./Lemonade";
import LMStudio from "./LMStudio";
import Mistral from "./Mistral";
import MockLLM from "./Mock";
@ -82,6 +83,7 @@ export const LLMClasses = [
LlamaCpp,
OpenAI,
OVHcloud,
Lemonade,
LMStudio,
Mistral,
Bedrock,

View file

@ -0,0 +1,46 @@
import { RuleWithSource } from "../..";
import { getLastNPathParts } from "../../util/uri";
export function getRuleDisplayName(rule: RuleWithSource): string {
if (rule.name) {
return rule.name;
}
return getRuleSourceDisplayName(rule);
}
export function getRuleSourceDisplayName(rule: RuleWithSource): string {
switch (rule.source) {
case ".continuerules":
return "Project rules";
case "default-chat":
return "Default chat system message";
case "default-plan":
return "Default plan mode system message";
case "default-agent":
return "Default agent system message";
case "json-systemMessage":
return "System Message (JSON)";
case "model-options-agent":
return "Base System Agent Message";
case "model-options-plan":
return "Base System Plan Message";
case "model-options-chat":
return "Base System Chat Message";
case "agent-file":
if (rule.ruleFile) {
return getLastNPathParts(rule.ruleFile, 2);
} else {
return "Agent file";
}
case "colocated-markdown":
if (rule.ruleFile) {
return getLastNPathParts(rule.ruleFile, 2);
} else {
return "rules.md";
}
case "rules-block":
return "Rules Block";
default:
return rule.source;
}
}

View file

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

View file

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

View file

@ -203,7 +203,9 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
if (
model.toLowerCase().startsWith("meta-llama-3") ||
model.toLowerCase().includes("llama-4") ||
model.toLowerCase().includes("deepseek")
model.toLowerCase().includes("deepseek") ||
model.toLowerCase().includes("gpt") ||
model.toLowerCase().includes("qwen")
) {
return true;
}
@ -374,9 +376,8 @@ export function isRecommendedAgentModel(modelName: string): boolean {
[/o[134]/],
[/deepseek/, /r1|reasoner/],
[/gemini/, /2\.5/, /pro/],
[/gpt/, /4/],
[/gpt-5/],
[/claude/, /sonnet/, /3\.5|3\.7|3-5|3-7|-4/],
[/claude/, /sonnet/, /3\.7|3-7|-4/],
[/claude/, /opus/, /-4/],
];
for (const combo of recs) {

55
core/package-lock.json generated
View file

@ -152,10 +152,10 @@
},
"../packages/config-yaml": {
"name": "@continuedev/config-yaml",
"version": "1.0.96",
"version": "1.17.0",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "file:../config-types",
"@continuedev/config-types": "^1.0.14",
"yaml": "^2.6.1",
"zod": "^3.24.2"
},
@ -179,17 +179,22 @@
},
"../packages/fetch": {
"name": "@continuedev/fetch",
"version": "1.0.16",
"version": "1.1.0",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "file:../config-types",
"@continuedev/config-types": "^1.0.14",
"follow-redirects": "^1.15.6",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.5",
"node-fetch": "^3.3.2"
},
"devDependencies": {
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^9.2.6",
"@semantic-release/npm": "^10.0.6",
"@types/follow-redirects": "^1.14.4",
"semantic-release": "^21.1.2",
"typescript": "^5.0.0",
"vitest": "^3.2.0"
}
@ -199,20 +204,25 @@
"version": "1.0.9",
"license": "Apache-2.0",
"devDependencies": {
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^9.2.6",
"@semantic-release/npm": "^10.0.6",
"@types/node": "^22.15.29",
"semantic-release": "^21.1.2",
"typescript": "^5.5.2"
}
},
"../packages/openai-adapters": {
"name": "@continuedev/openai-adapters",
"version": "1.5.1",
"version": "1.15.0",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.842.0",
"@aws-sdk/credential-providers": "^3.840.0",
"@continuedev/config-types": "^1.0.14",
"@continuedev/config-yaml": "^1.8.0",
"@continuedev/fetch": "^1.0.16",
"@continuedev/config-yaml": "^1.14.0",
"@continuedev/fetch": "^1.1.0",
"dotenv": "^16.5.0",
"google-auth-library": "^10.1.0",
"json-schema": "^0.4.0",
@ -7903,13 +7913,13 @@
"integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw=="
},
"node_modules/axios": {
"version": "1.8.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.8.2.tgz",
"integrity": "sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==",
"version": "1.12.0",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.12.0.tgz",
"integrity": "sha512-oXTDccv8PcfjZmPGlWsPSwtOJCZ/b6W5jAMCNcfwJbCzDckwG0jrYJFaWH1yvivfCXjVzV/SPDEhMB3Q+DSurg==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",
"form-data": "^4.0.4",
"proxy-from-env": "^1.1.0"
}
},
@ -9922,14 +9932,15 @@
}
},
"node_modules/es-set-tostringtag": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.3.tgz",
"integrity": "sha512-3T8uNMC3OQTHkFUsFq8r/BwAXLHvU/9O9mE0fBc/MY5iq/8H7ncvO947LmYA6ldWw9Uh8Yhf25zu6n7nML5QWQ==",
"peer": true,
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
"license": "MIT",
"dependencies": {
"get-intrinsic": "^1.2.4",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.6",
"has-tostringtag": "^1.0.2",
"hasown": "^2.0.1"
"hasown": "^2.0.2"
},
"engines": {
"node": ">= 0.4"
@ -11326,12 +11337,15 @@
}
},
"node_modules/form-data": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.1.tgz",
"integrity": "sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==",
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
"integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"es-set-tostringtag": "^2.1.0",
"hasown": "^2.0.2",
"mime-types": "^2.1.12"
},
"engines": {
@ -11980,7 +11994,6 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
"peer": true,
"dependencies": {
"has-symbols": "^1.0.3"
},

View file

@ -35,7 +35,7 @@ import {
RangeInFileWithNextEditInfo,
SerializedContinueConfig,
Session,
SessionMetadata,
BaseSessionMetadata,
SiteIndexingConfig,
SlashCommandDescWithSource,
StreamDiffLinesPayload,
@ -49,7 +49,10 @@ import {
ControlPlaneEnv,
ControlPlaneSessionInfo,
} from "../control-plane/AuthTypes";
import { FreeTrialStatus } from "../control-plane/client";
import {
FreeTrialStatus,
RemoteSessionMetadata,
} from "../control-plane/client";
import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue";
import { NextEditOutcome } from "../nextEdit/types";
@ -71,10 +74,15 @@ export type ToCoreFromIdeOrWebviewProtocol = {
cancelApply: [undefined, void];
// History
"history/list": [ListHistoryOptions, SessionMetadata[]];
"history/list": [
ListHistoryOptions,
(BaseSessionMetadata | RemoteSessionMetadata)[],
];
"history/delete": [{ id: string }, void];
"history/load": [{ id: string }, Session];
"history/loadRemote": [{ remoteId: string }, Session];
"history/save": [Session, void];
"history/share": [{ id: string; outputDir?: string }, void];
"history/clear": [undefined, void];
"devdata/log": [DevDataLogEvent, void];
"config/addOpenAiKey": [string, void];
@ -140,6 +148,8 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
void,
];
"mcp/disconnectServer": [{ id: string }, void];
"mcp/getDisconnectedServers": [undefined, string[]];
"mcp/getPrompt": [
{
serverName: string;
@ -313,5 +323,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
];
"process/markAsBackgrounded": [{ toolCallId: string }, void];
"process/isBackgrounded": [{ toolCallId: string }, boolean];
"process/killTerminalProcess": [{ toolCallId: string }, void];
"mdm/setLicenseKey": [{ licenseKey: string }, boolean];
};

View file

@ -48,6 +48,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
];
"edit/addCurrentSelection": [undefined, void];
"edit/clearDecorations": [undefined, void];
"session/share": [{ sessionId: string }, void];
};
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {

View file

@ -13,6 +13,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"history/list",
"history/delete",
"history/load",
"history/loadRemote",
"history/save",
"history/clear",
"devdata/log",
@ -31,6 +32,8 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"mcp/getPrompt",
"mcp/startAuthentication",
"mcp/removeAuthentication",
"mcp/disconnectServer",
"mcp/getDisconnectedServers",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",
@ -86,6 +89,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"isItemTooBig",
"process/markAsBackgrounded",
"process/isBackgrounded",
"process/killTerminalProcess",
];
// Message types to pass through from core to webview

View file

@ -1,3 +1,4 @@
import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js";
import { ContextItem, Tool, ToolCall, ToolExtras } from "..";
import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
import { canParseUrl } from "../util/url";
@ -87,10 +88,14 @@ async function callToolFromUri(
if (!client) {
throw new Error("MCP connection not found");
}
const response = await client.client.callTool({
name: toolName,
arguments: args,
});
const response = await client.client.callTool(
{
name: toolName,
arguments: args,
},
CallToolResultSchema,
{ timeout: client.options.timeout },
);
if (response.isError === true) {
throw new Error(JSON.stringify(response.content));

View file

@ -4,9 +4,9 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const createNewFileTool: Tool = {
type: "function",
displayTitle: "Create New File",
wouldLikeTo: "create a new file at {{{ filepath }}}",
isCurrently: "creating a new file at {{{ filepath }}}",
hasAlready: "created a new file at {{{ filepath }}}",
wouldLikeTo: "create {{{ filepath }}}",
isCurrently: "creating {{{ filepath }}}",
hasAlready: "created {{{ filepath }}}",
group: BUILT_IN_GROUP_NAME,
readonly: false,
isInstant: true,

View file

@ -84,4 +84,5 @@ For example:`,
["alwaysApply", "false"],
],
},
toolCallIcon: "PencilIcon",
};

View file

@ -6,7 +6,7 @@ export const fetchUrlContentTool: Tool = {
displayTitle: "Read URL",
wouldLikeTo: "fetch {{{ url }}}",
isCurrently: "fetching {{{ url }}}",
hasAlready: "viewed {{{ url }}}",
hasAlready: "fetched {{{ url }}}",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
@ -30,4 +30,5 @@ export const fetchUrlContentTool: Tool = {
prefix: `To fetch the content of a URL, use the ${BuiltInToolNames.FetchUrlContent} tool. For example, to read the contents of a webpage, you might respond with:`,
exampleArgs: [["url", "https://example.com"]],
},
toolCallIcon: "GlobeAltIcon",
};

View file

@ -4,16 +4,16 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const globSearchTool: Tool = {
type: "function",
displayTitle: "Glob File Search",
wouldLikeTo: 'find file matches for "{{{ pattern }}}"',
isCurrently: 'finding file matches for "{{{ pattern }}}"',
hasAlready: 'retrieved file matches for "{{{ pattern }}}"',
wouldLikeTo: 'search for files like "{{{ pattern }}}"',
isCurrently: 'searching for files like "{{{ pattern }}}"',
hasAlready: 'searched for files like "{{{ pattern }}}"',
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.FileGlobSearch,
description:
"Search for files recursively in the project using glob patterns. Supports ** for recursive directory search. Output may be truncated; use targeted patterns",
"Search for files recursively in the project using glob patterns. Supports ** for recursive directory search. Will not show many build, cache, secrets dirs/files (can use ls tool instead). Output may be truncated; use targeted patterns",
parameters: {
type: "object",
required: ["pattern"],
@ -30,4 +30,5 @@ export const globSearchTool: Tool = {
prefix: `To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`,
exampleArgs: [["pattern", "*.py"]],
},
toolCallIcon: "MagnifyingGlassIcon",
};

View file

@ -4,16 +4,16 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const grepSearchTool: Tool = {
type: "function",
displayTitle: "Grep Search",
wouldLikeTo: 'search for "{{{ query }}}" in the repository',
isCurrently: 'getting search results for "{{{ query }}}"',
hasAlready: 'retrieved search results for "{{{ query }}}"',
wouldLikeTo: 'search for "{{{ query }}}"',
isCurrently: 'searching for "{{{ query }}}"',
hasAlready: 'searched for "{{{ query }}}"',
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.GrepSearch,
description:
"Perform a search over the repository using ripgrep. Output may be truncated, so use targeted queries",
"Perform a search over the repository using ripgrep. Will not include results for many build, cache, secrets dirs/files. Output may be truncated, so use targeted queries",
parameters: {
type: "object",
required: ["query"],
@ -31,4 +31,5 @@ export const grepSearchTool: Tool = {
prefix: `To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`,
exampleArgs: [["query", ".*main_services.*"]],
},
toolCallIcon: "MagnifyingGlassIcon",
};

View file

@ -5,9 +5,9 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const lsTool: Tool = {
type: "function",
displayTitle: "ls",
wouldLikeTo: "list files and folders in {{{ dirPath }}}",
isCurrently: "listing files and folders in {{{ dirPath }}}",
hasAlready: "listed files and folders in {{{ dirPath }}}",
wouldLikeTo: "list files in {{{ dirPath }}}",
isCurrently: "listing files in {{{ dirPath }}}",
hasAlready: "listed files in {{{ dirPath }}}",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
@ -38,4 +38,5 @@ export const lsTool: Tool = {
["recursive", "false"],
],
},
toolCallIcon: "FolderIcon",
};

View file

@ -50,12 +50,6 @@ CRITICAL REQUIREMENTS:
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked
- Use replace_all for replacing and renaming all matches for a string across the file. This parameter is useful if you want to rename a variable, for instance
If you want to create a new file, use:
- A new file path, including new directory if needed
- First edit: empty old_string and the new file's contents as new_string
- Subsequent edits are not allowed - there is no need since you are creating
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required
WARNINGS:
- If earlier edits affect the text that later edits are trying to find, files can become mangled
- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace)

View file

@ -6,7 +6,7 @@ export const readCurrentlyOpenFileTool: Tool = {
displayTitle: "Read Currently Open File",
wouldLikeTo: "read the current file",
isCurrently: "reading the current file",
hasAlready: "viewed the current file",
hasAlready: "read the current file",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
@ -24,4 +24,5 @@ export const readCurrentlyOpenFileTool: Tool = {
prefix: `To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool.
If the user is asking about a file and you don't see any code, use this to check the current file`,
},
toolCallIcon: "DocumentTextIcon",
};

View file

@ -6,7 +6,7 @@ export const readFileTool: Tool = {
displayTitle: "Read File",
wouldLikeTo: "read {{{ filepath }}}",
isCurrently: "reading {{{ filepath }}}",
hasAlready: "viewed {{{ filepath }}}",
hasAlready: "read {{{ filepath }}}",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
@ -31,4 +31,5 @@ export const readFileTool: Tool = {
exampleArgs: [["filepath", "path/to/the_file.txt"]],
},
defaultToolPolicy: "allowedWithoutPermission",
toolCallIcon: "DocumentIcon",
};

View file

@ -9,7 +9,7 @@ export const readFileRangeTool: Tool = {
isCurrently:
"reading lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
hasAlready:
"viewed lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
"read lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
@ -48,4 +48,5 @@ export const readFileRangeTool: Tool = {
],
},
defaultToolPolicy: "allowedWithoutPermission",
toolCallIcon: "DocumentIcon",
};

View file

@ -30,4 +30,5 @@ export const searchWebTool: Tool = {
prefix: `To search the web, use the ${BuiltInToolNames.SearchWeb} tool with a natural language query. For example, to search for the current weather, you would respond with:`,
exampleArgs: [["query", "What is the current weather in San Francisco?"]],
},
toolCallIcon: "GlobeAltIcon",
};

View file

@ -12,9 +12,9 @@ export interface SingleFindAndReplaceArgs {
export const singleFindAndReplaceTool: Tool = {
type: "function",
displayTitle: "Find and Replace",
wouldLikeTo: "find and replace in {{{ filepath }}}",
isCurrently: "finding and replacing in {{{ filepath }}}",
hasAlready: "found and replaced in {{{ filepath }}}",
wouldLikeTo: "edit {{{ filepath }}}",
isCurrently: "editing {{{ filepath }}}",
hasAlready: "edited {{{ filepath }}}",
group: BUILT_IN_GROUP_NAME,
readonly: false,
isInstant: false,

View file

@ -23,4 +23,5 @@ export const viewDiffTool: Tool = {
prefix: `To view the current git diff, use the ${BuiltInToolNames.ViewDiff} tool. This will show you the changes made in the working directory compared to the last commit.`,
},
defaultToolPolicy: "allowedWithoutPermission",
toolCallIcon: "CodeBracketIcon",
};

View file

@ -23,4 +23,5 @@ export const viewRepoMapTool: Tool = {
prefix: `To view the repository map, use the ${BuiltInToolNames.ViewRepoMap} tool. This will provide a visual representation of the project's structure and organization.`,
},
defaultToolPolicy: "allowedWithPermission",
toolCallIcon: "MapIcon",
};

View file

@ -30,4 +30,5 @@ export const viewSubdirectoryTool: Tool = {
exampleArgs: [["directory_path", "path/to/subdirectory"]],
},
defaultToolPolicy: "allowedWithPermission",
toolCallIcon: "FolderOpenIcon",
};

View file

@ -36,8 +36,11 @@ import { fileURLToPath } from "node:url";
import { ToolImpl } from ".";
import {
isProcessBackgrounded,
markProcessAsRunning,
removeBackgroundedProcess,
} from "../../util/processTerminalBackgroundStates";
removeRunningProcess,
updateProcessOutput,
} from "../../util/processTerminalStates";
import { getBooleanArg, getStringArg } from "../parseArgs";
const asyncExec = util.promisify(childProcess.exec);
@ -120,6 +123,16 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
env: getColorEnv(), // Add enhanced environment for colors
});
// Track this process for foreground cancellation
if (toolCallId && waitForCompletion) {
markProcessAsRunning(
toolCallId,
childProc,
extras.onPartialOutput,
terminalOutput,
);
}
childProc.stdout?.on("data", (data) => {
// Skip if this process has been backgrounded
if (isProcessBackgrounded(toolCallId)) return;
@ -127,6 +140,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
const newOutput = getDecodedOutput(data);
terminalOutput += newOutput;
// Update the tracked output for potential cancellation notifications
if (toolCallId && waitForCompletion) {
updateProcessOutput(toolCallId, terminalOutput);
}
// Send partial output to UI
if (extras.onPartialOutput) {
const status = waitForCompletion
@ -153,6 +171,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
const newOutput = getDecodedOutput(data);
terminalOutput += newOutput;
// Update the tracked output for potential cancellation notifications
if (toolCallId && waitForCompletion) {
updateProcessOutput(toolCallId, terminalOutput);
}
// Send partial output to UI, status is not required
if (extras.onPartialOutput) {
extras.onPartialOutput({
@ -182,15 +205,19 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
}
childProc.on("close", (code) => {
// If this process has been backgrounded, clean it up from the map and return
if (isProcessBackgrounded(toolCallId)) {
removeBackgroundedProcess(toolCallId);
return;
// Clean up process tracking
if (toolCallId) {
if (isProcessBackgrounded(toolCallId)) {
removeBackgroundedProcess(toolCallId);
return;
}
// Remove from foreground tracking if it was tracked
removeRunningProcess(toolCallId);
}
if (waitForCompletion) {
// Normal completion, resolve now
if (code === 0) {
if (!code || code === 0) {
const status = "Command completed";
resolve([
{
@ -234,10 +261,14 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
});
childProc.on("error", (error) => {
// If this process has been backgrounded, clean it up from the map and return
if (isProcessBackgrounded(toolCallId)) {
removeBackgroundedProcess(toolCallId);
return;
// Clean up process tracking
if (toolCallId) {
if (isProcessBackgrounded(toolCallId)) {
removeBackgroundedProcess(toolCallId);
return;
}
// Remove from foreground tracking if it was tracked
removeRunningProcess(toolCallId);
}
reject(error);
@ -281,6 +312,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
},
);
// Track this process for foreground cancellation
if (toolCallId) {
markProcessAsRunning(toolCallId, childProc, undefined, "");
}
let stdout = "";
let stderr = "";
@ -293,6 +329,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
});
childProc.on("close", (code) => {
// Clean up process tracking
if (toolCallId) {
removeRunningProcess(toolCallId);
}
if (code === 0) {
resolve({ stdout, stderr });
} else {
@ -305,6 +346,10 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
});
childProc.on("error", (error) => {
// Clean up process tracking
if (toolCallId) {
removeRunningProcess(toolCallId);
}
reject(error);
});
},

View file

@ -12,7 +12,7 @@ import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { IDE, ToolExtras } from "../..";
import * as processBackgroundStates from "../../util/processTerminalBackgroundStates";
import * as processTerminalStates from "../../util/processTerminalStates";
import { runTerminalCommandImpl } from "./runTerminalCommand";
import { runTerminalCommandTool } from "../definitions/runTerminalCommand";
@ -39,12 +39,8 @@ describe("runTerminalCommandImpl", () => {
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
const processMap = (processBackgroundStates as any)
.processTerminalBackgroundStates;
if (processMap && typeof processMap.clear === "function") {
processMap.clear();
}
// Clear any processes that might be already tracked
processTerminalStates.clearAllBackgroundProcesses();
// Setup IDE mocks
mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" }));

View file

@ -9,6 +9,17 @@ export const viewDiffImpl: ToolImpl = async (args, extras) => {
// TODO includeUnstaged should be an option
const combinedDiff = diffs.join("\n");
if (!combinedDiff.trim()) {
return [
{
name: "Diff",
description: "current Git diff",
content: "The current diff is empty",
},
];
}
const diffLines = combinedDiff.split("\n");
let truncated = false;

View file

@ -1,10 +1,10 @@
import { ConfigDependentToolParams, Tool } from "..";
import { isRecommendedAgentModel } from "../llm/toolSupport";
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,
@ -13,7 +13,6 @@ export const getBaseToolDefinitions = () => [
toolDefinitions.lsTool,
toolDefinitions.createRuleBlock,
toolDefinitions.fetchUrlContentTool,
toolDefinitions.singleFindAndReplaceTool,
];
export const getConfigDependentToolDefinitions = (
@ -38,10 +37,11 @@ export const getConfigDependentToolDefinitions = (
);
}
if (modelName?.includes("claude") || modelName?.includes("gpt-5")) {
if (modelName && isRecommendedAgentModel(modelName)) {
tools.push(toolDefinitions.multiEditTool);
} else {
tools.push(toolDefinitions.editFileTool);
tools.push(toolDefinitions.singleFindAndReplaceTool);
}
// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269

View file

@ -5,6 +5,7 @@ import { getMCPToolName } from "./mcpToolName";
const createMcpServer = (name: string): MCPServerStatus => ({
name,
errors: [],
infos: [],
prompts: [],
tools: [],
resources: [],

View file

@ -44,9 +44,8 @@ export type GlobalContextType = {
isSupportedLanceDbCpuTargetForLinux: boolean;
sharedConfig: SharedConfigSchema;
failedDocs: SiteIndexingConfig[];
shownDeprecatedProviderWarnings: {
[providerTitle: string]: boolean;
};
shownDeprecatedProviderWarnings: { [providerTitle: string]: boolean };
autoUpdateCli: boolean;
mcpOauthStorage: {
[serverUrl: string]: {
clientInformation?: OAuthClientInformationFull;
@ -66,16 +65,7 @@ export class GlobalContext {
) {
const filepath = getGlobalContextFilePath();
if (!fs.existsSync(filepath)) {
fs.writeFileSync(
filepath,
JSON.stringify(
{
[key]: value,
},
null,
2,
),
);
fs.writeFileSync(filepath, JSON.stringify({ [key]: value }, null, 2));
} else {
const data = fs.readFileSync(filepath, "utf-8");
@ -113,10 +103,7 @@ export class GlobalContext {
}
// Recreate the file with salvaged values plus the new value
const newData = {
...salvaged,
[key]: value,
};
const newData = { ...salvaged, [key]: value };
fs.writeFileSync(filepath, JSON.stringify(newData, null, 2));
return;
@ -174,10 +161,7 @@ export class GlobalContext {
newValues: Partial<SharedConfigSchema>,
): SharedConfigSchema {
const currentSharedConfig = this.getSharedConfig();
const updatedSharedConfig = {
...currentSharedConfig,
...newValues,
};
const updatedSharedConfig = { ...currentSharedConfig, ...newValues };
this.update("sharedConfig", updatedSharedConfig);
return updatedSharedConfig;
}
@ -189,10 +173,7 @@ export class GlobalContext {
): GlobalContextModelSelections {
const currentSelections = this.get("selectedModelsByProfileId") ?? {};
const forProfile = currentSelections[profileId] ?? {};
const newSelections = {
...forProfile,
[role]: title,
};
const newSelections = { ...forProfile, [role]: title };
this.update("selectedModelsByProfileId", {
...currentSelections,

View file

@ -10,3 +10,44 @@ export function getRootCause(err: any): any {
}
return err;
}
export class ContinueError extends Error {
reason: ContinueErrorReason;
constructor(reason: ContinueErrorReason, message?: string) {
super(message);
this.reason = reason;
this.name = "ContinueError";
}
}
export enum ContinueErrorReason {
// Find and Replace validation errors
FindAndReplaceIdenticalOldAndNewStrings = "find_and_replace_identical_old_and_new_strings",
FindAndReplaceMissingOldString = "find_and_replace_missing_old_string",
FindAndReplaceNonFirstEmptyOldString = "find_and_replace_non_first_empty_old_string",
FindAndReplaceMissingNewString = "find_and_replace_missing_new_string",
FindAndReplaceOldStringNotFound = "find_and_replace_old_string_not_found",
FindAndReplaceMultipleOccurrences = "find_and_replace_multiple_occurrences",
FindAndReplaceMissingFilepath = "find_and_replace_missing_filepath",
// Multi-edit
MultiEditEditsArrayRequired = "multi_edit_edits_array_required",
MultiEditEditsArrayEmpty = "multi_edit_edits_array_empty",
MultiEditSubsequentEditsOnCreation = "multi_edit_subsequent_edits_on_creation",
MultiEditEmptyOldStringNotFirst = "multi_edit_empty_old_string_not_first",
// General Edit
EditToolFileNotRead = "edit_tool_file_not_yet_read",
// General File
FileAlreadyExists = "file_already_exists",
FileNotFound = "file_not_found",
FileWriteError = "file_write_error",
FileIsSecurityConcern = "file_is_security_concern",
ParentDirectoryNotFound = "parent_directory_not_found",
// Other
Unspecified = "unspecified",
Unknown = "unknown",
}

View file

@ -1,6 +1,6 @@
import * as fs from "fs";
import { Session, SessionMetadata } from "../index.js";
import { Session, BaseSessionMetadata } from "../index.js";
import { ListHistoryOptions } from "../protocol/core.js";
import { NEW_SESSION_TITLE } from "./constants.js";
@ -22,14 +22,14 @@ function safeParseArray<T>(
}
export class HistoryManager {
list(options: ListHistoryOptions): SessionMetadata[] {
list(options: ListHistoryOptions): BaseSessionMetadata[] {
const filepath = getSessionsListPath();
if (!fs.existsSync(filepath)) {
return [];
}
const content = fs.readFileSync(filepath, "utf8");
let sessions = safeParseArray<SessionMetadata>(content) ?? [];
let sessions = safeParseArray<BaseSessionMetadata>(content) ?? [];
sessions = sessions
.filter((session: any) => {
// Filter out old format
@ -59,7 +59,7 @@ export class HistoryManager {
const sessionsListFile = getSessionsListPath();
const sessionsListRaw = fs.readFileSync(sessionsListFile, "utf-8");
let sessionsList =
safeParseArray<SessionMetadata>(
safeParseArray<BaseSessionMetadata>(
sessionsListRaw,
"Error parsing sessions.json",
) ?? [];
@ -118,7 +118,7 @@ export class HistoryManager {
try {
const rawSessionsList = fs.readFileSync(sessionsListFilePath, "utf-8");
let sessionsList: SessionMetadata[];
let sessionsList: BaseSessionMetadata[];
try {
sessionsList = JSON.parse(rawSessionsList);
} catch (e) {
@ -141,7 +141,7 @@ export class HistoryManager {
}
if (!found) {
const sessionMetadata: SessionMetadata = {
const sessionMetadata: BaseSessionMetadata = {
sessionId: session.sessionId,
title: session.title,
dateCreated: String(Date.now()),

105
core/util/historyUtils.ts Normal file
View file

@ -0,0 +1,105 @@
import fs from "fs";
import { homedir } from "node:os";
import { fileURLToPath, pathToFileURL } from "node:url";
import path from "path";
import { languageForFilepath } from "../autocomplete/constants/AutocompleteLanguageInfo.js";
import { ChatMessage, IDE } from "../index.js";
import { renderChatMessage } from "../util/messageContent.js";
import { getContinueGlobalPath } from "../util/paths.js";
// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
function getOffsetDatetime(date: Date): Date {
const offset = date.getTimezoneOffset();
const offsetHours = Math.floor(offset / 60);
const offsetMinutes = offset % 60;
date.setHours(date.getHours() - offsetHours);
date.setMinutes(date.getMinutes() - offsetMinutes);
return date;
}
function asBasicISOString(date: Date): string {
const isoString = date.toISOString();
return isoString.replace(/[-:]|(\.\d+Z)/g, "");
}
function reformatCodeBlocks(msgText: string): string {
const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g;
msgText = msgText.replace(
codeBlockFenceRegex,
(match, metadata, filename, extension) => {
const lang = languageForFilepath(filename);
return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`;
},
);
// Appease the markdown linter
return msgText.replace(/```\n```/g, "```\n\n```");
}
export function toMarkDown(history: ChatMessage[], time?: Date): string {
if (!time) {
time = new Date();
}
let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${time.toLocaleString()}`;
for (const msg of history) {
let msgText = renderChatMessage(msg);
if (!msgText) {
continue; // Skip messages without content
}
if (msg.role === "user" && msgText.search("```") > -1) {
msgText = reformatCodeBlocks(msgText);
}
// format messages as blockquotes
msgText = msgText.replace(/^/gm, "> ");
content += `\n\n#### ${
msg.role === "user" ? "_User_" : "_Assistant_"
}\n\n${msgText}`;
}
return content;
}
export async function shareSession(
ide: IDE,
history: ChatMessage[],
outputDir?: string,
) {
const now = new Date();
const content = toMarkDown(history, now);
outputDir = outputDir ?? getContinueGlobalPath();
if (outputDir.startsWith("~")) {
outputDir = outputDir.replace(/^~/, homedir);
} else if (
outputDir.startsWith("./") ||
outputDir.startsWith(".\\") ||
outputDir === "."
) {
const workspaceDirs = await ide.getWorkspaceDirs();
// Although the most common situation is to have one directory open in a
// workspace it's also possible to have just a file open without an
// associated directory or to use multi-root workspaces in which multiple
// folders are included. We default to using the first item in the list, if
// it exists.
const workspaceDirectory = workspaceDirs?.[0] || "";
outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory));
}
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
const dtString = asBasicISOString(getOffsetDatetime(now));
const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming?
const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^
await ide.writeFile(fileUrl, content);
await ide.openFile(fileUrl);
return fileUrl;
}

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