Merge branch 'main' of github.com:continuedev/continue into jacob/feature/static

This commit is contained in:
Jacob Kim 2025-07-09 21:08:43 -07:00
commit d937a448cd
217 changed files with 8695 additions and 1212 deletions

View file

@ -0,0 +1,200 @@
---
alwaysApply: false
---
# Continue Development Data (Dev Data) Guide
## Overview
Development data (dev data) captures detailed information about how developers interact with LLM-aided development tools. Unlike basic telemetry, dev data includes lots of details into the complete software development workflow, including code context, user interactions, and development patterns.
## Core Architecture
### Primary Implementation Files
- **`/core/data/log.ts`**: Main `DataLogger` class - singleton for event logging and remote transmission
- **`/packages/config-yaml/src/schemas/data/`**: Schema definitions for all event types
### Storage Locations
- **Default storage**: `~/.continue/dev_data/`
- **Event files**: `~/.continue/dev_data/{version}/{eventName}.jsonl`
## Event Types and Schemas
### Core Event Types
1. **`tokensGenerated`**: LLM token usage tracking
2. **`autocomplete`**: Code completion interactions
3. **`chatInteraction`**: Chat-based development assistance
4. **`editInteraction`**: Code editing sessions
5. **`editOutcome`**: Results of edit operations
6. **`nextEditOutcome`**: Next Edit feature outcomes
7. **`chatFeedback`**: User feedback on AI responses
8. **`toolUsage`**: Tool interaction statistics
9. **`quickEdit`**: Quick edit functionality usage
### Schema Versioning
- **Version 0.1.0**: Initial schema implementation
- **Version 0.2.0**: Current schema with expanded fields and metadata
- **Schema files**: Located in `/packages/config-yaml/src/schemas/data/`
### Base Schema Structure
All events inherit from a base schema (`/packages/config-yaml/src/schemas/data/base.ts`):
```typescript
{
eventName: string,
schema: string,
timestamp: string,
userId: string,
userAgent: string,
selectedProfileId: string
}
```
## Key Integration Points
### Autocomplete System
- **File**: `/core/autocomplete/util/AutocompleteLoggingService.ts`
- **Purpose**: Tracks code completion acceptance/rejection, timing, and cache hits
- **Integration**: Called from autocomplete engine when completions are shown/accepted
### Chat Interface
- **Integration**: Chat interactions logged through `DataLogger.logDevData()`
- **Data**: Includes prompts, responses, context, and user feedback
- **Privacy**: Can be configured to exclude code content
### Edit Features
- **Files**: `/extensions/vscode/src/extension/EditOutcomeTracker.ts`, `/core/nextEdit/NextEditLoggingService.ts`
- **Purpose**: Track edit suggestions, acceptance rates, and outcomes
- **Integration**: Embedded in edit workflow to capture user decisions
### LLM Token Tracking
- **File**: `/core/llm/index.ts`
- **Purpose**: Track token usage across all LLM providers
- **Storage**: SQLite database for efficient querying and reporting
## Configuration and Customization
### Configuration Structure
Dev data is configured through `data` blocks in your Continue config:
```yaml
data:
- name: "Local Development Data"
destination: "file:///Users/developer/.continue/dev_data"
schema: "0.2.0"
level: "all"
events: ["autocomplete", "chatInteraction", "editOutcome"]
- name: "Team Analytics"
destination: "https://analytics.yourcompany.com/api/events"
schema: "0.2.0"
level: "noCode"
apiKey: "your-api-key-here"
events: ["tokensGenerated", "toolUsage"]
```
### Configuration Options
- **`destination`**: Where to send data (`file://` for local, `http://`/`https://` for remote)
- **`schema`**: Schema version to use (`"0.1.0"` or `"0.2.0"`)
- **`level`**: Data detail level (`"all"` includes code, `"noCode"` excludes code content)
- **`events`**: Array of event types to collect
- **`apiKey`**: Authentication for remote endpoints
### Privacy Controls
- **`"all"` level**: Includes code content (prefixes, suffixes, completions)
- **`"noCode"` level**: Excludes code content, only metadata and metrics
- **Local-first**: Data is always stored locally, remote transmission is optional
## Making Changes to Dev Data
### Adding New Event Types
1. **Create schema**: Add new event schema in `/packages/config-yaml/src/schemas/data/`
2. **Update index**: Add to schema aggregator in `/packages/config-yaml/src/schemas/data/index.ts`
3. **Implement logging**: Add logging calls in relevant service files
4. **Update version**: Consider schema version bump if breaking changes
### Modifying Existing Events
1. **Schema changes**: Update schema files in `/packages/config-yaml/src/schemas/data/`
2. **Backward compatibility**: Ensure changes don't break existing data consumers
3. **Version management**: Increment schema version for breaking changes
4. **Test thoroughly**: Validate schema changes with existing data
### Adding New Logging Points
1. **Import DataLogger**: `import { DataLogger } from "core/data/log"`
2. **Log events**: Call `DataLogger.getInstance().logDevData(eventName, data)`
3. **Follow patterns**: Use existing logging services as examples
4. **Validate data**: Ensure logged data matches schema requirements
### Debugging Dev Data Issues
1. **Check local storage**: Verify files are being created in `~/.continue/dev_data/`
2. **Validate schemas**: Ensure event data matches expected schema format
3. **Review configuration**: Check `data` blocks in Continue config
4. **Test endpoints**: Verify remote endpoints are reachable and accepting data
## Best Practices
### When Adding New Events
- Follow existing naming conventions for event types
- Include sufficient context for analysis without oversharing sensitive data
- Consider privacy implications and respect user configuration levels
- Add appropriate error handling and logging
### When Modifying Schemas
- Maintain backward compatibility when possible
- Document schema changes thoroughly
- Consider impact on existing data consumers
- Test with real development data
### When Integrating Logging
- Use the singleton pattern: `DataLogger.getInstance()`
- Log events at appropriate points in user workflow
- Respect user privacy settings and configuration
- Handle errors gracefully without disrupting user experience
## Common Patterns
### Service-Based Logging
Most dev data logging follows a service pattern:
```typescript
export class FeatureLoggingService {
private dataLogger = DataLogger.getInstance();
logFeatureUsage(data: FeatureUsageData) {
this.dataLogger.logDevData("featureUsage", data);
}
}
```
### Event-Driven Logging
Events are typically logged at key interaction points:
```typescript
// When user accepts autocomplete
onAutocompleteAccepted(completion: CompletionData) {
AutocompleteLoggingService.getInstance().logAutocompleteAccepted(completion);
}
```
This guide provides the foundation for understanding and working with Continue's dev data system. Always prioritize user privacy and follow established patterns when making changes.

197
.github/workflows/compliance.yaml vendored Normal file
View file

@ -0,0 +1,197 @@
name: PR Compliance Checks
on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
branches: [main]
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
conventional-commits:
name: Validate Conventional Commits (Warning Only)
runs-on: ubuntu-latest
if: ${{ !github.event.pull_request.draft }}
continue-on-error: true
permissions:
pull-requests: write
issues: write
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Validate conventional commits
id: commitlint
uses: wagoid/commitlint-github-action@v6
with:
configFile: .commitlintrc.warning.json
continue-on-error: true
- name: Add commit message guidance comment
if: steps.commitlint.outcome == 'failure'
uses: actions/github-script@v7
with:
script: |
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
});
const botComment = comments.find(comment =>
comment.user.type === 'Bot' &&
comment.body.includes('Conventional Commit Format')
);
if (!botComment) {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: [
"## ⚠️ Conventional Commit Format",
"",
"Your commit messages don't follow the conventional commit format, but **this won't block your PR from being merged**. We recommend downloading [this extension](https://marketplace.visualstudio.com/items?itemName=vivaxy.vscode-conventional-commits) if you are using VS Code.",
"",
"### Expected Format:",
"```",
"<type>[optional scope]: <description>",
"",
"[optional body]",
"",
"[optional footer(s)]",
"```",
"",
"### Examples:",
"- `feat: add changelog generation support`",
"- `fix: resolve login redirect issue`",
"- `docs: update README with new instructions`",
"- `chore: update dependencies`",
"",
"### Valid Types:",
"`feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`",
"",
"This helps with:",
"- 📝 Automatic changelog generation",
"- 🚀 Automated semantic versioning",
"- 📊 Better project history tracking",
"",
"*This is a non-blocking warning - your PR can still be merged without fixing this.*"
].join('\n')
});
}
security-audit:
name: Security Audit
runs-on: ubuntu-latest
if: ${{ !github.event.pull_request.draft }}
permissions:
security-events: write
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
cache: "npm"
- name: Install dependencies
run: npm ci
- name: Fix vulnerabilities
run: npm audit fix
- name: Run npm audit
run: npm audit --audit-level=moderate
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: javascript
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
# Use this for any files that we want to be certain exist
# Basically creates a forcing function to discuss were anyone to want to remove them
file-validation:
name: Required Files Check
runs-on: ubuntu-latest
if: ${{ !github.event.pull_request.draft }}
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Check required files
run: |
required_files=(
"package.json"
"package-lock.json"
"README.md"
"LICENSE"
".gitignore"
"tsconfig.json"
"SECURITY.md"
"CONTRIBUTING.md"
".nvmrc"
".prettierrc"
".prettierignore"
)
missing_files=()
for file in "${required_files[@]}"; do
if [[ ! -f "$file" ]]; then
missing_files+=("$file")
fi
done
if [[ ${#missing_files[@]} -gt 0 ]]; then
echo "❌ Missing required files:"
printf '%s\n' "${missing_files[@]}"
exit 1
else
echo "✅ All required files present"
fi
compliance-summary:
name: Compliance Summary
runs-on: ubuntu-latest
needs: [conventional-commits, security-audit, file-validation]
if: always() && !github.event.pull_request.draft
steps:
- name: Check compliance status
run: |
echo "## 🔍 Compliance Check Results" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
if [[ "${{ needs.conventional-commits.result }}" == "success" ]]; then
echo "✅ Conventional Commits: PASSED" >> $GITHUB_STEP_SUMMARY
elif [[ "${{ needs.conventional-commits.result }}" == "failure" ]]; then
echo "⚠️ Conventional Commits: WARNING (non-blocking)" >> $GITHUB_STEP_SUMMARY
else
echo "❌ Conventional Commits: SKIPPED" >> $GITHUB_STEP_SUMMARY
fi
if [[ "${{ needs.security-audit.result }}" == "success" ]]; then
echo "✅ Security Audit: PASSED" >> $GITHUB_STEP_SUMMARY
else
echo "❌ Security Audit: FAILED" >> $GITHUB_STEP_SUMMARY
fi
if [[ "${{ needs.file-validation.result }}" == "success" ]]; then
echo "✅ File Validation: PASSED" >> $GITHUB_STEP_SUMMARY
else
echo "❌ File Validation: FAILED" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
echo "📊 **Overall Status**: ${{ job.status }}" >> $GITHUB_STEP_SUMMARY

View file

@ -168,7 +168,7 @@ jobs:
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
- name: Build packages (Unix)
run: ./scripts/build-packages.sh
run: cd ../.. && ./scripts/build-packages.sh
# npm install core
- name: Install core node_modules

1
.vscode/launch.json vendored
View file

@ -19,7 +19,6 @@
"pauseForSourceMap": false,
"outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"],
"preLaunchTask": "vscode-extension:build",
"postDebugTask": "Terminate All Tasks",
"env": {
// "CONTROL_PLANE_ENV": "local",
"CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug"

13
.vscode/tasks.json vendored
View file

@ -223,19 +223,6 @@
],
"type": "shell",
"problemMatcher": []
},
{
"label": "Terminate All Tasks",
"command": "${input:terminate}",
"type": "shell"
}
],
"inputs": [
{
"id": "terminate",
"type": "command",
"command": "workbench.action.tasks.terminate",
"args": "terminateAll"
}
]
}

View file

@ -260,7 +260,7 @@ export class CompletionProvider {
completionId: helper.input.completionId,
gitRepo: await this.ide.getRepoName(helper.filepath),
uniqueId: await this.ide.getUniqueId(),
timestamp: Date.now(),
timestamp: new Date().toISOString(),
...helper.options,
};

View file

@ -41,6 +41,6 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions {
gitRepo?: string;
completionId: string;
uniqueId: string;
timestamp: number;
timestamp: string;
enabledStaticContextualization?: boolean;
}

View file

