Merge branch 'main' into feat/cometapi

This commit is contained in:
TensorNull 2025-09-24 10:26:16 +08:00 • committed by GitHub
commit bcd4981660
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
317 changed files with 13055 additions and 6984 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,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@8373ac24010df1110cd00512f925b63813362da1
uses: continuedev/continue/actions/detailed-review@12e933bf9d13736c5f47728c436445ef4127fd52
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@8373ac24010df1110cd00512f925b63813362da1
uses: continuedev/continue/actions/general-review@12e933bf9d13736c5f47728c436445ef4127fd52
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

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

@ -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>;

View file

@ -4,6 +4,7 @@ import {
ConfigResult,
ConfigValidationError,
isAssistantUnrolledNonNullable,
mergeConfigYamlRequestOptions,
mergeUnrolledAssistants,
ModelRole,
PackageIdentifier,
@ -24,7 +25,6 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
import { convertRuleBlockToSlashCommand } from "../../commands/slash/ruleBlockSlashCommand";
import { getControlPlaneEnvSync } from "../../control-plane/env";
import { PolicySingleton } from "../../control-plane/PolicySingleton";
import { getBaseToolDefinitions } from "../../tools";
@ -34,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;
@ -155,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[] = [];
@ -192,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
@ -211,22 +208,15 @@ async function configYamlToContinueConfig(options: {
for (const rule of config.rules ?? []) {
const convertedRule = convertYamlRuleToContinueRule(rule);
continueConfig.rules.push(convertedRule);
// Convert invokable rules to slash commands
if (convertedRule.invokable) {
try {
const slashCommand = convertRuleBlockToSlashCommand(convertedRule);
continueConfig.slashCommands?.push(slashCommand);
} catch (e) {
localErrors.push({
message: `Error converting invokable rule ${convertedRule.name} to slash command: ${e instanceof Error ? e.message : e}`,
fatal: false,
});
}
}
}
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,
@ -250,12 +240,6 @@ async function configYamlToContinueConfig(options: {
});
});
continueConfig.experimental = {
modelContextProtocolServers: config.mcpServers?.map(
convertYamlMcpToContinueMcp,
),
};
// Prompt files -
try {
const promptFiles = await getAllPromptFiles(ide, undefined, true);
@ -307,9 +291,7 @@ async function configYamlToContinueConfig(options: {
try {
const llms = await llmsFromModelConfig({
model,
ide,
uniqueId,
ideSettings,
llmLogger,
config: continueConfig,
});
@ -394,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();
@ -406,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,
@ -464,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

@ -16,7 +16,7 @@ export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
description: rule.description,
ruleFile: rule.sourceFile,
alwaysApply: rule.alwaysApply,
invokable: rule.invokable,
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[] = [];
@ -93,6 +94,7 @@ class MCPConnection {
return {
...this.options,
errors: this.errors,
infos: this.infos,
prompts: this.prompts,
resources: this.resources,
resourceTemplates: this.resourceTemplates,
@ -122,6 +124,7 @@ class MCPConnection {
this.resources = [];
this.resourceTemplates = [];
this.errors = [];
this.infos = [];
this.stdioOutput = { stdout: "", stderr: "" };
this.abortController.abort();
@ -280,6 +283,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

@ -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";
@ -77,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";
@ -231,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);
});
});
@ -313,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) => {
@ -325,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();
});
@ -728,20 +773,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) => {
@ -1201,6 +1239,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"))) ||
@ -1263,6 +1304,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;
}
@ -1348,6 +1392,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);

