Merge branch 'main' into core-vitest/config

This commit is contained in:
uinstinct 2025-06-23 18:44:06 +05:30
commit 3cb606bc86
246 changed files with 8381 additions and 8451 deletions

View file

@ -44,8 +44,8 @@ export const AllMediaTypes = [
2. EXTRACT NEW INFORMATION
New information will be pulled from the internet.
If you do not see a web search tool, let me know.
Fetch information from the internet using the search web and read url tools.
If you do not see either of these tools, stop and let me know.
Retrieve the following sites per these providers, and consider these notes on how to extract the information:
- "gemini": https://ai.google.dev/gemini-api/docs/models - maxCompletionTokens is called "Output token limit", contextLength is called "Input token limit"

View file

@ -1,16 +1,111 @@
---
globs: docs/**/*.{md,mdx}
description: Standards for writing and maintaining Continue Docs
globs: docs/\*_/_.{md,mdx}
description: This style guide should be used as a reference for maintaining consistency across all Continue documentation
alwaysApply: false
---
# Continue Docs Standards
# Continue Documentation Style Guide
## Overview
## Writing Tone & Voice
### Conversational and Direct
- Follow Docusaurus documentation standards
- Include YAML frontmatter with title, description, and keywords
- Use consistent heading hierarchy starting with h2 (##)
- Include relevant Admonition components for tips, warnings, and info
- Use descriptive alt text for images
- Include cross-references to related documentation
- Reference other docs with relative paths
- Use simple, conversational language that gets straight to the point
- Avoid overly technical jargon when simpler terms work
- Write as if speaking directly to the developer using the tool
- Keep paragraphs concise and scannable
- Use code blocks with appropriate language tags
**Example:**
✅ "You send it a question, and it replies with an answer"
❌ "The system processes user queries and generates corresponding responses"
### Helpful and Instructional
- Focus on helping users accomplish their goals
- Use active voice and imperative mood for instructions
- Assume users want to get things done quickly
- Include relevant Admonition components for tips, warnings, and info
**Example:**
✅ "Press cmd/ctrl + L to begin a new session"
❌ "A new session can be initiated by pressing cmd/ctrl + L"
### Practical and Task-Oriented
- Emphasize what users can accomplish with each feature
- Lead with benefits and use cases before diving into mechanics
- Keep explanations grounded in real-world scenarios
## Content Structure
### Page Organization
1. **Visual Introduction**: Lead with GIFs or images showing the feature in action
2. **Purpose Statement**: Brief explanation of what the feature does and when to use it
3. **Step-by-Step Instructions**: Clear, actionable steps with keyboard shortcuts
4. **Platform-Specific Notes**: Separate sections for VS Code and JetBrains when needed
5. **Additional Tips**: Advanced usage or troubleshooting notes
### Section Headers
- Use consistent heading hierarchy starting with h2 (##)
- Include YAML frontmatter with title, description, and keywords
- Use action-oriented headers that describe what users will do
- Format: "Verb + object" (e.g., "Type a request and press enter")
- Keep headers concise but descriptive
- Use title case
**Examples:**
✅ "Highlight code and activate"
✅ "Accept or reject changes"
✅ "Switch between different models"
### Lists and Steps
- Use numbered lists for sequential steps
- Use bullet points for feature lists or options
- Keep list items parallel in structure
- Start action items with verbs
## Technical Writing Standards
### Code and Keyboard Shortcuts
- Use `backticks` for inline code elements
- Format keyboard shortcuts consistently: `cmd/ctrl + L`
- Always provide shortcuts for Mac/Windows/Linux
- Use code blocks for configuration examples with proper syntax highlighting
### Cross-References
- Link to related sections using descriptive anchor text
- Use relative links to other documentation pages
- Format: `[descriptive text](/path/to/page)`
### Platform Differences
- Always address both VS Code and JetBrains when applicable
- Use clear subheadings to separate platform-specific instructions
- Lead with the more common platform (typically VS Code) when both are covered
## Language Conventions
### Terminology
- **Consistent Terms**: Use the same terms throughout (e.g., "LLM" not "AI model" in some places)
- **Product Names**: Capitalize product names correctly (VS Code, JetBrains, Continue)
- **Feature Names**: Use consistent capitalization for Continue features (Chat, Edit, Agent, Autocomplete)
### Abbreviations
- Spell out acronyms on first use, then use abbreviation consistently
- Common abbreviations: LLM, IDE, API, URL
### Pronouns
- Use "you" to address the user directly
- Use "it" to refer to the tool/model
- Avoid "we" unless referring to the Continue team

View file

@ -10,6 +10,7 @@
"@typescript-eslint/naming-convention": "off",
"@typescript-eslint/no-floating-promises": "warn",
"@typescript-eslint/semi": "warn",
"@typescript-eslint/no-misused-promises": "error",
"curly": "warn",
"eqeqeq": "warn",
"no-throw-literal": "warn",

View file

@ -396,6 +396,11 @@ jobs:
npx tsc --noEmit
npm run lint
- name: Run vitest tests
run: |
cd extensions/vscode
npm run vitest
core-tests:
needs: [install-core, install-config-yaml]
runs-on: ubuntu-latest
@ -434,7 +439,7 @@ jobs:
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}

View file

@ -123,6 +123,12 @@ version of Node.js for this project by running the following command in the root
nvm use
```
Then, install Vite globally
```bash
npm i -g vite
```
#### Fork the Continue Repository
1. Go to the [Continue GitHub repository](https://github.com/continuedev/continue) and fork it to your GitHub account.

View file

@ -20,6 +20,7 @@
"posthog-node": "^3.6.3",
"system-ca": "^1.0.2",
"tar": "^7.4.3",
"undici": "^7.10.0",
"uuid": "^9.0.1",
"vectordb": "^0.4.20",
"win-ca": "^3.5.1"
@ -52,9 +53,9 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.10",
"@continuedev/fetch": "^1.0.13",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.25",
"@continuedev/openai-adapters": "^1.0.32",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -105,6 +106,7 @@
"sqlite3": "^5.1.7",
"system-ca": "^1.0.3",
"tar": "^7.4.3",
"tree-sitter-structured-text": "^0.0.1",
"tree-sitter-wasms": "^0.1.11",
"uuid": "^9.0.1",
"vectordb": "^0.4.20",
@ -143,8 +145,10 @@
"myers-diff": "^2.1.0",
"onnxruntime-common": "1.14.0",
"onnxruntime-web": "1.14.0",
"tree-sitter-cli": "^0.22.5",
"ts-jest": "^29.1.1",
"typescript": "^5.6.3"
"typescript": "^5.6.3",
"vitest": "^3.1.4"
},
"engines": {
"node": ">=20.19.0"
@ -6773,6 +6777,15 @@
"node": ">=8"
}
},
"node_modules/undici": {
"version": "7.10.0",
"resolved": "https://registry.npmmirror.com/undici/-/undici-7.10.0.tgz",
"integrity": "sha512-u5otvFBOBZvmdjWLVW+5DAc9Nkq8f24g0O9oY7qw2JVIF1VocIFoyz9JFkuVOS2j41AufeO0xnlweJ2RLT8nGw==",
"license": "MIT",
"engines": {
"node": ">=20.18.1"
}
},
"node_modules/universal-user-agent": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.1.tgz",

View file

@ -53,6 +53,7 @@
"posthog-node": "^3.6.3",
"system-ca": "^1.0.2",
"tar": "^7.4.3",
"undici": "^7.10.0",
"uuid": "^9.0.1",
"vectordb": "^0.4.20",
"win-ca": "^3.5.1"

View file

@ -4,6 +4,7 @@ const { rimrafSync } = require("rimraf");
const tar = require("tar");
const { RIPGREP_VERSION, TARGET_TO_RIPGREP_RELEASE } = require("./targets");
const AdmZip = require("adm-zip");
const { ProxyAgent } = require("undici");
const RIPGREP_BASE_URL = `https://github.com/BurntSushi/ripgrep/releases/download/${RIPGREP_VERSION}`;
@ -16,8 +17,13 @@ const RIPGREP_BASE_URL = `https://github.com/BurntSushi/ripgrep/releases/downloa
*/
async function downloadFile(url, destPath) {
// Use the built-in fetch API instead of node-fetch
// Use proxy if set in environment variables
const proxy = process.env.https_proxy || process.env.HTTPS_PROXY;
const agent = proxy ? new ProxyAgent(proxy) : undefined;
const response = await fetch(url, {
redirect: "follow", // Automatically follow redirects
dispatcher: agent,
});
if (!response.ok) {

View file

@ -127,6 +127,7 @@ export class CompletionProvider {
public async provideInlineCompletionItems(
input: AutocompleteInput,
token: AbortSignal | undefined,
force?: boolean,
): Promise<AutocompleteOutcome | undefined> {
try {
// Create abort signal if not given
@ -146,8 +147,12 @@ export class CompletionProvider {
const options = await this._getAutocompleteOptions(llm);
// Debounce
if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) {
return undefined;
if (!force) {
if (
await this.debouncer.delayAndShouldDebounce(options.debounceDelay)
) {
return undefined;
}
}
if (llm.promptTemplates?.autocomplete) {

View file

@ -40,7 +40,7 @@ export async function testRootPathContext(
// @ts-ignore
.spyOn(service, "getSnippets")
// @ts-ignore
.mockImplementation(async (_filepath, _endPosition) => {
.mockImplementation((_filePath, _endPosition) => {
return [];
});

View file

@ -25,6 +25,7 @@ export function slashFromCustomCommand(
config,
selectedCode,
fetch,
abortController,
}) {
// Render prompt template
let renderedPrompt: string;
@ -63,7 +64,7 @@ export function slashFromCustomCommand(
for await (const chunk of llm.streamChat(
messages,
new AbortController().signal,
abortController.signal,
completionOptions,
)) {
yield renderChatMessage(chunk);

View file

@ -4,7 +4,7 @@ import { renderChatMessage } from "../../util/messageContent.js";
const CommitMessageCommand: SlashCommand = {
name: "commit",
description: "Generate a commit message for current changes",
run: async function* ({ ide, llm, params }) {
run: async function* ({ ide, llm, params, abortController }) {
const includeUnstaged = params?.includeUnstaged ?? false;
const diff = await ide.getDiff(includeUnstaged);
@ -16,7 +16,7 @@ const CommitMessageCommand: SlashCommand = {
const prompt = `${diff.join("\n")}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`;
for await (const chunk of llm.streamChat(
[{ role: "user", content: prompt }],
new AbortController().signal,
abortController.signal,
)) {
yield renderChatMessage(chunk);
}

View file

@ -24,7 +24,7 @@ Body:\n\n`;
const DraftIssueCommand: SlashCommand = {
name: "issue",
description: "Draft a GitHub issue",
run: async function* ({ input, llm, history, params }) {
run: async function* ({ input, llm, history, params, abortController }) {
if (params?.repositoryUrl === undefined) {
yield "This command requires a repository URL to be set in the config file.";
return;
@ -46,7 +46,7 @@ const DraftIssueCommand: SlashCommand = {
for await (const chunk of llm.streamChat(
messages,
new AbortController().signal,
abortController.signal,
)) {
body += chunk.content;
yield renderChatMessage(chunk);

View file

@ -60,7 +60,7 @@ export function constructMcpSlashCommand(
for await (const chunk of context.llm.streamChat(
messages,
new AbortController().signal,
context.abortController.signal,
context.completionOptions,
)) {
yield renderChatMessage(chunk);

View file

@ -41,7 +41,7 @@ const MAX_EXPLORE_DEPTH = 2;
const OnboardSlashCommand: SlashCommand = {
name: "onboard",
description: "Familiarize yourself with the codebase",
run: async function* ({ llm, ide }) {
run: async function* ({ llm, ide, abortController }) {
const [workspaceDir] = await ide.getWorkspaceDirs();
const context = await gatherProjectContext(workspaceDir, ide);
@ -49,7 +49,7 @@ const OnboardSlashCommand: SlashCommand = {
for await (const chunk of llm.streamChat(
[{ role: "user", content: prompt }],
new AbortController().signal,
abortController.signal,
)) {
yield renderChatMessage(chunk);
}

View file

@ -38,14 +38,14 @@ function getLastUserHistory(history: ChatMessage[]): string {
const ReviewMessageCommand: SlashCommand = {
name: "review",
description: "Review code and give feedback",
run: async function* ({ llm, history }) {
run: async function* ({ llm, history, abortController }) {
const reviewText = getLastUserHistory(history).replace("\\review", "");
const content = `${prompt} \r\n ${reviewText}`;
for await (const chunk of llm.streamChat(
[{ role: "user", content: content }],
new AbortController().signal,
abortController.signal,
)) {
yield renderChatMessage(chunk);
}

View file

@ -87,38 +87,40 @@ export class ProfileLifecycleManager {
}
// Set pending config promise
this.pendingConfigPromise = new Promise(async (resolve, reject) => {
let result: ConfigResult<ContinueConfig>;
// This try catch is expected to catch high-level errors that aren't block-specific
// Like invalid json, invalid yaml, file read errors, etc.
// NOT block-specific loading errors
try {
result = await this.profileLoader.doLoadConfig();
} catch (e) {
const message =
e instanceof Error
? `${e.message}\n${e.stack ? e.stack : ""}`
: "Error loading config";
result = {
errors: [
{
fatal: true,
message,
},
],
config: undefined,
configLoadInterrupted: true,
};
}
this.pendingConfigPromise = new Promise((resolve) => {
void (async () => {
let result: ConfigResult<ContinueConfig>;
// This try catch is expected to catch high-level errors that aren't block-specific
// Like invalid json, invalid yaml, file read errors, etc.
// NOT block-specific loading errors
try {
result = await this.profileLoader.doLoadConfig();
} catch (e) {
const message =
e instanceof Error
? `${e.message}\n${e.stack ? e.stack : ""}`
: "Error loading config";
result = {
errors: [
{
fatal: true,
message,
},
],
config: undefined,
configLoadInterrupted: true,
};
}
if (result.config) {
// Add registered context providers
result.config.contextProviders = (
result.config.contextProviders ?? []
).concat(additionalContextProviders);
}
if (result.config) {
// Add registered context providers
result.config.contextProviders = (
result.config.contextProviders ?? []
).concat(additionalContextProviders);
}
resolve(result);
resolve(result);
})();
});
// Wait for the config promise to resolve

View file

@ -0,0 +1,241 @@
import { walkDirCache } from "../indexing/walkDir";
import { testIde } from "../test/fixtures";
import { addToTestDir, setUpTestDir, tearDownTestDir } from "../test/testDir";
import {
getAllDotContinueDefinitionFiles,
LoadAssistantFilesOptions,
} from "./loadLocalAssistants";
describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
beforeEach(() => {
setUpTestDir();
walkDirCache.invalidate();
// Add test files to the test directory
addToTestDir([
".continue/assistants/",
[".continue/assistants/assistant1.yaml", "yaml content 1"],
[".continue/assistants/assistant2.yml", "yaml content 2"],
[".continue/assistants/assistant3.md", "markdown content 1"],
[".continue/assistants/assistant4.txt", "txt content"],
]);
});
afterEach(() => {
tearDownTestDir();
walkDirCache.invalidate();
});
it("should return only YAML files when fileExtType is 'yaml'", async () => {
const options: LoadAssistantFilesOptions = {
includeGlobal: false, // Only test workspace for simplicity
includeWorkspace: true,
fileExtType: "yaml",
};
const result = await getAllDotContinueDefinitionFiles(
testIde,
options,
"assistants",
);
expect(result).toHaveLength(2);
expect(result.map((f) => f.path.split("/").pop())).toEqual(
expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
);
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
"assistant3.md",
);
});
it("should return only Markdown files when fileExtType is 'markdown'", async () => {
const options: LoadAssistantFilesOptions = {
includeGlobal: false,
includeWorkspace: true,
fileExtType: "markdown",
};
const result = await getAllDotContinueDefinitionFiles(
testIde,
options,
"assistants",
);
expect(result).toHaveLength(1);
expect(result.map((f) => f.path.split("/").pop())).toEqual([
"assistant3.md",
]);
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
"assistant1.yaml",
);
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
"assistant2.yml",
);
});
it("should return all supported files when fileExtType is not specified", async () => {
const options: LoadAssistantFilesOptions = {
includeGlobal: false,
includeWorkspace: true,
// fileExtType not specified
};
const result = await getAllDotContinueDefinitionFiles(
testIde,
options,
"assistants",
);
expect(result).toHaveLength(3);
expect(result.map((f) => f.path.split("/").pop())).toEqual(
expect.arrayContaining([
"assistant1.yaml",
"assistant2.yml",
"assistant3.md",
]),
);
// Should not include .txt files
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
"assistant4.txt",
);
});
it("should respect includeWorkspace option with fileExtType", async () => {
// Test with includeWorkspace: false
const workspaceOffOptions: LoadAssistantFilesOptions = {
includeGlobal: false,
includeWorkspace: false,
fileExtType: "yaml",
};
const noWorkspaceResult = await getAllDotContinueDefinitionFiles(
testIde,
workspaceOffOptions,
"assistants",
);
expect(noWorkspaceResult).toHaveLength(0);
// Test with includeWorkspace: true
const workspaceOnOptions: LoadAssistantFilesOptions = {
includeGlobal: false,
includeWorkspace: true,
fileExtType: "yaml",
};
const workspaceResult = await getAllDotContinueDefinitionFiles(
testIde,
workspaceOnOptions,
"assistants",
);
expect(workspaceResult).toHaveLength(2);
expect(workspaceResult.map((f) => f.path.split("/").pop())).toEqual(
expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
);
});
it("should return empty array when no files match the specified extension type", async () => {
// Create a test directory with only non-matching files
tearDownTestDir();
walkDirCache.invalidate();
setUpTestDir();
addToTestDir([
".continue/assistants/",
[".continue/assistants/nonmatch1.txt", "txt content"],
[".continue/assistants/nonmatch2.json", "json content"],
]);
const options: LoadAssistantFilesOptions = {
includeGlobal: false,
includeWorkspace: true,
fileExtType: "yaml",
};
const result = await getAllDotContinueDefinitionFiles(
testIde,
options,
"assistants",
);
expect(result).toHaveLength(0);
});
it("should handle directories that don't exist", async () => {
// Create a clean test directory without the assistants folder
tearDownTestDir();
setUpTestDir();
const options: LoadAssistantFilesOptions = {
includeGlobal: false,
includeWorkspace: true,
fileExtType: "yaml",
};
const result = await getAllDotContinueDefinitionFiles(
testIde,
options,
"assistants",
);
expect(result).toHaveLength(0);
});
it("should return correct file content", async () => {
const options: LoadAssistantFilesOptions = {
includeGlobal: false,
includeWorkspace: true,
fileExtType: "yaml",
};
const result = await getAllDotContinueDefinitionFiles(
testIde,
options,
"assistants",
);
expect(result).toHaveLength(2);
const yamlFile = result.find((f) => f.path.includes("assistant1.yaml"));
expect(yamlFile?.content).toBe("yaml content 1");
});
it("should filter by file extension case sensitively", async () => {
// Add files with uppercase extensions
addToTestDir([
[".continue/assistants/assistant5.YAML", "uppercase yaml"],
[".continue/assistants/assistant6.YML", "uppercase yml"],
[".continue/assistants/assistant7.MD", "uppercase md"],
]);
const yamlOptions: LoadAssistantFilesOptions = {
includeGlobal: false,
includeWorkspace: true,
fileExtType: "yaml",
};
const yamlResult = await getAllDotContinueDefinitionFiles(
testIde,
yamlOptions,
"assistants",
);
// Should only get lowercase extensions (current implementation)
expect(yamlResult).toHaveLength(2);
expect(yamlResult.map((f) => f.path.split("/").pop())).toEqual(
expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
);
expect(yamlResult.map((f) => f.path.split("/").pop())).not.toContain(
"assistant5.YAML",
);
const markdownOptions: LoadAssistantFilesOptions = {
includeGlobal: false,
includeWorkspace: true,
fileExtType: "markdown",
};
const markdownResult = await getAllDotContinueDefinitionFiles(
testIde,
markdownOptions,
"assistants",
);
expect(markdownResult).toHaveLength(1);
expect(markdownResult.map((f) => f.path.split("/").pop())).toEqual([
"assistant3.md",
]);
expect(markdownResult.map((f) => f.path.split("/").pop())).not.toContain(
"assistant7.MD",
);
});
});

View file

@ -1,4 +1,5 @@
import ignore from "ignore";
import * as URI from "uri-js";
import { IDE } from "..";
import {
DEFAULT_IGNORE_DIRS,
@ -12,18 +13,19 @@ import { joinPathsToUri } from "../util/uri";
export const ASSISTANTS = "assistants";
export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`;
export function isLocalAssistantFile(uri: string): boolean {
export function isLocalDefinitionFile(uri: string): boolean {
if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) {
return false;
}
const normalizedUri = uri.replace(/\\/g, "/");
const normalizedUri = URI.normalize(uri);
return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`);
}
async function getDefinitionFilesInDir(
ide: IDE,
dir: string,
fileExtType?: "yaml" | "markdown",
): Promise<{ path: string; content: string }[]> {
try {
const exists = await ide.fileExists(dir);
@ -40,9 +42,19 @@ async function getDefinitionFilesInDir(
overrideDefaultIgnores,
source: "get assistant files",
});
const assistantFilePaths = uris.filter(
(p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"),
);
let assistantFilePaths: string[];
if (fileExtType === "yaml") {
assistantFilePaths = uris.filter(
(p) => p.endsWith(".yaml") || p.endsWith(".yml"),
);
} else if (fileExtType === "markdown") {
assistantFilePaths = uris.filter((p) => p.endsWith(".md"));
} else {
assistantFilePaths = uris.filter(
(p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"),
);
}
const results = assistantFilePaths.map(async (uri) => {
const content = await ide.readFile(uri); // make a try catch
return { path: uri, content };
@ -57,6 +69,7 @@ async function getDefinitionFilesInDir(
export interface LoadAssistantFilesOptions {
includeGlobal: boolean;
includeWorkspace: boolean;
fileExtType?: "yaml" | "markdown";
}
export function getDotContinueSubDirs(
@ -84,7 +97,7 @@ export function getDotContinueSubDirs(
/**
* This method searches in both ~/.continue and workspace .continue
* for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts
* for all YAML/Markdown files in the specified subdirectory, for example .continue/assistants or .continue/prompts
*/
export async function getAllDotContinueDefinitionFiles(
ide: IDE,
@ -101,15 +114,14 @@ export async function getAllDotContinueDefinitionFiles(
subDirName,
);
// Get all assistant files from the directories
const assistantFiles = (
await Promise.all(fullDirs.map((dir) => getDefinitionFilesInDir(ide, dir)))
// Get all definition files from the directories
const definitionFiles = (
await Promise.all(
fullDirs.map((dir) =>
getDefinitionFilesInDir(ide, dir, options.fileExtType),
),
)
).flat();
return await Promise.all(
assistantFiles.map(async (file) => {
const content = await ide.readFile(file.path);
return { path: file.path, content };
}),
);
return definitionFiles;
}

View file

@ -1,3 +1 @@
export * from "./createMarkdownRule";
export * from "./loadMarkdownRules";
export * from "./parseMarkdownRule";

View file

@ -1,9 +1,11 @@
import { ConfigValidationError } from "@continuedev/config-yaml";
import {
ConfigValidationError,
markdownToRule,
} from "@continuedev/config-yaml";
import { IDE, RuleWithSource } from "../..";
import { walkDirs } from "../../indexing/walkDir";
import { RULES_MARKDOWN_FILENAME } from "../../llm/rules/constants";
import { getUriPathBasename } from "../../util/uri";
import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule";
/**
* Loads rules from rules.md files colocated in the codebase
@ -29,9 +31,9 @@ export async function loadCodebaseRules(ide: IDE): Promise<{
for (const filePath of rulesMdFiles) {
try {
const content = await ide.readFile(filePath);
const rule = convertMarkdownRuleToContinueRule(filePath, content);
const rule = markdownToRule(content, { uriType: "file", filePath });
rules.push(rule);
rules.push({ ...rule, source: "rules-block" });
} catch (e) {
errors.push({
fatal: false,

View file

@ -1,16 +1,16 @@
import { markdownToRule } from "@continuedev/config-yaml";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { IDE } from "../..";
import { walkDirs } from "../../indexing/walkDir";
import { loadCodebaseRules } from "./loadCodebaseRules";
import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule";
// Mock dependencies
vi.mock("../../indexing/walkDir", () => ({
walkDirs: vi.fn(),
}));
vi.mock("./parseMarkdownRule", () => ({
convertMarkdownRuleToContinueRule: vi.fn(),
vi.mock("@continuedev/config-yaml", () => ({
markdownToRule: vi.fn(),
}));
describe("loadCodebaseRules", () => {
@ -82,10 +82,10 @@ describe("loadCodebaseRules", () => {
return Promise.resolve(mockRuleContent[path] || "");
});
// Mock convertMarkdownRuleToContinueRule to return converted rules
(convertMarkdownRuleToContinueRule as any).mockImplementation(
(path: string, content: string) => {
return mockConvertedRules[path];
// Mock markdownToRule to return converted rules
(markdownToRule as any).mockImplementation(
(content: string, options: any) => {
return mockConvertedRules[options.filePath];
},
);
});
@ -107,7 +107,7 @@ describe("loadCodebaseRules", () => {
expect(mockIde.readFile).toHaveBeenCalledWith(".continue/rules.md");
// Should convert all rules
expect(convertMarkdownRuleToContinueRule).toHaveBeenCalledTimes(4);
expect(markdownToRule).toHaveBeenCalledTimes(4);
// Should return all rules
expect(rules).toHaveLength(4);

View file

@ -1,7 +1,9 @@
import { ConfigValidationError } from "@continuedev/config-yaml";
import {
ConfigValidationError,
markdownToRule,
} from "@continuedev/config-yaml";
import { IDE, RuleWithSource } from "../..";
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule";
/**
* Loads rules from markdown files in the .continue/rules directory
@ -17,7 +19,7 @@ export async function loadMarkdownRules(ide: IDE): Promise<{
// Get all .md files from .continue/rules
const markdownFiles = await getAllDotContinueDefinitionFiles(
ide,
{ includeGlobal: true, includeWorkspace: true },
{ includeGlobal: true, includeWorkspace: true, fileExtType: "markdown" },
"rules",
);
@ -27,8 +29,11 @@ export async function loadMarkdownRules(ide: IDE): Promise<{
// Process each markdown file
for (const file of mdFiles) {
try {
const rule = convertMarkdownRuleToContinueRule(file.path, file.content);
rules.push(rule);
const rule = markdownToRule(file.content, {
uriType: "file",
filePath: file.path,
});
rules.push({ ...rule, source: "rules-block" });
} catch (e) {
errors.push({
fatal: false,

View file

@ -1,193 +0,0 @@
import { describe, expect, it } from "vitest";
import {
convertMarkdownRuleToContinueRule,
parseMarkdownRule,
} from "./parseMarkdownRule";
describe("parseMarkdownRule", () => {
it("should correctly parse markdown with YAML frontmatter", () => {
const content = `---
globs: "**/test/**/*.kt"
---
# Test Rule
This is a test rule.`;
const result = parseMarkdownRule(content);
expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
});
it("should handle missing frontmatter", () => {
const content = `# Test Rule
This is a test rule without frontmatter.`;
const result = parseMarkdownRule(content);
expect(result.frontmatter).toEqual({});
expect(result.markdown).toBe(content);
});
it("should handle empty frontmatter", () => {
const content = `---
---
# Test Rule
This is a test rule with empty frontmatter.`;
const result = parseMarkdownRule(content);
// Log exact strings for debugging
console.log("Actual:", JSON.stringify(result.markdown));
console.log(
"Expected:",
JSON.stringify(
"# Test Rule\n\nThis is a test rule with empty frontmatter.",
),
);
expect(result.frontmatter).toEqual({});
expect(result.markdown).toBe(
"# Test Rule\n\nThis is a test rule with empty frontmatter.",
);
});
it("should handle frontmatter with whitespace", () => {
const content = `---
globs: "**/test/**/*.kt"
---
# Test Rule
This is a test rule.`;
const result = parseMarkdownRule(content);
expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
});
it("should handle Windows line endings (CRLF)", () => {
// Using \r\n for CRLF line endings
const content = `---\r
globs: "**/test/**/*.kt"\r
---\r
\r
# Test Rule\r
\r
This is a test rule.`;
const result = parseMarkdownRule(content);
expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" });
// The result should be normalized to \n
expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule.");
});
it("should handle malformed frontmatter", () => {
const content = `---
globs: - "**/test/**/*.kt"
invalid: yaml: content
---
# Test Rule
This is a test rule.`;
// Should treat as only markdown when frontmatter is malformed
const result = parseMarkdownRule(content);
expect(result.frontmatter).toEqual({});
expect(result.markdown).toBe(content);
});
});
describe("convertMarkdownRuleToContinueRule", () => {
it("should convert markdown with frontmatter to a rule", () => {
const content = `---
globs: "**/test/**/*.kt"
name: Custom Name
---
# Test Rule
This is a test rule.`;
const result = convertMarkdownRuleToContinueRule(
"/path/to/rule.md",
content,
);
expect(result.rule).toBe("# Test Rule\n\nThis is a test rule.");
expect(result.globs).toBe("**/test/**/*.kt");
expect(result.name).toBe("Custom Name");
expect(result.source).toBe("rules-block");
expect(result.ruleFile).toBe("/path/to/rule.md");
});
it("should use the first heading as name if not in frontmatter", () => {
const content = `---
globs: "**/test/**/*.kt"
---
# Test Rule Title
This is a test rule.`;
const result = convertMarkdownRuleToContinueRule(
"/path/to/rule.md",
content,
);
expect(result.name).toBe("Test Rule Title");
});
it("should use filename as name if no heading or frontmatter name", () => {
const content = `---
globs: "**/test/**/*.kt"
---
This is a test rule without a heading.`;
const result = convertMarkdownRuleToContinueRule(
"/path/to/custom-rule.md",
content,
);
expect(result.name).toBe("custom-rule");
});
it("should include description from frontmatter", () => {
const content = `---
globs: "**/test/**/*.kt"
name: Test Rule
description: This is a rule description from frontmatter
---
# Test Rule
This is the content of the rule.`;
const result = convertMarkdownRuleToContinueRule(
"/path/to/rule.md",
content,
);
expect(result.description).toBe(
"This is a rule description from frontmatter",
);
});
it("should include `alwaysApply` from frontmatter", () => {
const content = `---
globs: "**/test/**/*.kt"
name: Test Rule
alwaysApply: false
---
# Test Rule
This is a rule with alwaysApply explicitly set to false.`;
const result = convertMarkdownRuleToContinueRule(
"/path/to/rule.md",
content,
);
expect(result.alwaysApply).toBe(false);
});
});

View file

@ -0,0 +1,21 @@
import {
RULE_FILE_EXTENSION,
sanitizeRuleName,
} from "@continuedev/config-yaml";
import { joinPathsToUri } from "../../util/uri";
/**
* Creates the file path for a rule in the workspace .continue/rules directory
*/
export function createRuleFilePath(
workspaceDir: string,
ruleName: string,
): string {
const safeRuleName = sanitizeRuleName(ruleName);
return joinPathsToUri(
workspaceDir,
".continue",
"rules",
`${safeRuleName}.${RULE_FILE_EXTENSION}`,
);
}

View file

@ -0,0 +1,19 @@
import { describe, expect, it } from "vitest";
import { createRuleFilePath } from "./utils";
describe("createRuleFilePath", () => {
it("should create correct rule file path", () => {
const result = createRuleFilePath("/workspace", "My Test Rule");
expect(result).toBe("/workspace/.continue/rules/my-test-rule.md");
});
it("should handle special characters in rule name", () => {
const result = createRuleFilePath("/home/user", "Rule with @#$% chars");
expect(result).toBe("/home/user/.continue/rules/rule-with-chars.md");
});
it("should handle edge case rule names", () => {
const result = createRuleFilePath("/test", " Multiple Spaces ");
expect(result).toBe("/test/.continue/rules/multiple-spaces.md");
});
});

View file

@ -211,6 +211,6 @@ export function migrateJsonSharedConfig(filepath: string, ide: IDE): void {
new GlobalContext().updateSharedConfig(shareConfigUpdates);
}
} catch (e) {
throw new Error(`Migration: Failed to parse config.json: ${e}`);
console.error(`Migration: Failed to parse config.json: ${e}`);
}
}

View file

@ -719,7 +719,7 @@ declare global {
getPinnedFiles(): Promise<string[]>;
getSearchResults(query: string): Promise<string>;
getSearchResults(query: string, maxResults?: number): Promise<string>;
subprocess(command: string, cwd?: string): Promise<[string, string]>;

View file

@ -0,0 +1,344 @@
import { jest } from "@jest/globals";
import { BrowserSerializedContinueConfig } from "..";
// Create the mock before importing anything else
const mockDecodeSecretLocation = jest.fn();
// Mock the module
jest.unstable_mockModule("@continuedev/config-yaml", () => ({
SecretType: {
User: "user",
Organization: "organization",
FreeTrial: "free_trial",
},
decodeSecretLocation: mockDecodeSecretLocation,
}));
// Import after mocking
const { usesFreeTrialApiKey } = await import("./usesFreeTrialApiKey");
const { SecretType } = await import("@continuedev/config-yaml");
beforeEach(() => {
mockDecodeSecretLocation.mockReset();
});
test("usesFreeTrialApiKey should return false when config is null", () => {
const result = usesFreeTrialApiKey(null);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when config is undefined", () => {
const result = usesFreeTrialApiKey(undefined as any);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
underlyingProviderName: "test",
},
{
title: "Model 2",
provider: "test",
model: "test-model-2",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
],
edit: [
{
title: "Model 2",
provider: "test",
model: "test-model-2",
apiKeyLocation: "organization:testorg/api-key",
underlyingProviderName: "test",
},
],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.Organization,
orgSlug: "testorg",
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
});
test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
{
title: "Free Trial Model",
provider: "test",
model: "free-trial-model",
apiKeyLocation: "free_trial:owner/package/api-key",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.FreeTrial,
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(true);
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
});
test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
],
edit: [
{
title: "Free Trial Edit Model",
provider: "test",
model: "free-trial-edit-model",
apiKeyLocation: "free_trial:owner/package/api-key",
underlyingProviderName: "test",
},
],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.FreeTrial,
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(true);
});
test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => {
const consoleSpy = jest.spyOn(console, "error").mockImplementation(() => {});
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "invalid-secret-location",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation.mockImplementation(() => {
throw new Error("Invalid secret location format");
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(consoleSpy).toHaveBeenCalledWith(
"Error checking for free trial API key:",
expect.any(Error),
);
consoleSpy.mockRestore();
});
test("usesFreeTrialApiKey should handle empty modelsByRole object", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(mockDecodeSecretLocation).not.toHaveBeenCalled();
});

View file

@ -1,5 +1,6 @@
import { decodeSecretLocation, SecretType } from "@continuedev/config-yaml";
import { BrowserSerializedContinueConfig } from "core";
import { BrowserSerializedContinueConfig } from "..";
/**
* Helper function to determine if the config uses a free trial API key
* @param config The serialized config object

View file

@ -1,12 +1,10 @@
import { BlockType } from "@continuedev/config-yaml";
import { describe, expect, test } from "vitest";
import { RULE_FILE_EXTENSION } from "../markdown";
import { BlockType, RULE_FILE_EXTENSION } from "@continuedev/config-yaml";
import { describe, expect, test } from "@jest/globals";
import { findAvailableFilename, getFileContent } from "./workspaceBlocks";
describe("getFileContent", () => {
test("returns markdown content for rules block type", () => {
const result = getFileContent("rules");
expect(result).toContain("# New Rule");
expect(result).toContain("Your rule content");
expect(result).toContain("A description of your rule");
});

View file

@ -1,8 +1,12 @@
import { BlockType, ConfigYaml } from "@continuedev/config-yaml";
import {
BlockType,
ConfigYaml,
createRuleMarkdown,
RULE_FILE_EXTENSION,
} from "@continuedev/config-yaml";
import * as YAML from "yaml";
import { IDE } from "../..";
import { joinPathsToUri } from "../../util/uri";
import { RULE_FILE_EXTENSION, createRuleMarkdown } from "../markdown";
const BLOCK_TYPE_CONFIG: Record<
BlockType,

View file

@ -97,7 +97,7 @@ async function loadConfigYaml(options: {
for (const blockType of BLOCK_TYPES) {
const localBlocks = await getAllDotContinueDefinitionFiles(
ide,
{ includeGlobal: true, includeWorkspace: true },
{ includeGlobal: true, includeWorkspace: true, fileExtType: "yaml" },
blockType,
);
allLocalBlocks.push(
@ -134,6 +134,7 @@ async function loadConfigYaml(options: {
rootPath,
}),
{
renderSecrets: true,
currentUserSlug: "",
onPremProxyUrl: null,
orgScopeId,
@ -142,9 +143,7 @@ async function loadConfigYaml(options: {
controlPlaneClient,
ide,
),
renderSecrets: true,
injectBlocks: allLocalBlocks,
asConfigResult: true,
},
);
config = unrollResult.config;
@ -153,13 +152,8 @@ async function loadConfigYaml(options: {
}
}
if (config) {
isAssistantUnrolledNonNullable(config)
? errors.push(...validateConfigYaml(config))
: errors.push({
fatal: true,
message: "Assistant includes blocks that don't exist",
});
if (config && isAssistantUnrolledNonNullable(config)) {
errors.push(...validateConfigYaml(config));
}
if (errors?.some((error) => error.fatal)) {
@ -223,7 +217,8 @@ async function configYamlToContinueConfig(options: {
config: continueConfig,
errors: [
{
message: "Found missing blocks in config.yaml",
message:
"Failed to load config due to missing blocks, see which blocks are missing below",
fatal: true,
},
],

View file

@ -6,6 +6,7 @@ import {
import { formatGrepSearchResults } from "../../util/grepSearch.js";
import { BaseContextProvider } from "../index.js";
const DEFAULT_MAX_SEARCH_CONTEXT_RESULTS = 200;
class SearchContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "search",
@ -19,8 +20,12 @@ class SearchContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const results = await extras.ide.getSearchResults(query);
const formatted = formatGrepSearchResults(results);
const results = await extras.ide.getSearchResults(
query,
this.options?.maxResults ?? DEFAULT_MAX_SEARCH_CONTEXT_RESULTS,
);
// Note, search context provider will not truncate result chars, but will limit number of results
const { formatted } = formatGrepSearchResults(results);
return [
{
description: "Search results",

View file

@ -1,4 +1,5 @@
import { Chunk } from "../../../";
import { Telemetry } from "../../../util/posthog";
import { findUriInDirs } from "../../../util/uri";
import { requestFilesFromRepoMap } from "../repoMapRequest";
import { deduplicateChunks } from "../util";
@ -23,7 +24,8 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
try {
ftsChunks = await this.retrieveFts(args, ftsNFinal);
} catch (error) {
console.error("Error retrieving FTS chunks:", error);
await Telemetry.captureError("no_reranker_fts_retrieval", error);
// console.error("Error retrieving FTS chunks:", error);
}
let embeddingsChunks: Chunk[] = [];
@ -32,6 +34,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
? await this.retrieveEmbeddings(input, embeddingsNFinal)
: [];
} catch (error) {
await Telemetry.captureError("no_reranker_embeddings_retrieval", error);
console.error("Error retrieving embeddings:", error);
}
@ -40,6 +43,10 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal);
} catch (error) {
await Telemetry.captureError(
"no_reranker_recently_edited_retrieval",
error,
);
console.error("Error retrieving recently edited files:", error);
}
@ -53,6 +60,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
filterDirectory,
);
} catch (error) {
await Telemetry.captureError("no_reranker_repo_map_retrieval", error);
console.error("Error retrieving repo map chunks:", error);
}

View file

@ -1,5 +1,6 @@
import { Chunk } from "../../..";
import { RETRIEVAL_PARAMS } from "../../../util/parameters";
import { Telemetry } from "../../../util/posthog";
import { findUriInDirs } from "../../../util/uri";
import { requestFilesFromRepoMap } from "../repoMapRequest";
import { deduplicateChunks } from "../util";
@ -20,7 +21,8 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
try {
ftsChunks = await this.retrieveFts(args, nRetrieve);
} catch (error) {
console.error("Error retrieving FTS chunks:", error);
await Telemetry.captureError("reranker_fts_retrieval", error);
// console.error("Error retrieving FTS chunks:", error);
}
let embeddingsChunks: Chunk[] = [];
@ -29,6 +31,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
? await this.retrieveEmbeddings(input, nRetrieve)
: [];
} catch (error) {
await Telemetry.captureError("reranker_embeddings_retrieval", error);
console.error("Error retrieving embeddings chunks:", error);
}
@ -37,6 +40,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve);
} catch (error) {
await Telemetry.captureError("reranker_recently_edited_retrieval", error);
console.error("Error retrieving recently edited files chunks:", error);
}
@ -50,6 +54,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
filterDirectory,
);
} catch (error) {
await Telemetry.captureError("reranker_repo_map_retrieval", error);
console.error("Error retrieving repo map chunks:", error);
}

View file

@ -182,4 +182,38 @@ export class ControlPlaneClient {
return null;
}
}
/**
* JetBrains does not support deep links, so we only check for `vsCodeUriScheme`
* @param vsCodeUriScheme
* @returns
*/
public async getModelsAddOnCheckoutUrl(
vsCodeUriScheme?: string,
): Promise<{ url: string } | null> {
if (!(await this.isSignedIn())) {
return null;
}
try {
const params = new URLSearchParams({
// LocalProfileLoader ID
profile_id: "local",
});
if (vsCodeUriScheme) {
params.set("vscode_uri_scheme", vsCodeUriScheme);
}
const resp = await this.request(
`ide/get-models-add-on-checkout-url?${params.toString()}`,
{
method: "GET",
},
);
return (await resp.json()) as { url: string };
} catch (e) {
return null;
}
}
}

View file

@ -42,14 +42,15 @@ import {
IdeSettings,
ModelDescription,
RangeInFile,
ToolCall,
type ContextItem,
type ContextItemId,
type IDE,
} from ".";
import { ConfigYaml } from "@continuedev/config-yaml";
import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
import { isLocalAssistantFile } from "./config/loadLocalAssistants";
import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
import {
setupLocalConfig,
setupProviderConfig,
@ -58,6 +59,7 @@ import {
import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks";
import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
import { setMdmLicenseKey } from "./control-plane/mdm/mdm";
import { ApplyAbortManager } from "./edit/applyAbortManager";
import { streamDiffLines } from "./edit/streamDiffLines";
import { shouldIgnore } from "./indexing/shouldIgnore";
import { walkDirCache } from "./indexing/walkDir";
@ -67,7 +69,6 @@ import { llmStreamChat } from "./llm/streamChat";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import { OnboardingModes } from "./protocol/core";
import type { IMessenger, Message } from "./protocol/messenger";
import { StreamAbortManager } from "./util/abortManager";
import { getUriPathBasename } from "./util/uri";
const hasRulesFiles = (uris: string[]): boolean => {
@ -145,8 +146,20 @@ export class Core {
this.messenger,
);
MCPManagerSingleton.getInstance().onConnectionsRefreshed = async () => {
await this.configHandler.reloadConfig();
MCPManagerSingleton.getInstance().onConnectionsRefreshed = () => {
void this.configHandler.reloadConfig();
// Refresh @mention dropdown submenu items for MCP providers
const mcpManager = MCPManagerSingleton.getInstance();
const mcpProviderNames = Array.from(mcpManager.connections.keys()).map(
(mcpId) => `mcp-${mcpId}`,
);
if (mcpProviderNames.length > 0) {
this.messenger.send("refreshSubmenuItems", {
providers: mcpProviderNames,
});
}
};
this.codeBaseIndexer = new CodebaseIndexer(
@ -156,24 +169,26 @@ export class Core {
this.globalContext.get("indexingPaused"),
);
this.configHandler.onConfigUpdate(async (result) => {
const serializedResult = await this.configHandler.getSerializedConfig();
this.messenger.send("configUpdate", {
result: serializedResult,
profileId:
this.configHandler.currentProfile?.profileDescription.id || null,
organizations: this.configHandler.getSerializedOrgs(),
selectedOrgId: this.configHandler.currentOrg.id,
});
// update additional submenu context providers registered via VSCode API
const additionalProviders =
this.configHandler.getAdditionalSubmenuContextProviders();
if (additionalProviders.length > 0) {
this.messenger.send("refreshSubmenuItems", {
providers: additionalProviders,
this.configHandler.onConfigUpdate((result) => {
void (async () => {
const serializedResult = await this.configHandler.getSerializedConfig();
this.messenger.send("configUpdate", {
result: serializedResult,
profileId:
this.configHandler.currentProfile?.profileDescription.id || null,
organizations: this.configHandler.getSerializedOrgs(),
selectedOrgId: this.configHandler.currentOrg.id,
});
}
// update additional submenu context providers registered via VSCode API
const additionalProviders =
this.configHandler.getAdditionalSubmenuContextProviders();
if (additionalProviders.length > 0) {
this.messenger.send("refreshSubmenuItems", {
providers: additionalProviders,
});
}
})();
});
// Dev Data Logger
@ -357,6 +372,12 @@ export class Core {
return this.configHandler.controlPlaneClient.getFreeTrialStatus();
});
on("controlPlane/getModelsAddOnUpgradeUrl", async (msg) => {
return this.configHandler.controlPlaneClient.getModelsAddOnCheckoutUrl(
msg.data.vsCodeUriScheme,
);
});
on("mcp/reloadServer", async (msg) => {
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
});
@ -504,6 +525,11 @@ export class Core {
throw new Error("No model selected");
}
const abortManager = ApplyAbortManager.getInstance();
const abortController = abortManager.get(
data.fileUri ?? "current-file-stream",
); // not super important since currently cancelling apply will cancel all streams it's one file at a time
return streamDiffLines({
highlighted: data.highlighted,
prefix: data.prefix,
@ -517,13 +543,13 @@ export class Core {
language: data.language,
onlyOneInsertion: false,
overridePrompt: undefined,
abortControllerId: data.fileUri ?? "current-file-stream", // not super important since currently cancelling apply will cancel all streams it's one file at a time
abortController,
});
});
on("cancelApply", async (msg) => {
const abortManager = StreamAbortManager.getInstance();
abortManager.clear();
const abortManager = ApplyAbortManager.getInstance();
abortManager.clear(); // for now abort all streams
});
on("onboarding/complete", this.handleCompleteOnboarding.bind(this));
@ -600,7 +626,7 @@ export class Core {
// If it's a local assistant being created, we want to reload all assistants so it shows up in the list
let localAssistantCreated = false;
for (const uri of data.uris) {
if (isLocalAssistantFile(uri)) {
if (isLocalDefinitionFile(uri)) {
localAssistantCreated = true;
}
}
@ -730,44 +756,9 @@ export class Core {
return { url };
});
on("tools/call", async ({ data: { toolCall } }) => {
const { config } = await this.configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
const tool = config.tools.find(
(t) => t.function.name === toolCall.function.name,
);
if (!tool) {
throw new Error(`Tool ${toolCall.function.name} not found`);
}
if (!config.selectedModelByRole.chat) {
throw new Error("No chat model selected");
}
// Define a callback for streaming output updates
const onPartialOutput = (params: {
toolCallId: string;
contextItems: ContextItem[];
}) => {
this.messenger.send("toolCallPartialOutput", params);
};
return await callTool(tool, toolCall, {
config,
ide: this.ide,
llm: config.selectedModelByRole.chat,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
tool,
toolCallId: toolCall.id,
onPartialOutput,
codeBaseIndexer: this.codeBaseIndexer,
});
});
on("tools/call", async ({ data: { toolCall } }) =>
this.handleToolCall(toolCall),
);
on("isItemTooBig", async ({ data: { item } }) => {
return this.isItemTooBig(item);
@ -792,6 +783,45 @@ export class Core {
});
}
private async handleToolCall(toolCall: ToolCall) {
const { config } = await this.configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
const tool = config.tools.find(
(t) => t.function.name === toolCall.function.name,
);
if (!tool) {
throw new Error(`Tool ${toolCall.function.name} not found`);
}
if (!config.selectedModelByRole.chat) {
throw new Error("No chat model selected");
}
// Define a callback for streaming output updates
const onPartialOutput = (params: {
toolCallId: string;
contextItems: ContextItem[];
}) => {
this.messenger.send("toolCallPartialOutput", params);
};
return await callTool(tool, toolCall, {
config,
ide: this.ide,
llm: config.selectedModelByRole.chat,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
tool,
toolCallId: toolCall.id,
onPartialOutput,
codeBaseIndexer: this.codeBaseIndexer,
});
}
private async isItemTooBig(item: ContextItemWithId) {
const { config } = await this.configHandler.loadConfig();
if (!config) {
@ -879,7 +909,12 @@ export class Core {
uri.endsWith(".prompt") ||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
(uri.includes(".continue") && uri.endsWith(".yaml")) ||
uri.endsWith(RULES_MARKDOWN_FILENAME)
uri.endsWith(RULES_MARKDOWN_FILENAME) ||
BLOCK_TYPES.some(
(blockType) =>
uri.includes(`.continue/${blockType}`) ||
uri.includes(`.continue\\${blockType}`),
)
) {
await this.configHandler.reloadConfig();
} else if (

View file

@ -1,16 +1,16 @@
export class StreamAbortManager {
private static instance: StreamAbortManager;
export class ApplyAbortManager {
private static instance: ApplyAbortManager;
private controllers: Map<string, AbortController>;
private constructor() {
this.controllers = new Map();
}
public static getInstance(): StreamAbortManager {
if (!StreamAbortManager.instance) {
StreamAbortManager.instance = new StreamAbortManager();
public static getInstance(): ApplyAbortManager {
if (!ApplyAbortManager.instance) {
ApplyAbortManager.instance = new ApplyAbortManager();
}
return StreamAbortManager.instance;
return ApplyAbortManager.instance;
}
public get(id: string): AbortController {

View file

@ -16,6 +16,7 @@ export async function applyCodeBlock(
newLazyFile: string,
filename: string,
llm: ILLM,
abortController: AbortController,
): Promise<{
isInstantApply: boolean;
diffLinesGenerator: AsyncGenerator<DiffLine>;
@ -51,6 +52,12 @@ export async function applyCodeBlock(
return {
isInstantApply: false,
diffLinesGenerator: streamLazyApply(oldFile, filename, newLazyFile, llm),
diffLinesGenerator: streamLazyApply(
oldFile,
filename,
newLazyFile,
llm,
abortController,
),
};
}

View file

@ -59,6 +59,7 @@ export async function* getReplacementWithLlm(
linesBefore: string[],
linesAfter: string[],
llm: ILLM,
abortController: AbortController,
): AsyncGenerator<string> {
const userPrompt = dedent`
ORIGINAL CODE:
@ -88,7 +89,7 @@ export async function* getReplacementWithLlm(
{ role: "user", content: userPrompt },
{ role: "assistant", content: assistantPrompt },
],
new AbortController().signal,
abortController.signal,
);
let lines = streamLines(completion);

View file

@ -16,6 +16,7 @@ export async function* streamLazyApply(
filename: string,
newCode: string,
llm: ILLM,
abortController: AbortController,
): AsyncGenerator<DiffLine> {
const promptFactory = lazyApplyPromptForModel(llm.model, llm.providerName);
if (!promptFactory) {
@ -23,10 +24,7 @@ export async function* streamLazyApply(
}
const promptMessages = promptFactory(oldCode, filename, newCode);
const lazyCompletion = llm.streamChat(
promptMessages,
new AbortController().signal,
);
const lazyCompletion = llm.streamChat(promptMessages, abortController.signal);
// Do find and replace over the lazy edit response
async function* replacementFunction(
@ -39,6 +37,7 @@ export async function* streamLazyApply(
linesBefore,
linesAfter,
llm,
abortController,
)) {
yield line;
}

View file

@ -20,7 +20,6 @@ import { streamDiff } from "../diff/streamDiff";
import { streamLines } from "../diff/util";
import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
import { gptEditPrompt } from "../llm/templates/edit";
import { StreamAbortManager } from "../util/abortManager";
import { findLast } from "../util/findLast";
import { Telemetry } from "../util/posthog";
import { recursiveStream } from "./recursiveStream";
@ -64,7 +63,7 @@ export async function* streamDiffLines({
highlighted,
suffix,
llm,
abortControllerId,
abortController,
input,
language,
onlyOneInsertion,
@ -75,15 +74,13 @@ export async function* streamDiffLines({
highlighted: string;
suffix: string;
llm: ILLM;
abortControllerId: string;
abortController: AbortController;
input: string;
language: string | undefined;
onlyOneInsertion: boolean;
overridePrompt: ChatMessage[] | undefined;
rulesToInclude: RuleWithSource[] | undefined;
}): AsyncGenerator<DiffLine> {
const abortManager = StreamAbortManager.getInstance();
const abortController = abortManager.get(abortControllerId);
void Telemetry.capture(
"inlineEdit",
{

7
core/index.d.ts vendored
View file

@ -781,9 +781,9 @@ export interface IDE {
getPinnedFiles(): Promise<string[]>;
getSearchResults(query: string): Promise<string>;
getSearchResults(query: string, maxResults?: number): Promise<string>;
getFileResults(pattern: string): Promise<string[]>;
getFileResults(pattern: string, maxResults?: number): Promise<string[]>;
subprocess(command: string, cwd?: string): Promise<[string, string]>;
@ -833,6 +833,7 @@ export interface ContinueSDK {
config: ContinueConfig;
fetch: FetchFunction;
completionOptions?: LLMFullCompletionOptions;
abortController: AbortController;
}
export interface SlashCommand {
@ -1280,7 +1281,7 @@ export interface HighlightedCodePayload {
}
export interface AcceptOrRejectDiffPayload {
filepath: string;
filepath?: string;
streamId?: string;
}

View file

@ -97,8 +97,8 @@ export class LanceDbIndex implements CodebaseIndex {
contents TEXT NOT NULL
)`);
await new Promise((resolve) =>
migrate(
await new Promise((resolve) => {
void migrate(
"lancedb_sqlite_artifact_id_column",
async () => {
try {
@ -118,8 +118,8 @@ export class LanceDbIndex implements CodebaseIndex {
}
},
() => resolve(undefined),
),
);
);
});
}
private async computeRows(items: PathAndCacheKey[]): Promise<LanceDbRow[]> {

View file

@ -50,24 +50,25 @@ export async function* chunkDocument({
maxChunkSize,
)) {
chunkPromises.push(
new Promise(async (resolve) => {
if ((await countTokensAsync(chunkWithoutId.content)) > maxChunkSize) {
// console.debug(
// `Chunk with more than ${maxChunkSize} tokens constructed: `,
// filepath,
// countTokens(chunkWithoutId.content),
// );
return resolve(undefined);
}
resolve({
...chunkWithoutId,
digest,
index,
filepath,
});
new Promise((resolve) => {
void (async () => {
if ((await countTokensAsync(chunkWithoutId.content)) > maxChunkSize) {
// console.debug(
// `Chunk with more than ${maxChunkSize} tokens constructed: `,
// filepath,
// countTokens(chunkWithoutId.content),
// );
return resolve(undefined);
}
resolve({
...chunkWithoutId,
digest,
index: index++,
filepath,
});
})();
}),
);
index++;
}
for await (const chunk of chunkPromises) {
if (!chunk) {

View file

@ -186,7 +186,9 @@ export default class DocsService {
private async init(configHandler: ConfigHandler) {
const result = await configHandler.loadConfig();
await this.handleConfigUpdate(result);
configHandler.onConfigUpdate(this.handleConfigUpdate.bind(this));
configHandler.onConfigUpdate(
this.handleConfigUpdate.bind(this) as (arg: any) => void,
);
}
readonly statuses: Map<string, IndexingStatus> = new Map();

View file

@ -6,8 +6,8 @@ import { editConfigFile, migrate } from "../../util/paths.js";
import DocsService, { SqliteDocsRow } from "./DocsService.js";
export async function runLanceMigrations(table: Table) {
await new Promise((resolve) =>
migrate(
await new Promise((resolve) => {
void migrate(
"rename_baseurl_column_for_lance_docs",
async () => {
try {
@ -21,8 +21,8 @@ export async function runLanceMigrations(table: Table) {
}
},
() => resolve(undefined),
),
);
);
});
}
export async function runSqliteMigrations(db: Database) {

View file

@ -29,12 +29,5 @@ export default {
globalSetup: "<rootDir>/test/jest.global-setup.ts",
setupFilesAfterEnv: ["<rootDir>/test/jest.setup-after-env.js"],
maxWorkers: 1, // equivalent to CLI --runInBand
// modulePathIgnorePatterns: [
// "<rootDir>/config/yaml/LocalPlatformClient.test.ts",
// ],
testPathIgnorePatterns: [
"<rootDir>/config/",
"<rootDir>/autocomplete/",
"<rootDir>/context/",
],
testMatch: ["**/*.test.ts"],
};

View file

@ -52,6 +52,7 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [
"msty",
"anthropic",
"bedrock",
"cohere",
"sagemaker",
"continue-proxy",
"mistral",
@ -65,6 +66,7 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [
const PROVIDER_SUPPORTS_IMAGES: string[] = [
"openai",
"ollama",
"cohere",
"gemini",
"msty",
"anthropic",
@ -89,6 +91,8 @@ const MODEL_SUPPORTS_IMAGES: string[] = [
"gpt-4o-mini",
"gpt-4-vision",
"claude-3",
"c4ai-aya-vision-8b",
"c4ai-aya-vision-32b",
"gemini-ultra",
"gemini-1.5-pro",
"gemini-1.5-flash",
@ -140,6 +144,7 @@ function modelSupportsImages(
const PARALLEL_PROVIDERS: string[] = [
"anthropic",
"bedrock",
"cohere",
"sagemaker",
"deepinfra",
"gemini",
@ -176,6 +181,7 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
if (
lower.includes("gpt") ||
lower.includes("command") ||
lower.includes("aya") ||
lower.includes("chat-bison") ||
lower.includes("pplx") ||
lower.includes("gemini") ||

View file

@ -11,6 +11,7 @@ import { findLast } from "../util/findLast";
import { normalizeToMessageParts } from "../util/messageContent";
import { isUserOrToolMsg } from "./messages";
import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
import { RulePolicies } from "./rules/types";
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
@ -108,6 +109,7 @@ export function constructMessages(
history: ChatHistoryItem[],
baseChatOrAgentSystemMessage: string | undefined,
rules: RuleWithSource[],
rulePolicies?: RulePolicies,
): ChatMessage[] {
const filteredHistory = history.filter(
(item) => item.message.role !== "system",
@ -164,6 +166,7 @@ export function constructMessages(
rules,
userMessage: lastUserMsg,
contextItems: lastUserContextItems,
rulePolicies,
});
if (systemMessage.trim()) {

View file

@ -1068,9 +1068,17 @@ export abstract class BaseLLM implements ILLM {
documents: chunks.map((chunk) => chunk.content),
});
// Put them in the order they were given
const sortedResults = results.data.sort((a, b) => a.index - b.index);
return sortedResults.map((result) => result.relevance_score);
// Standard OpenAI format
if (results.data && Array.isArray(results.data)) {
return results.data
.sort((a, b) => a.index - b.index)
.map((result) => result.relevance_score);
}
throw new Error(
`Unexpected rerank response format from ${this.providerName}. ` +
`Expected 'data' array but got: ${JSON.stringify(Object.keys(results))}`,
);
}
throw new Error(

View file

@ -161,12 +161,7 @@ function testLLM(
group: "Hello",
},
],
toolChoice: {
type: "function",
function: {
name: "say_hello",
},
},
toolChoice: { type: "function", function: { name: "say_hello" } },
},
)) {
const typedChunk = chunk as AssistantChatMessage;
@ -211,10 +206,7 @@ describe("LLM", () => {
model: "claude-3-5-sonnet-latest",
apiKey: process.env.ANTHROPIC_API_KEY,
}),
{
skip: false,
testToolCall: true,
},
{ skip: false, testToolCall: true },
);
testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "gpt-4o" }), {
skip: false,
@ -240,12 +232,7 @@ describe("LLM", () => {
apiKey: process.env.MISTRAL_API_KEY,
model: "codestral-latest",
}),
{
testFim: true,
skip: false,
testToolCall: true,
timeout: 60000,
},
{ testFim: true, skip: false, testToolCall: true, timeout: 60000 },
);
testLLM(
new Azure({
@ -260,11 +247,10 @@ describe("LLM", () => {
);
testLLM(
new Azure({
apiKey: process.env.AZURE_FOUNDRY_API_KEY,
model: "codestral-latest",
apiBase:
"https://codestral-2501-continue-testing.eastus.models.ai.azure.com",
apiType: "azure-foundry",
apiKey: process.env.AZURE_FOUNDRY_CODESTRAL_API_KEY,
model: "Codestral-2501",
apiBase: "https://continue-foundry-resource.services.ai.azure.com",
env: { apiType: "azure-foundry", apiVersion: "2024-05-01-preview" },
}),
{ testFim: false, skip: false, timeout: 20000 },
);

View file

@ -1,9 +1,10 @@
import { streamJSON } from "@continuedev/fetch";
import { streamSse } from "@continuedev/fetch";
import {
ChatMessage,
Chunk,
CompletionOptions,
LLMOptions,
MessageContent,
} from "../../index.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
@ -11,21 +12,89 @@ import { BaseLLM } from "../index.js";
class Cohere extends BaseLLM {
static providerName = "cohere";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.cohere.ai/v1",
apiBase: "https://api.cohere.ai/v2",
maxEmbeddingBatchSize: 96,
};
static maxStopSequences = 5;
private _convertMessages(msgs: ChatMessage[]): any[] {
const messages = [];
let lastToolPlan: MessageContent | undefined;
for (const m of msgs) {
if (m.role === "system" || !m.content) {
if (!m.content) {
continue;
}
messages.push({
role: m.role === "assistant" ? "chatbot" : m.role,
message: m.content,
});
switch (m.role) {
case "user":
if (typeof m.content === "string") {
messages.push({
role: m.role,
content: m.content,
});
break;
}
messages.push({
role: m.role,
content: m.content.map((part) => {
if (part.type === "imageUrl") {
return {
type: "image_url",
image_url: { url: part.imageUrl.url },
};
}
return part;
}),
});
break;
case "thinking":
lastToolPlan = m.content;
break;
case "assistant":
if (m.toolCalls) {
if (!lastToolPlan) {
throw new Error("No tool plan found");
}
messages.push({
role: m.role,
tool_calls: m.toolCalls.map((toolCall) => ({
id: toolCall.id,
type: "function",
function: {
name: toolCall.function?.name,
arguments: toolCall.function?.arguments,
},
})),
// Ideally the tool plan would be in this message, but it is
// split in another, usually the previous, this one's content is
// a space.
// tool_plan: m.content,
tool_plan: lastToolPlan,
});
lastToolPlan = undefined;
break;
}
messages.push({
role: m.role,
content: m.content,
});
break;
case "system":
messages.push({
role: m.role,
content: stripImages(m.content),
});
break;
case "tool":
messages.push({
role: m.role,
content: m.content,
tool_call_id: m.toolCallId,
});
break;
default:
break;
}
}
return messages;
}
@ -41,7 +110,14 @@ class Cohere extends BaseLLM {
stop_sequences: options.stop?.slice(0, Cohere.maxStopSequences),
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
raw_prompting: options.raw,
tools: options.tools?.map((tool) => ({
type: "function",
function: {
name: tool.function.name,
parameters: tool.function.parameters,
description: tool.function.description,
},
})),
};
}
@ -67,19 +143,12 @@ class Cohere extends BaseLLM {
...this.requestOptions?.headers,
};
let preamble: string | undefined = undefined;
const systemMessage = messages.find((m) => m.role === "system")?.content;
if (systemMessage) {
preamble = stripImages(systemMessage);
}
const resp = await this.fetch(new URL("chat", this.apiBase), {
method: "POST",
headers,
body: JSON.stringify({
...this._convertArgs(options),
message: messages.pop()?.content,
chat_history: this._convertMessages(messages),
preamble,
messages: this._convertMessages(messages),
}),
signal,
});
@ -90,13 +159,97 @@ class Cohere extends BaseLLM {
if (options.stream === false) {
const data = await resp.json();
yield { role: "assistant", content: data.text };
if (data.message.tool_calls) {
yield {
// Use the "thinking" role for `tool_plan`, since there is no such
// role in the Cohere API at the moment and it is a "a
// chain-of-thought style reflection".
role: "thinking",
content: data.message.tool_plan,
};
yield {
role: "assistant",
content: "",
toolCalls: data.message.tool_calls.map((toolCall: any) => ({
id: toolCall.id,
type: "function",
function: {
name: toolCall.function?.name,
arguments: toolCall.function?.arguments,
},
})),
};
return;
}
yield { role: "assistant", content: data.message.content[0].text };
return;
}
for await (const value of streamJSON(resp)) {
if (value.event_type === "text-generation") {
yield { role: "assistant", content: value.text };
let lastToolUseId: string | undefined;
let lastToolUseName: string | undefined;
for await (const value of streamSse(resp)) {
// https://docs.cohere.com/v2/docs/streaming#stream-events
switch (value.type) {
// https://docs.cohere.com/v2/docs/streaming#content-delta
case "content-delta":
yield {
role: "assistant",
content: value.delta.message.content.text,
};
break;
// https://docs.cohere.com/reference/chat-stream#request.body.messages.assistant.tool_plan
case "tool-plan-delta":
// Use the "thinking" role for `tool_plan`, since there is no such
// role in the Cohere API at the moment and it is a "a
// chain-of-thought style reflection".
yield {
role: "thinking",
content: value.delta.message.tool_plan,
};
break;
case "tool-call-start":
lastToolUseId = value.delta.message.tool_calls.id;
lastToolUseName = value.delta.message.tool_calls.function.name;
yield {
role: "assistant",
content: "",
toolCalls: [
{
id: lastToolUseId,
type: "function",
function: {
name: lastToolUseName,
arguments: value.delta.message.tool_calls.function.arguments,
},
},
],
};
break;
case "tool-call-delta":
if (!lastToolUseId || !lastToolUseName) {
throw new Error("No tool use found");
}
yield {
role: "assistant",
content: "",
toolCalls: [
{
id: lastToolUseId,
type: "function",
function: {
name: lastToolUseName,
arguments: value.delta.message.tool_calls.function.arguments,
},
},
],
};
break;
case "tool-call-end":
lastToolUseId = undefined;
lastToolUseName = undefined;
break;
default:
break;
}
}
}

View file

@ -1,7 +1,25 @@
import { LLMOptions } from "../../index.js";
import { Chunk, LLMOptions } from "../../index.js";
import OpenAI from "./OpenAI.js";
// vLLM-specific rerank response types
interface VllmRerankItem {
index: number;
document: {
text: string;
};
relevance_score: number;
}
interface VllmRerankResponse {
id: string;
model: string;
usage: {
total_tokens: number;
};
results: VllmRerankItem[];
}
class Vllm extends OpenAI {
static providerName = "vllm";
constructor(options: LLMOptions) {
@ -16,6 +34,28 @@ class Vllm extends OpenAI {
return false;
}
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
if (this.useOpenAIAdapterFor.includes("rerank") && this.openaiAdapter) {
const results = (await this.openaiAdapter.rerank({
model: this.model,
query,
documents: chunks.map((chunk) => chunk.content),
})) as unknown as VllmRerankResponse;
// vLLM uses 'results' array instead of 'data'
if (results.results && Array.isArray(results.results)) {
const sortedResults = results.results.sort((a, b) => a.index - b.index);
return sortedResults.map((result) => result.index);
}
throw new Error(
`vLLM rerank response missing 'results' array. Got: ${JSON.stringify(Object.keys(results))}`,
);
}
throw new Error("vLLM rerank requires OpenAI adapter");
}
private _setupCompletionOptions() {
this.fetch(this._getEndpoint("models"), {
method: "GET",

View file

@ -0,0 +1,186 @@
import { describe, expect, it } from "vitest";
import {
ContextItemId,
ContextItemWithId,
RuleWithSource,
UserChatMessage,
} from "../..";
import { getApplicableRules } from "./getSystemMessageWithRules";
describe("alwaysApply Behavior", () => {
// Common test fixtures
const testFile = "src/app.ts";
const matchingFile = "src/components/Button.tsx";
const nonMatchingFile = "src/utils/helper.js"; // Not matching *.tsx glob
// File context items
const matchingFileContext: ContextItemWithId = {
id: { providerTitle: "file", itemId: "match1" } as ContextItemId,
uri: { type: "file", value: matchingFile },
content: "export const Button = () => {...}",
name: "Button.tsx",
description: "Component file",
};
const nonMatchingFileContext: ContextItemWithId = {
id: { providerTitle: "file", itemId: "nonmatch1" } as ContextItemId,
uri: { type: "file", value: nonMatchingFile },
content: "export const helper = () => {...}",
name: "helper.js",
description: "Helper file",
};
// Message with no file references
const messageWithoutFile: UserChatMessage = {
role: "user",
content: "Can you help me understand how this works?",
};
it("alwaysApply: true - Always include the rule, regardless of file context", () => {
// Rule with alwaysApply: true
const alwaysApplyRule: RuleWithSource = {
name: "Always Apply Rule",
rule: "This rule should always be applied",
alwaysApply: true,
globs: "**/*.tsx", // Should be ignored since alwaysApply is true
source: "rules-block",
ruleFile: ".continue/rules.md",
};
// Test with no file context
let applicableRules = getApplicableRules(
messageWithoutFile,
[alwaysApplyRule],
[],
);
expect(applicableRules).toHaveLength(1);
expect(applicableRules[0].name).toBe("Always Apply Rule");
// Test with matching file
applicableRules = getApplicableRules(
undefined,
[alwaysApplyRule],
[matchingFileContext],
);
expect(applicableRules).toHaveLength(1);
expect(applicableRules[0].name).toBe("Always Apply Rule");
// Test with non-matching file
applicableRules = getApplicableRules(
undefined,
[alwaysApplyRule],
[nonMatchingFileContext],
);
expect(applicableRules).toHaveLength(1);
expect(applicableRules[0].name).toBe("Always Apply Rule");
});
it("alwaysApply: false - Only include if globs exist AND match file context", () => {
// Rule with alwaysApply: false and globs
const conditionalRule: RuleWithSource = {
name: "Conditional Rule",
rule: "Apply only to matching files",
alwaysApply: false,
globs: "**/*.tsx",
source: "rules-block",
ruleFile: ".continue/rules.md",
};
// Rule with alwaysApply: false and no globs
const neverApplyRule: RuleWithSource = {
name: "Never Apply Rule",
rule: "This rule should never apply",
alwaysApply: false,
// No globs
source: "rules-block",
ruleFile: ".continue/rules.md",
};
// Test with no file context
let applicableRules = getApplicableRules(
messageWithoutFile,
[conditionalRule, neverApplyRule],
[],
);
expect(applicableRules).toHaveLength(0); // No rules should apply
// Test with matching file
applicableRules = getApplicableRules(
undefined,
[conditionalRule, neverApplyRule],
[matchingFileContext],
);
expect(applicableRules).toHaveLength(1);
expect(applicableRules[0].name).toBe("Conditional Rule");
expect(applicableRules.map((r) => r.name)).not.toContain(
"Never Apply Rule",
);
// Test with non-matching file
applicableRules = getApplicableRules(
undefined,
[conditionalRule, neverApplyRule],
[nonMatchingFileContext],
);
expect(applicableRules).toHaveLength(0); // No rules should apply
});
it("alwaysApply: undefined - Default behavior: include if no globs exist OR globs exist and match", () => {
// Rule with undefined alwaysApply and no globs (should behave like a global rule)
const defaultNoGlobsRule: RuleWithSource = {
name: "Default No Globs Rule",
rule: "Default rule with no globs",
source: "rules-block",
ruleFile: ".continue/rules.md",
// No alwaysApply, no globs
};
// Rule with undefined alwaysApply and globs
const defaultWithGlobsRule: RuleWithSource = {
name: "Default With Globs Rule",
rule: "Default rule with globs",
globs: "**/*.tsx",
source: "rules-block",
ruleFile: ".continue/rules.md",
// No alwaysApply, with globs
};
// Test with no file context
let applicableRules = getApplicableRules(
messageWithoutFile,
[defaultNoGlobsRule, defaultWithGlobsRule],
[],
);
expect(applicableRules).toHaveLength(1);
expect(applicableRules[0].name).toBe("Default No Globs Rule");
expect(applicableRules.map((r) => r.name)).not.toContain(
"Default With Globs Rule",
);
// Test with matching file
applicableRules = getApplicableRules(
undefined,
[defaultNoGlobsRule, defaultWithGlobsRule],
[matchingFileContext],
);
expect(applicableRules).toHaveLength(2);
expect(applicableRules.map((r) => r.name)).toContain(
"Default No Globs Rule",
);
expect(applicableRules.map((r) => r.name)).toContain(
"Default With Globs Rule",
);
// Test with non-matching file
applicableRules = getApplicableRules(
undefined,
[defaultNoGlobsRule, defaultWithGlobsRule],
[nonMatchingFileContext],
);
expect(applicableRules).toHaveLength(1);
expect(applicableRules[0].name).toBe("Default No Globs Rule");
expect(applicableRules.map((r) => r.name)).not.toContain(
"Default With Globs Rule",
);
});
});

View file

@ -6,6 +6,7 @@ import {
UserChatMessage,
} from "../..";
import { getApplicableRules } from "./getSystemMessageWithRules";
import { RulePolicies } from "./types";
describe("Rule application with alwaysApply", () => {
// Create an always-apply rule
@ -136,4 +137,38 @@ describe("Rule application with alwaysApply", () => {
expect(applicableRules).toHaveLength(1);
expect(applicableRules.map((r) => r.name)).toContain("Always Apply Rule");
});
it("should respect 'off' rulePolicies over alwaysApply when there are no file paths", () => {
// Rule with alwaysApply: true
const globalRule: RuleWithSource = {
name: "Global Rule",
rule: "This rule has alwaysApply: true but is blocked by rulePolicies",
alwaysApply: true,
source: "rules-block",
ruleFile: "src/some/path.md",
};
// Message with no code blocks or file references
const simpleMessage: UserChatMessage = {
role: "user",
content: "Can you help me with something?",
};
// Create a rule policy that blocks the rule
const rulePolicies: RulePolicies = {
"Global Rule": "off",
};
// The rule should NOT be applied due to the "off" policy,
// even though it has alwaysApply: true and there are no file paths
const applicableRules = getApplicableRules(
simpleMessage,
[globalRule],
[],
rulePolicies,
);
expect(applicableRules).toHaveLength(0);
expect(applicableRules.map((r) => r.name)).not.toContain("Global Rule");
});
});

View file

@ -8,6 +8,7 @@ import {
import { renderChatMessage } from "../../util/messageContent";
import { getCleanUriPath } from "../../util/uri";
import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
import { RulePolicies } from "./types";
/**
* Checks if a path matches any of the provided globs
@ -120,13 +121,21 @@ const isGlobalRule = (rule: RuleWithSource): boolean => {
export const shouldApplyRule = (
rule: RuleWithSource,
filePaths: string[],
rulePolicies: RulePolicies = {},
): boolean => {
const policy = rulePolicies[rule.name || ""];
// Never apply if policy is "off"
if (policy === "off") {
return false;
}
// If it's a global rule, always apply it regardless of file paths
if (isGlobalRule(rule)) {
return true;
}
// If there are no file paths to check:
// If there are no file paths to check and we've made it here:
// - We've already handled global rules above
// - Don't apply other rules since we have no files to match against
if (filePaths.length === 0) {
@ -196,11 +205,9 @@ export const getApplicableRules = (
userMessage: UserChatMessage | ToolResultChatMessage | undefined,
rules: RuleWithSource[],
contextItems: ContextItemWithId[],
rulePolicies: RulePolicies = {},
): RuleWithSource[] => {
// First, extract any global rules that should always apply
const globalRules = rules.filter((rule) => isGlobalRule(rule));
// Get file paths from message and context for regular rule matching
// Get file paths from message and context for rule matching
const filePathsFromMessage = userMessage
? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
: [];
@ -213,41 +220,34 @@ export const getApplicableRules = (
// Combine file paths from both sources
const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems];
// If we have no file paths, just return the global rules
if (allFilePaths.length === 0) {
return globalRules;
}
// Apply shouldApplyRule to all rules - this will handle global rules, rule policies,
// and path matching in a consistent way
const applicableRules = rules.filter((rule) =>
shouldApplyRule(rule, allFilePaths, rulePolicies),
);
// Get rules that match file paths
const matchingRules = rules
.filter((rule) => !isGlobalRule(rule)) // Skip global rules as we've already handled them
.filter((rule) => shouldApplyRule(rule, allFilePaths));
// Combine global rules with matching rules, ensuring no duplicates
return [...globalRules, ...matchingRules];
return applicableRules;
};
/**
* Creates a system message string with applicable rules appended
*
* @param baseSystemMessage - The base system message to start with
* @param userMessage - The user message to check for file paths
* @param rules - The list of rules to filter
* @param contextItems - Context items to check for file paths
* @returns System message with applicable rules appended
*/
export const getSystemMessageWithRules = ({
baseSystemMessage,
userMessage,
rules,
contextItems,
rulePolicies = {},
}: {
baseSystemMessage?: string;
userMessage: UserChatMessage | ToolResultChatMessage | undefined;
rules: RuleWithSource[];
contextItems: ContextItemWithId[];
rulePolicies?: RulePolicies;
}) => {
const applicableRules = getApplicableRules(userMessage, rules, contextItems);
const applicableRules = getApplicableRules(
userMessage,
rules,
contextItems,
rulePolicies,
);
let systemMessage = baseSystemMessage ?? "";
for (const rule of applicableRules) {

View file

@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { RuleWithSource } from "../..";
import { shouldApplyRule } from "./getSystemMessageWithRules";
import { RulePolicies } from "./types";
describe("Rule colocation glob matching", () => {
// This test file demonstrates the expected behavior after our fix
@ -132,3 +133,114 @@ describe("Rule colocation glob matching", () => {
);
});
});
describe("Rule policies", () => {
const componentRule: RuleWithSource = {
name: "Components Rule",
rule: "Use functional components with hooks",
source: "rules-block",
ruleFile: "src/components/rules.md",
};
const testFiles = ["src/components/Button.tsx"];
const nonMatchingFiles = ["src/utils/helpers.ts"];
it("should never apply rules with 'off' policy regardless of file paths", () => {
const rulePolicies: RulePolicies = {
"Components Rule": "off",
};
// Should not apply even to matching files
expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(false);
// Rule with alwaysApply: true should still be overridden by 'off' policy
const alwaysApplyRule: RuleWithSource = {
name: "Always Apply Rule",
rule: "This rule would normally always apply",
alwaysApply: true,
source: "rules-block",
ruleFile: "src/components/rules.md",
};
const offPolicies: RulePolicies = {
"Always Apply Rule": "off",
};
expect(shouldApplyRule(alwaysApplyRule, testFiles, offPolicies)).toBe(
false,
);
});
it("should apply 'on' policy rules based on normal matching logic", () => {
const rulePolicies: RulePolicies = {
"Components Rule": "on",
};
// Should apply to matching files
expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(true);
// Should not apply to non-matching files
expect(shouldApplyRule(componentRule, nonMatchingFiles, rulePolicies)).toBe(
false,
);
});
it("should use default behavior when no policy is specified", () => {
// Empty policies object should use default behavior
const rulePolicies: RulePolicies = {};
// Should apply to matching files
expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(true);
// Should not apply to non-matching files
expect(shouldApplyRule(componentRule, nonMatchingFiles, rulePolicies)).toBe(
false,
);
});
it("should handle policy interaction with global rules", () => {
// Root level rule which would normally apply globally
const rootRule: RuleWithSource = {
name: "Root Rule",
rule: "Follow project standards",
source: "rules-block",
ruleFile: ".continue/rules.md",
};
// Off policy should override even global rules
const offPolicies: RulePolicies = {
"Root Rule": "off",
};
expect(shouldApplyRule(rootRule, testFiles, offPolicies)).toBe(false);
// On policy should maintain global rule behavior
const onPolicies: RulePolicies = {
"Root Rule": "on",
};
expect(shouldApplyRule(rootRule, testFiles, onPolicies)).toBe(true);
});
it("should prioritize 'off' policy over alwaysApply and directory restrictions", () => {
// Create rule with multiple matching criteria
const complexRule: RuleWithSource = {
name: "Complex Rule",
rule: "This rule has complex matching logic",
alwaysApply: true,
globs: "**/*.ts",
source: "rules-block",
ruleFile: "src/utils/rules.md",
};
// Off policy should win over everything
const offPolicies: RulePolicies = {
"Complex Rule": "off",
};
// Even with matching files and alwaysApply: true, off policy wins
expect(
shouldApplyRule(complexRule, ["src/utils/test.ts"], offPolicies),
).toBe(false);
});
});

2
core/llm/rules/types.ts Normal file
View file

@ -0,0 +1,2 @@
export type RulePolicy = "on" | "off";
export type RulePolicies = { [ruleName: string]: RulePolicy };

View file

@ -1,6 +1,7 @@
import { fetchwithRequestOptions } from "@continuedev/fetch";
import { ChatMessage, IDE, PromptLog } from "..";
import { ConfigHandler } from "../config/ConfigHandler";
import { usesFreeTrialApiKey } from "../config/usesFreeTrialApiKey";
import { FromCoreProtocol, ToCoreProtocol } from "../protocol";
import { IMessenger, Message } from "../protocol/messenger";
import { Telemetry } from "../util/posthog";
@ -84,6 +85,7 @@ export async function* llmStreamChat(
config.requestOptions,
),
completionOptions,
abortController,
});
let next = await gen.next();
while (!next.done) {
@ -135,6 +137,8 @@ export async function* llmStreamChat(
true,
);
void checkForFreeTrialExceeded(configHandler, messenger);
if (!next.done) {
throw new Error("Will never happen");
}
@ -142,3 +146,29 @@ export async function* llmStreamChat(
return next.value;
}
}
async function checkForFreeTrialExceeded(
configHandler: ConfigHandler,
messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
) {
const { config } = await configHandler.getSerializedConfig();
// Only check if the user is using the free trial
if (config && !usesFreeTrialApiKey(config)) {
return;
}
try {
const freeTrialStatus =
await configHandler.controlPlaneClient.getFreeTrialStatus();
if (
freeTrialStatus &&
freeTrialStatus.chatCount &&
freeTrialStatus.chatCount > freeTrialStatus.chatLimit
) {
void messenger.request("freeTrialExceeded", undefined);
}
} catch (error) {
console.error("Error checking free trial status:", error);
}
}

View file

@ -109,6 +109,19 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
});
});
describe("cohere", () => {
const supportsFn = PROVIDER_TOOL_SUPPORT["cohere"];
it("should return true for Command models", () => {
expect(supportsFn("command-r")).toBe(true);
expect(supportsFn("command-a")).toBe(true);
});
it("should return false for other models", () => {
expect(supportsFn("c4ai-aya-expanse-32b")).toBe(false);
});
});
describe("gemini", () => {
const supportsFn = PROVIDER_TOOL_SUPPORT["gemini"];
@ -221,6 +234,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
expect(supportsFn("qwen2")).toBe(true);
expect(supportsFn("mixtral-8x7b")).toBe(true);
expect(supportsFn("command-r")).toBe(true);
expect(supportsFn("command-a")).toBe(true);
expect(supportsFn("smollm2")).toBe(true);
expect(supportsFn("hermes3")).toBe(true);
expect(supportsFn("athene-v2")).toBe(true);

View file

@ -71,6 +71,9 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
return false;
},
cohere: (model) => {
return model.toLowerCase().startsWith("command");
},
gemini: (model) => {
// All gemini models support function calling
return model.toLowerCase().includes("gemini");
@ -144,6 +147,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"qwen3",
"mixtral",
"command-r",
"command-a",
"smollm2",
"hermes3",
"athene-v2",
@ -226,6 +230,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"qwen/qwen3",
"qwen/qwen-",
"cohere/command-r",
"cohere/command-a",
"ai21/jamba-1.6",
"mistralai/mistral",
"mistralai/ministral",

View file

@ -113,10 +113,10 @@
"node": ">=20.19.0"
}
},
"../../../../dallin/documents/code/continuedev/continue/packages/config-yaml": {
"../../../dallin/documents/code/continuedev/continue/packages/config-yaml": {
"extraneous": true
},
"../../../../documents/code/continuedev/continue/packages/config-yaml": {
"../../../documents/code/continuedev/continue/packages/config-yaml": {
"version": "1.0.78",
"extraneous": true,
"license": "Apache-2.0",

View file

@ -79,7 +79,7 @@ export function slashCommandFromPromptFileV1(
for await (const chunk of context.llm.streamChat(
messages,
new AbortController().signal,
context.abortController.signal,
context.completionOptions,
)) {
yield renderChatMessage(chunk);

View file

@ -40,6 +40,7 @@ import { FreeTrialStatus } from "../control-plane/client";
export enum OnboardingModes {
API_KEY = "API Key",
LOCAL = "Local",
MODELS_ADD_ON = "Models Add-On",
}
export interface ListHistoryOptions {
@ -199,6 +200,10 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"clipboardCache/add": [{ content: string }, void];
"controlPlane/openUrl": [{ path: string; orgSlug?: string }, void];
"controlPlane/getFreeTrialStatus": [undefined, FreeTrialStatus | null];
"controlPlane/getModelsAddOnUpgradeUrl": [
{ vsCodeUriScheme?: string },
{ url: string } | null,
];
isItemTooBig: [{ item: ContextItemWithId }, boolean];
didChangeControlPlaneSessionInfo: [
{ sessionInfo: ControlPlaneSessionInfo | undefined },

View file

@ -29,8 +29,8 @@ export type ToIdeFromWebviewOrCoreProtocol = {
openFile: [{ path: string }, void];
openUrl: [string, void];
runCommand: [{ command: string; options?: TerminalOptions }, void];
getSearchResults: [{ query: string }, string];
getFileResults: [{ pattern: string }, string[]];
getSearchResults: [{ query: string; maxResults?: number }, string];
getFileResults: [{ pattern: string; maxResults?: number }, string[]];
subprocess: [{ command: string; cwd?: string }, [string, string]];
saveFile: [{ filepath: string }, void];
fileExists: [{ filepath: string }, boolean];

View file

@ -76,7 +76,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
setColors: [{ [key: string]: string }, void];
"jetbrains/editorInsetRefresh": [undefined, void];
"jetbrains/isOSREnabled": [boolean, void];
addApiKey: [undefined, void];
setupApiKey: [undefined, void];
setupLocalConfig: [undefined, void];
incrementFtc: [undefined, void];
openOnboardingCard: [undefined, void];

View file

@ -185,8 +185,8 @@ export class MessageIde implements IDE {
return this.request("getPinnedFiles", undefined);
}
getSearchResults(query: string): Promise<string> {
return this.request("getSearchResults", { query });
getSearchResults(query: string, maxResults?: number): Promise<string> {
return this.request("getSearchResults", { query, maxResults });
}
getFileResults(pattern: string): Promise<string[]> {

View file

@ -159,11 +159,11 @@ export class ReverseMessageIde {
});
this.on("getSearchResults", (data) => {
return this.ide.getSearchResults(data.query);
return this.ide.getSearchResults(data.query, data.maxResults);
});
this.on("getFileResults", (data) => {
return this.ide.getFileResults(data.pattern);
return this.ide.getFileResults(data.pattern, data.maxResults);
});
this.on("getProblems", (data) => {

View file

@ -61,6 +61,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"didChangeSelectedOrg",
"tools/call",
"controlPlane/openUrl",
"controlPlane/getModelsAddOnUpgradeUrl",
"isItemTooBig",
"process/markAsBackgrounded",
"process/isBackgrounded",
@ -84,4 +85,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
"sessionUpdate",
"didCloseFiles",
"toolCallPartialOutput",
"freeTrialExceeded",
];

View file

@ -43,4 +43,5 @@ export type ToWebviewFromIdeOrCoreProtocol = {
"jetbrains/setColors": [Record<string, string | null | undefined>, void];
sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void];
toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void];
freeTrialExceeded: [undefined, void];
};

View file

@ -11,6 +11,7 @@ export enum BuiltInToolNames {
LSTool = "builtin_ls",
CreateRuleBlock = "builtin_create_rule_block",
RequestRule = "builtin_request_rule",
FetchUrlContent = "builtin_fetch_url_content",
// excluded from allTools for now
ViewRepoMap = "builtin_view_repo_map",

View file

@ -5,6 +5,7 @@ import { BuiltInToolNames } from "./builtIn";
import { createNewFileImpl } from "./implementations/createNewFile";
import { createRuleBlockImpl } from "./implementations/createRuleBlock";
import { fetchUrlContentImpl } from "./implementations/fetchUrlContent";
import { fileGlobSearchImpl } from "./implementations/globSearch";
import { grepSearchImpl } from "./implementations/grepSearch";
import { lsToolImpl } from "./implementations/lsTool";
@ -151,6 +152,8 @@ async function callBuiltInTool(
return await runTerminalCommandImpl(args, extras);
case BuiltInToolNames.SearchWeb:
return await searchWebImpl(args, extras);
case BuiltInToolNames.FetchUrlContent:
return await fetchUrlContentImpl(args, extras);
case BuiltInToolNames.ViewDiff:
return await viewDiffImpl(args, extras);
case BuiltInToolNames.LSTool:

View file

@ -14,6 +14,7 @@ export const editFileTool: Tool = {
hasAlready: "edited {{{ filepath }}}",
group: BUILT_IN_GROUP_NAME,
readonly: false,
isInstant: false,
function: {
name: BuiltInToolNames.EditExistingFile,
description:

View file

@ -0,0 +1,28 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const fetchUrlContentTool: Tool = {
type: "function",
displayTitle: "Read URL",
wouldLikeTo: "fetch {{{ url }}}",
isCurrently: "fetching {{{ url }}}",
hasAlready: "viewed {{{ url }}}",
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.FetchUrlContent,
description:
"Can be used to view the contents of a website using a URL. Do NOT use this for files.",
parameters: {
type: "object",
required: ["url"],
properties: {
url: {
type: "string",
description: "The URL to read",
},
},
},
},
};

View file

@ -12,7 +12,8 @@ export const globSearchTool: Tool = {
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.FileGlobSearch,
description: "Search for files in the project",
description:
"Search for files in the project. Output may be truncated; use targeted patterns",
parameters: {
type: "object",
required: ["pattern"],

View file

@ -12,7 +12,8 @@ export const grepSearchTool: Tool = {
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.GrepSearch,
description: "Perform a search over the repository using ripgrep.",
description:
"Perform a search over the repository using ripgrep. Output may be truncated, so use targeted queries",
parameters: {
type: "object",
required: ["query"],

View file

@ -1,5 +1,5 @@
import { parseMarkdownRule } from "@continuedev/config-yaml";
import { jest } from "@jest/globals";
import { parseMarkdownRule } from "../../config/markdown";
import { createRuleBlockImpl } from "./createRuleBlock";
const mockIde = {
@ -40,7 +40,6 @@ test("createRuleBlockImpl should create a rule with glob pattern", async () => {
globs: "**/*.{ts,tsx}",
});
expect(markdown).toContain("# TypeScript Rule");
expect(markdown).toContain("Use interfaces for object shapes");
});
@ -76,7 +75,6 @@ test("createRuleBlockImpl should create a rule with description pattern", async
description: "This is a detailed explanation of the rule",
});
expect(markdown).toContain("# Description Test");
expect(markdown).toContain("This is the rule content");
});
@ -100,7 +98,6 @@ test("createRuleBlockImpl should include both globs and description in frontmatt
globs: "**/*.js",
});
expect(markdown).toContain("# Complete Rule");
expect(markdown).toContain("Follow this standard");
});

View file

@ -1,6 +1,7 @@
import { createRuleMarkdown } from "@continuedev/config-yaml";
import { ToolImpl } from ".";
import { RuleWithSource } from "../..";
import { createRuleFilePath, createRuleMarkdown } from "../../config/markdown";
import { createRuleFilePath } from "../../config/markdown/utils";
export type CreateRuleBlockArgs = Pick<
Required<RuleWithSource>,

View file

@ -0,0 +1,6 @@
import { ToolImpl } from ".";
import { getUrlContextItems } from "../../context/providers/URLContextProvider";
export const fetchUrlContentImpl: ToolImpl = async (args, extras) => {
return getUrlContextItems(args.url, extras.fetch);
};

View file

@ -1,12 +1,28 @@
import { ToolImpl } from ".";
import { ContextItem } from "../..";
const MAX_AGENT_GLOB_RESULTS = 100;
export const fileGlobSearchImpl: ToolImpl = async (args, extras) => {
const results = await extras.ide.getFileResults(args.pattern);
return [
const results = await extras.ide.getFileResults(
args.pattern,
MAX_AGENT_GLOB_RESULTS,
);
const contextItems: ContextItem[] = [
{
name: "File results",
description: "Results from file glob search",
content: results.join("\n"),
},
];
// In case of truncation, add a warning
if (results.length === MAX_AGENT_GLOB_RESULTS) {
contextItems.push({
name: "Truncation warning",
description: "Inform the model that results were truncated",
content: `Warning: the results above were truncated to the first ${MAX_AGENT_GLOB_RESULTS} files. If the results are not satisfactory, refine your search pattern`,
});
}
return contextItems;
};

View file

@ -1,13 +1,44 @@
import { ToolImpl } from ".";
import { ContextItem } from "../..";
import { formatGrepSearchResults } from "../../util/grepSearch";
const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100;
const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now
export const grepSearchImpl: ToolImpl = async (args, extras) => {
const results = await extras.ide.getSearchResults(args.query);
return [
const results = await extras.ide.getSearchResults(
args.query,
DEFAULT_GREP_SEARCH_RESULTS_LIMIT,
);
const { formatted, numResults, truncated } = formatGrepSearchResults(
results,
DEFAULT_GREP_SEARCH_CHAR_LIMIT,
);
const truncationReasons: string[] = [];
if (numResults === DEFAULT_GREP_SEARCH_RESULTS_LIMIT) {
truncationReasons.push(
`the number of results exceeded ${DEFAULT_GREP_SEARCH_RESULTS_LIMIT}`,
);
}
if (truncated) {
truncationReasons.push(
`the number of characters exceeded ${DEFAULT_GREP_SEARCH_CHAR_LIMIT}`,
);
}
const contextItems: ContextItem[] = [
{
name: "Search results",
description: "Results from grep search",
content: formatGrepSearchResults(results),
content: formatted,
},
];
if (truncationReasons.length > 0) {
contextItems.push({
name: "Search truncation warning",
description: "Informs the model that search results were truncated",
content: `The above search results were truncated because ${truncationReasons.join(" and ")}. If the results are not satisfactory, try refining your search query.`,
});
}
return contextItems;
};

View file

@ -1,5 +1,4 @@
import { ToolImpl } from ".";
import { parseMarkdownRule } from "../../config/markdown/parseMarkdownRule";
export const requestRuleImpl: ToolImpl = async (args, extras) => {
// Find the rule by name in the config
@ -11,14 +10,11 @@ export const requestRuleImpl: ToolImpl = async (args, extras) => {
);
}
const fileContent = await extras.ide.readFile(rule.ruleFile);
const { markdown, frontmatter } = parseMarkdownRule(fileContent);
return [
{
name: frontmatter.name ?? "",
description: frontmatter.description ?? "",
content: markdown,
name: rule.name ?? "",
description: rule.description ?? "",
content: rule.rule,
uri: {
type: "file",
value: rule.ruleFile,

View file

@ -10,6 +10,16 @@ import {
const asyncExec = util.promisify(childProcess.exec);
// Add color-supporting environment variables
const getColorEnv = () => ({
...process.env,
FORCE_COLOR: "1",
COLORTERM: "truecolor",
TERM: "xterm-256color",
CLICOLOR: "1",
CLICOLOR_FORCE: "1",
});
const ENABLED_FOR_REMOTES = [
"",
"local",
@ -56,10 +66,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
}
}
// Use spawn instead of exec to get streaming output
// Use spawn with color environment
const childProc = childProcess.spawn(args.command, {
cwd,
shell: true,
env: getColorEnv(), // Add enhanced environment for colors
});
childProc.stdout?.on("data", (data) => {
@ -130,26 +141,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
return;
}
if (!waitForCompletion) {
// Already resolved, just update the UI with final output
if (extras.onPartialOutput) {
const status =
code === 0 || !code
? "\nBackground command completed"
: `\nBackground command failed with exit code ${code}`;
extras.onPartialOutput({
toolCallId,
contextItems: [
{
name: "Terminal",
description: "Terminal command output",
content: terminalOutput,
status: status,
},
],
});
}
} else {
if (waitForCompletion) {
// Normal completion, resolve now
if (code === 0) {
const status = "Command completed";
@ -172,6 +164,25 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
},
]);
}
} else {
// Already resolved, just update the UI with final output
if (extras.onPartialOutput) {
const status =
code === 0 || !code
? "\nBackground command completed"
: `\nBackground command failed with exit code ${code}`;
extras.onPartialOutput({
toolCallId,
contextItems: [
{
name: "Terminal",
description: "Terminal command output",
content: terminalOutput,
status: status,
},
],
});
}
}
});
@ -197,14 +208,43 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
const workspaceDirs = await extras.ide.getWorkspaceDirs();
const cwd = fileURLToPath(workspaceDirs[0]);
if (!waitForCompletion) {
if (waitForCompletion) {
// Standard execution, waiting for completion
try {
// Use color environment for exec as well
const output = await asyncExec(args.command, {
cwd,
env: getColorEnv(),
});
const status = "Command completed";
return [
{
name: "Terminal",
description: "Terminal command output",
content: output.stdout ?? "",
status: status,
},
];
} catch (error: any) {
const status = `Command failed with: ${error.message || error.toString()}`;
return [
{
name: "Terminal",
description: "Terminal command output",
content: error.stderr ?? error.toString(),
status: status,
},
];
}
} else {
// For non-streaming but also not waiting for completion, use spawn
// but don't attach any listeners other than error
try {
// Use spawn instead of exec but don't wait
// Use spawn with color environment
const childProc = childProcess.spawn(args.command, {
cwd,
shell: true,
env: getColorEnv(), // Add color environment
// Detach the process so it's not tied to the parent
detached: true,
// Redirect to /dev/null equivalent (works cross-platform)
@ -246,30 +286,6 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
},
];
}
} else {
// Standard execution, waiting for completion
try {
const output = await asyncExec(args.command, { cwd });
const status = "Command completed";
return [
{
name: "Terminal",
description: "Terminal command output",
content: output.stdout ?? "",
status: status,
},
];
} catch (error: any) {
const status = `Command failed with: ${error.message || error.toString()}`;
return [
{
name: "Terminal",
description: "Terminal command output",
content: error.stderr ?? error.toString(),
status: status,
},
];
}
}
}
}

View file

@ -2,6 +2,7 @@ import { ConfigDependentToolParams, Tool } from "..";
import { createNewFileTool } from "./definitions/createNewFile";
import { createRuleBlock } from "./definitions/createRuleBlock";
import { editFileTool } from "./definitions/editFile";
import { fetchUrlContentTool } from "./definitions/fetchUrlContent";
import { globSearchTool } from "./definitions/globSearch";
import { grepSearchTool } from "./definitions/grepSearch";
import { lsTool } from "./definitions/lsTool";
@ -24,6 +25,7 @@ export const baseToolDefinitions = [
readCurrentlyOpenFileTool,
lsTool,
createRuleBlock,
fetchUrlContentTool,
// replacing with ls tool for now
// viewSubdirectoryTool,
// viewRepoMapTool,

View file

@ -234,11 +234,14 @@ class FileSystemIde implements IDE {
return Promise.resolve([]);
}
async getSearchResults(query: string): Promise<string> {
async getSearchResults(query: string, maxResults?: number): Promise<string> {
return "";
}
async getFileResults(pattern: string): Promise<string[]> {
async getFileResults(
pattern: string,
maxResults?: number,
): Promise<string[]> {
return [];
}

View file

@ -1,4 +1,19 @@
export function formatGrepSearchResults(results: string): string {
/*
Formats the output of a grep search to reduce unnecessary indentation, lines, etc
Assumes a command with these params
ripgrep -i --ignore-file .continueignore --ignore-file .gitignore -C 2 --heading -m 100 -e <query> .
Also can truncate the output to a specified number of characters
*/
export function formatGrepSearchResults(
results: string,
maxChars?: number,
): {
formatted: string;
numResults: number;
truncated: boolean;
} {
let numResults = 0;
const keepLines: string[] = [];
function countLeadingSpaces(line: string) {
@ -45,6 +60,7 @@ export function formatGrepSearchResults(results: string): string {
if (line.startsWith("./") || line === "--") {
processResult(resultLines); // process previous result
resultLines = [line];
numResults++;
continue;
}
@ -57,5 +73,18 @@ export function formatGrepSearchResults(results: string): string {
}
processResult(resultLines);
return keepLines.join("\n");
const formatted = keepLines.join("\n");
if (maxChars && formatted.length > maxChars) {
return {
formatted: formatted.substring(0, maxChars),
numResults,
truncated: true,
};
} else {
return {
formatted,
numResults,
truncated: false,
};
}
}

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