@ -8,8 +8,19 @@
* we rarely ever need syntax highlighting outside of
* creating a render of it.
*/
import {
transformerMetaHighlight,
transformerNotationDiff,
transformerNotationFocus,
transformerNotationHighlight,
} from "@shikijs/transformers";
import { JSDOM } from "jsdom";
import { BundledTheme, codeToHtml, getSingletonHighlighter } from "shiki";
import {
BundledLanguage,
BundledTheme,
getSingletonHighlighter,
Highlighter,
} from "shiki";
import { escapeForSVG, kebabOfStr } from "../util/text";
interface CodeRendererOptions {
@ -42,6 +53,8 @@ export class CodeRenderer {
private currentTheme: string = "dark-plus";
private editorBackground: string = "#000000";
private editorForeground: string = "#FFFFFF";
private editorLineHighlight: string = "#000000";
private highlighter: Highlighter | null = null;
private constructor() {}
@ -62,13 +75,17 @@ export class CodeRenderer {
? "dark-plus"
: kebabOfStr(themeName);
const highlighter = await getSingletonHighlighter({
this.highlighter = await getSingletonHighlighter({
langs: ["typescript"],
themes: [this.currentTheme],
});
const th = highlighter.getTheme(this.currentTheme);
const th = this.highlighter.getTheme(this.currentTheme);
this.editorBackground = th.bg;
this.editorForeground = th.fg;
this.editorLineHighlight =
th.colors!["editor.lineHighlightBackground"] ?? "#000000";
} else {
this.currentTheme = "dark-plus";
}
@ -148,10 +165,29 @@ export class CodeRenderer {
async highlightCode(
code: string,
language: string = "javascript",
currLineOffsetFromTop: number,
): Promise<string> {
return await codeToHtml(code, {
const annotatedCode = code
.split("\n")
.map((line, i) =>
i === currLineOffsetFromTop
? line + " \/\/ \[\!code highlight\]"
: line,
)
.join("\n");
await this.highlighter!.loadLanguage(language as BundledLanguage);
return this.highlighter!.codeToHtml(annotatedCode, {
lang: language,
theme: this.currentTheme,
transformers: [
// transformerColorizedBrackets(),
transformerMetaHighlight(),
transformerNotationHighlight(),
transformerNotationDiff(),
transformerNotationFocus(),
],
});
}
@ -163,23 +199,40 @@ export class CodeRenderer {
dimensions: Dimensions,
lineHeight: number,
options: ConversionOptions,
currLineOffsetFromTop: number,
): Promise<Buffer> {
const highlightedCodeHtml = await this.highlightCode(code, language);
const strokeWidth = 1;
const highlightedCodeHtml = await this.highlightCode(
code,
language,
currLineOffsetFromTop,
);
// console.log(highlightedCodeHtml);
const guts = this.convertShikiHtmlToSvgGut(
const { guts, lineBackgrounds } = this.convertShikiHtmlToSvgGut(
highlightedCodeHtml,
fontSize,
fontFamily,
lineHeight,
dimensions,
);
const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${dimensions.width}" height="${dimensions.height}">
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${dimensions.width}" height="${dimensions.height}" shape-rendering="crispEdges">
<style>
:root {
--purple: rgb(112, 114, 209);
--green: rgb(136, 194, 163);
--blue: rgb(107, 166, 205);
}
</style>
<g>
<rect width="${dimensions.width}" height="${dimensions.height}" fill="${backgroundColor}" stroke="${this.editorForeground}" stroke-width="1" />
<rect x="0" y="0" rx="10" ry="10" width="${dimensions.width}" height="${dimensions.height}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
${lineBackgrounds}
${guts}
</g>
</svg>`;
console.log(svg);
return Buffer.from(svg, "utf8");
}
@ -189,7 +242,8 @@ export class CodeRenderer {
fontSize: number,
fontFamily: string,
lineHeight: number,
): string {
dimensions: Dimensions,
): { guts: string; lineBackgrounds: string } {
const dom = new JSDOM(shikiHtml);
const document = dom.window.document;
@ -204,19 +258,70 @@ export class CodeRenderer {
const el = node as HTMLElement;
const style = el.getAttribute("style") || "";
const colorMatch = style.match(/color:\s*(#[0-9a-fA-F]{6})/);
const fill = colorMatch ? ` fill="${colorMatch[1]}"` : "";
const classes = el.getAttribute("class") || "";
let fill = colorMatch ? ` fill="${colorMatch[1]}"` : "";
if (classes.includes("highlighted")) {
fill = ` fill="${this.editorLineHighlight}"`;
}
const content = el.textContent || "";
return `<tspan xml:space="preserve"${fill}>${escapeForSVG(content)}</tspan>`;
})
.join("");
const y = (index + 1) * lineHeight;
return `<text x="0" y="${y}" font-family="${fontFamily}" font-size="${fontSize.toString()}" xml:space="preserve">${spans}</text>`;
// Typography notes:
// Each line of code is a <text> inside a <rect>.
// Math becomes interesting here; the y value is actually aligned to the topmost border.
// So y = 0 will have the rect be flush with the top border.
// More importantly, text will also be positioned that way.
// Since y = 0 is the axis the text will align itself to, the default settings will actually have the text sitting "on top of" the y = 0 axis, which effectively shifts them up.
// To prevent this, we want the alignment axis to be at the middle of each rect, and have the text align itself vertically to the center (skwered by the axis).
// The first step is to add lineHeight / 2 to move the axis down.
// The second step is to add 'dominant-baseline="central"' to vertically center the text.
// Note that we choose "central" over "middle". "middle" will center the text too perfectly, which is actually undesirable!
const y = index * lineHeight + lineHeight / 2;
return `<text x="0" y="${y}" font-family="${fontFamily}" font-size="${fontSize.toString()}" xml:space="preserve" dominant-baseline="central" shape-rendering="crispEdges">${spans}</text>`;
});
return `
${svgLines.join("\n")}
`.trim();
const lineBackgrounds = lines
.map((line, index) => {
const classes = line?.getAttribute("class") || "";
const bgColor = classes.includes("highlighted")
? this.editorLineHighlight
: this.editorBackground;
const y = index * lineHeight;
const isFirst = index === 0;
const isLast = index === lines.length - 1;
const radius = 10;
// 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 + lineHeight}
L ${0} ${y + radius}
Q ${0} ${y} ${radius} ${y}
L ${dimensions.width - radius} ${y}
Q ${dimensions.width} ${y} ${dimensions.width} ${y + radius}
L ${dimensions.width} ${y + lineHeight}
Z"
fill="${bgColor}" />`
: isLast
? `<path d="M ${0} ${y}
L ${0} ${y + lineHeight - radius}
Q ${0} ${y + lineHeight} ${radius} ${y + lineHeight}
L ${dimensions.width - radius} ${y + lineHeight}
Q ${dimensions.width} ${y + lineHeight} ${dimensions.width} ${y + lineHeight - 10}
L ${dimensions.width} ${y}
Z"
fill="${bgColor}" />`
: `<rect x="0" y="${y}" rx="${radius}" ry="${radius}" width="100%" height="${lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`;
})
.join("\n");
return {
guts: svgLines.join("\n"),
lineBackgrounds,
};
}
getBackgroundColor(shikiHtml: string): string {
@ -244,6 +349,7 @@ export class CodeRenderer {
dimensions: Dimensions,
lineHeight: number,
options: ConversionOptions,
currLineOffsetFromTop: number,
): Promise<DataUri> {
switch (options.imageType) {
// case "png":
@ -265,6 +371,7 @@ export class CodeRenderer {
dimensions,
lineHeight,
options,
currLineOffsetFromTop,
);
return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
}

View file

@ -643,6 +643,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
template: llm.template,
completionOptions: llm.completionOptions,
baseAgentSystemMessage: llm.baseAgentSystemMessage,
basePlanSystemMessage: llm.basePlanSystemMessage,
baseChatSystemMessage: llm.baseChatSystemMessage,
requestOptions: llm.requestOptions,
promptTemplates: serializePromptTemplates(llm.promptTemplates),
@ -650,6 +651,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
roles: llm.roles,
configurationStatus: llm.getConfigurationStatus(),
apiKeyLocation: llm.apiKeyLocation,
envSecretLocations: llm.envSecretLocations,
};
}

View file

@ -1004,6 +1004,8 @@ declare global {
type: "stdio";
command: string;
args: string[];
env?: Record<string, string>;
cwd?: string;
}
interface WebSocketOptions {

View file

@ -69,6 +69,7 @@ function convertYamlMcpToContinueMcp(
command: server.command,
args: server.args ?? [],
env: server.env,
cwd: server.cwd,
} as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union)
timeout: server.connectionTimeout,
};

View file

@ -0,0 +1,128 @@
import { describe, it, expect } from "vitest";
import {
validateConfigYaml,
AssistantUnrolledNonNullable,
} from "@continuedev/config-yaml";
describe("MCP Server cwd configuration", () => {
describe("YAML schema validation", () => {
it("should accept valid MCP server with cwd", () => {
const config: AssistantUnrolledNonNullable = {
name: "test-assistant",
version: "1.0.0",
mcpServers: [
{
name: "test-server",
command: "node",
args: ["server.js"],
env: { NODE_ENV: "production" },
cwd: "/path/to/project",
connectionTimeout: 5000,
},
],
};
const errors = validateConfigYaml(config);
expect(errors).toHaveLength(0);
});
it("should accept MCP server without cwd", () => {
const config: AssistantUnrolledNonNullable = {
name: "test-assistant",
version: "1.0.0",
mcpServers: [
{
name: "test-server",
command: "python",
args: ["-m", "server"],
},
],
};
const errors = validateConfigYaml(config);
expect(errors).toHaveLength(0);
});
it("should accept relative paths in cwd", () => {
const config: AssistantUnrolledNonNullable = {
name: "test-assistant",
version: "1.0.0",
mcpServers: [
{
name: "test-server",
command: "cargo",
args: ["run"],
cwd: "./rust-project",
},
],
};
const errors = validateConfigYaml(config);
expect(errors).toHaveLength(0);
});
it("should accept empty string cwd", () => {
const config: AssistantUnrolledNonNullable = {
name: "test-assistant",
version: "1.0.0",
mcpServers: [
{
name: "test-server",
command: "deno",
args: ["run", "server.ts"],
cwd: "",
},
],
};
const errors = validateConfigYaml(config);
expect(errors).toHaveLength(0);
});
});
describe("MCP server configuration examples", () => {
it("should support common MCP server patterns with cwd", () => {
const configs = [
{
name: "Local project MCP server",
server: {
name: "project-mcp",
command: "npm",
args: ["run", "mcp-server"],
cwd: "/Users/developer/my-project",
},
},
{
name: "Python MCP with virtual environment",
server: {
name: "python-mcp",
command: "python",
args: ["-m", "my_mcp_server"],
env: { PYTHONPATH: "./src" },
cwd: "/home/user/python-project",
},
},
{
name: "Relative path MCP server",
server: {
name: "relative-mcp",
command: "node",
args: ["index.js"],
cwd: "../mcp-servers/filesystem",
},
},
];
configs.forEach(({ name, server }) => {
const config: AssistantUnrolledNonNullable = {
name: "test-assistant",
version: "1.0.0",
mcpServers: [server],
};
const errors = validateConfigYaml(config);
expect(errors).toHaveLength(0);
});
});
});
});

View file

@ -63,6 +63,7 @@ async function modelConfigToBaseLLM({
template: model.promptTemplates?.chat,
promptTemplates: model.promptTemplates,
baseAgentSystemMessage: model.chatOptions?.baseAgentSystemMessage,
basePlanSystemMessage: model.chatOptions?.basePlanSystemMessage,
baseChatSystemMessage: model.chatOptions?.baseSystemMessage,
capabilities: {
tools: model.capabilities?.includes("tool_use"),
@ -126,6 +127,12 @@ async function modelConfigToBaseLLM({
if ("profile" in env && typeof env.profile === "string") {
options.profile = env.profile;
}
if ("accessKeyId" in env && typeof env.accessKeyId === "string") {
options.accessKeyId = env.accessKeyId;
}
if ("secretAccessKey" in env && typeof env.secretAccessKey === "string") {
options.secretAccessKey = env.secretAccessKey;
}
if ("modelArn" in env && typeof env.modelArn === "string") {
options.modelArn = env.modelArn;
}

View file

@ -329,6 +329,7 @@ class MCPConnection {
command,
args,
env,
cwd: options.transport.cwd,
stderr: "pipe",
});

View file

@ -1,6 +1,7 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { beforeEach, describe, expect, it, vi } from "vitest";
import MCPConnection from "./MCPConnection";
import { StdioOptions } from "../../index.d.js";
describe("MCPConnection", () => {
beforeEach(() => {
@ -25,6 +26,27 @@ describe("MCPConnection", () => {
expect(conn.status).toBe("not-connected");
});
it("should create instance with stdio transport including cwd", () => {
const options = {
name: "test-mcp",
id: "test-id",
transport: {
type: "stdio" as const,
command: "test-cmd",
args: ["--test"],
env: { TEST: "true" },
cwd: "/path/to/working/directory",
},
};
const conn = new MCPConnection(options);
expect(conn).toBeInstanceOf(MCPConnection);
expect(conn.status).toBe("not-connected");
if (conn.options.transport.type === "stdio") {
expect(conn.options.transport.cwd).toBe("/path/to/working/directory");
}
});
it("should create instance with websocket transport", () => {
const options = {
name: "test-mcp",

View file

@ -145,6 +145,11 @@ class DocsContextProvider extends BaseContextProvider {
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const { config } = args;
// This set is used to filter out the docs that is not in docs config but exist in sqlite metadata
const configDocsSet = new Set(
config.docs?.map((doc) => doc.startUrl) || [],
);
// Get docs service
const docsService = DocsService.getSingleton();
if (!docsService) {
@ -159,12 +164,14 @@ class DocsContextProvider extends BaseContextProvider {
// Get all indexed docs from the database
const docs = (await docsService.listMetadata()) ?? [];
for (const { startUrl, title, favicon } of docs) {
submenuItems.push({
title,
id: startUrl,
description: new URL(startUrl).hostname,
icon: favicon,
});
if (configDocsSet.has(startUrl)) {
submenuItems.push({
title,
id: startUrl,
description: new URL(startUrl).hostname,
icon: favicon,
});
}
}
// Sort alphabetically

View file

@ -72,6 +72,10 @@ class HttpContextProvider extends BaseContextProvider {
description: item.description ?? "HTTP Context Item",
content: item.content ?? "",
name: item.name ?? this.options.title ?? "HTTP",
uri: {
type: item.uri.type,
value: item.uri.value,
},
});
return Array.isArray(json)

View file

@ -225,9 +225,11 @@ Determine which tools should be used to answer this query. You should feel free
.join("");
const parsed = JSON.parse(responseContent);
toolCalls = parsed.tools || [];
console.log("retrieveWithTools", toolCalls);
} catch (e) {
console.log("Failed to parse tool selection response", e);
console.log(
`Failed to parse tool selection response: ${toolSelectionResponse.content}\n\n`,
e,
);
return [];
}

View file

@ -1,319 +1,546 @@
import { findSearchMatch } from "./findSearchMatch";
describe("findSearchMatch", () => {
describe("Exact matches", () => {
it("should find exact match at the beginning of file", () => {
const fileContent = `function hello() {
describe("Exact matches", () => {
it("should find exact match at the beginning of file", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `function hello() {
const searchContent = `function hello() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: fileContent.length,
});
expect(result).toEqual({
startIndex: 0,
endIndex: fileContent.length,
strategyName: "exactMatch",
});
});
it("should find exact match in the middle of file", () => {
const fileContent = `const a = 1;
it("should find exact match in the middle of file", () => {
const fileContent = `const a = 1;
function hello() {
console.log("world");
}
const b = 2;`;
const searchContent = `function hello() {
const searchContent = `function hello() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 13, // After "const a = 1;\n"
endIndex: 13 + searchContent.length,
});
expect(result).toEqual({
startIndex: 13, // After "const a = 1;\n"
endIndex: 13 + searchContent.length,
strategyName: "exactMatch",
});
});
it("should find exact match at the end of file", () => {
const fileContent = `const a = 1;
it("should find exact match at the end of file", () => {
const fileContent = `const a = 1;
function hello() {
console.log("world");
}`;
const searchContent = `function hello() {
const searchContent = `function hello() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 13, // After "const a = 1;\n"
endIndex: fileContent.length,
});
expect(result).toEqual({
startIndex: 13, // After "const a = 1;\n"
endIndex: fileContent.length,
strategyName: "exactMatch",
});
});
it("should find exact match with single line", () => {
const fileContent = `const a = 1;
it("should find exact match with single line", () => {
const fileContent = `const a = 1;
const b = 2;
const c = 3;`;
const searchContent = `const b = 2;`;
const searchContent = `const b = 2;`;
const result = findSearchMatch(fileContent, searchContent);
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 13, // After "const a = 1;\n"
endIndex: 13 + searchContent.length,
});
expect(result).toEqual({
startIndex: 13, // After "const a = 1;\n"
endIndex: 13 + searchContent.length,
strategyName: "exactMatch",
});
});
it("should find exact match with whitespace preserved", () => {
const fileContent = `function test() {
it("should find exact match with whitespace preserved", () => {
const fileContent = `function test() {
const x = 1;
const y = 2;
}`;
const searchContent = ` const x = 1;
const searchContent = ` const x = 1;
const y = 2;`;
const result = findSearchMatch(fileContent, searchContent);
const result = findSearchMatch(fileContent, searchContent);
// The actual indexOf result is 18, not 17
expect(result).toEqual({
startIndex: 18,
endIndex: 18 + searchContent.length,
});
// The actual indexOf result is 18, not 17
expect(result).toEqual({
startIndex: 18,
endIndex: 18 + searchContent.length,
strategyName: "exactMatch",
});
});
});
describe("Trimmed matches", () => {
it("should find trimmed match when exact match fails due to leading newlines", () => {
const fileContent = `function hello() {
describe("Trimmed matches", () => {
it("should find trimmed match when exact match fails due to leading newlines", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `\n\nfunction hello() {
const searchContent = `\n\nfunction hello() {
console.log("world");
}\n\n`;
const result = findSearchMatch(fileContent, searchContent);
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: fileContent.length, // Uses trimmed length
});
expect(result).toEqual({
startIndex: 0,
endIndex: fileContent.length, // Uses trimmed length
strategyName: "trimmedMatch",
});
});
it("should find trimmed match when exact match fails due to trailing newlines", () => {
const fileContent = `const a = 1;
it("should find trimmed match when exact match fails due to trailing newlines", () => {
const fileContent = `const a = 1;
function hello() {
return "world";
}
const b = 2;`;
const searchContent = `\nfunction hello() {
const searchContent = `\nfunction hello() {
return "world";
}\n`;
const result = findSearchMatch(fileContent, searchContent);
const result = findSearchMatch(fileContent, searchContent);
// The function finds the exact match first (at index 12), not the trimmed match
expect(result).toEqual({
startIndex: 12,
endIndex: 12 + searchContent.length,
});
// The function finds the exact match first (at index 12), not the trimmed match
expect(result).toEqual({
startIndex: 12,
endIndex: 12 + searchContent.length,
strategyName: "exactMatch",
});
});
it("should find trimmed match for single line with extra whitespace", () => {
const fileContent = `const a = 1;
it("should find trimmed match for single line with extra whitespace", () => {
const fileContent = `const a = 1;
const b = 2;
const c = 3;`;
const searchContent = `\n const b = 2; \n`;
const searchContent = `\n const b = 2; \n`;
const result = findSearchMatch(fileContent, searchContent);
const result = findSearchMatch(fileContent, searchContent);
const trimmedSearchContent = searchContent.trim();
const expectedStart = fileContent.indexOf(trimmedSearchContent);
const trimmedSearchContent = searchContent.trim();
const expectedStart = fileContent.indexOf(trimmedSearchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + trimmedSearchContent.length,
});
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + trimmedSearchContent.length,
strategyName: "trimmedMatch",
});
});
});
describe("Empty search content", () => {
it("should match at beginning for empty search content", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = "";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
describe("Empty search content", () => {
it("should match at beginning for empty search content", () => {
const fileContent = `function hello() {
it("should match at beginning for whitespace-only search content", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = "";
const searchContent = "\n\n \t \n";
const result = findSearchMatch(fileContent, searchContent);
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
});
});
it("should match at beginning for whitespace-only search content", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = "\n\n \t \n";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
});
});
it("should match at beginning for empty file and empty search", () => {
const fileContent = "";
const searchContent = "";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
});
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
describe("No matches", () => {
it("should return null when search content is not found", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `function goodbye() {
console.log("world");
}`;
it("should match at beginning for empty file and empty search", () => {
const fileContent = "";
const searchContent = "";
const result = findSearchMatch(fileContent, searchContent);
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
});
it("should return null when trimmed search content is not found", () => {
const fileContent = `function hello() {
describe("No matches", () => {
it("should return null when search content is not found", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `\n\nfunction goodbye() {
const searchContent = `function goodbye() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result?.strategyName).toEqual("jaroWinklerFuzzyMatch");
});
it("should return only fuzzy result when trimmed search content is not found", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `\n\nfunction goodbye() {
console.log("world");
}\n\n`;
const result = findSearchMatch(fileContent, searchContent);
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
expect(result?.strategyName).toEqual("jaroWinklerFuzzyMatch");
});
});
it("should return null for non-existent single line", () => {
const fileContent = `const a = 1;
const b = 2;
const c = 3;`;
const searchContent = `const d = 4;`;
describe("Edge cases", () => {
it("should handle empty file with non-empty search", () => {
const fileContent = "";
const searchContent = "function hello() {}";
const result = findSearchMatch(fileContent, searchContent);
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
expect(result).toBeNull();
});
it("should return null for partial match", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `function hello() {
console.log("universe");
}`;
it("should handle very large content", () => {
const repeatedLine = "const x = 1;\n";
const fileContent =
repeatedLine.repeat(1000) +
"const target = 2;\n" +
repeatedLine.repeat(1000);
const searchContent = "const target = 2;";
const result = findSearchMatch(fileContent, searchContent);
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
const expectedStart = repeatedLine.length * 1000;
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
strategyName: "exactMatch",
});
});
describe("Edge cases", () => {
it("should handle empty file with non-empty search", () => {
const fileContent = "";
const searchContent = "function hello() {}";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should handle very large content", () => {
const repeatedLine = "const x = 1;\n";
const fileContent =
repeatedLine.repeat(1000) +
"const target = 2;\n" +
repeatedLine.repeat(1000);
const searchContent = "const target = 2;";
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = repeatedLine.length * 1000;
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
});
});
it("should handle special characters and symbols", () => {
const fileContent = `const regex = /[a-zA-Z]+/g;
it("should handle special characters and symbols", () => {
const fileContent = `const regex = /[a-zA-Z]+/g;
const symbols = !@#$%^&*();
const unicode = "🚀 Hello 世界";`;
const searchContent = `const symbols = !@#$%^&*();`;
const searchContent = `const symbols = !@#$%^&*();`;
const result = findSearchMatch(fileContent, searchContent);
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = fileContent.indexOf(searchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
});
const expectedStart = fileContent.indexOf(searchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
strategyName: "exactMatch",
});
});
it("should prefer exact match over trimmed match", () => {
const fileContent = `function test() {
it("should prefer exact match over trimmed match", () => {
const fileContent = `function test() {
const x = 1;
}
function test() {
const x = 1;
}`;
const searchContent = `function test() {
const searchContent = `function test() {
const x = 1;
}`;
const result = findSearchMatch(fileContent, searchContent);
const result = findSearchMatch(fileContent, searchContent);
// Should find the first exact match, not a trimmed version
expect(result).toEqual({
startIndex: 0,
endIndex: searchContent.length,
});
});
it("should handle multiple occurrences and return first match", () => {
const fileContent = `const a = 1;
const b = 2;
const a = 1;`;
const searchContent = `const a = 1;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: searchContent.length,
});
// Should find the first exact match, not a trimmed version
expect(result).toEqual({
startIndex: 0,
endIndex: searchContent.length,
strategyName: "exactMatch",
});
});
describe("Real-world scenarios", () => {
it("should match typical function replacement", () => {
const fileContent = `class Calculator {
it("should handle multiple occurrences and return first match", () => {
const fileContent = `const a = 1;
const b = 2;
const a = 1;`;
const searchContent = `const a = 1;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: searchContent.length,
strategyName: "exactMatch",
});
});
});
describe("Whitespace-ignored matches", () => {
it("should match code with different indentation", () => {
const fileContent = `function example() {
const x = 1;
const y = 2;
return x + y;
}`;
const searchContent = `const x=1;
const y=2;
return x+y;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(20); // After "function example() {\n"
expect(result!.endIndex).toBe(72); // End of " return x + y;"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content contains the original whitespace
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
const x = 1;
const y = 2;
return x + y;`);
});
it("should match single line with different spacing", () => {
const fileContent = `const a = 1;
const b = 2;
const c = 3;`;
const searchContent = `const b=2;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(12); // After "const a = 1;"
expect(result!.endIndex).toBe(32); // End of "const b = 2;"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content preserves original spacing
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
const b = 2;`);
});
it("should match with tabs vs spaces", () => {
const fileContent = `function test() {
\tif (condition) {
\t\treturn true;
\t}
}`;
const searchContent = `if (condition) {
return true;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(17); // After "function test() {"
expect(result!.endIndex).toBe(53); // End of "\t}"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content preserves original tabs
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
\tif (condition) {
\t\treturn true;
\t}`);
});
it("should match complex whitespace patterns", () => {
const fileContent = `const obj = {
key1 : 'value1',
key2 : 'value2',
key3 : 'value3'
};`;
const searchContent = `key1:'value1',
key2:'value2',
key3:'value3'`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(13); // After "const obj = {"
expect(result!.endIndex).toBe(83); // End of " key3 : 'value3'"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content preserves original formatting
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
key1 : 'value1',
key2 : 'value2',
key3 : 'value3'`);
});
it("should handle newlines and mixed whitespace", () => {
const fileContent = `function calc() {
let result = 0;
result += 5;
return result;
}`;
const searchContent = `let result=0;result+=5;return result;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(17); // After "function calc() {\n\n"
expect(result!.endIndex).toBe(78); // End of " return result;"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content includes all original whitespace
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
let result = 0;
result += 5;
return result;`);
});
it("should prefer exact match over whitespace-ignored match", () => {
const fileContent = `const x=1;
const x = 1;`;
const searchContent = `const x=1;`;
const result = findSearchMatch(fileContent, searchContent);
// Should find the exact match first (at index 0), not the whitespace-ignored match
expect(result).toEqual({
startIndex: 0,
endIndex: 10,
strategyName: "exactMatch",
});
});
it("should handle empty content after whitespace removal", () => {
const fileContent = `function test() {
return 1;
}`;
const searchContent = `\n\n \t \n`;
const result = findSearchMatch(fileContent, searchContent);
// Should match at beginning for empty/whitespace-only content
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should handle complex code blocks with different formatting", () => {
const fileContent = `class Example {
constructor(name) {
this.name = name;
this.value = 0;
}
getValue() {
return this.value;
}
}`;
const searchContent = `constructor(name){
this.name=name;
this.value=0;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.startIndex).toBe(15); // After "class Example {"
expect(result!.endIndex).toBe(95); // End of " }"
expect(result!.strategyName).toBe("whitespaceIgnoredMatch");
// Verify the matched content preserves original formatting
const matchedContent = fileContent.substring(
result!.startIndex,
result!.endIndex,
);
expect(matchedContent).toBe(`
constructor(name) {
this.name = name;
this.value = 0;
}`);
});
it("should return null when no close match exists", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `this has nothing to do with the other option`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should handle multiple potential matches and return first", () => {
const fileContent = `const a=1;
const a = 1;
const a = 1;`;
const searchContent = `const a=1;`;
const result = findSearchMatch(fileContent, searchContent);
// Should find the first exact match
expect(result).toEqual({
startIndex: 0,
endIndex: 10,
strategyName: "exactMatch",
});
});
});
describe("Real-world scenarios", () => {
it("should match typical function replacement", () => {
const fileContent = `class Calculator {
constructor() {
this.result = 0;
}
@ -328,41 +555,43 @@ const a = 1;`;
return this;
}
}`;
const searchContent = ` reset() {
const searchContent = ` reset() {
this.result = 0;
return this;
}`;
const result = findSearchMatch(fileContent, searchContent);
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = fileContent.indexOf(searchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
});
const expectedStart = fileContent.indexOf(searchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
strategyName: "exactMatch",
});
});
it("should match import statement", () => {
const fileContent = `import React from 'react';
it("should match import statement", () => {
const fileContent = `import React from 'react';
import { useState, useEffect } from 'react';
import './App.css';
function App() {
return <div>Hello World</div>;
}`;
const searchContent = `import { useState, useEffect } from 'react';`;
const searchContent = `import { useState, useEffect } from 'react';`;
const result = findSearchMatch(fileContent, searchContent);
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = fileContent.indexOf(searchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
});
const expectedStart = fileContent.indexOf(searchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
strategyName: "exactMatch",
});
});
it("should match comment block", () => {
const fileContent = `/**
it("should match comment block", () => {
const fileContent = `/**
* This is a comment
* that spans multiple lines
*/
@ -370,16 +599,169 @@ function test() {
// Single line comment
return true;
}`;
const searchContent = `/**
const searchContent = `/**
* This is a comment
* that spans multiple lines
*/`;
const result = findSearchMatch(fileContent, searchContent);
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: searchContent.length,
expect(result).toEqual({
startIndex: 0,
endIndex: searchContent.length,
strategyName: "exactMatch",
});
});
describe("Jaro-Winkler fuzzy matching", () => {
describe("Basic fuzzy matching", () => {
it("should find fuzzy match for similar strings", () => {
const fileContent = `function calculateSum(a, b) {
return a + b;
}`;
const searchContent = `function calculateSum(x, y) {
return x + y;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
});
it("should find fuzzy match with minor typos", () => {
const fileContent = `const message = "Hello World";`;
const searchContent = `const mesage = "Hello World";`; // Missing 's' in 'message'
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result?.startIndex).toBe(0);
});
it("should find fuzzy match with different variable names", () => {
const fileContent = `let userAge = 25;
let userName = "John";`;
const searchContent = `let age = 25;
let name = "John";`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
});
it("should find fuzzy match for similar function signature", () => {
const fileContent = `function processUserData(userData) {
validateInput(userData);
return formatOutput(userData);
}`;
const searchContent = `function processData(data) {
validateInput(data);
return formatOutput(data);
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
});
});
describe("Multi-line fuzzy matching", () => {
it("should find fuzzy match for multi-line blocks", () => {
const fileContent = `class Calculator {
constructor() {
this.result = 0;
}
add(value) {
this.result += value;
return this;
}
}`;
const searchContent = `class Calculator {
constructor() {
this.value = 0;
}
add(num) {
this.value += num;
return this;
}
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
});
it("should find fuzzy match for partial blocks", () => {
const fileContent = `function processData(input) {
const validated = validateInput(input);
const processed = transformData(validated);
const result = formatOutput(processed);
return result;
}`;
const searchContent = `const validated = validateInput(input);
const processed = transformData(validated);`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
});
});
describe("Edge cases with fuzzy matching", () => {
it("should handle empty search content with fuzzy matching enabled", () => {
const fileContent = `function test() {}`;
const searchContent = "";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should handle empty file content with fuzzy matching enabled", () => {
const fileContent = "";
const searchContent = "function test() {}";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should prefer exact match over fuzzy match", () => {
const fileContent = `function test() { return true; }
function test() { return false; }`;
const searchContent = `function test() { return true; }`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result?.startIndex).toBe(0);
});
it("should handle very short strings", () => {
const fileContent = `a b c`;
const searchContent = `a c`;
const result = findSearchMatch(fileContent, searchContent);
// Should not match due to low similarity
expect(result).toBeNull();
});
it("should handle special characters in fuzzy matching", () => {
const fileContent = `const regex = /[a-zA-Z]+/g;
const symbols = !@#$%^&*();`;
const searchContent = `const regex = /[a-zA-Z0-9]+/g;
const symbols = !@#$%^&*();`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
});
});
});

View file

@ -1,7 +1,7 @@
/**
* Represents a match result with start and end character positions
* Represents a basic match result with start and end character positions
*/
export interface SearchMatchResult {
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 */
@ -9,31 +9,28 @@ export interface SearchMatchResult {
}
/**
* Find the exact match position for search content in file content.
* Uses simple exact matching with trimmed newlines for MVP.
*
* Matching Strategy:
* 1. If search content is empty, matches at the beginning of file (position 0)
* 2. Try exact string match first
* 3. Fallback to trimmed content match if exact match fails
*
* @param fileContent - The complete content of the file to search in
* @param searchContent - The content to search for
* @returns Match result with character positions, or null if no match found
* Represents a match result with start and end character positions
*/
export function findSearchMatch(
export interface SearchMatchResult extends BasicMatchResult {
/** The name of the strategy that successfully matched */
strategyName: string;
}
/**
* Strategy function type for finding matches
*/
type MatchStrategy = (
fileContent: string,
searchContent: string,
): SearchMatchResult | null {
// Strip leading/trailing newlines for basic matching strategy
const trimmedSearchContent = searchContent.trim();
) => BasicMatchResult | null;
if (trimmedSearchContent === "") {
// Empty search content matches the beginning of the file
return { startIndex: 0, endIndex: 0 };
}
// Try exact match first
/**
* Exact string matching strategy
*/
function exactMatch(
fileContent: string,
searchContent: string,
): BasicMatchResult | null {
const exactIndex = fileContent.indexOf(searchContent);
if (exactIndex !== -1) {
return {
@ -41,8 +38,17 @@ export function findSearchMatch(
endIndex: exactIndex + searchContent.length,
};
}
return null;
}
// Fallback: try trimmed content match
/**
* Trimmed content matching strategy
*/
function trimmedMatch(
fileContent: string,
searchContent: string,
): BasicMatchResult | null {
const trimmedSearchContent = searchContent.trim();
const trimmedIndex = fileContent.indexOf(trimmedSearchContent);
if (trimmedIndex !== -1) {
return {
@ -50,6 +56,262 @@ export function findSearchMatch(
endIndex: trimmedIndex + trimmedSearchContent.length,
};
}
return null;
}
/**
* Whitespace-ignored matching strategy
* Removes all whitespace from both content and search, then finds the match
*/
function whitespaceIgnoredMatch(
fileContent: string,
searchContent: string,
): BasicMatchResult | null {
// Remove all whitespace (spaces, tabs, newlines, etc.)
const strippedFileContent = fileContent.replace(/\s/g, "");
const strippedSearchContent = searchContent.replace(/\s/g, "");
if (strippedSearchContent === "") {
return null; // Empty search after stripping whitespace
}
const strippedIndex = strippedFileContent.indexOf(strippedSearchContent);
if (strippedIndex === -1) {
return null;
}
// Map the stripped position back to the original file content
let originalStartIndex = 0;
let strippedCharCount = 0;
// Find the original position by counting non-whitespace characters
for (let i = 0; i < fileContent.length; i++) {
if (strippedCharCount === strippedIndex) {
originalStartIndex = i;
break;
}
if (!/\s/.test(fileContent[i])) {
strippedCharCount++;
}
}
// Find the end position by counting the length of the search content
let originalEndIndex = originalStartIndex;
let matchedChars = 0;
for (
let i = originalStartIndex;
i < fileContent.length && matchedChars < strippedSearchContent.length;
i++
) {
if (!/\s/.test(fileContent[i])) {
matchedChars++;
}
originalEndIndex = i + 1;
}
return {
startIndex: originalStartIndex,
endIndex: originalEndIndex,
};
}
/**
* Calculate the Jaro similarity between two strings
*/
function jaroSimilarity(s1: string, s2: string): number {
if (s1 === s2) return 1.0;
if (s1.length === 0 || s2.length === 0) return 0.0;
const matchDistance = Math.floor(Math.max(s1.length, s2.length) / 2) - 1;
if (matchDistance < 0) return 0.0;
const s1Matches = new Array(s1.length).fill(false);
const s2Matches = new Array(s2.length).fill(false);
let matches = 0;
let transpositions = 0;
// Find matches
for (let i = 0; i < s1.length; i++) {
const start = Math.max(0, i - matchDistance);
const end = Math.min(i + matchDistance + 1, s2.length);
for (let j = start; j < end; j++) {
if (s2Matches[j] || s1[i] !== s2[j]) continue;
s1Matches[i] = true;
s2Matches[j] = true;
matches++;
break;
}
}
if (matches === 0) return 0.0;
// Count transpositions
let k = 0;
for (let i = 0; i < s1.length; i++) {
if (!s1Matches[i]) continue;
while (!s2Matches[k]) k++;
if (s1[i] !== s2[k]) transpositions++;
k++;
}
return (
(matches / s1.length +
matches / s2.length +
(matches - transpositions / 2) / matches) /
3.0
);
}
/**
* Calculate the Jaro-Winkler similarity between two strings
*/
function jaroWinklerSimilarity(
s1: string,
s2: string,
prefixScale = 0.1,
): number {
const jaroSim = jaroSimilarity(s1, s2);
if (jaroSim < 0.7) return jaroSim;
// Calculate common prefix length (up to 4 characters)
let prefixLength = 0;
const maxPrefix = Math.min(4, Math.min(s1.length, s2.length));
for (let i = 0; i < maxPrefix; i++) {
if (s1[i] === s2[i]) {
prefixLength++;
} else {
break;
}
}
return jaroSim + prefixLength * prefixScale * (1 - jaroSim);
}
/**
* Find the best fuzzy match for search content in file content using Jaro-Winkler
*/
function findFuzzyMatch(
fileContent: string,
searchContent: string,
threshold: number = 0.9,
): BasicMatchResult | null {
const searchLines = searchContent.split("\n");
const fileLines = fileContent.split("\n");
let bestMatch: BasicMatchResult | null = null;
let bestSimilarity = 0;
// Try matching the search content as a whole block
const searchBlock = searchContent.trim();
if (searchBlock.length > 5) {
// Require minimum length for meaningful matches
// Use sliding window approach for multi-line search
for (let i = 0; i <= fileLines.length - searchLines.length; i++) {
const candidateLines = fileLines.slice(i, i + searchLines.length);
const candidateBlock = candidateLines.join("\n").trim();
if (candidateBlock.length < 5) continue; // Skip very short blocks
const similarity = jaroWinklerSimilarity(searchBlock, candidateBlock);
if (similarity >= threshold && similarity > bestSimilarity) {
// Calculate character positions
const linesBeforeMatch = fileLines.slice(0, i);
const startIndex =
linesBeforeMatch.join("\n").length +
(linesBeforeMatch.length > 0 ? 1 : 0);
const endIndex = startIndex + candidateBlock.length;
bestMatch = {
startIndex,
endIndex,
};
bestSimilarity = similarity;
}
}
}
// Also try line-by-line matching for better granularity
for (
let searchLineIdx = 0;
searchLineIdx < searchLines.length;
searchLineIdx++
) {
const searchLine = searchLines[searchLineIdx].trim();
if (searchLine.length === 0 || searchLine.length < 3) continue; // Skip very short lines
for (let fileLineIdx = 0; fileLineIdx < fileLines.length; fileLineIdx++) {
const fileLine = fileLines[fileLineIdx].trim();
if (fileLine.length === 0 || fileLine.length < 3) continue; // Skip very short lines
const similarity = jaroWinklerSimilarity(searchLine, fileLine);
if (similarity >= threshold && similarity > bestSimilarity) {
// Calculate character positions for the line
const linesBeforeMatch = fileLines.slice(0, fileLineIdx);
const startIndex =
linesBeforeMatch.join("\n").length +
(linesBeforeMatch.length > 0 ? 1 : 0);
const endIndex = startIndex + fileLines[fileLineIdx].length;
bestMatch = {
startIndex,
endIndex,
};
bestSimilarity = similarity;
}
}
}
return bestMatch;
}
/**
* Ordered list of matching strategies to try with their names
*/
const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [
{ strategy: exactMatch, name: "exactMatch" },
{ strategy: trimmedMatch, name: "trimmedMatch" },
{ strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" },
{ strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" },
];
/**
* Find the exact match position for search content in file content.
* Uses multiple matching strategies in order of preference.
*
* Matching Strategy:
* 1. If search content is empty, matches at the beginning of file (position 0)
* 2. Try each matching strategy in order until one succeeds
*
* @param fileContent - The complete content of the file to search in
* @param searchContent - The content to search for
* @param config - Configuration options for matching behavior
* @returns Match result with character positions, or null if no match found
*/
export function findSearchMatch(
fileContent: string,
searchContent: string,
): SearchMatchResult | null {
const trimmedSearchContent = searchContent.trim();
if (trimmedSearchContent === "") {
// Empty search content matches the beginning of the file
return { startIndex: 0, endIndex: 0, strategyName: "emptySearch" };
}
// Try each matching strategy in order
for (const { strategy, name } of matchingStrategies) {
const result = strategy(fileContent, searchContent);
if (result !== null) {
return { ...result, strategyName: name };
}
}
return null;
}

View file

@ -55,7 +55,11 @@ export async function* addIndentation(
}
function modelIsInept(model: string): boolean {
return !(model.includes("gpt") || model.includes("claude"));
return !(
model.includes("gpt") ||
model.includes("claude") ||
model.includes("nova")
);
}
export async function* streamDiffLines({

15
core/index.d.ts vendored
View file

@ -428,7 +428,7 @@ export interface PromptLog {
completion: string;
}
export type MessageModes = "chat" | "agent";
export type MessageModes = "chat" | "agent" | "plan";
export type ToolStatus =
| "generating"
@ -568,6 +568,7 @@ export interface LLMOptions {
title?: string;
uniqueId?: string;
baseAgentSystemMessage?: string;
basePlanSystemMessage?: string;
baseChatSystemMessage?: string;
autocompleteOptions?: Partial<TabAutocompleteOptions>;
contextLength?: number;
@ -583,6 +584,7 @@ export interface LLMOptions {
// continueProperties
apiKeyLocation?: string;
envSecretLocations?: Record<string, string>;
apiBase?: string;
orgScopeId?: string | null;
@ -611,6 +613,8 @@ export interface LLMOptions {
// AWS options
profile?: string;
modelArn?: string;
accessKeyId?: string;
secretAccessKey?: string;
// AWS and VertexAI Options
region?: string;
@ -1084,6 +1088,7 @@ export interface ModelDescription {
apiBase?: string;
apiKeyLocation?: string;
envSecretLocations?: Record<string, string>;
orgScopeId?: string | null;
onPremProxyUrl?: string | null;
@ -1093,6 +1098,7 @@ export interface ModelDescription {
template?: TemplateType;
completionOptions?: BaseCompletionOptions;
baseAgentSystemMessage?: string;
basePlanSystemMessage?: string;
baseChatSystemMessage?: string;
requestOptions?: RequestOptions;
promptTemplates?: { [key: string]: string };
@ -1165,6 +1171,7 @@ export interface StdioOptions {
command: string;
args: string[];
env?: Record<string, string>;
cwd?: string;
requestOptions?: RequestOptions;
}
@ -1707,9 +1714,11 @@ export interface TerminalOptions {
export type RuleSource =
| "default-chat"
| "default-plan"
| "default-agent"
| "model-chat-options"
| "model-agent-options"
| "model-options-chat"
| "model-options-plan"
| "model-options-agent"
| "rules-block"
| "json-systemMessage"
| ".continuerules";

View file

@ -234,6 +234,23 @@ export class LanceDbIndex implements CodebaseIndex {
return results;
}
/**
* Due to a bug in indexing, some indexes have vectors
* without the surrounding []. These would fail to parse
* but this allows such existing indexes to function properly
*/
private parseVector(vector: string): number[] {
try {
return JSON.parse(vector);
} catch (err) {
try {
return JSON.parse(`[${vector}]`);
} catch (err2) {
throw new Error(`Failed to parse vector: ${vector}`, { cause: err2 });
}
}
}
async *update(
tag: IndexTag,
results: RefreshIndexResults,
@ -297,7 +314,7 @@ export class LanceDbIndex implements CodebaseIndex {
const lanceRows: LanceDbRow[] = [];
for (const item of cachedItems) {
try {
const vector = JSON.parse(item.vector);
const vector = this.parseVector(item.vector);
const { uuid, startLine, endLine, contents } = item;
lanceRows.push({

View file

@ -107,6 +107,17 @@ const siteIndexingConfigsAreEqual = (
);
};
const siteIndexingConfigsAreEqualExceptTitleAndFavicon = (
config1: SiteIndexingConfig,
config2: SiteIndexingConfig,
) => {
return (
config1.startUrl === config2.startUrl &&
config1.maxDepth === config2.maxDepth &&
config1.useLocalCrawling === config2.useLocalCrawling
);
};
/*
General process:
- On config update:
@ -395,6 +406,21 @@ export default class DocsService {
siteIndexingConfig: SiteIndexingConfig,
): Promise<boolean> {
try {
// Set a initial status when retrieving cache
this.handleStatusUpdate({
type: "docs",
id: startUrl,
embeddingsProviderId: embeddingId,
isReindexing: false,
title: siteIndexingConfig.title,
debugInfo: "Loaded from cache",
icon: siteIndexingConfig.faviconUrl,
url: startUrl,
progress: 0,
description: "Try to retrieve cache",
status: "indexing",
});
const cacheHit = await this.tryFetchFromCache(startUrl, embeddingId);
if (cacheHit) {
@ -429,7 +455,8 @@ export default class DocsService {
siteIndexingConfig: SiteIndexingConfig,
forceReindex: boolean = false,
): Promise<void> {
const { startUrl, useLocalCrawling, maxDepth } = siteIndexingConfig;
const { startUrl, useLocalCrawling, maxDepth, faviconUrl } =
siteIndexingConfig;
// First, if indexing is already in process, don't attempt
// This queue is necessary because indexAndAdd is invoked circularly by config edits
@ -685,7 +712,9 @@ export default class DocsService {
await this.deleteIndexes(startUrl);
}
const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl));
const favicon =
faviconUrl ||
(await fetchFavicon(new URL(siteIndexingConfig.startUrl)));
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
return;
@ -718,10 +747,6 @@ export default class DocsService {
void this.ide.showToast("info", `Successfully indexed ${startUrl}`);
}
this.messenger?.send("refreshSubmenuItems", {
providers: ["docs"],
});
removeFromFailedGlobalContext(siteIndexingConfig);
} catch (e) {
console.error(
@ -766,14 +791,22 @@ export default class DocsService {
const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
// Try to get a favicon for the site
const favicon = await fetchFavicon(new URL(startUrl));
const favicon =
this.statuses.get(startUrl)?.icon ||
(await fetchFavicon(new URL(startUrl)));
// Always try to make the title match what users set in the config
const title =
this.statuses.get(startUrl)?.title ||
siteEmbeddings.title ||
new URL(startUrl).hostname;
// Add the cached embeddings to our database
await this.add({
favicon,
siteIndexingConfig: {
startUrl,
title: siteEmbeddings.title || new URL(startUrl).hostname,
title,
},
chunks: siteEmbeddings.chunks,
embeddings: siteEmbeddings.chunks.map((c) => c.embedding),
@ -910,6 +943,10 @@ export default class DocsService {
);
if (cacheHit) {
// If cache hit, refresh the submenu items for docs
this.messenger?.send("refreshSubmenuItems", {
providers: ["docs"],
});
// If cache hit, retry the search once
return await this.retrieveChunks(startUrl, vector, nRetrieve, true);
}
@ -987,8 +1024,7 @@ export default class DocsService {
const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl);
// Anything found in old config, new config, AND sqlite that doesn't match should be reindexed
// TODO if only favicon and title change, only update, don't embed
// Otherwise anything found in new config that isn't in sqlite should be added/indexed
// Anything found in new config that isn't in sqlite should be added/indexed
const addedDocs: SiteIndexingConfig[] = [];
const changedDocs: SiteIndexingConfig[] = [];
for (const doc of newConfigDocs) {
@ -999,12 +1035,26 @@ export default class DocsService {
(d) => d.startUrl === doc.startUrl,
);
// TODO: Changes to the docs config made while Continue isn't running won't be caught
if (oldConfigDoc && !siteIndexingConfigsAreEqual(oldConfigDoc, doc)) {
changedDocs.push(doc);
// When only the title or faviconUrl changed, Update the sqlite metadate instead of reindexing
if (
siteIndexingConfigsAreEqualExceptTitleAndFavicon(
oldConfigDoc,
doc,
)
) {
await this.updateMetadataInSqlite(doc);
} else {
changedDocs.push(doc);
}
} else {
if (forceReindex) {
changedDocs.push(doc);
} else {
// This is a temperary fix to catch the changes to the docs config that were made when Continue isn't running
// We only update title and faviconUrl here
await this.updateMetadataInSqlite(doc);
// if get's here, not changed, no update needed, mark as complete
this.handleStatusUpdate({
type: "docs",
@ -1036,6 +1086,10 @@ export default class DocsService {
console.error("Error syncing docs index on config update", e);
} finally {
this.isSyncing = false;
// Refresh the submenu items for docs
this.messenger?.send("refreshSubmenuItems", {
providers: ["docs"],
});
}
}
@ -1182,6 +1236,27 @@ export default class DocsService {
);
}
private async updateMetadataInSqlite(siteIndexingConfig: SiteIndexingConfig) {
const { startUrl, title, faviconUrl } = siteIndexingConfig;
const favicon = faviconUrl || (await fetchFavicon(new URL(startUrl)));
if (!this.config.selectedModelByRole.embed) {
console.warn(
`Attempting to add metadata for ${startUrl} without embeddings provider specified`,
);
return;
}
const db = await this.getOrCreateSqliteDb();
await db.run(
`UPDATE ${DocsService.sqlitebTableName} SET title = ?, favicon = ? WHERE startUrl = ? AND embeddingsProviderId = ?`,
title,
favicon,
startUrl,
this.config.selectedModelByRole.embed.embeddingId,
);
}
private addToConfig(siteIndexingConfig: SiteIndexingConfig) {
// Handles the case where a user has manually added the doc to config.json
// so it already exists in the file
@ -1286,5 +1361,6 @@ export default class DocsService {
this.messenger?.send("refreshSubmenuItems", {
providers: ["docs"],
});
this.statuses.delete(startUrl);
}
}

View file

@ -46,6 +46,7 @@ import { PROVIDER_TOOL_SUPPORT } from "./toolSupport.js";
const PROVIDER_HANDLES_TEMPLATING: string[] = [
"lmstudio",
"openai",
"nvidia",
"ollama",
"together",
"novita",
@ -237,6 +238,11 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
return "none";
}
// Nova Pro requests always sent through Converse API, so formatting not necessary
if (lower.includes("nova")) {
return "none";
}
if (lower.includes("codestral")) {
return "none";
}

View file

@ -106,6 +106,19 @@ test("autodetectTemplateType returns 'none' for Codestral models", () => {
expect(autodetectTemplateType("codestral-22b")).toBe("none");
});
test("autodetectTemplateType returns 'none' for Nova models", () => {
expect(autodetectTemplateType("nova")).toBe("none");
expect(autodetectTemplateType("Nova")).toBe("none");
expect(autodetectTemplateType("nova-pro")).toBe("none");
expect(autodetectTemplateType("nova-lite")).toBe("none");
expect(autodetectTemplateType("nova-micro")).toBe("none");
expect(autodetectTemplateType("nova-premier")).toBe("none");
expect(autodetectTemplateType("amazon-nova-pro")).toBe("none");
expect(autodetectTemplateType("amazon-nova-lite")).toBe("none");
expect(autodetectTemplateType("amazon-nova-micro")).toBe("none");
expect(autodetectTemplateType("amazon-nova-premier")).toBe("none");
});
test("autodetectTemplateType returns 'alpaca' for Alpaca and Wizard models", () => {
expect(autodetectTemplateType("alpaca")).toBe("alpaca");
expect(autodetectTemplateType("Alpaca")).toBe("alpaca");

View file

@ -15,6 +15,7 @@ const DEFAULT_MAX_BATCH_SIZE = 64;
export enum LLMConfigurationStatuses {
VALID = "valid",
MISSING_API_KEY = "missing-api-key",
MISSING_ENV_SECRET = "missing-env-secret",
}
export {

View file

@ -1,7 +1,4 @@
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
"https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts";
export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL =
export const DEFAULT_SYSTEM_MESSAGES_URL =
"https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts";
export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\
@ -54,7 +51,7 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
You are in chat mode.
If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically.
If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
If needed concisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
${EDIT_CODE_INSTRUCTIONS}
@ -66,3 +63,17 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
</important_rules>`;
// The note about read-only tools is for MCP servers
// For now, all MCP tools are included so model can decide if they are read-only
export const DEFAULT_PLAN_SYSTEM_MESSAGE = `\
<important_rules>
You are in plan mode, in which you help the user understand and construct a plan.
Only use read-only tools. Do not use any tools that would write to non-temporary files.
If the user wants to make changes, offer that they can switch to Agent mode to give you access to write tools to make the suggested updates.
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
${EDIT_CODE_INSTRUCTIONS}
In plan mode, only write code when directly suggesting changes. Prioritize understanding and developing a plan.
</important_rules>`;

View file

@ -141,6 +141,7 @@ export abstract class BaseLLM implements ILLM {
title?: string;
baseChatSystemMessage?: string;
basePlanSystemMessage?: string;
baseAgentSystemMessage?: string;
contextLength: number;
maxStopWords?: number | undefined;
@ -155,6 +156,7 @@ export abstract class BaseLLM implements ILLM {
// continueProperties
apiKeyLocation?: string;
envSecretLocations?: Record<string, string>;
apiBase?: string;
orgScopeId?: string | null;
@ -172,6 +174,8 @@ export abstract class BaseLLM implements ILLM {
accountId?: string;
aiGatewaySlug?: string;
profile?: string | undefined;
accessKeyId?: string;
secretAccessKey?: string;
// For IBM watsonx
deploymentId?: string;
@ -209,6 +213,7 @@ export abstract class BaseLLM implements ILLM {
this.title = options.title;
this.uniqueId = options.uniqueId ?? "None";
this.baseAgentSystemMessage = options.baseAgentSystemMessage;
this.basePlanSystemMessage = options.basePlanSystemMessage;
this.baseChatSystemMessage = options.baseChatSystemMessage;
this.contextLength =
options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH;
@ -246,6 +251,7 @@ export abstract class BaseLLM implements ILLM {
// continueProperties
this.apiKeyLocation = options.apiKeyLocation;
this.envSecretLocations = options.envSecretLocations;
this.orgScopeId = options.orgScopeId;
this.apiBase = options.apiBase;
@ -270,6 +276,8 @@ export abstract class BaseLLM implements ILLM {
this.region = options.region;
this.projectId = options.projectId;
this.profile = options.profile;
this.accessKeyId = options.accessKeyId;
this.secretAccessKey = options.secretAccessKey;
this.openaiAdapter = this.createOpenAiAdapter();

View file

@ -71,11 +71,7 @@ class Bedrock extends BaseLLM {
if (!options.apiBase) {
this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
if (options.profile) {
this.profile = options.profile;
} else {
this.profile = "bedrock";
}
this.requestOptions = {
region: options.region,
headers: {},
@ -609,17 +605,24 @@ class Bedrock extends BaseLLM {
}
private async _getCredentials() {
if (this.accessKeyId && this.secretAccessKey) {
return {
accessKeyId: this.accessKeyId,
secretAccessKey: this.secretAccessKey,
};
}
const profile = this.profile ?? "bedrock";
try {
return await fromNodeProviderChain({
profile: this.profile,
profile: profile,
ignoreCache: true,
})();
} catch (e) {
console.warn(
`AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
`AWS profile with name ${profile} not found in ~/.aws/credentials, using default profile`,
);
return await fromNodeProviderChain()();
}
return await fromNodeProviderChain()();
}
// EMBED //

View file

@ -1,4 +1,4 @@
import { GoogleAuth } from "google-auth-library";
import { AuthClient, GoogleAuth, JWT, auth } from "google-auth-library";
import { streamResponse, streamSse } from "@continuedev/fetch";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
@ -14,30 +14,40 @@ class VertexAI extends BaseLLM {
declare vertexProvider: "mistral" | "anthropic" | "gemini" | "unknown";
declare anthropicInstance: Anthropic;
declare geminiInstance: Gemini;
static AUTH_SCOPES = "https://www.googleapis.com/auth/cloud-platform";
static defaultOptions: Partial<LLMOptions> | undefined = {
maxEmbeddingBatchSize: 250,
region: "us-central1",
};
private clientPromise = new GoogleAuth({
scopes: "https://www.googleapis.com/auth/cloud-platform",
})
.getClient()
.catch((e) => {
console.warn(`Failed to load credentials for Vertex AI: ${e.message}`);
});
private clientPromise: Promise<AuthClient | void>;
private static getDefaultApiBaseFrom(options: LLMOptions) {
const { region, projectId } = options;
if (!region || !projectId) {
throw new Error(
"region and projectId must be defined if apiBase is not provided",
);
}
return `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/`;
}
/*
Vertex Supports 3 different URL formats
1. Standard VertexAI: e.g. https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/publishers/google/models/{model}:streamGenerateContent
2. Tuned model: e.g. https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/endpoints/{endpoint}:streamGenerateContent
3. Express mode: e.g. https://aiplatform.googleapis.com/v1/publishers/google/models/{model}:streamGenerateContent?key={API_KEY} // see https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview
Authentication can be done using the following
2. Access token obtained using Google Auth client, passed to endpoint that includes full model path with project id and region
1. API Key (express mode), region and projectId will be ignored
In all cases we have defined apiBase to be up to everything including the location.
Standard api base: https://{location}-aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/
Express api base: https://aiplatform.googleapis.com/v1/
TODO endpoints is not currently supported (api base is same as standard but we don't have a way to add endpoint name yet
Note that VertexAI uses the term "service endpoint" and "model", like:
{service-endpoint}/v1/{model}:streamGenerateContent
So "model" includes the project, location, publisher, etc
Express mode has limited support
and CRITICALLY is only available to NEW users who had NOT used cloud services before.
However it is pretty common as gemini becomes more popular.
Only Gemini models are supported for now
https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview#models
*/
constructor(_options: LLMOptions) {
if (_options.region !== "us-central1") {
// Any region outside of us-central1 has a max batch size of 5.
@ -47,7 +57,7 @@ class VertexAI extends BaseLLM {
);
}
super(_options);
this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options);
this.vertexProvider =
_options.model.includes("mistral") ||
_options.model.includes("codestral") ||
@ -58,24 +68,130 @@ class VertexAI extends BaseLLM {
: _options.model.includes("gemini")
? "gemini"
: "unknown";
// Set client authentication promise
const { apiKey, region, projectId, env } = _options;
const keyFile = env?.keyFile;
const keyJson = env?.keyJson;
// Acceptable authentication methods:
// apiKey only
// region and projectId AND (keyFile OR keyJson OR nothing)
if (apiKey) {
// Consider warning here instead of throwing error
if (region || projectId || keyFile || keyJson) {
throw new Error(
"Vertex in express mode (api key only) cannot be configured with region, projectId, keyFile, or keyJson",
);
// console.warn(
// "Region, projectId, and key path/file are ignored when apiKey is set. See VertexAI Express Mode docs https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview",
// );
}
if (this.vertexProvider !== "gemini") {
throw new Error(
"VertexAI: only gemini models are supported in express (apiKey) mode. See https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview#models",
);
}
} else {
if (!region && !projectId) {
throw new Error(
"region and projectId are required for VertexAI (when not using express/apiKey mode)",
);
}
if (keyFile && keyJson) {
throw new Error(
"VertexAI credentials can be configured with either keyFile or keyJson but not both",
);
}
}
if (keyJson) {
// Loading keys from manually set JSON
if (typeof keyJson !== "string") {
throw new Error("VertexAI: keyJson must be a JSON string");
}
try {
const parsed = JSON.parse(keyJson);
if (!parsed?.private_key) {
throw new Error("VertexAI: keyJson must contain a valid private key");
}
parsed.private_key = parsed.private_key.replace(/\\n/g, "\n");
const jsonClient = auth.fromJSON(parsed);
if (jsonClient instanceof JWT) {
jsonClient.scopes = [VertexAI.AUTH_SCOPES];
} else {
throw new Error("VertexAI: keyJson must be a valid JWT");
}
this.clientPromise = Promise.resolve(jsonClient);
} catch (e) {
throw new Error("VertexAI: Failed to parse keyJson");
}
} else if (keyFile) {
// Loading keys from manually set file path
if (typeof keyFile !== "string") {
throw new Error("VertexAI: keyFile must be a string");
}
this.clientPromise = new GoogleAuth({
scopes: VertexAI.AUTH_SCOPES,
keyFile,
})
.getClient()
.catch((e) => {
console.warn(
`Failed to load credentials for Vertex AI: ${e.message}`,
);
});
} else {
// Loading keys from local credentials or environment variable
this.clientPromise = new GoogleAuth({
scopes: VertexAI.AUTH_SCOPES,
})
.getClient()
.catch((e) => {
console.warn(
`Failed to load credentials for Vertex AI: ${e.message}`,
);
});
}
// Set api base
if (!this.apiBase) {
if (apiKey) {
// Express mode
this.apiBase = `https://aiplatform.googleapis.com/v1/`;
} else {
this.apiBase = `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/`;
}
}
// Uses instances of other LLMs since underlying functionality is the same
this.anthropicInstance = new Anthropic(_options);
this.geminiInstance = new Gemini(_options);
}
async fetch(url: RequestInfo | URL, init?: RequestInit) {
const client = await this.clientPromise;
const result = await client?.getAccessToken();
if (!result?.token) {
throw new Error(
"Could not get an access token. Set up your Google Application Default Credentials.",
);
async fetch(url: URL, init?: RequestInit) {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (this.apiKey) {
url.searchParams.set("key", this.apiKey);
} else {
const client = await this.clientPromise;
const result = await client?.getAccessToken();
if (!result?.token) {
throw new Error(
"Could not get an access token. Set up your Google Application Default Credentials.",
);
}
headers.Authorization = `Bearer ${result.token}`;
}
return await super.fetch(url, {
...init,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${result.token}`,
...init?.headers,
...headers,
},
});
}
@ -85,6 +201,10 @@ class VertexAI extends BaseLLM {
const convertedArgs = this.anthropicInstance.convertArgs(options);
// Remove the `model` property and add `anthropic_version`
// For claude 4 models
// anthropic_version is a required parameter and must be set to "vertex-2024-10-22".
// const
const { model, ...finalOptions } = convertedArgs;
return {
...finalOptions,
@ -104,6 +224,8 @@ class VertexAI extends BaseLLM {
this.cacheBehavior?.cacheSystemMessage && systemMessage
);
// <code>/v1/publishers/anthropic/models/claude-3-5-sonnet-20240620:streamRawPredict
const apiURL = new URL(
`publishers/anthropic/models/${options.model}:streamRawPredict`,
this.apiBase,

View file

@ -8,7 +8,6 @@ import {
LLMOptions,
} from "../..";
import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString";
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../defaultSystemMessages";
import { BaseLLM } from "../index";
import Anthropic from "./Anthropic";
import Asksage from "./Asksage";
@ -141,9 +140,9 @@ export async function llmFromDescription(
let baseChatSystemMessage: string | undefined = undefined;
if (desc.systemMessage !== undefined) {
baseChatSystemMessage = DEFAULT_CHAT_SYSTEM_MESSAGE;
baseChatSystemMessage += "\n\n";
baseChatSystemMessage += await renderTemplatedString(
// baseChatSystemMessage = DEFAULT_CHAT_SYSTEM_MESSAGE;
// baseChatSystemMessage += "\n\n";
baseChatSystemMessage = await renderTemplatedString(
Handlebars,
desc.systemMessage,
{},
@ -163,6 +162,7 @@ export async function llmFromDescription(
cls.defaultOptions?.completionOptions?.maxTokens,
},
baseChatSystemMessage,
basePlanSystemMessage: baseChatSystemMessage,
baseAgentSystemMessage: baseChatSystemMessage,
logger: llmLogger,
uniqueId,

View file

@ -40,6 +40,7 @@ class ContinueProxy extends OpenAI {
this.apiType = undefined;
this.actualApiBase = options.apiBase;
this.apiKeyLocation = options.apiKeyLocation;
this.envSecretLocations = options.envSecretLocations;
this.orgScopeId = options.orgScopeId;
this.onPremProxyUrl = options.onPremProxyUrl;
if (this.onPremProxyUrl) {
@ -60,6 +61,7 @@ class ContinueProxy extends OpenAI {
protected extraBodyProperties(): Record<string, any> {
const continueProperties: ContinueProperties = {
apiKeyLocation: this.apiKeyLocation,
envSecretLocations: this.envSecretLocations,
apiBase: this.actualApiBase,
orgScopeId: this.orgScopeId ?? null,
env: this.configEnv,
@ -70,13 +72,24 @@ class ContinueProxy extends OpenAI {
}
getConfigurationStatus() {
if (!this.apiKeyLocation) {
if (!this.apiKeyLocation && !this.envSecretLocations) {
return LLMConfigurationStatuses.VALID;
}
const secretLocation = decodeSecretLocation(this.apiKeyLocation);
if (secretLocation.secretType === SecretType.NotFound) {
return LLMConfigurationStatuses.MISSING_API_KEY;
if (this.apiKeyLocation) {
const secretLocation = decodeSecretLocation(this.apiKeyLocation);
if (secretLocation.secretType === SecretType.NotFound) {
return LLMConfigurationStatuses.MISSING_API_KEY;
}
}
if (this.envSecretLocations) {
for (const secretLocation of Object.values(this.envSecretLocations)) {
const decoded = decodeSecretLocation(secretLocation);
if (decoded.secretType === SecretType.NotFound) {
return LLMConfigurationStatuses.MISSING_ENV_SECRET;
}
}
}
return LLMConfigurationStatuses.VALID;

View file

@ -324,6 +324,10 @@ export const getApplicableRules = (
return applicableRules;
};
export function getRuleId(rule: RuleWithSource): string {
return rule.slug ?? rule.ruleFile ?? rule.name ?? rule.source;
}
export const getSystemMessageWithRules = ({
baseSystemMessage,
userMessage,

View file

@ -19,6 +19,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"claude-3-7",
"claude-3.7",
"claude-sonnet-4",
"claude-4-sonnet",
"gpt-4",
"o3",
"gemini",
@ -33,6 +34,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"claude-3-7",
"claude-3.7",
"claude-sonnet-4",
"claude-4-sonnet",
"claude-opus-4",
].some((part) => model.toLowerCase().startsWith(part))
) {
@ -95,7 +97,12 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"claude-3-7-sonnet",
"claude-3.7-sonnet",
"claude-sonnet-4",
"claude-4-sonnet",
"claude-opus-4",
"nova-lite",
"nova-pro",
"nova-micro",
"nova-premier",
].some((part) => model.toLowerCase().includes(part))
) {
return true;

89
core/package-lock.json generated
View file

@ -82,6 +82,8 @@
"@babel/preset-env": "^7.24.7",
"@biomejs/biome": "1.6.4",
"@google/generative-ai": "^0.11.4",
"@shikijs/colorized-brackets": "^3.7.0",
"@shikijs/transformers": "^3.7.0",
"@types/diff": "^7.0.1",
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.12",
@ -4752,66 +4754,87 @@
"integrity": "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==",
"peer": true
},
"node_modules/@shikijs/core": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/@shikijs/core/-/core-3.6.0.tgz",
"integrity": "sha512-9By7Xb3olEX0o6UeJyPLI1PE1scC4d3wcVepvtv2xbuN9/IThYN4Wcwh24rcFeASzPam11MCq8yQpwwzCgSBRw==",
"node_modules/@shikijs/colorized-brackets": {
"version": "3.7.0",
"resolved": "https://registry.npmjs.org/@shikijs/colorized-brackets/-/colorized-brackets-3.7.0.tgz",
"integrity": "sha512-4tGMLMTqP7cw3AddjIjz7AlpPFuXpm2aDO25+uUHhGOVJvyDkm3a4cVb5W66QiBZFYsOyU6mx+lnsSimNTLsWQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@shikijs/types": "3.6.0",
"shiki": "3.7.0"
}
},
"node_modules/@shikijs/core": {
"version": "3.7.0",
"resolved": "https://registry.npmjs.org/@shikijs/core/-/core-3.7.0.tgz",
"integrity": "sha512-yilc0S9HvTPyahHpcum8eonYrQtmGTU0lbtwxhA6jHv4Bm1cAdlPFRCJX4AHebkCm75aKTjjRAW+DezqD1b/cg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@shikijs/types": "3.7.0",
"@shikijs/vscode-textmate": "^10.0.2",
"@types/hast": "^3.0.4",
"hast-util-to-html": "^9.0.5"
}
},
"node_modules/@shikijs/engine-javascript": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-3.6.0.tgz",
"integrity": "sha512-7YnLhZG/TU05IHMG14QaLvTW/9WiK8SEYafceccHUSXs2Qr5vJibUwsDfXDLmRi0zHdzsxrGKpSX6hnqe0k8nA==",
"version": "3.7.0",
"resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-3.7.0.tgz",
"integrity": "sha512-0t17s03Cbv+ZcUvv+y33GtX75WBLQELgNdVghnsdhTgU3hVcWcMsoP6Lb0nDTl95ZJfbP1mVMO0p3byVh3uuzA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@shikijs/types": "3.6.0",
"@shikijs/types": "3.7.0",
"@shikijs/vscode-textmate": "^10.0.2",
"oniguruma-to-es": "^4.3.3"
}
},
"node_modules/@shikijs/engine-oniguruma": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-3.6.0.tgz",
"integrity": "sha512-nmOhIZ9yT3Grd+2plmW/d8+vZ2pcQmo/UnVwXMUXAKTXdi+LK0S08Ancrz5tQQPkxvjBalpMW2aKvwXfelauvA==",
"version": "3.7.0",
"resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-3.7.0.tgz",
"integrity": "sha512-5BxcD6LjVWsGu4xyaBC5bu8LdNgPCVBnAkWTtOCs/CZxcB22L8rcoWfv7Hh/3WooVjBZmFtyxhgvkQFedPGnFw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@shikijs/types": "3.6.0",
"@shikijs/types": "3.7.0",
"@shikijs/vscode-textmate": "^10.0.2"
}
},
"node_modules/@shikijs/langs": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-3.6.0.tgz",
"integrity": "sha512-IdZkQJaLBu1LCYCwkr30hNuSDfllOT8RWYVZK1tD2J03DkiagYKRxj/pDSl8Didml3xxuyzUjgtioInwEQM/TA==",
"version": "3.7.0",
"resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-3.7.0.tgz",
"integrity": "sha512-1zYtdfXLr9xDKLTGy5kb7O0zDQsxXiIsw1iIBcNOO8Yi5/Y1qDbJ+0VsFoqTlzdmneO8Ij35g7QKF8kcLyznCQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@shikijs/types": "3.6.0"
"@shikijs/types": "3.7.0"
}
},
"node_modules/@shikijs/themes": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-3.6.0.tgz",
"integrity": "sha512-Fq2j4nWr1DF4drvmhqKq8x5vVQ27VncF8XZMBuHuQMZvUSS3NBgpqfwz/FoGe36+W6PvniZ1yDlg2d4kmYDU6w==",
"version": "3.7.0",
"resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-3.7.0.tgz",
"integrity": "sha512-VJx8497iZPy5zLiiCTSIaOChIcKQwR0FebwE9S3rcN0+J/GTWwQ1v/bqhTbpbY3zybPKeO8wdammqkpXc4NVjQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@shikijs/types": "3.6.0"
"@shikijs/types": "3.7.0"
}
},
"node_modules/@shikijs/transformers": {
"version": "3.7.0",
"resolved": "https://registry.npmjs.org/@shikijs/transformers/-/transformers-3.7.0.tgz",
"integrity": "sha512-VplaqIMRNsNOorCXJHkbF5S0pT6xm8Z/s7w7OPZLohf8tR93XH0krvUafpNy/ozEylrWuShJF0+ftEB+wFRwGA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@shikijs/core": "3.7.0",
"@shikijs/types": "3.7.0"
}
},
"node_modules/@shikijs/types": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/@shikijs/types/-/types-3.6.0.tgz",
"integrity": "sha512-cLWFiToxYu0aAzJqhXTQsFiJRTFDAGl93IrMSBNaGSzs7ixkLfdG6pH11HipuWFGW5vyx4X47W8HDQ7eSrmBUg==",
"version": "3.7.0",
"resolved": "https://registry.npmjs.org/@shikijs/types/-/types-3.7.0.tgz",
"integrity": "sha512-MGaLeaRlSWpnP0XSAum3kP3a8vtcTsITqoEPYdt3lQG3YCdQH4DnEhodkYcNMcU0uW0RffhoD1O3e0vG5eSBBg==",
"dev": true,
"license": "MIT",
"dependencies": {
@ -16249,18 +16272,18 @@
}
},
"node_modules/shiki": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/shiki/-/shiki-3.6.0.tgz",
"integrity": "sha512-tKn/Y0MGBTffQoklaATXmTqDU02zx8NYBGQ+F6gy87/YjKbizcLd+Cybh/0ZtOBX9r1NEnAy/GTRDKtOsc1L9w==",
"version": "3.7.0",
"resolved": "https://registry.npmjs.org/shiki/-/shiki-3.7.0.tgz",
"integrity": "sha512-ZcI4UT9n6N2pDuM2n3Jbk0sR4Swzq43nLPgS/4h0E3B/NrFn2HKElrDtceSf8Zx/OWYOo7G1SAtBLypCp+YXqg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@shikijs/core": "3.6.0",
"@shikijs/engine-javascript": "3.6.0",
"@shikijs/engine-oniguruma": "3.6.0",
"@shikijs/langs": "3.6.0",
"@shikijs/themes": "3.6.0",
"@shikijs/types": "3.6.0",
"@shikijs/core": "3.7.0",
"@shikijs/engine-javascript": "3.7.0",
"@shikijs/engine-oniguruma": "3.7.0",
"@shikijs/langs": "3.7.0",
"@shikijs/themes": "3.7.0",
"@shikijs/types": "3.7.0",
"@shikijs/vscode-textmate": "^10.0.2",
"@types/hast": "^3.0.4"
}

View file

@ -18,6 +18,8 @@
"@babel/preset-env": "^7.24.7",
"@biomejs/biome": "1.6.4",
"@google/generative-ai": "^0.11.4",
"@shikijs/colorized-brackets": "^3.7.0",
"@shikijs/transformers": "^3.7.0",
"@types/diff": "^7.0.1",
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.12",

View file

@ -22,7 +22,7 @@ export const searchAndReplaceInFileTool: Tool = {
function: {
name: BuiltInToolNames.SearchAndReplaceInFile,
description:
"Description: Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.",
"Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.",
parameters: {
type: "object",
required: ["filepath", "diff"],
@ -56,7 +56,11 @@ Critical rules:
* Include just the changing lines, and a few surrounding lines if needed for uniqueness.
* Do not include long runs of unchanging lines in SEARCH/REPLACE blocks.
* Each line must be complete. Never truncate lines mid-way through as this can cause matching failures.
4. Special operations:
4. Splitting up tool calls:
* When making multiple closely related edits to the same file, you should try to use multiple SEARCH/REPLACE blocks in a single tool call, rather than making multiple separate tool calls
* If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls
* DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call]
5. Special operations:
* To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
* To delete code: Use empty REPLACE section

View file

@ -1,6 +1,34 @@
import { ToolImpl } from ".";
import { getUrlContextItems } from "../../context/providers/URLContextProvider";
const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000;
export const fetchUrlContentImpl: ToolImpl = async (args, extras) => {
return getUrlContextItems(args.url, extras.fetch);
const contextItems = await getUrlContextItems(args.url, extras.fetch);
// Track truncated content
const truncatedUrls: string[] = [];
// Check and truncate each context item
const processedItems = contextItems.map((item) => {
if (item.content.length > DEFAULT_FETCH_URL_CHAR_LIMIT) {
truncatedUrls.push(args.url);
return {
...item,
content: item.content.substring(0, DEFAULT_FETCH_URL_CHAR_LIMIT),
};
}
return item;
});
// Add truncation warning if needed
if (truncatedUrls.length > 0) {
processedItems.push({
name: "URL content truncation warning",
description: "Informs that URL content was truncated",
content: `The content from ${truncatedUrls.join(", ")} was truncated because it exceeded the ${DEFAULT_FETCH_URL_CHAR_LIMIT} character limit. If you need more content, consider fetching specific sections or using a more targeted approach.`,
});
}
return processedItems;
};

View file

@ -0,0 +1,91 @@
import { expect, test, vi } from "vitest";
import { fetchUrlContentImpl } from "./fetchUrlContent";
vi.mock("../../context/providers/URLContextProvider", () => ({
getUrlContextItems: vi.fn(),
}));
import { ToolExtras } from "../..";
import { getUrlContextItems } from "../../context/providers/URLContextProvider";
const mockExtras = {
fetch: vi.fn() as any,
ide: {} as any,
} as unknown as ToolExtras;
test("fetchUrlContent should not truncate content under character limit", async () => {
const shortContent = "This is a short content";
const mockContextItems = [
{
name: "Test URL",
description: "Test URL description",
content: shortContent,
},
];
(getUrlContextItems as any).mockResolvedValue(mockContextItems);
const result = await fetchUrlContentImpl(
{ url: "https://example.com" },
mockExtras,
);
expect(result).toHaveLength(1);
expect(result[0].content).toBe(shortContent);
});
test("fetchUrlContent should truncate content exceeding character limit", async () => {
const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000;
// Create a string exceeding the character limit
const longContent = "a".repeat(DEFAULT_FETCH_URL_CHAR_LIMIT + 1000);
const mockContextItems = [
{
name: "Test URL",
description: "Test URL description",
content: longContent,
},
];
(getUrlContextItems as any).mockResolvedValue(mockContextItems);
const result = await fetchUrlContentImpl(
{ url: "https://example.com" },
mockExtras,
);
expect(result).toHaveLength(2); // Original item + warning
expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT);
expect(result[1].name).toBe("URL content truncation warning");
expect(result[1].content).toContain("was truncated");
expect(result[1].content).toContain("20000 character limit");
});
test("fetchUrlContent should add truncation warning with multiple truncated items", async () => {
const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000;
// Create strings exceeding the character limit
const longContent1 = "a".repeat(DEFAULT_FETCH_URL_CHAR_LIMIT + 500);
const longContent2 = "b".repeat(DEFAULT_FETCH_URL_CHAR_LIMIT + 1000);
const mockContextItems = [
{
name: "Test URL 1",
description: "Test URL description 1",
content: longContent1,
},
{
name: "Test URL 2",
description: "Test URL description 2",
content: longContent2,
},
];
(getUrlContextItems as any).mockResolvedValue(mockContextItems);
const result = await fetchUrlContentImpl(
{ url: "https://example.com" },
mockExtras,
);
expect(result).toHaveLength(3); // Two original items + warning
expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT);
expect(result[1].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT);
expect(result[2].name).toBe("URL content truncation warning");
});

View file

@ -2,30 +2,59 @@ import { ToolImpl } from ".";
import { walkDir } from "../../indexing/walkDir";
import { resolveRelativePathInDir } from "../../util/ideUtils";
export function resolveLsToolDirPath(dirPath: string | undefined) {
if (!dirPath || dirPath === ".") {
return "/";
}
if (dirPath.startsWith(".")) {
return dirPath.slice(1);
}
return dirPath.replace(/\\/g, "/");
}
const MAX_LS_TOOL_LINES = 200;
export const lsToolImpl: ToolImpl = async (args, extras) => {
const uri = await resolveRelativePathInDir(args.dirPath, extras.ide);
const dirPath = resolveLsToolDirPath(args?.dirPath);
const uri = await resolveRelativePathInDir(dirPath, extras.ide);
if (!uri) {
throw new Error(
`Directory ${args.dirPath} not found. Make sure to use forward-slash paths. Do not use e.g. "."`,
`Directory ${args.dirPath} not found. Make sure to use forward-slash paths`,
);
}
const entries = await walkDir(uri, extras.ide, {
returnRelativeUrisPaths: true,
include: "both",
recursive: args.recursive ?? false,
recursive: args?.recursive ?? false,
});
const content =
entries.length > 0
? entries.join("\n")
: `No files/folders found in ${args.dirPath}`;
const lines = entries.slice(0, MAX_LS_TOOL_LINES);
return [
let content =
lines.length > 0
? lines.join("\n")
: `No files/folders found in ${dirPath}`;
const contextItems = [
{
name: "File/folder list",
description: `Files/folders in ${args.dirPath}`,
description: `Files/folders in ${dirPath}`,
content,
},
];
if (entries.length > MAX_LS_TOOL_LINES) {
let warningContent = `${entries.length - MAX_LS_TOOL_LINES} ls entries were truncated`;
if (args?.recursive) {
warningContent += ". Try using a non-recursive search";
}
contextItems.push({
name: "ls truncation warning",
description: "Informs the model that ls results were truncated",
content: warningContent,
});
}
return contextItems;
};

View file

@ -0,0 +1,96 @@
import { expect, test, vi } from "vitest";
import { ToolExtras } from "../..";
import * as walkDirModule from "../../indexing/walkDir";
import { lsToolImpl, resolveLsToolDirPath } from "./lsTool";
vi.mock("../../indexing/walkDir");
const mockExtras = {
ide: {
fileExists: async (path: string) => true,
getWorkspaceDirs: async () => ["dir1"],
},
} as unknown as ToolExtras;
test("resolveLsToolDirPath handles undefined path", () => {
expect(resolveLsToolDirPath(undefined)).toBe("/");
});
test("resolveLsToolDirPath handles empty string", () => {
expect(resolveLsToolDirPath("")).toBe("/");
});
test("resolveLsToolDirPath handles dot", () => {
expect(resolveLsToolDirPath(".")).toBe("/");
});
test("resolveLsToolDirPath handles dot relative", () => {
expect(resolveLsToolDirPath("./hi")).toBe("/hi");
});
test("resolveLsToolDirPath normalizes backslashes to forward slashes", () => {
expect(resolveLsToolDirPath("path\\to\\dir")).toBe("path/to/dir");
});
test("resolveLsToolDirPath preserves forward slashes", () => {
expect(resolveLsToolDirPath("path/to/dir")).toBe("path/to/dir");
});
test("lsToolImpl truncates output when entries exceed MAX_LS_TOOL_LINES", async () => {
// Generate more than MAX_LS_TOOL_LINES entries (which is 200)
const mockEntries = Array.from({ length: 250 }, (_, i) => `file${i}.txt`);
// Mock walkDir to return our large array
vi.spyOn(walkDirModule, "walkDir").mockResolvedValue(mockEntries);
const result = await lsToolImpl(
{ dirPath: "testDir", recursive: true },
mockExtras,
);
// Check that the result contains the truncation message
expect(result.length).toBe(2);
expect(result[0].content).toContain("file1.txt");
expect(result[0].content).toContain("file199.txt");
expect(result[1].content).toContain("Try using a non-recursive search");
expect(result[1].content).toContain("50 ls entries were truncated");
// Check that only MAX_LS_TOOL_LINES entries are included
const contentLines = result[0].content.split("\n");
// Account for the truncation message line
expect(contentLines.length).toBe(200);
// Check the suggestion to use non-recursive search is included
expect(result[1].content).toContain("Try using a non-recursive search");
});
test("lsToolImpl shows truncation message without suggestion for non-recursive search", async () => {
// Generate more than MAX_LS_TOOL_LINES entries
const mockEntries = Array.from({ length: 250 }, (_, i) => `file${i}.txt`);
// Mock walkDir to return our large array
vi.spyOn(walkDirModule, "walkDir").mockResolvedValue(mockEntries);
const result = await lsToolImpl(
{ dirPath: "testDir", recursive: false },
mockExtras,
);
// Check that the result contains the truncation message
expect(result.length).toBe(2);
expect(result[1].content).toContain("50 ls entries were truncated");
// Check that the suggestion to use non-recursive search is NOT included
expect(result[1].content).not.toContain("Try using a non-recursive search");
});
test("lsToolImpl shows message when no files are found", async () => {
// Mock walkDir to return empty array
vi.spyOn(walkDirModule, "walkDir").mockResolvedValue([]);
const result = await lsToolImpl({ dirPath: "emptyDir" }, mockExtras);
// Check that the result contains the "no files found" message
expect(result.length).toBe(1);
expect(result[0].content).toBe("No files/folders found in emptyDir");
});

View file

@ -1,8 +1,36 @@
import { ToolImpl } from ".";
import { fetchSearchResults } from "../../context/providers/WebContextProvider";
import { ToolImpl } from ".";
const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000;
export const searchWebImpl: ToolImpl = async (args, extras) => {
const webResults = await fetchSearchResults(args.query, 5, extras.fetch);
return webResults;
// Track truncated results
const truncatedResults: string[] = [];
// Check and truncate each result
const processedResults = webResults.map((result, index) => {
if (result.content.length > DEFAULT_WEB_SEARCH_CHAR_LIMIT) {
truncatedResults.push(
result.name || result.description || `Result #${index + 1}`,
);
return {
...result,
content: result.content.substring(0, DEFAULT_WEB_SEARCH_CHAR_LIMIT),
};
}
return result;
});
// Add truncation warning if needed
if (truncatedResults.length > 0) {
processedResults.push({
name: "Web search truncation warning",
description: "Informs that search results were truncated",
content: `The content from the following search results was truncated because it exceeded the ${DEFAULT_WEB_SEARCH_CHAR_LIMIT} character limit: ${truncatedResults.join(", ")}. For more detailed information, consider refining your search query.`,
});
}
return processedResults;
};

View file

@ -0,0 +1,107 @@
import { expect, test, vi } from "vitest";
import { searchWebImpl } from "./searchWeb";
// Mock the fetchSearchResults function
vi.mock("../../context/providers/WebContextProvider", () => ({
fetchSearchResults: vi.fn(),
}));
const mockExtras = {
fetch: vi.fn() as any,
ide: {} as any,
} as unknown as ToolExtras;
import { ToolExtras } from "../..";
import { fetchSearchResults } from "../../context/providers/WebContextProvider";
test("searchWeb should not truncate results under character limit", async () => {
const shortContent = "This is a short search result content";
const mockSearchResults = [
{
name: "Result 1",
description: "Search result description 1",
content: shortContent,
},
{
name: "Result 2",
description: "Search result description 2",
content: shortContent,
},
];
(fetchSearchResults as any).mockResolvedValue(mockSearchResults);
const result = await searchWebImpl({ query: "test query" }, mockExtras);
expect(result).toHaveLength(2);
expect(result[0].content).toBe(shortContent);
expect(result[1].content).toBe(shortContent);
});
test("searchWeb should truncate results exceeding character limit", async () => {
const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000;
// Create a string exceeding the character limit
const longContent = "a".repeat(DEFAULT_WEB_SEARCH_CHAR_LIMIT + 1000);
const shortContent = "This is a short search result content";
const mockSearchResults = [
{
name: "Result 1",
description: "Search result description 1",
content: longContent,
},
{
name: "Result 2",
description: "Search result description 2",
content: shortContent,
},
];
(fetchSearchResults as any).mockResolvedValue(mockSearchResults);
const result = await searchWebImpl({ query: "test query" }, mockExtras);
expect(result).toHaveLength(3); // Two results + warning
expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT);
expect(result[1].content).toBe(shortContent);
expect(result[2].name).toBe("Web search truncation warning");
expect(result[2].content).toContain("truncated");
expect(result[2].content).toContain("Result 1");
expect(result[2].content).not.toContain("Result 2");
});
test("searchWeb should include all truncated results in the warning", async () => {
const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000;
// Create strings exceeding the character limit
const longContent1 = "a".repeat(DEFAULT_WEB_SEARCH_CHAR_LIMIT + 500);
const longContent2 = "b".repeat(DEFAULT_WEB_SEARCH_CHAR_LIMIT + 1000);
const shortContent = "This is a short search result content";
const mockSearchResults = [
{
name: "Result 1",
description: "Search result description 1",
content: longContent1,
},
{
name: "Result 2",
description: "Search result description 2",
content: longContent2,
},
{
name: "Result 3",
description: "Search result description 3",
content: shortContent,
},
];
(fetchSearchResults as any).mockResolvedValue(mockSearchResults);
const result = await searchWebImpl({ query: "test query" }, mockExtras);
expect(result).toHaveLength(4); // Three results + warning
expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT);
expect(result[1].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT);
expect(result[2].content).toBe(shortContent);
expect(result[3].name).toBe("Web search truncation warning");
expect(result[3].content).toContain("Result 1");
expect(result[3].content).toContain("Result 2");
expect(result[3].content).not.toContain("Result 3");
});

View file

@ -1,15 +1,39 @@
import { ToolImpl } from ".";
import { ContextItem } from "../..";
import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache";
export const DEFAULT_GIT_DIFF_LINE_LIMIT = 5000;
export const viewDiffImpl: ToolImpl = async (args, extras) => {
const diffs = await getDiffsFromCache(extras.ide); // const diffs = await extras.ide.getDiff(true);
// TODO includeUnstaged should be an option
return [
const combinedDiff = diffs.join("\n");
const diffLines = combinedDiff.split("\n");
let truncated = false;
let processedDiff = combinedDiff;
if (diffLines.length > DEFAULT_GIT_DIFF_LINE_LIMIT) {
truncated = true;
processedDiff = diffLines.slice(0, DEFAULT_GIT_DIFF_LINE_LIMIT).join("\n");
}
const contextItems: ContextItem[] = [
{
name: "Diff",
description: "The current git diff",
content: diffs.join("\n"),
content: processedDiff,
},
];
if (truncated) {
contextItems.push({
name: "Diff truncation warning",
description: "Informs that git diff was truncated",
content: `The git diff was truncated because it exceeded ${DEFAULT_GIT_DIFF_LINE_LIMIT} lines. Consider viewing specific files or focusing on smaller changes.`,
});
}
return contextItems;
};

View file

@ -0,0 +1,87 @@
import { expect, test, vi } from "vitest";
import { DEFAULT_GIT_DIFF_LINE_LIMIT, viewDiffImpl } from "./viewDiff";
// Mock the getDiffsFromCache function
vi.mock("../../autocomplete/snippets/gitDiffCache", () => ({
getDiffsFromCache: vi.fn(),
}));
import { ToolExtras } from "../..";
import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache";
const mockExtras = {
fetch: vi.fn() as any,
ide: {} as any,
} as unknown as ToolExtras;
test("viewDiff should not truncate diffs under line limit", async () => {
// Create a small diff with just a few lines
const smallDiff = [
"diff --git a/file1.txt b/file1.txt",
"index 1234..5678 100644",
"--- a/file1.txt",
"+++ b/file1.txt",
"@@ -1,3 +1,4 @@",
" line1",
"-line2",
"+line2 modified",
"+line3 added",
];
(getDiffsFromCache as any).mockResolvedValue(smallDiff);
const result = await viewDiffImpl({}, mockExtras);
expect(result).toHaveLength(1); // Just the diff, no warning
expect(result[0].name).toBe("Diff");
expect(result[0].content).toBe(smallDiff.join("\n"));
});
test("viewDiff should truncate diffs exceeding line limit", async () => {
// Create a large diff that exceeds the line limit
const largeDiffLines = Array(DEFAULT_GIT_DIFF_LINE_LIMIT + 1000).fill(
"line content",
);
const largeDiff = [
"diff --git a/file1.txt b/file1.txt",
"index 1234..5678 100644",
...largeDiffLines,
];
(getDiffsFromCache as any).mockResolvedValue([largeDiff.join("\n")]);
const result = await viewDiffImpl({}, mockExtras);
expect(result).toHaveLength(2); // Diff + warning
// Count the number of lines in the result
const resultLines = result[0].content.split("\n");
expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT);
// Check the warning
expect(result[1].name).toBe("Diff truncation warning");
expect(result[1].content).toContain("truncated");
expect(result[1].content).toContain(`${DEFAULT_GIT_DIFF_LINE_LIMIT} lines`);
});
test("viewDiff should handle multiple diffs correctly", async () => {
const DEFAULT_GIT_DIFF_LINE_LIMIT = 5000;
// Create multiple diffs that together exceed the line limit
const diff1Lines = Array(3000).fill("diff1 line");
const diff2Lines = Array(3000).fill("diff2 line");
const diff1 = diff1Lines.join("\n");
const diff2 = diff2Lines.join("\n");
(getDiffsFromCache as any).mockResolvedValue([diff1, diff2]);
const result = await viewDiffImpl({}, mockExtras);
expect(result).toHaveLength(2); // Diff + warning
// Count the number of lines in the result
const resultLines = result[0].content.split("\n");
expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT);
// Check the warning
expect(result[1].name).toBe("Diff truncation warning");
});

View file

@ -39,14 +39,13 @@ export const getConfigDependentToolDefinitions = (
params: ConfigDependentToolParams,
): Tool[] => [
requestRuleTool(params),
// Search and replace is now generally available
searchAndReplaceInFileTool,
// Keep edit file tool available for models that need it
editFileTool,
...(params.enableExperimentalTools
? [
searchAndReplaceInFileTool,
viewRepoMapTool,
viewSubdirectoryTool,
codebaseTool,
]
: [editFileTool]),
? [viewRepoMapTool, viewSubdirectoryTool, codebaseTool]
: []),
];
export const getToolsForIde = async (ide: IDE): Promise<Tool[]> =>

View file

@ -6,11 +6,11 @@ keywords: [customize, configure, config]
Continue can be deeply customized. For example you might:
- **Change your Model Provider**. Continue allows you to choose your favorite or even add multiple model providers. This allows you to use different models for different tasks, or to try another model if you're not happy with the results from your current model. Continue supports all of the popular model providers, including OpenAI, Anthropic, Microsoft/Azure, Mistral, and more. You can even self host your own model provider if you'd like. Learn more about [model providers](../advanced/model-providers/top-level/openai.mdx).
- **Select different models for specific tasks**. Different Continue features can use different models. We call these _model roles_. For example, you can use a different model for chat than you do for autocomplete. Learn more about [model roles](../advanced/model-roles/00-intro.mdx).
- **Add a Context Provider**. Context providers allow you to add information to your prompts, giving your LLM additional context to work with. Context providers allow you to reference snippets from your codebase, or lookup relevant documentation, or use a search engine to find information and much more. Learn more about [context providers](../advanced/custom-providers.mdx).
- **Create a Slash Command**. Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](../advanced/deep-dives/slash-commands.mdx).
- **Call external tools and functions**. Unchain your LLM with the power of tools using [Agent](../features/agent/quick-start.mdx). Add custom tools using [MCP Servers](../advanced/deep-dives/mcp.mdx)
- **Change your Model Provider**. Continue allows you to choose your favorite or even add multiple model providers. This allows you to use different models for different tasks, or to try another model if you're not happy with the results from your current model. Continue supports all of the popular model providers, including OpenAI, Anthropic, Microsoft/Azure, Mistral, and more. You can even self host your own model provider if you'd like. Learn more about [model providers](../customize/model-providers/top-level/openai.mdx).
- **Select different models for specific tasks**. Different Continue features can use different models. We call these _model roles_. For example, you can use a different model for chat than you do for autocomplete. Learn more about [model roles](../customize/model-roles/00-intro.mdx).
- **Add a Context Provider**. Context providers allow you to add information to your prompts, giving your LLM additional context to work with. Context providers allow you to reference snippets from your codebase, or lookup relevant documentation, or use a search engine to find information and much more. Learn more about [context providers](../customize/custom-providers.mdx).
- **Create a Slash Command**. Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](../customize/deep-dives/slash-commands.mdx).
- **Call external tools and functions**. Unchain your LLM with the power of tools using [Agent](../features/agent/quick-start.mdx). Add custom tools using [MCP Servers](../customize/deep-dives/mcp.mdx)
Whatever you choose, you'll probably start by editing your Assistant.
@ -21,4 +21,4 @@ You can easily access your assistant configuration from the Continue Chat sideba
![configure an assistant](/img/configure-continue.png)
- See [Editing Hub Assistants](../hub/assistants/edit-an-assistant.md) for more details on managing your hub assistant
- See the [Config Deep Dive](../advanced/deep-dives/configuration.md) for more details on configuring local assistants.
- See the [Config Deep Dive](../customize/deep-dives/configuration.md) for more details on configuring local assistants.

View file

@ -18,23 +18,4 @@ Model Context Protocol servers provide specialized functionality:
## Learn More
Learn more in the [MCP deep dive](../advanced/deep-dives/mcp.mdx), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details.
description: Model Context Protocol servers provide specialized functionality
keywords: [mcp, blocks, model context protocol, integrations, tools]
sidebar_position: 4
---
Model Context Protocol servers provide specialized functionality:
- Enable integration with external tools and systems
- Create extensible interfaces for custom capabilities
- Support more complex interactions with your development environment
- Allow partners to contribute specialized functionality
- Database Connectors: Understand schema and data models during development
![MCP Blocks Overview](/img/mcp-blocks-overview.png)
## Learn More
Learn more in the [MCP deep dive](../advanced/deep-dives/mcp.mdx), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details.
Learn more in the [MCP deep dive](../customize/deep-dives/mcp.mdx), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details.

View file

@ -8,17 +8,17 @@ sidebar_position: 1
These blocks form the foundation of the entire assistant experience, offering different specialized capabilities:
- **[Chat](../advanced/model-roles/chat.mdx)**: Power conversational interactions about code and provide detailed guidance
- **[Edit](../advanced/model-roles/edit.mdx)**: Handle complex code transformations and refactoring tasks
- **[Apply](../advanced/model-roles/apply.mdx)**: Execute targeted code modifications with high accuracy
- **[Autocomplete](../advanced/model-roles/autocomplete.md)**: Provide real-time suggestions as developers type
- **[Embedding](../advanced/model-roles/embeddings.mdx)**: Transform code into vector representations for semantic search
- **[Reranker](../advanced/model-roles/reranking.mdx)**: Improve search relevance by ordering results based on semantic meaning
- **[Chat](../customize/model-roles/chat.mdx)**: Power conversational interactions about code and provide detailed guidance
- **[Edit](../customize/model-roles/edit.mdx)**: Handle complex code transformations and refactoring tasks
- **[Apply](../customize/model-roles/apply.mdx)**: Execute targeted code modifications with high accuracy
- **[Autocomplete](../customize/model-roles/autocomplete.md)**: Provide real-time suggestions as developers type
- **[Embedding](../customize/model-roles/embeddings.mdx)**: Transform code into vector representations for semantic search
- **[Reranker](../customize/model-roles/reranking.mdx)**: Improve search relevance by ordering results based on semantic meaning
![Model Blocks Overview](/img/model-blocks-overview.png)
## Learn More
Continue supports [many model providers](../advanced/model-providers/top-level/openai.mdx), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have various roles like `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`.
Continue supports [many model providers](../customize/model-providers/top-level/openai.mdx), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have various roles like `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`.
Read more about roles [here](../advanced/model-roles/00-intro.mdx) and view [`models`](/reference#models) in the YAML Reference.
Read more about roles [here](../customize/model-roles/00-intro.mdx) and view [`models`](/reference#models) in the YAML Reference.

View file

@ -18,4 +18,4 @@ These are the specialized instructions that shape how models respond:
## Learn More
Prompt blocks have the same syntax as [prompt files](../advanced/deep-dives/prompts.md). The `config.yaml` spec for `prompts` can be found [here](/reference#prompts).
Prompt blocks have the same syntax as [prompt files](../customize/deep-dives/prompts.md). The `config.yaml` spec for `prompts` can be found [here](/reference#prompts).

View file

@ -22,4 +22,4 @@ Your assistant detects rule blocks and applies the specified rules while in [Age
## Learn More
Learn more in the [rules deep dive](../advanced/deep-dives/rules.mdx), and view [`rules`](/reference#rules) in the YAML Reference for more details.
Learn more in the [rules deep dive](../customize/deep-dives/rules.mdx), and view [`rules`](/reference#rules) in the YAML Reference for more details.

View file

@ -987,6 +987,33 @@ The response 200 OK should be a JSON object with the following structure:
"description": "",
"content": ""
}
// For response context items with hyperlinks
[
{
"name": "",
"description": "",
"content": "",
"uri": {
"type": "file" or "url",
"value": "file:///path/to/file" or "https://example.com",
}
}
]
// OR
{
"name": "",
"description": "",
"content": "",
"uri": {
"type": "file" or "url",
"value": "file:///path/to/file" or "https://example.com",
}
}
```
### `@Commits`

View file

@ -91,7 +91,7 @@ Explore autocomplete model configurations on [the hub](https://hub.continue.dev/
### Autocomplete User Settings
{/* - `Use autocomplete cache`: If on, caches completions */}
The following settings can be configured for autocompletion in the IDE extension [User Settings Page](./settings.md):
The following settings can be configured for autocompletion in the IDE extension [User Settings Page](../settings.md):
- `Multiline Autocompletions`: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto`
- `Disable autocomplete in files`: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., "\_/.md, \*/.txt"

View file

@ -110,6 +110,7 @@ MCP blocks follow the established syntax for blocks, with a few additional prope
- `type` (optional): The type of the MCP server: `sse`, `stdio`, `streamable-http`
- `args` (optional): Arguments to pass to the command.
- `env` (optional): Secrets to be injected into the command as environment variables.
- `cwd` (optional): Working directory to run the command in. Can be absolute or relative path.
### Transport Types
@ -132,12 +133,22 @@ For local MCP servers that communicate via standard input and output:
```yaml
mcpServers:
- name: Name
- name: SQLite Server
type: stdio
command: npx
args:
- "@modelcontextprotocol/server-sqlite"
- "/path/to/your/database.db"
- "./database.db"
cwd: "/path/to/project"
- name: Local Project Server
command: npm
args:
- "run"
- "mcp-server"
cwd: "./my-project"
env:
NODE_ENV: "production"
```
#### Streamable HTTP Transport

View file

@ -14,7 +14,7 @@ Below are details for each property that can be set in `config.json`. The config
### `models`
Your **chat** models are defined here, which are used for [Chat](/features/chat/how-it-works), [Edit](/features/edit/how-it-works) and [VS Code actions](/advanced/deep-dives/vscode-actions).
Your **chat** models are defined here, which are used for [Chat](/features/chat/how-it-works), [Edit](/features/edit/how-it-works) and [VS Code actions](/customize/deep-dives/vscode-actions).
Each model has specific configuration options tailored to its provider and functionality, which can be seen as suggestions while editing the json.
@ -506,7 +506,7 @@ Example
### Fully deprecated settings
Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the [User Settings Page](/advanced/deep-dives/settings). If found in `config.json`, they will be auto-migrated to User Settings and removed from `config.json`.
Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the [User Settings Page](/customize/settings). If found in `config.json`, they will be auto-migrated to User Settings and removed from `config.json`.
- `allowAnonymousTelemetry`: This value will be migrated to the safest merged value (`false` if either are `false`).
- `promptPath`: This value will override during migration.
@ -527,4 +527,4 @@ Some deprecated `config.json` settings are no longer stored in config and have b
- `displayRawMarkdown`
- `showChatScrollbar`
See [User Settings Page](/advanced/deep-dives/settings) for more information about each option.
See [User Settings Page](/customize/settings) for more information about each option.

View file

Before

Width:  |  Height:  |  Size: 858 KiB

After

Width:  |  Height:  |  Size: 858 KiB

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