32
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[];
@ -1390,7 +1390,9 @@ export interface ApplyState {
autoFormattingDiff?: string;
}
export interface StreamDiffLinesPayload {
export type StreamDiffLinesType = "edit" | "apply";
interface StreamDiffLinesOptionsBase {
type: StreamDiffLinesType;
prefix: string;
highlighted: string;
suffix: string;
@ -1401,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;
@ -1796,7 +1811,8 @@ export type RuleSource =
| "rules-block"
| "colocated-markdown"
| "json-systemMessage"
| ".continuerules";
| ".continuerules"
| "agent-file";
export interface RuleWithSource {
name?: string;

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

@ -45,6 +45,7 @@ import {
const PROVIDER_HANDLES_TEMPLATING: string[] = [
"lmstudio",
"lemonade",
"openai",
"nvidia",
"ollama",
@ -67,6 +68,7 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [
const PROVIDER_SUPPORTS_IMAGES: string[] = [
"openai",
"ollama",
"lemonade",
"cohere",
"gemini",
"msty",

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

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

@ -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 {

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

@ -34,6 +34,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";
@ -84,6 +85,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) {

24
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",

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];

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",

View file

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

View file

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

@ -13,7 +13,7 @@ export const globSearchTool: Tool = {
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

@ -13,7 +13,7 @@ export const grepSearchTool: Tool = {
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

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

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

@ -31,4 +31,5 @@ export const readFileTool: Tool = {
exampleArgs: [["filepath", "path/to/the_file.txt"]],
},
defaultToolPolicy: "allowedWithoutPermission",
toolCallIcon: "DocumentIcon",
};

View file

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

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

@ -1,4 +1,5 @@
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.
@ -36,7 +37,7 @@ export const getConfigDependentToolDefinitions = (
);
}
if (modelName?.includes("claude") || modelName?.includes("gpt-5")) {
if (modelName && isRecommendedAgentModel(modelName)) {
tools.push(toolDefinitions.multiEditTool);
} else {
tools.push(toolDefinitions.editFileTool);

View file

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

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;
}

View file

@ -0,0 +1,59 @@
import { exec } from "node:child_process";
import { IDE } from "..";
export async function isLemonadeInstalled(): Promise<boolean> {
// On Windows, check if lemonade-server command exists
if (process.platform === "win32") {
return new Promise((resolve, _reject) => {
exec("where.exe lemonade-server", (error, _stdout, _stderr) => {
resolve(!error);
});
});
}
// On Linux, check if the health endpoint is accessible
try {
const response = await fetch("http://localhost:8000/api/v1/health", {
method: "GET",
signal: AbortSignal.timeout(3000), // 3 second timeout
});
if (response.ok) {
const data = await response.json();
return data.status === "ok";
}
return false;
} catch {
return false;
}
}
export async function startLocalLemonade(ide: IDE): Promise<any> {
let startCommand: string | undefined;
switch (process.platform) {
case "linux": // Linux
// On Linux, direct users to start Lemonade manually
return ide.showToast(
"info",
"Please start Lemonade manually. Visit https://lemonade-server.ai for instructions.",
);
case "win32": // Windows
startCommand = "lemonade-server serve\n";
break;
default:
return ide.showToast(
"error",
"Cannot start Lemonade: platform not supported!",
);
}
if (startCommand) {
return ide.runCommand(startCommand, {
reuseTerminal: true,
terminalName: "Start Lemonade",
});
}
}

View file

@ -19,116 +19,62 @@ You can add any built-in context-providers in your config file as shown below:
Reference any file in your current workspace.
- YAML
- JSON
config.yaml
```
context: - provider: file
```
config.json
```json
{ "contextProviders": [{ "name": "file" }] }
```
### @Code Context Provider – Reference Functions and Classes
Reference specific functions or classes from throughout your project.
- YAML
- JSON
config.yaml
```
context: - provider: code
```
config.json
```json
{ "contextProviders": [{ "name": "code" }] }
```
### @Git Diff Context Provider – Reference Branch Changes
Reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing.
- YAML
- JSON
config.yaml
```
context: - provider: diff
```
config.json
```json
{ "contextProviders": [{ "name": "diff" }] }
```
### @Current File Context Provider – Reference the Active File
Reference the currently open file.
- YAML
- JSON
config.yaml
```
context: - provider: currentFile
```
config.json
```json
{ "contextProviders": [{ "name": "currentFile" }] }
```
### @Terminal Context Provider – Reference Last Terminal Command and Output
Reference the last command you ran in your IDE's terminal and its output.
- YAML
- JSON
config.yaml
```
context: - provider: terminal
```
config.json
```json
{ "contextProviders": [{ "name": "terminal" }] }
```
### @Docs Context Provider – Reference Documentation Site Content
Reference the contents from any documentation site.
- YAML
- JSON
config.yaml
```
context: - provider: docs
```
config.json
```json
{ "contextProviders": [{ "name": "docs" }] }
```
Note that this will only enable the `@Docs` context provider.
To use it, you need to add a documentation site to your config file. See the [docs](/customize/overview#documentation-context) page for more information.
@ -137,9 +83,6 @@ To use it, you need to add a documentation site to your config file. See the [do
Reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files.
- YAML
- JSON
config.yaml
```
@ -149,21 +92,12 @@ context:
onlyPinned: true
```
config.json
```json
{ "contextProviders": [{ "name": "open", "params": { "onlyPinned": true } }] }
```
### @Web Context Provider – Reference Relevant Web Pages
Reference relevant pages from across the web, automatically determined from your input.
Optionally, set `n` to limit the number of results returned (default 6).
- YAML
- JSON
config.yaml
```
@ -173,19 +107,10 @@ context:
n: 5
```
config.json
```json
{ "contextProviders": [{ "name": "web", "params": { "n": 5 } }] }
```
### @Codebase Context Provider – Reference Relevant Codebase Snippets
Reference the most relevant snippets from your codebase.
- YAML
- JSON
config.yaml
```
@ -193,40 +118,22 @@ context:
- provider: codebase
```
config.json
```json
{ "contextProviders": [{ "name": "codebase" }] }
```
Read more about indexing and retrieval [here](/customize/overview#codebase-context).
### @Folder Context Provider – Reference Code from a Specific Folder
Uses the same retrieval mechanism as `@Codebase`, but only on a single folder.
- YAML
- JSON
config.yaml
```
context: - provider: folder
```
config.json
```json
{ "contextProviders": [{ "name": "folder" }] }
```
### @Search Context Provider – Reference Code Search Results
Reference the results of codebase search, just like the results you would get from VS Code search.
- YAML
- JSON
config.yaml
```
@ -236,21 +143,12 @@ context:
maxResults: 100 # optional, defaults to 200
```
config.json
```json
{ "contextProviders": [ { "name": "search", "params": { "maxResults": 100 // optional, defaults to 200 } } ]}
```
This context provider is powered by [ripgrep](https://github.com/BurntSushi/ripgrep).
### @Url Context Provider – Reference Content from a URL
Reference the markdown converted contents of a given URL.
- YAML
- JSON
config.yaml
```
@ -258,19 +156,10 @@ context:
- provider: url
```
config.json
```json
{ "contextProviders": [{ "name": "url" }] }
```
### @Clipboard Context Provider – Reference Clipboard Items
Reference recent clipboard items
- YAML
- JSON
config.yaml
```
@ -278,19 +167,10 @@ context:
- provider: clipboard
```
config.json
```json
{ "contextProviders": [{ "name": "clipboard" }] }
```
### @Tree Context Provider – Reference Workspace File Structure
Reference the structure of your current workspace.
- YAML
- JSON
config.yaml
```
@ -298,19 +178,10 @@ context:
- provider: tree
```
config.json
```json
{ "contextProviders": [{ "name": "tree" }] }
```
### @Problems Context Provider – Reference Problems in the Current File
Get Problems from the current file.
- YAML
- JSON
config.yaml
```
@ -318,19 +189,10 @@ context:
- provider: problems
```
config.json
```json
{ "contextProviders": [{ "name": "problems" }] }
```
### @Debugger Context Provider – Reference Debugger Local Variables
Reference the contents of the local variables in the debugger. Currently only available in VS Code.
- YAML
- JSON
config.yaml
```
@ -340,12 +202,6 @@ context:
stackDepth: 3
```
config.json
```json
{ "contextProviders": [{ "name": "debugger", "params": { "stackDepth": 3 } }] }
```
Uses the top _n_ levels (defaulting to 3) of the call stack for that thread.
### @Repository Map Context Provider – Reference Codebase Outline and Signatures
@ -354,9 +210,6 @@ Reference the outline of your codebase. By default, signatures are included alon
`includeSignatures` params can be set to false to exclude signatures. This could be necessary for large codebases and/or to reduce context size significantly. Signatures will not be included if indexing is disabled.
- YAML
- JSON
config.yaml
```
@ -366,12 +219,6 @@ context:
includeSignatures: false # default true
```
config.json
```json
{ "contextProviders": [ { "name": "repo-map", "params": { "includeSignatures": false // default true } } ]}
```
Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase.
In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repository map from.
@ -382,9 +229,6 @@ This context provider is inspired by [Aider's repository map](https://aider.chat
Reference the architecture and platform of your current operating system.
- YAML
- JSON
config.yaml
```
@ -392,19 +236,10 @@ context:
- provider: os
```
config.json
```json
{ "contextProviders": [{ "name": "os" }] }
```
### Using the Model Context Protocol (MCP) in Continue
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then set up your configuration like this:
- YAML
- JSON
config.yaml
```
@ -417,24 +252,6 @@ mcpServers:
- /Users/NAME/test.db
```
config.json
```json
{
"experimental": {
"modelContextProtocolServers": [
{
"transport": {
"type": "stdio",
"command": "uvx",
"args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
}
}
]
}
}
```
You'll then be able to type "@" and see "MCP" in the context providers dropdown.
### How to Request a New Context Provider in Continue

View file

@ -15,251 +15,95 @@ You can add any built-in context-providers in your config file as shown below:
Reference any file in your current workspace.
<Tabs>
<Tab title="YAML">
```yaml config.yaml
context:
- provider: file
```
</Tab>
<Tab title="JSON (Deprecated)">
```json config.json
{
"contextProviders": [
{
"name": "file"
}
]
}
```
</Tab>
</Tabs>
```yaml config.yaml
context:
- provider: file
```
### `@Code`
Reference specific functions or classes from throughout your project.
<Tabs>
<Tab title="YAML">
```yaml config.yaml
context:
- provider: code
```
</Tab>
<Tab title="JSON (Deprecated)">
```json config.json
{
"contextProviders": [
{
"name": "code"
}
]
}
```
</Tab>
</Tabs>
```yaml config.yaml
context:
- provider: code
```
### `@Git Diff`
Reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing.
<Tabs>
<Tab title="YAML">
```yaml config.yaml
context:
- provider: diff
```
</Tab>
<Tab title="JSON (Deprecated)">
```json config.json
{
"contextProviders": [
{
"name": "diff"
}
]
}
```
</Tab>
</Tabs>
```yaml config.yaml
context:
- provider: diff
```
### `@Current File`
Reference the currently open file.
<Tabs>
<Tab title="YAML">
```yaml config.yaml
context:
- provider: currentFile
```
</Tab>
<Tab title="JSON (Deprecated)">
```json config.json
{
"contextProviders": [
{
"name": "currentFile"
}
]
}
```
</Tab>
</Tabs>
```yaml config.yaml
context:
- provider: currentFile
```
### `@Terminal`
Reference the last command you ran in your IDE's terminal and its output.
<Tabs>
<Tab title="YAML">
```yaml config.yaml
context:
- provider: terminal
```
</Tab>
<Tab title="JSON (Deprecated)">
```json config.json
{
"contextProviders": [
{
"name": "terminal"
}
]
}
```
</Tab>
</Tabs>
```yaml config.yaml
context:
- provider: terminal
```
### `@Open`
Reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files.
<Tabs>
<Tab title="YAML">
```yaml config.yaml
context:
- provider: open
params:
onlyPinned: true
```
</Tab>
<Tab title="JSON (Deprecated)">
```json config.json
{
"contextProviders": [
{
"name": "open",
"params": {
"onlyPinned": true
}
}
]
}
```
</Tab>
</Tabs>
```yaml config.yaml
context:
- provider: open
params:
onlyPinned: true
```
### `@Clipboard`
Reference recent clipboard items
<Tabs>
<Tab title="YAML">
```yaml config.yaml
context:
- provider: clipboard
```
</Tab>
<Tab title="JSON (Deprecated)">
```json config.json
{
"contextProviders": [
{
"name": "clipboard"
}
]
}
```
</Tab>
</Tabs>
```yaml config.yaml
context:
- provider: clipboard
```
### `@Tree`
Reference the structure of your current workspace.
<Tabs>
<Tab title="YAML">
```yaml config.yaml
context:
- provider: tree
```
</Tab>
<Tab title="JSON (Deprecated)">
```json config.json
{
"contextProviders": [
{
"name": "tree"
}
]
}
```
</Tab>
</Tabs>
```yaml config.yaml
context:
- provider: tree
```
### `@Problems`
Get Problems from the current file.
<Tabs>
<Tab title="YAML">
```yaml config.yaml
context:
- provider: problems
```
</Tab>
<Tab title="JSON (Deprecated)">
```json config.json
{
"contextProviders": [
{
"name": "problems"
}
]
}
```
</Tab>
</Tabs>
```yaml config.yaml
context:
- provider: problems
```
### `@Debugger`
Reference the contents of the local variables in the debugger. Currently only available in VS Code.
<Tabs>
<Tab title="YAML">
```yaml config.yaml
context:
- provider: debugger
params:
stackDepth: 3
```
</Tab>
<Tab title="JSON (Deprecated)">
```json config.json
{
"contextProviders": [
{
"name": "debugger",
"params": {
"stackDepth": 3
}
}
]
}
```
</Tab>
</Tabs>
```yaml config.yaml
context:
- provider: debugger
params:
stackDepth: 3
```
Uses the top _n_ levels (defaulting to 3) of the call stack for that thread.
@ -269,30 +113,12 @@ Reference the outline of your codebase. By default, signatures are included alon
`includeSignatures` params can be set to false to exclude signatures. This could be necessary for large codebases and/or to reduce context size significantly. Signatures will not be included if indexing is disabled.
<Tabs>
<Tab title="YAML">
```yaml config.yaml
context:
- provider: repo-map
params:
includeSignatures: false # default true
```
</Tab>
<Tab title="JSON (Deprecated)">
```json config.json
{
"contextProviders": [
{
"name": "repo-map",
"params": {
"includeSignatures": false // default true
}
}
]
}
```
</Tab>
</Tabs>
```yaml config.yaml
context:
- provider: repo-map
params:
includeSignatures: false # default true
```
Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase.
@ -304,56 +130,23 @@ This context provider is inpsired by [Aider's repository map](https://aider.chat
Reference the architecture and platform of your current operating system.
<Tabs>
<Tab title="YAML">
```yaml config.yaml
context:
- provider: os
```
</Tab>
<Tab title="JSON (Deprecated)">
```json config.json
{
"contextProviders": [
{
"name": "os"
}
]
}
```
</Tab>
</Tabs>
```yaml config.yaml
context:
- provider: os
```
### `@HTTP`
The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems.
<Tabs>
<Tab title="YAML">
```yaml config.yaml
context:
- provider: http
params:
url: "https://api.example.com/v1/users"
headers:
- Authorization: "Bearer <token>"
```
</Tab>
<Tab title="JSON (Deprecated)">
```json config.json
{
"contextProviders": [
{
"name": "http",
"params": {
"url": "https://api.example.com/v1/users"
}
}
]
}
```
</Tab>
</Tabs>
```yaml config.yaml
context:
- provider: http
params:
url: "https://api.example.com/v1/users"
headers:
- Authorization: "Bearer <token>"
```
The receiving URL should expect to receive the following parameters:
@ -375,36 +168,15 @@ Response
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then set up your configuration like this:
<Tabs>
<Tab title="YAML">
```yaml config.yaml
mcpServers:
- name: My MCP Server
command: uvx
args:
- mcp-server-sqlite
- --db-path
- /Users/NAME/test.db
```
</Tab>
<Tab title="JSON (Deprecated)">
```json config.json
{
"experimental": {
"modelContextProtocolServers": [
{
"transport": {
"type": "stdio",
"command": "uvx",
"args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"]
}
}
]
}
}
```
</Tab>
</Tabs>
```yaml config.yaml
mcpServers:
- name: My MCP Server
command: uvx
args:
- mcp-server-sqlite
- --db-path
- /Users/NAME/test.db
```
You'll then be able to type "@" and see "MCP" in the context providers dropdown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 144 KiB

After

Width:  |  Height:  |  Size: 265 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

View file

@ -1,6 +1,6 @@
---
title: "SambaNova"
description: "Configure SambaNova Cloud with Continue to access their high-performance platform for running large AI models, including Llama 4 Scout with world record open source model performance"
description: "Configure SambaCloud with Continue to access their high-performance platform for running large AI models, including Llama 4 Scout with world record open source model performance"
---
The SambaNova Cloud is a cloud platform for running large AI models with the world record open source models performance. You can follow the instructions in [this blog post](https://sambanova.ai/blog/accelerating-coding-with-sambanova-cloud?ref=blog.continue.dev) to configure your setup.
@ -9,9 +9,9 @@ The SambaNova Cloud is a cloud platform for running large AI models with the wor
<Tab title="YAML">
```yaml title="config.yaml"
models:
- name: SambaNova Llama 4 Scout
- name: GPT OSS 120B
provider: sambanova
model: Llama-4-Scout-17B-16E-Instruct
model: gpt-oss-120b
apiKey: <YOUR_SAMBANOVA_API_KEY>
```
</Tab>
@ -20,9 +20,9 @@ The SambaNova Cloud is a cloud platform for running large AI models with the wor
{
"models": [
{
"title": "SambaNova Llama 4 Scout",
"title": "GPT OSS 120B",
"provider": "sambanova",
"model": "Llama-4-Scout-17B-16E-Instruct",
"model": "gpt-oss-120b",
"apiKey": "<YOUR_SAMBANOVA_API_KEY>"
}
]

View file

@ -0,0 +1,81 @@
---
title: "Lemonade Server"
description: "Configure Lemonade Server with Continue for refreshingly fast local LLM inference on GPUs and NPUs"
---
<Info>
Get started with [Lemonade Server](https://lemonade-server.ai/) - Refreshingly fast LLMs on GPUs and NPUs with seamless Continue integration
</Info>
## Overview
Lemonade Server provides optimized local LLM inference with support for GPU and NPU hardware acceleration. It offers an OpenAI-compatible API that seamlessly integrates with Continue and other open-source platforms.
## Installation
Download and install Lemonade Server from [lemonade-server.ai](https://lemonade-server.ai/).
## Configuration
Lemonade Server is available directly in the Continue UI as a provider. You can select it from the model provider dropdown without manual configuration.
### Option 1: Using the Continue UI (Recommended)
1. Click on the model selector dropdown in Continue
2. Select "Add Model"
3. Choose "Lemonade Server" from the provider list
4. Continue will automatically configure the connection
### Option 2: Manual Configuration
If you need custom settings, you can manually configure Lemonade:
<Tabs>
<Tab title="YAML">
```yaml title="config.yaml"
models:
- name: Lemonade
provider: lemonade
model: <MODEL_NAME>
apiBase: http://localhost:8000/api/v1/
```
</Tab>
<Tab title="JSON (Deprecated)">
```json title="config.json"
{
"models": [
{
"title": "Lemonade",
"provider": "lemonade",
"model": "<MODEL_NAME>",
"apiBase": "http://localhost:8000/api/v1/"
}
]
}
```
</Tab>
</Tabs>
## Getting Started
1. **Install Lemonade Server**: Download from [lemonade-server.ai](https://lemonade-server.ai/)
2. **Start the server**: Launch Lemonade Server (runs on `http://localhost:8000/api/v1/` by default)
3. **Add to Continue**: Select Lemonade Server from the model provider dropdown in Continue
4. **Load a model**: Choose your preferred model through the interface
## Hardware Support
Lemonade Server automatically detects and optimizes for available hardware:
- **NPU**: Neural Processing Unit acceleration for efficient inference
- **GPU**: Full GPU acceleration support
- **CPU**: Optimized CPU fallback when accelerators are unavailable
## Key Features
- OpenAI-compatible API for seamless integration
- Support for popular model formats
- Automatic hardware detection and optimization
- Integration with Continue, Open WebUI, Gaia, and AnythingLLM
- Active open-source community
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Lemonade.ts)

View file

@ -3,81 +3,250 @@ title: "Tetrate Agent Router Service"
sidebarTitle: "Tetrate Agent Router Service"
slug: ../tetrate-agent-router-service
---
The **Tetrate Agent Router Service** provides a unified Gateway for accessing various AI models with fast inference capabilities as well as embedding services.
The **Tetrate Agent Router Service** provides a unified Gateway for accessing various AI models with fast inference capabilities.
This gateway acts as an intelligent router that can distribute requests across multiple model providers, offering enterprise-grade reliability and performance optimization.
## Getting Started
<Tip>
Want to get started quickly? Sign up for the [Tetrate Agent Router Service](https://router.tetrate.ai/) to get an API key, then use [Tetrate on Continue Hub](https://hub.continue.dev/tetrate) to get started fast.
</Tip>
1. Obtain an API key from the [Agent Router Service portal](https://api.router.tetrate.ai/)
2. Configure Continue to use Agent Router Service as your model provider
## Setup
## Configuring Models
<Steps>
<Step title="Sign in or sign up">
Visit the [Agent Router Service portal](https://router.tetrate.ai/) and create an account to get your API key
<img src="../assets/tetrate-sign-in.png" alt="Tetrate sign in page" style={{width: '250px', maxWidth: '100%'}} />
</Step>
You can also quickly use models from Tetrate on the Cotninue Hub by visiting Tetrate on the Continue Hub [here](https://hub.continue.dev/tetrate). The easiest way if you don't see the model you want to use is to remix one of the models on the Tetrate page and change the model to the one you want to use.
<Step title="Get your API key">
Go to the [API keys page](https://router.tetrate.ai/api-keys) to get your key
<img src="../assets/tetrate-get-api-key.png" alt="Tetrate get API key" style={{width: '250px', maxWidth: '100%'}} />
</Step>
<Step title="Configure Continue">
- Choose a configuration method below.
- If you use the Continue VS Code extension, install version `>=1.2.3`.
</Step>
</Steps>
### Quickstart with Continue Hub
Fastest way: use preconfigured models from Tetrate on Continue Hub
<Steps>
<Step title="Browse models">
Open [Tetrate on Continue Hub](https://hub.continue.dev/tetrate) and pick a model (e.g., [Claude Sonnet 4](https://hub.continue.dev/tetrate/claude-sonnet-4))
</Step>
<Step title="Use or remix">
Click "Use Model", or "Remix" to change the model ID if needed
</Step>
<Step title="Add your API key">
Add your API key to Continue. See [adding secrets in Continue Hub](/hub/secrets/secret-types) and [managing local secrets in the FAQ](/faqs#managing-local-secrets-and-environment-variables)
<Tip>
Add it as a Continue Hub secret named `TETRATE_API_KEY` to reuse across projects.
</Tip>
</Step>
</Steps>
![Remix a model from Tetrate on Continue Hub](../assets/tetrate-remix.png)
### Available Models
<Info>
If a model is missing, remix a similar one and set the `model` field to the target ID.
</Info>
Agent Router Service supports routing to various models.
Go to the [Agent Router Service model catalog](https://router.tetrate.ai/models) for a full list of supported models.
### Configuration Methods
## Configuration Options
<CardGroup cols={1}>
<Card title="In Local Agent Configuration" icon="folder" vertical>
Use a Tetrate model block from the Hub or define it directly in your local agent configuration.
</Card>
<Card title="Continue Hub" icon="cloud" vertical>
Use a Tetrate model block from the Hub or define your own on the Hub.
</Card>
<Card title="Using Local Model Blocks" icon="file-lines" vertical>
Create a local model block for reuse across agents without publishing it to the Hub.
</Card>
</CardGroup>
As Agent Router Service is an OpenAI API compatible provider, you can configure it like any other OpenAI API compatible provider. Therefore you will be setting `provider: openai` and `apiBase: https://api.router.tetrate.ai/v1`.
Update your Continue configuration file (`~/.continue/config.yaml`) with your Agent Router Service API key:
### Configuration Examples
<Info>
**Click a tab** to see an example.
</Info>
<Tabs>
<Tab title="In Local Agent Configuration">
### On your local machine
**When to use**: Simple local setups (like using the VS Code extension) when you don't need shared or published blocks.
#### In your config.yaml
Use a Tetrate model block from the Hub in your local agent configuration:
```yaml title="config.yaml"
```yaml title="~/.continue/config.yaml"
name: Local Agent
version: 1.0.0
schema: v1
models:
- name: <MODEL_NAME>
provider: openai
model: <MODEL_ID>
apiKey: <TETRATE_API_KEY>
apiBase: https://api.router.tetrate.ai/v1
- uses: tetrate/claude-sonnet-4
with:
TETRATE_API_KEY: ${{ secrets.TETRATE_API_KEY }}
context:
- provider: code
- provider: docs
- provider: diff
- provider: terminal
- provider: problems
- provider: folder
- provider: codebase
```
#### As a local model block
Or define the model directly:
Review the configuration reference for [model blocks](/reference#models) and using [local blocks](/reference#local-blocks). Ensure you look at the roles and capabilities section and review the [model capabilities guide](/customize/deep-dives/model-capabilities).
```yaml title="~/.continue/config.yaml"
name: Local Agent
version: 1.0.0
schema: v1
models:
- name: Claude Sonnet 4
provider: tars
model: claude-4-sonnet-20250514
apiKey: ${{ secrets.TETRATE_API_KEY }}
roles:
- chat
- edit
- apply
capabilities:
- tool_use
context:
- provider: code
- provider: docs
- provider: diff
- provider: terminal
- provider: problems
- provider: folder
- provider: codebase
```
</Tab>
<Tab title="Continue Hub">
**When to use**: Share configurations across teams or contribute to the community.
```yaml title="model_name.yaml"
name: <MODEL_NAME>
models:
- name: <MODEL_NAME>
provider: openai
model: <MODEL_ID>
apiKey: ${{ inputs.TETRATE_API_KEY }}
apiBase: https://api.router.tetrate.ai/v1
roles:
- chat
- edit
- apply
capabilities:
- tool_use
**The Model Block:**
```yaml title="tetrate/claude-sonnet-4"
name: Claude Sonnet 4
version: 1.0.14
schema: v1
models:
- name: Claude Sonnet 4 - Tetrate
provider: tars
model: claude-4-sonnet-20250514
apiKey: ${{ inputs.TETRATE_API_KEY }}
roles:
- chat
- edit
- apply
capabilities:
- tool_use
```
View the model block `tetrate/claude-sonnet-4` on the [Continue Hub](https://hub.continue.dev/tetrate/claude-sonnet-4).
**Reference it in your Agent configuration:**
```yaml title="my-agent"
name: My Agent
version: 1.0.0
schema: v1
models:
- uses: tetrate/claude-sonnet-4
with:
TETRATE_API_KEY: ${{ secrets.TETRATE_API_KEY }}
context:
- uses: continuedev/diff-context
- uses: continuedev/terminal-context
- uses: continuedev/file-context
```
<Tip>
To customize, see the [model block creation guide](/hub/blocks/create-a-block).
</Tip>
</Tab>
<Tab title="Using Local Model Blocks">
**When to use**: Reuse configurations across agents and keep them local or in GitHub (not on Continue Hub).
**The Local Model Block:**
<Info>
Name the file `my-claude-4-model.yaml` so you can reference it in the Agent.
</Info>
```yaml title="~/.continue/models/my-claude-4-model.yaml"
name: Claude Sonnet 4
version: 1.0.1
schema: v1
models:
- name: Claude Sonnet 4
provider: tars
model: claude-4-sonnet-20250514
apiKey: ${{ inputs.TETRATE_API_KEY }}
roles:
- chat
- edit
- apply
capabilities:
- tool_use
```
Reference it as `my-claude-4-model` in your Agent configuration:
```yaml title="~/.continue/agents/simple-agent.yaml"
name: Simple Agent
version: 1.0.0
schema: v1
models:
- uses: my-claude-4-model
with:
TETRATE_API_KEY: ${{ secrets.TETRATE_API_KEY }}
context:
- uses: continuedev/diff-context
- uses: continuedev/terminal-context
- uses: continuedev/file-context
```
### On Model Block on Continue Hub
Learn how to use model blocks on Continue Hub [here](/hub/blocks/create-a-block).
<Tip>
Learn more about [model blocks](/reference#models) and [local blocks](/reference#local-blocks).
</Tip>
```yaml title="model_name.yaml"
name: <MODEL_NAME>
models:
- name: <MODEL_NAME>
provider: openai
model: <MODEL_ID>
apiKey: ${{ inputs.TETRATE_API_KEY }}
apiBase: https://api.router.tetrate.ai/v1
roles:
- chat
- edit
- apply
capabilities:
- tool_use
```
</Tab>
</Tabs>
---
## Troubleshooting Common Issues
<CardGroup cols={2}>
<Card title="Invalid API key" icon="key" vertical>
Verify your API key is active and has no extra spaces.
</Card>
<Card title="Model not found" icon="ban" href="https://router.tetrate.ai/models" vertical>
Confirm the model ID matches the Tetrate catalog.
</Card>
<Card title="Slow responses" icon="code" vertical>
Check your network or try a less-loaded model. Contact Tetrate support if issues persist.
</Card>
<Card title="Configuration not loading" icon="file-lines" vertical>
Validate YAML syntax and review error messages in Continue. If using Hub, ensure the block is published.
</Card>
</CardGroup>
---
## Join the Community
Connect with Tetrate and other builders for help and discussion.
<CardGroup cols={1}>
<Card title="Join the Tetrate Community" icon="slack" href="https://join.slack.com/t/tetrate-agent-router/shared_invite/zt-399tv7hjm-6YMXztGywTOQrMIolvEBNg">
Get answers, insights, and best practices for secure, scalable infrastructure
</Card>
</CardGroup>

View file

@ -36,20 +36,6 @@ Our current top recommendations are Claude Opus 4.1 and Claude Sonnet 4 from [An
apiKey: <YOUR_ANTHROPIC_API_KEY>
```
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"models": [
{
"title": "Claude Opus 4.1",
"provider": "anthropic",
"model": "claude-4-1-opus",
"apiKey": "<YOUR_ANTHROPIC_API_KEY>"
}
]
}
```
</Tab>
</Tabs>
### Gemma from Google DeepMind
@ -88,37 +74,6 @@ If you prefer to use an open-weight model, then the Gemma family of Models from
</Tab>
</Tabs>
</Tab>
<Tab title="JSON">
<Tabs>
<Tab title="Ollama">
```json title="config.json"
{
"models": [
{
"title": "Gemma 3 27B",
"provider": "ollama",
"model": "gemma3:27b"
}
]
}
```
</Tab>
<Tab title="Together">
```json title="config.json"
{
"models": [
{
"title": "Gemma 3 27B",
"provider": "together",
"model": "google/gemma-2-27b-it",
"apiKey": "<YOUR_TOGETHER_API_KEY>"
}
]
}
```
</Tab>
</Tabs>
</Tab>
</Tabs>
### GPT-4o from OpenAI
@ -138,20 +93,6 @@ If you prefer to use a model from [OpenAI](../model-providers/top-level/openai),
apiKey: <YOUR_OPENAI_API_KEY>
```
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"models": [
{
"title": "GPT-4o",
"provider": "openai",
"model": "",
"apiKey": "<YOUR_OPENAI_API_KEY>"
}
]
}
```
</Tab>
</Tabs>
### Grok-2 from xAI
@ -171,20 +112,6 @@ If you prefer to use a model from [xAI](../model-providers/more/xAI), then we re
apiKey: <YOUR_XAI_API_KEY>
```
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"models": [
{
"title": "Grok-2",
"provider": "xAI",
"model": "grok-2-latest",
"apiKey": "<YOUR_XAI_API_KEY>"
}
]
}
```
</Tab>
</Tabs>
### Gemini 2.0 Flash from Google
@ -204,20 +131,6 @@ If you prefer to use a model from [Google](../model-providers/top-level/gemini),
apiKey: <YOUR_GEMINI_API_KEY>
```
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"models": [
{
"title": "Gemini 2.0 Flash",
"provider": "gemini",
"model": "gemini-2.0-flash",
"apiKey": "<YOUR_GEMINI_API_KEY>"
}
]
}
```
</Tab>
</Tabs>
## Local, offline experience
@ -268,49 +181,6 @@ If your local machine can run an 8B parameter model, then we recommend running L
</Tab>
</Tabs>
</Tab>
<Tab title="JSON">
<Tabs>
<Tab title="Ollama">
```json title="config.json"
{
"models": [
{
"title": "Llama 3.1 8B",
"provider": "ollama",
"model": "llama3.1:8b"
}
]
}
```
</Tab>
<Tab title="LM Studio">
```json title="config.json"
{
"models": [
{
"title": "Llama 3.1 8B",
"provider": "lmstudio",
"model": "llama3.1-8b"
}
]
}
```
</Tab>
<Tab title="Msty">
```json title="config.json"
{
"models": [
{
"title": "Llama 3.1 8B",
"provider": "msty",
"model": "llama3.1-8b"
}
]
}
```
</Tab>
</Tabs>
</Tab>
</Tabs>
### DeepSeek Coder 2 16B
@ -357,50 +227,6 @@ If your local machine can run a 16B parameter model, then we recommend running D
</Tab>
</Tabs>
</Tab>
<Tab title="JSON">
<Tabs>
<Tab title="Ollama">
```json title="config.json"
{
"models": [
{
"title": "DeepSeek Coder 2 16B",
"provider": "ollama",
"model": "deepseek-coder-v2:16b",
"apiBase": "http://localhost:11434"
}
]
}
```
</Tab>
<Tab title="LM Studio">
```json title="config.json"
{
"models": [
{
"title": "DeepSeek Coder 2 16B",
"provider": "lmstudio",
"model": "deepseek-coder-v2:16b"
}
]
}
```
</Tab>
<Tab title="Msty">
```json title="config.json"
{
"models": [
{
"title": "DeepSeek Coder 2 16B",
"provider": "msty",
"model": "deepseek-coder-v2:16b"
}
]
}
```
</Tab>
</Tabs>
</Tab>
</Tabs>
## Other experiences

View file

@ -10,38 +10,15 @@ It's often useful to select a different model to respond to Edit prompts than fo
In Continue, you can add `edit` to a model's roles to specify that it can be used for Edit requests. If no edit models are specified, the selected `chat` model is used.
<Tabs>
<Tab title="YAML">
Use model roles.
```yaml title="config.yaml"
models:
- name: Claude 3.5 Sonnet
provider: anthropic
model: claude-3-5-sonnet-latest
apiKey: <YOUR_ANTHROPIC_API_KEY>
roles:
- edit
```
</Tab>
<Tab title="JSON">
Set the `experimental.modelRoles.inlineEdit` property in `config.json`.
```json title="config.json"
{
"models": {
"name": "Claude 3.5 Sonnet",
"provider": "anthropic",
"model": "claude-3-5-sonnet-latest",
"apiKey": "<YOUR_ANTHROPIC_API_KEY>"
},
"experimental": {
"modelRoles": {
"inlineEdit": "Claude 3.5 Sonnet",
}
}
}
```
</Tab>
</Tabs>
```yaml title="config.yaml"
models:
- name: Claude 4 Sonnet
provider: anthropic
model: claude-3-5-sonnet-latest
apiKey: <YOUR_ANTHROPIC_API_KEY>
roles:
- edit
```
Explore edit models in [the hub](https://hub.continue.dev/explore/models?roles=edit). Generally, our recommendations for Edit overlap with recommendations for Chat.

View file

@ -23,7 +23,10 @@ Voyage AI offers the best reranking model for code with their `rerank-2` model.
<Tabs>
<Tab title="Hub">
[Voyage Rerank 2 Block](https://hub.continue.dev/voyageai/rerank-2)
```yaml title="config.yaml"
models:
- uses: voyageai/rerank-2
```
</Tab>
<Tab title="YAML">
```yaml title="config.yaml"
@ -36,19 +39,6 @@ Voyage AI offers the best reranking model for code with their `rerank-2` model.
- rerank
```
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"reranker": {
"name": "voyage",
"params": {
"model": "rerank-2",
"apiKey": "<YOUR_VOYAGE_API_KEY>"
}
}
}
```
</Tab>
</Tabs>
### Cohere
@ -71,19 +61,6 @@ See Cohere's documentation for rerankers [here](https://docs.cohere.com/docs/rer
- rerank
```
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"reranker": {
"name": "cohere",
"params": {
"model": "rerank-english-v3.0",
"apiKey": "<YOUR_COHERE_API_KEY>"
}
}
}
```
</Tab>
</Tabs>
### LLM
@ -105,21 +82,9 @@ If you only have access to a single LLM, then you can use it as a reranker. This
- rerank
```
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"reranker": {
"name": "llm",
"params": {
"modelTitle": "My Model Title"
}
}
}
```
</Tab>
</Tabs>
The `"modelTitle"` field must match one of the models in your "models" array in config.json.
### Text Embeddings Inference
@ -142,17 +107,4 @@ The `"modelTitle"` field must match one of the models in your "models" array in
- rerank
```
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"reranker": {
"name": "huggingface-tei",
"params": {
"apiBase": "http://localhost:8080",
"apiKey": "<YOUR_TEI_API_KEY>"
}
}
}
```
</Tab>
</Tabs>

View file

@ -233,7 +233,7 @@
"guides/codebase-documentation-awareness",
"guides/cli",
"guides/continuous-ai",
"guides/posthog-github-continuous-ai",
"guides/snyk-mcp-continue-cookbook",
"guides/continuous-ai-readiness-assessment",
"guides/plan-mode-guide",
"guides/ollama-guide",
@ -242,6 +242,14 @@
"guides/custom-code-rag",
"guides/how-to-self-host-a-model"
]
},
{
"group": "Cookbooks",
"icon": "book-open-cover",
"pages": [
"guides/posthog-github-continuous-ai",
"guides/netlify-mcp-continuous-deployment"
]
}
]
},
@ -355,10 +363,6 @@
"source": "/hub/blocks",
"destination": "/hub/blocks/intro"
},
{
"source": "/hub/agents/intro",
"destination": "/hub/agents/intro"
},
{
"source": "/customize",
"destination": "/customization/overview"

View file

@ -87,6 +87,12 @@ cn --ask Bash(curl*)
cn --exclude Fetch
```
## API Key Authentication
For automation in CI or other headless environments, you can use an API key to authenticate with Continue. First, obtain your personal API key [here](https://hub.continue.dev/settings/api-keys). Then, set it as the `CONTINUE_API_KEY` environment variable. You can now use `cn -p` (headless mode) without needing to log in.
If you wish to run an automation on behalf of your organization you can obtain an organization-scoped API key by going to [your organization's settings](https://hub.continue.dev/settings/organizations) -> API Keys.
## Troubleshooting
Run `cn` with the `--verbose` flag to see more detailed logs. These will be output to `~/.continue/logs/cn.log`.

View file

@ -9,7 +9,7 @@ description: "Learn how to run Instinct, Continue's leading open Next Edit model
[HuggingFace model card](https://huggingface.co/continuedev/instinct).
</Warning>
We recently released Instinct, a state-of-the-art open Next Edit model. Robustly fine-tuned from Qwen2.5-Coder-7B, Instinct intelligently predicts your next move to keep you in flow. To learn more about the model, check out [our blog post](https://blog.continue.dev).
We recently released Instinct, a state-of-the-art open Next Edit model. Robustly fine-tuned from Qwen2.5-Coder-7B, Instinct intelligently predicts your next move to keep you in flow. To learn more about the model, check out [our blog post](https://blog.continue.dev/instinct/).
<Frame>
<img src="/images/instinct.gif" />
@ -17,7 +17,7 @@ We recently released Instinct, a state-of-the-art open Next Edit model. Robustly
### 1. Install Ollama
If you haven't already installed Ollama, see our guide [here](./ollama-guide.mdx).
If you haven't already installed Ollama, see our guide [here](./ollama-guide).
### 2. Download Instinct

View file

@ -0,0 +1,614 @@
---
title: "Netlify Performance Optimization Cookbook"
description: "Optimize web performance with A/B testing, automated monitoring, and data-driven improvements using Netlify MCP and Continue."
sidebarTitle: "Using Netlify MCP for Performance Optimization"
---
<Card title="Ship Faster Code, Not Slower Sites" icon="gauge-high">
Use AI to automatically monitor performance metrics, run A/B tests between
branches, and get actionable optimization suggestions based on real user data
from Netlify Analytics
</Card>
<Info>
**Did You Know?** Netlify is more than just static hosting! It offers:
- [Split Testing](https://docs.netlify.com/site-deploys/split-testing/) for A/B testing branches
- [Analytics](https://docs.netlify.com/analytics/get-started/) with Core Web Vitals tracking
- [Edge Functions](https://docs.netlify.com/edge-functions/overview/) for personalization at the edge
- [Build Plugins](https://docs.netlify.com/integrations/build-plugins/) ecosystem with 100+ integrations
- [Forms](https://docs.netlify.com/forms/setup/) with built-in spam protection
- [Identity](https://docs.netlify.com/visitor-access/identity/) for user authentication
- [Large Media](https://docs.netlify.com/large-media/overview/) for Git LFS support
This guide shows you how to leverage these features through natural language with Continue CLI!
</Info>
## What You'll Learn
This cookbook teaches you to:
- Run [A/B tests](https://docs.netlify.com/site-deploys/split-testing/) between branches to measure performance impact
- Monitor [Core Web Vitals](https://docs.netlify.com/analytics/get-started/#core-web-vitals) and build performance metrics
- Automatically block deploys that degrade performance using [Deploy Contexts](https://docs.netlify.com/site-deploys/overview/#deploy-contexts)
- Optimize build times with [Build Plugins](https://docs.netlify.com/integrations/build-plugins/) and bundle sizes with AI assistance
## Prerequisites
- GitHub repository with a web project
- [Netlify account](https://netlify.com) (free tier works)
- Node.js 22+ installed (required for Netlify)
- [Continue CLI](https://docs.continue.dev/guides/cli) (`npm i -g @continuedev/cli`)
- [Netlify MCP](https://hub.continue.dev/netlify/netlify-mcp) configured
- [Netlify Development Rules](https://hub.continue.dev/netlify/netlify-development) (recommended)
## Quick Setup
<Steps>
<Step title="Install Continue CLI">
```bash
npm i -g @continuedev/cli
```
</Step>
<Step title="Configure Netlify MCP">
1. Install Netlify CLI: `npm i -g netlify-cli` 2. Authenticate with Netlify:
`netlify login` 3. Visit [Netlify MCP on Continue
Hub](https://hub.continue.dev/netlify/netlify-mcp) 4. Follow the configuration
instructions for your editor
</Step>
<Step title="Add Development Rules">
Install the [Netlify Development Rules](https://hub.continue.dev/netlify/netlify-development) bundle for best practices:
1. Visit the bundle page on Continue Hub
2. Click **"Install Rules"**
3. Rules automatically apply to your agent
</Step>
<Step title="Verify Setup">
Test the connection with cn CLI:
```bash
cn
# Then in TUI mode:
"Check my Netlify auth and list sites"
```
</Step>
</Steps>
<Info>
The Netlify Development Rules bundle includes guardrails for: - Proper
`.gitignore` configuration - Function structure and placement - Edge function
constraints - Local development best practices
</Info>
## Performance Optimization Steps
### Step 1: Baseline Performance Metrics
Establish your current performance baseline using cn CLI:
```bash
# Start cn in TUI mode
cn
# Then ask:
"Show my site's Core Web Vitals and build times"
```
<Tip>
**Test in Plan Mode First**: Before making performance optimizations that
might affect your site, test your prompts in plan mode (see the [Plan Mode
Guide](/guides/plan-mode-guide); press **Shift+Tab** to switch modes). This
shows you what the agent will do without executing it. For example: `"Set up
A/B testing between main and feature branch with performance monitoring"`
</Tip>
<Info>
Netlify automatically tracks:
- **Build Performance**: Compile times, cache
hits
- **Runtime Performance**: Core Web Vitals, Time to Interactive
- **Resource Usage**: Bandwidth, function execution times
</Info>
### Step 2: A/B Test Branch Performance
Compare performance between branches:
```bash
# In cn TUI mode:
"Set up A/B test between main and feature branch on Netlify:
- Split traffic 50/50 between branches
- Track Core Web Vitals for each variant
- Monitor conversion metrics and bounce rate
- Enable analytics to measure performance impact
- Configure cookie-based visitor persistence
- Set test duration for 1000 unique visitors
- Auto-conclude test when statistical significance reached
Report winner based on performance + conversion metrics"
```
<Info>
**Enhanced Analytics**: Combine Netlify's A/B testing with PostHog session
recordings to understand not just which variant performs better, but why users
behave differently. See our [PostHog session analysis
guide](/guides/posthog-github-continuous-ai) to set up session tracking and
create a complete continuous AI analytics workflow.
</Info>
### Step 3: Advanced Build Optimization with Netlify
Leverage Netlify's powerful build features to dramatically reduce build times:
```bash
# In cn TUI mode:
"Optimize my Netlify build performance using these features:
1. Enable Netlify Cache Plugin for dependency caching
- Configure @netlify/plugin-cache for node_modules
- Set up custom cache directories for .next/cache or .nuxt
- Enable Gatsby's incremental builds if applicable
2. Set up Build Plugins from Netlify's ecosystem:
- Install @netlify/plugin-lighthouse for performance monitoring
- Add netlify-plugin-checklinks to prevent broken links
- Configure netlify-plugin-submit-sitemap for SEO
3. Implement Conditional Builds:
- Skip builds when only docs change (ignore: /docs/**)
- Use build.ignore script for custom logic
- Set up monorepo-specific build triggers
4. Configure concurrent builds for monorepos
- Set base directory per package
- Use pnpm workspaces or yarn workspaces
Show me the netlify.toml configuration and explain each optimization"
```
<Info>
**Netlify Build Features You're Getting**:
- [Build Caching](https://docs.netlify.com/configure-builds/build-caching/) - Persist dependencies between builds
- [Build Plugins](https://docs.netlify.com/integrations/build-plugins/) - Extend build process with 100+ plugins
- [Conditional Builds](https://docs.netlify.com/configure-builds/ignore-builds/) - Skip unnecessary builds
- [Monorepo Support](https://docs.netlify.com/configure-builds/monorepos/) - Optimize multi-package repos
These features can reduce build times by 50-70% for most projects!
</Info>
<Tip>
**Discover more optimization prompts!** The Netlify community has documented dozens of build optimization strategies in their [Support Guide: How can I optimize my Netlify build time](https://answers.netlify.com/t/support-guide-how-can-i-optimize-my-netlify-build-time/3907).
Use this guide as inspiration for cn CLI prompts not covered in this cookbook, such as:
- `"Configure my builds to skip Dependabot PRs automatically"`
- `"Set up custom ignore patterns for documentation-only changes"`
- `"Optimize my Contentful webhooks to prevent duplicate builds"`
- `"Show me how to use build hooks instead of automatic git triggers"`
- `"Help me choose between Astro and Hugo based on build performance"`
The community guide contains real-world scenarios that you can turn into AI-assisted solutions - just describe what you want to achieve and let cn CLI handle the implementation!
</Tip>
### Step 4: Bundle Analysis with Netlify's Built-in Tools
Use Netlify's bundle analyzer and optimization features:
```bash
# In cn TUI mode:
"Analyze and optimize my bundle using Netlify's tools:
1. Enable Netlify Bundle Analyzer:
- Add @netlify/plugin-bundle-analyzer to plugins
- Configure size thresholds in netlify.toml
- Generate visual bundle reports
2. Set up Asset Optimization:
- Enable automatic JS minification
- Configure CSS optimization
- Turn on HTML minification
- Set up image processing pipeline
3. Implement Smart Code Splitting:
- Analyze current chunks with the bundle analyzer
- Identify components over 50KB for splitting
- Configure webpack/vite for optimal chunking
- Set up route-based code splitting
4. Configure Netlify's CDN for optimal delivery:
- Set cache headers for static assets
- Enable Brotli compression
- Configure edge caching rules
Generate a full report with before/after bundle sizes"
```
<Card title="Netlify's Performance Arsenal" icon="rocket">
**Features Available Through Netlify MCP**:
- [Bundle
Analyzer](https://docs.netlify.com/configure-builds/build-plugins/bundle-analyzer/): Visualize your JavaScript bundles
- [Asset
Optimization](https://docs.netlify.com/configure-builds/post-processing/):
Automatic minification and compression
- [Edge
Network](https://docs.netlify.com/platform/edge-network/): Global CDN with
smart caching
- [Deploy
Previews](https://docs.netlify.com/site-deploys/deploy-previews/): Test
optimizations before production
</Card>
### Step 5: Image Optimization
Optimize images for better performance:
```bash
# In cn TUI mode:
"Set up Cloudinary image optimization for my Netlify site:
- Install @cloudinary/netlify-plugin via MCP
- Auto-convert images to WebP with fallbacks
- Generate responsive sizes (320w, 640w, 1024w, 1920w)
- Add lazy loading for all images
- Configure blur-up placeholders
- Update netlify.toml with Cloudinary settings
Target: Reduce image payload by 60-80% and improve LCP"
```
## Continuous Performance Monitoring
### Step 6: Performance Budget Enforcement with Lighthouse CI
Set and enforce performance budgets with automated testing:
```bash
# In cn TUI mode:
"Set up Lighthouse CI with performance budgets for my Netlify site:
Requirements:
- LCP must be < 2.5 seconds
- JavaScript bundle must be < 200KB
- Total size < 500KB
- Performance score >= 90
Setup needed:
1. Install @lhci/cli and @netlify/plugin-lighthouse
2. Create lighthouserc.js with these budget assertions
3. Configure netlify.toml to run checks on all deploys
4. Add GitHub status checks to block PRs that exceed budgets
5. Create performance dashboard at /lighthouse-reports
Please configure the complete Lighthouse CI setup with these budgets."
```
<Tip>
This comprehensive setup will automatically test every deploy preview and
production deployment, blocking any changes that violate your performance
budgets.
</Tip>
### Step 7: Real User Monitoring with Netlify Analytics
Leverage Netlify's built-in analytics and integrate advanced RUM solutions:
```bash
# In cn TUI mode:
"Set up comprehensive Real User Monitoring for my Netlify site:
1. Configure Netlify Analytics Pro (requires Pro account):
- Set up server-side analytics (no JS required)
- Track Core Web Vitals (LCP, FID, CLS, INP)
- Monitor top pages by performance score
- Create custom performance alerts
- Configure weekly performance reports
2. Integrate Web Vitals tracking:
- Install web-vitals library for detailed metrics
- Send metrics to Netlify Functions endpoint
- Store performance data in Netlify Blobs
- Create performance dashboard at /metrics
3. Set up Performance Alerts:
- Alert when P75 LCP > 3 seconds
- Notify if CLS increases by 20%
- Monitor JavaScript error rates
- Track 404s and broken resources
- Send alerts to Slack via Netlify Functions
4. Configure Geographic Performance Monitoring:
- Use Netlify Edge Functions to track region-specific metrics
- Identify slow regions with Edge geo data
- Compare performance across CDN nodes
- Optimize edge caching for slow regions
5. Create Custom Performance Dashboard:
- Build dashboard page using Netlify Functions
- Display real-time Core Web Vitals
- Show performance trends over time
- Include browser and device breakdowns
Show me the complete implementation with all code and configurations"
```
<Warning>
**Note**: Netlify Analytics Pro requires a paid Netlify Pro account ($19/month
per site). The prompt above assumes you have this plan. For free tier users,
focus on steps 2-5 which use Netlify Functions and Edge Functions to build
custom analytics.
</Warning>
<Info>
**Netlify Analytics Advantages**:
- [Server-side Analytics](https://docs.netlify.com/analytics/get-started/) - No client-side JavaScript needed
- [Core Web Vitals](https://docs.netlify.com/analytics/core-web-vitals/) - Automatic tracking of Google's metrics
- [Custom Metrics](https://docs.netlify.com/functions/logs/) - Track any metric via Functions
- [Edge Insights](https://docs.netlify.com/edge-functions/overview/#geolocation) - Geographic performance data
- [No Cookie Banner Required](https://docs.netlify.com/analytics/get-started/#privacy) - GDPR compliant by default
Unlike Google Analytics, Netlify Analytics:
- Doesn't slow down your site (server-side)
- Captures 100% of traffic (no ad blockers)
- Respects user privacy (no cookies)
- Shows bot traffic separately
</Info>
<Tip>
**Pro Tip**
Combine Netlify Analytics with Edge Functions to create a
powerful RUM solution that:
- Tracks performance by user segment
- A/B tests
performance optimizations
- Personalizes content based on connection speed
- Automatically serves lighter assets to slow connections
</Tip>
## Automated Performance Checks
### GitHub Actions Performance Guard
Block PRs that degrade performance:
```yaml
name: Performance Check
on:
pull_request:
jobs:
performance:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "22"
- name: Deploy and Test Performance
id: perf
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
run: |
npx @continuedev/cli@latest << 'EOF'
Deploy PR preview and run Lighthouse.
Compare scores with main branch.
Output JSON with score deltas.
EOF > performance.json
- name: Comment Performance Results
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const perf = JSON.parse(fs.readFileSync('performance.json'));
const emoji = perf.score_delta < -10 ? '🔴' :
perf.score_delta < 0 ? '🟡' : '🟢';
const comment = `## ${emoji} Performance Impact
| Metric | Main | PR | Delta |
|--------|------|----|---------|
| Performance Score | ${perf.main_score} | ${perf.pr_score} | ${perf.score_delta > 0 ? '+' : ''}${perf.score_delta} |
| LCP | ${perf.main_lcp}s | ${perf.pr_lcp}s | ${perf.lcp_delta > 0 ? '+' : ''}${perf.lcp_delta}s |
| Bundle Size | ${perf.main_bundle}KB | ${perf.pr_bundle}KB | ${perf.bundle_delta > 0 ? '+' : ''}${perf.bundle_delta}KB |
${perf.score_delta < -10 ? '⚠️ **This PR significantly degrades performance. Please optimize before merging.**' : ''}
[View Full Report](${perf.report_url})`;
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: comment
});
// Fail check if performance degrades significantly
if (perf.score_delta < -10) {
core.setFailed('Performance degraded by more than 10 points');
}
```
<Warning>
This workflow will: - **Block merge** if performance score drops >10 points -
**Warn** on any performance regression - **Celebrate** improvements with green
indicators
</Warning>
## Performance Testing Locally
### Step 8: Local Performance Testing
Test performance before deploying:
```bash
# In cn TUI mode:
"Run production build and measure bundle sizes"
```
### Step 9: Pre-commit Performance Checks
Prevent performance regressions before they happen:
```bash
# In cn TUI mode:
"Add pre-commit hooks for bundle size limits"
```
## Performance Troubleshooting
### Debug Performance Issues
Identify and fix performance bottlenecks:
```bash
# In cn TUI mode:
"Why did my performance score drop?"
```
### Performance Issue Quick Fixes
| Issue | Quick Fix Command (in cn TUI) |
| ------------- | --------------------------------- |
| Slow LCP | `"Preload critical resources"` |
| High CLS | `"Add size attributes to images"` |
| Large bundles | `"Implement code splitting"` |
| Slow builds | `"Enable build caching"` |
| Poor caching | `"Configure cache headers"` |
## What You've Accomplished
<Card title="Performance-First Development" icon="gauge-high">
You've built an AI-powered performance optimization system that:
- Automatically monitors Core Web Vitals
- Runs A/B tests between branches
- Blocks deployments that degrade performance
- Provides actionable optimization
suggestions
</Card>
## Discover Netlify's Hidden Performance Gems
Features many developers don't know Netlify offers:
<CardGroup cols={2}>
<Card title="Edge Functions" icon="bolt">
**[Netlify Edge Functions](https://docs.netlify.com/edge-functions/overview/)**
- Run code at the edge, closer to users
- Transform responses on-the-fly
- A/B test at the edge level
- Personalize content without client-side JS
</Card>
<Card title="Netlify Graph" icon="diagram-project">
**[Netlify Graph](https://docs.netlify.com/graph/overview/)**
- Unified GraphQL gateway for all your APIs
- Automatic TypeScript generation
- Built-in authentication handling
- Zero client-side API keys needed
</Card>
<Card title="On-Demand Builders" icon="hammer">
**[On-Demand
Builders](https://docs.netlify.com/configure-builds/on-demand-builders/)** -
Generate pages only when requested - Cache dynamically generated content -
Perfect for large sites (10k+ pages) - Reduce build times dramatically
</Card>
<Card title="Netlify Functions" icon="function">
**[Background Functions](https://docs.netlify.com/functions/background-functions/)**
- Run tasks up to 15 minutes
- Process webhooks asynchronously
- Handle heavy computations
- No timeout worries
</Card>
</CardGroup>
```bash
# Try these advanced features in cn TUI mode:
"Show me how to use Netlify Edge Functions for geo-based personalization"
"Set up On-Demand Builders for my blog with 5000 posts"
"Configure Background Functions for image processing"
```
## Performance Best Practices
The Netlify Performance Rules enforce:
<CardGroup cols={3}>
<Card title="Build Optimization" icon="hammer">
- Dependency caching enabled
- Parallel builds when possible
- Incremental compilation
- Smart cache invalidation
</Card>
<Card title="Runtime Performance" icon="bolt">
- Automatic image optimization
- Efficient resource hints (preload, prefetch)
- Optimal cache headers
- CDN configuration
</Card>
<Card title="Monitoring Standards" icon="chart-line">
- Performance budgets enforced
- Core Web Vitals tracking
- Real user monitoring
- Automated alerts
</Card>
</CardGroup>
## Advanced Performance Strategies
### Progressive Enhancement
```bash
# In cn TUI mode:
"Implement progressive enhancement with basic HTML first"
```
### Multi-variant Testing
```bash
# In cn TUI mode:
"Test 3 bundle strategies and auto-select winner"
```
### Predictive Prefetching
```bash
# In cn TUI mode:
"Analyze navigation patterns and prefetch next pages"
```
## Next Steps
- Install [Netlify MCP](https://hub.continue.dev/netlify/netlify-mcp) from Continue Hub
- Set up [Performance Monitoring](https://docs.netlify.com/analytics/get-started/)
- Configure [A/B Testing](https://docs.netlify.com/split-testing/overview/)
- Join the [Continue Discord](https://discord.gg/continue) for support
## Resources
- [Netlify MCP on Continue Hub](https://hub.continue.dev/netlify/netlify-mcp)
- [Core Web Vitals Guide](https://web.dev/vitals/)
- [Netlify Analytics Documentation](https://docs.netlify.com/analytics/)
- [Continue Performance Guides](https://docs.continue.dev/guides)

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