Merge branch 'feature/nextEdit' of https://github.com/continuedev/continue into feature/nextEdit

This commit is contained in:
adarshramiyer 2025-06-23 16:00:06 -07:00
commit 34b3446a9a
237 changed files with 7015 additions and 8067 deletions

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

@ -0,0 +1,7 @@
---
name: Update docs from GitHub PR
description: Provide a PR link to update docs based on
alwaysApply: false
---
When provided with a GitHub PR URL, use the GitHub CLI (`gh pr view <PR_URL> --json title,body,commits,files,additions,deletions,changedFiles`) to fetch comprehensive PR details including title, description, commits, changed files, and diff statistics. Analyze the PR content to identify what documentation in the `docs` folder needs to be updated, created, or modified. Update relevant documentation files to reflect the changes, new features, bug fixes, or improvements described in the PR. Ensure documentation changes are accurate, well-structured, and maintain consistency with existing docs formatting and style.

View file

@ -0,0 +1,4 @@
If the user's request is vague and you don't have enough information to confidently answer, you can either
- In Chat OR Agent mode, stop and ask questions to clarify before proceeding
- In Agent mode, use tools to discover more information, starting with the glob/grep tools if available.

View file

@ -0,0 +1,6 @@
---
name: Programming principles
description: Guidelines for coding fundamentals in this project
---
Use functional programming paradigms whenever possible. Modifying existing classes or creating singletons where needed is acceptable. but otherwise, use functions.

View file

@ -0,0 +1 @@
Always create comprehensive unit tests for new pure functions. Tests should cover normal cases, edge cases, and boundary conditions.

View file

@ -6,25 +6,23 @@ rules:
rule: >-
For unit testing in this project:
1. The project uses Vitest and Jest for testing. Prefer Vitest
1. The project uses Jest as the testing framework
2. Run tests from within the specific package directory (e.g., `cd core && ..`
2. Run tests using `npm test` from within the specific package/module
directory
3. For vitest tests,
- Test files follow the pattern `*.vitest.ts`
- Run tests using `vitest` from within the specific package/module
directory: `cd [directory] && vitest -- [test file path]`
3. Command structure: `cd [directory] && npm test -- [test file path]`
4. For jest tests,
- Test files follow the pattern `*.test.ts`
- Run tests using `npm test` from within the specific package/module
directory: `cd [directory] && npm test -- [test file path]`
- The test script uses experimental VM modules via NODE_OPTIONS flag
4. The test script uses experimental VM modules via NODE_OPTIONS flag
5. Test files follow the pattern `*.test.ts`
6. Tests must import Jest with `import { jest } from "@jest/globals";`
7. Run tests from within the specific package directory (e.g., `cd core`
for core module tests)
8. Write tests as top-level `test()` functions - DO NOT use `describe()`
5. For both
- Write tests as top-level `test()` functions - DO NOT use `describe()`
blocks
9. Include the function name being tested in the test description for
- Include the function name being tested in the test description for
clarity

View file

@ -0,0 +1,5 @@
---
globs: "extensions/vscode/src/commands.ts"
---
When adding new commands to the commands map, always create a separate helper function for the command logic instead of defining it inline. Follow the pattern of existing commands like `streamInlineEdit` - define the helper function below the commands map, then call it from within the command entry.

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

@ -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"
@ -54,7 +55,7 @@
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@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,6 +145,7 @@
"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",
"vitest": "^3.1.4"
@ -6774,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

@ -1,3 +1,4 @@
import { describe, test } from "vitest";
import { PYTHON_TEST_CASES, TYPESCRIPT_TEST_CASES } from "./testCases";
import { testRootPathContext } from "./testUtils";

View file

@ -1,6 +1,6 @@
import { jest } from "@jest/globals";
import fs from "fs";
import path from "path";
import { expect, vi } from "vitest";
import Parser from "web-tree-sitter";
import { Position } from "../../../..";
@ -36,7 +36,7 @@ export async function testRootPathContext(
const importDefinitionsService = new ImportDefinitionsService(ide);
const service = new RootPathContextService(importDefinitionsService, ide);
const getSnippetsMock = jest
const getSnippetsMock = vi
// @ts-ignore
.spyOn(service, "getSnippets")
// @ts-ignore
@ -46,7 +46,7 @@ export async function testRootPathContext(
// Copy the folder to the test directory
const folderPath = path.join(
__dirname,
process.cwd(),
"autocomplete",
"context",
"root-path-context",

View file

@ -1,3 +1,4 @@
import { describe, expect, it } from "vitest";
import { stopAtStartOf, stopAtStopTokens } from "./charStream";
async function* createMockStream(chunks: string[]): AsyncGenerator<string> {

View file

@ -1,10 +1,10 @@
import { jest } from "@jest/globals";
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
import * as lineStream from "./lineStream";
// eslint-disable-next-line max-lines-per-function
describe("lineStream", () => {
let mockFullStop: jest.Mock;
let mockFullStop: Mock;
async function getLineGenerator(lines: any) {
return (async function* () {
@ -25,7 +25,7 @@ describe("lineStream", () => {
}
beforeEach(() => {
mockFullStop = jest.fn();
mockFullStop = vi.fn();
});
describe("noTopLevelKeywordsMidline", () => {

View file

@ -1,4 +1,9 @@
import { setUpTestDir, tearDownTestDir } from "../../../test/testDir";
import { afterAll, beforeAll, beforeEach, describe, it } from "vitest";
import {
addToTestDir,
setUpTestDir,
tearDownTestDir,
} from "../../../test/testDir";
import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases";
import {
@ -18,6 +23,7 @@ describe("Autocomplete filtering tests", () => {
beforeAll(async () => {
tearDownTestDir();
setUpTestDir();
addToTestDir([".continueignore"]);
});
afterAll(async () => {

View file

@ -1,3 +1,4 @@
import { expect } from "vitest";
import MockLLM from "../../../llm/llms/Mock";
import { testConfigHandler, testIde } from "../../../test/fixtures";
import { joinPathsToUri } from "../../../util/uri";

View file

@ -1,4 +1,12 @@
import { jest } from "@jest/globals";
import {
afterEach,
beforeEach,
describe,
expect,
Mock,
test,
vi,
} from "vitest";
import { GeneratorReuseManager } from "./GeneratorReuseManager";
function createMockGenerator(
@ -14,7 +22,7 @@ function createMockGenerator(
}
}
};
const newGenerator = jest
const newGenerator = vi
.fn<() => AsyncGenerator<string>>()
.mockReturnValue(mockGenerator());
@ -23,15 +31,15 @@ function createMockGenerator(
describe("GeneratorReuseManager", () => {
let reuseManager: GeneratorReuseManager;
let onErrorMock: jest.Mock;
let onErrorMock: Mock;
beforeEach(() => {
onErrorMock = jest.fn();
onErrorMock = vi.fn();
reuseManager = new GeneratorReuseManager(onErrorMock);
});
afterEach(() => {
jest.clearAllMocks();
vi.clearAllMocks();
});
test("creates new generator when there is no current generator", async () => {
@ -169,7 +177,7 @@ describe("GeneratorReuseManager", () => {
const mockGenerator = async function* () {
throw error;
};
const newGenerator = jest
const newGenerator = vi
.fn<() => AsyncGenerator<string>>()
.mockReturnValue(mockGenerator());

View file

@ -1,4 +1,4 @@
import { jest } from "@jest/globals";
import { describe, expect, it, vi } from "vitest";
import { ListenableGenerator } from "./ListenableGenerator";
@ -16,7 +16,7 @@ describe("ListenableGenerator", () => {
it("should yield values from the source generator via tee()", async () => {
const values = [1, 2, 3];
const source = asyncGenerator(values);
const onError = jest.fn();
const onError = vi.fn();
const lg = new ListenableGenerator<number>(
source,
@ -36,7 +36,7 @@ describe("ListenableGenerator", () => {
it("should allow listeners to receive values", async () => {
const values = [1, 2, 3];
const source = asyncGenerator(values, 10); // Introduce delay to simulate async behavior
const onError = jest.fn();
const onError = vi.fn();
const lg = new ListenableGenerator<number>(
source,
@ -44,7 +44,7 @@ describe("ListenableGenerator", () => {
new AbortController(),
);
const listener = jest.fn();
const listener = vi.fn();
// Add listener after some delay to simulate late subscription
setTimeout(() => {
@ -64,7 +64,7 @@ describe("ListenableGenerator", () => {
it("should buffer values for listeners added after some values have been yielded", async () => {
const values = [1, 2, 3];
const source = asyncGenerator(values, 10);
const onError = jest.fn();
const onError = vi.fn();
const lg = new ListenableGenerator<number>(
source,
@ -72,7 +72,7 @@ describe("ListenableGenerator", () => {
new AbortController(),
);
const initialListener = jest.fn();
const initialListener = vi.fn();
lg.listen(initialListener);
@ -80,7 +80,7 @@ describe("ListenableGenerator", () => {
await new Promise((resolve) => setTimeout(resolve, 15));
// Add a second listener
const newListener = jest.fn();
const newListener = vi.fn();
lg.listen(newListener);
// Wait for generator to finish
@ -98,7 +98,7 @@ describe("ListenableGenerator", () => {
it("should handle cancellation", async () => {
const values = [1, 2, 3, 4, 5];
const source = asyncGenerator(values, 10);
const onError = jest.fn();
const onError = vi.fn();
const lg = new ListenableGenerator<number>(
source,
@ -131,7 +131,7 @@ describe("ListenableGenerator", () => {
}
const source = errorGenerator();
const onError = jest.fn();
const onError = vi.fn();
const lg = new ListenableGenerator<number>(
source,
@ -152,7 +152,7 @@ describe("ListenableGenerator", () => {
it("should notify listeners when the generator ends", async () => {
const values = [1, 2, 3];
const source = asyncGenerator(values);
const onError = jest.fn();
const onError = vi.fn();
const lg = new ListenableGenerator<number>(
source,
@ -160,7 +160,7 @@ describe("ListenableGenerator", () => {
new AbortController(),
);
const listener = jest.fn();
const listener = vi.fn();
lg.listen(listener);
// Wait for the generator to finish

View file

@ -1,13 +1,13 @@
import { jest } from "@jest/globals";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { stopAfterMaxProcessingTime } from "./utils";
describe("stopAfterMaxProcessingTime", () => {
beforeEach(() => {
jest.useFakeTimers();
vi.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
vi.useRealTimers();
});
async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
@ -28,7 +28,7 @@ describe("stopAfterMaxProcessingTime", () => {
it("should yield all chunks when maxTimeMs is not reached", async () => {
const mockStream = createMockStream(["Hello", " world", "!"]);
const fullStop = jest.fn();
const fullStop = vi.fn();
const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop);
const output = await streamToString(result);
@ -37,11 +37,11 @@ describe("stopAfterMaxProcessingTime", () => {
expect(fullStop).not.toHaveBeenCalled();
});
it.only("should stop processing after max time is reached", async () => {
it("should stop processing after max time is reached", async () => {
// Mock implementation of Date.now
let currentTime = 0;
const originalDateNow = Date.now;
Date.now = jest.fn(() => currentTime);
Date.now = vi.fn(() => currentTime);
// Create a generator that we can control
async function* controlledGenerator(): AsyncGenerator<string> {
@ -54,7 +54,7 @@ describe("stopAfterMaxProcessingTime", () => {
}
}
const fullStop = jest.fn();
const fullStop = vi.fn();
const maxTimeMs = 500;
const transformedGenerator = stopAfterMaxProcessingTime(
@ -84,10 +84,10 @@ describe("stopAfterMaxProcessingTime", () => {
it("should check time only periodically based on checkInterval", async () => {
const chunks = Array(100).fill("x");
const mockStream = createMockStream(chunks);
const fullStop = jest.fn();
const fullStop = vi.fn();
// Spy on Date.now to count how many times it's called
const dateSpy = jest.spyOn(Date, "now");
const dateSpy = vi.spyOn(Date, "now");
// Stream should complete normally (not hitting the timeout)
await streamToString(
@ -105,7 +105,7 @@ describe("stopAfterMaxProcessingTime", () => {
it("should handle empty stream gracefully", async () => {
const mockStream = createMockStream([]);
const fullStop = jest.fn();
const fullStop = vi.fn();
const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop);
const output = await streamToString(result);
@ -117,7 +117,7 @@ describe("stopAfterMaxProcessingTime", () => {
it("should pass through all chunks if there's no timeout", async () => {
const chunks = Array(100).fill("test chunk");
const mockStream = createMockStream(chunks);
const fullStop = jest.fn();
const fullStop = vi.fn();
// Use undefined as timeout to simulate no timeout
const result = stopAfterMaxProcessingTime(

View file

@ -1,3 +1,4 @@
import { beforeEach, expect, test, vi } from "vitest";
import { GitDiffCache } from "./gitDiffCache";
beforeEach(() => {
@ -7,7 +8,7 @@ beforeEach(() => {
test("GitDiffCache returns cached results within cache time", async () => {
const mockDiff = ["file1.ts", "file2.ts"];
const getDiffFn = jest.fn().mockResolvedValue(mockDiff);
const getDiffFn = vi.fn().mockResolvedValue(mockDiff);
const cache = GitDiffCache.getInstance(getDiffFn, 1); // 1 second cache
const result1 = await cache.get();
@ -20,7 +21,7 @@ test("GitDiffCache returns cached results within cache time", async () => {
test("GitDiffCache refreshes cache after expiration", async () => {
const mockDiff = ["file1.ts"];
const getDiffFn = jest.fn().mockResolvedValue(mockDiff);
const getDiffFn = vi.fn().mockResolvedValue(mockDiff);
const cache = GitDiffCache.getInstance(getDiffFn, 0.1); // 100ms cache
const result1 = await cache.get();
@ -31,7 +32,7 @@ test("GitDiffCache refreshes cache after expiration", async () => {
});
test("GitDiffCache returns empty array on error", async () => {
const getDiffFn = jest.fn().mockRejectedValue(new Error("Git error"));
const getDiffFn = vi.fn().mockRejectedValue(new Error("Git error"));
const cache = GitDiffCache.getInstance(getDiffFn);
const result = await cache.get();
@ -41,7 +42,7 @@ test("GitDiffCache returns empty array on error", async () => {
test("GitDiffCache reuses pending request", async () => {
const mockDiff = ["file1.ts"];
let resolvePromise: (value: string[]) => void;
const getDiffFn = jest.fn().mockImplementation(() => {
const getDiffFn = vi.fn().mockImplementation(() => {
return new Promise((resolve) => {
resolvePromise = resolve;
});
@ -63,7 +64,7 @@ test("GitDiffCache reuses pending request", async () => {
test("GitDiffCache invalidate clears cache", async () => {
const mockDiff = ["file1.ts"];
const getDiffFn = jest.fn().mockResolvedValue(mockDiff);
const getDiffFn = vi.fn().mockResolvedValue(mockDiff);
const cache = GitDiffCache.getInstance(getDiffFn);
await cache.get();
@ -74,8 +75,8 @@ test("GitDiffCache invalidate clears cache", async () => {
});
test("GitDiffCache maintains singleton instance", () => {
const getDiffFn1 = jest.fn();
const getDiffFn2 = jest.fn();
const getDiffFn1 = vi.fn();
const getDiffFn2 = vi.fn();
const instance1 = GitDiffCache.getInstance(getDiffFn1);
const instance2 = GitDiffCache.getInstance(getDiffFn2);

View file

@ -3,6 +3,7 @@
*
*/
import { describe, expect, test } from "vitest";
import {
AutocompleteCodeSnippet,
AutocompleteDiffSnippet,

View file

@ -1,3 +1,4 @@
import { describe, expect, it } from "vitest";
import {
processTestCase,
type CompletionTestCase,

View file

@ -1,3 +1,4 @@
import { describe, expect, it } from "vitest";
import { processTestCase } from "./completionTestUtils";
import { processSingleLineCompletion } from "./processSingleLineCompletion";

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

@ -1,5 +1,6 @@
import { ctxItemToRifWithContents } from "./util";
import { describe, expect, it } from "vitest";
import { ContextItemWithId, RangeInFileWithContents } from "../index";
import { ctxItemToRifWithContents } from "./util";
describe("ctxItemToRifWithContents", () => {
it("should parse start and end lines from the item name when format is valid", () => {

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
@ -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,192 +0,0 @@
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

@ -1,12 +1,10 @@
import { BlockType } from "@continuedev/config-yaml";
import { BlockType, RULE_FILE_EXTENSION } from "@continuedev/config-yaml";
import { describe, expect, test } from "@jest/globals";
import { RULE_FILE_EXTENSION } from "../markdown";
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

@ -123,7 +123,6 @@ describe("LocalPlatformClient", () => {
expect(
(resolvedFQSNs[0] as SecretResult & { value: unknown })?.value,
).toBe(secretValue);
console.log("debug1 resolved fqsn", resolvedFQSNs);
});
});

View file

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

@ -56,7 +56,9 @@ class MCPContextProvider extends BaseContextProvider {
private insertInputToUriTemplate(uri: string, query: string): string {
const TEMPLATE_VAR = "query";
if (uri.includes(`{${TEMPLATE_VAR}}`)) {
return uri.replace(`{${TEMPLATE_VAR}}`, encodeURIComponent(query));
// Sending an empty string will result in an error, so we instead send "null"
const queryOrNull = query.trim() === "" ? "null" : query;
return uri.replace(`{${TEMPLATE_VAR}}`, encodeURIComponent(queryOrNull));
}
return uri;
}

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

@ -1,4 +1,5 @@
import * as crypto from "crypto";
import { expect, test } from "vitest";
import { LicenseKeyData, validateLicenseKey } from "./mdm";
// We'll create a real key pair once for all tests

View file

@ -44,12 +44,13 @@ import {
ModelDescription,
Position,
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 { isLocalDefinitionFile } from "./config/loadLocalAssistants";
import {
@ -60,6 +61,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";
@ -71,7 +73,6 @@ import { processNextEditData } from "./nextEdit/context/processNextEditData.js";
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 => {
@ -151,6 +152,18 @@ export class Core {
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(
@ -516,6 +529,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,
@ -529,13 +547,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));
@ -804,44 +822,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);
@ -866,6 +849,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) {
@ -953,7 +975,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,13 +1,22 @@
import { DevDataLogEvent } from "@continuedev/config-yaml";
import fs from "fs";
import path from "path";
import {
afterAll,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from "vitest";
import { IdeInfo, IdeSettings } from "..";
import { Core } from "../core";
import { getDevDataFilePath } from "../util/paths";
import { DataLogger } from "./log";
// Only mock fetch, not fs
jest.mock("@continuedev/fetch");
vi.mock("@continuedev/fetch");
const TEST_EVENT: DevDataLogEvent = {
name: "tokensGenerated",
@ -54,7 +63,7 @@ describe("DataLogger", () => {
beforeEach(() => {
// Reset mocks
jest.clearAllMocks();
vi.clearAllMocks();
// Remove test file if it exists
if (fs.existsSync(testFilePath)) {
@ -67,7 +76,7 @@ describe("DataLogger", () => {
// Mock core and required promises
dataLogger.core = {
configHandler: {
loadConfig: jest.fn().mockResolvedValue({
loadConfig: vi.fn().mockResolvedValue({
config: {
data: [],
},
@ -78,7 +87,7 @@ describe("DataLogger", () => {
},
},
controlPlaneClient: {
getAccessToken: jest.fn().mockResolvedValue("test-access-token"),
getAccessToken: vi.fn().mockResolvedValue("test-access-token"),
},
},
} as unknown as Core;
@ -184,7 +193,6 @@ describe("DataLogger", () => {
// Read file contents and verify
const fileContent = fs.readFileSync(filepath, "utf8");
console.log("debug1 filecontent", fileContent);
expect(fileContent).toContain('"eventName":"chatInteraction"');
expect(fileContent).toContain('"prompt":"Hello, world!"');
expect(fileContent).toContain('"completion":"Hello, world!"');
@ -195,10 +203,10 @@ describe("DataLogger", () => {
describe("logDevData", () => {
it("should log data locally and to configured destinations", async () => {
// Spy on logLocalData and logToOneDestination
const logLocalDataSpy = jest
const logLocalDataSpy = vi
.spyOn(dataLogger, "logLocalData")
.mockResolvedValue();
const logToOneDestinationSpy = jest
const logToOneDestinationSpy = vi
.spyOn(dataLogger, "logToOneDestination")
.mockResolvedValue();
@ -212,7 +220,7 @@ describe("DataLogger", () => {
},
};
dataLogger.core!.configHandler.loadConfig = jest
dataLogger.core!.configHandler.loadConfig = vi
.fn()
.mockResolvedValue(mockConfig);

View file

@ -1,3 +1,5 @@
import { describe, expect, test } from "vitest";
import { dedent } from "../util";
import { myersDiff } from "./myers";

View file

@ -1,6 +1,8 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, test } from "vitest";
// @ts-ignore no typings available
import { changed, diff as myersDiff } from "myers-diff";
import { streamDiff } from "../diff/streamDiff.js";
@ -54,12 +56,7 @@ function displayDiff(diff: DiffLine[]) {
}
async function expectDiff(file: string) {
const testFilePath = path.join(
__dirname,
"diff",
"test-examples",
file + ".diff",
);
const testFilePath = path.join(__dirname, "test-examples", file + ".diff");
const testFileContents = fs.readFileSync(testFilePath, "utf-8");
const [oldText, newText, expectedDiff] = testFileContents
.split("\n---\n")

View file

@ -1,8 +1,8 @@
// Generated by continue
import { matchLine, streamLines, generateLines } from "./util";
import { describe, expect, it, vi } from "vitest";
import { ChatMessage } from "../index";
import { jest } from "@jest/globals";
import { generateLines, matchLine, streamLines } from "./util";
describe.skip("matchLine", () => {
it("should match empty lines if the first old line is also empty", () => {
@ -146,7 +146,7 @@ describe("streamLines", () => {
content: "line4",
};
// const spy = jest.spyOn(messageContentModule, "renderChatMessage");
// const spy = vi.spyOn(messageContentModule, "renderChatMessage");
async function* streamCompletion(): AsyncGenerator<ChatMessage> {
yield messageChunk1;
@ -164,7 +164,7 @@ describe("streamLines", () => {
});
it("should log lines if log parameter is true", async () => {
const consoleSpy = jest.spyOn(console, "log").mockImplementation(() => {});
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
async function* streamCompletion(): AsyncGenerator<string> {
yield "line1\nline2\n";

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

9
core/index.d.ts vendored
View file

@ -783,9 +783,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]>;
@ -835,6 +835,7 @@ export interface ContinueSDK {
config: ContinueConfig;
fetch: FetchFunction;
completionOptions?: LLMFullCompletionOptions;
abortController: AbortController;
}
export interface SlashCommand {
@ -1283,7 +1284,7 @@ export interface HighlightedCodePayload {
}
export interface AcceptOrRejectDiffPayload {
filepath: string;
filepath?: string;
streamId?: string;
}
@ -1594,12 +1595,12 @@ export interface RuleWithSource {
slug?: string;
source: RuleSource;
globs?: string | string[];
regex?: string | string[];
rule: string;
description?: string;
ruleFile?: string;
alwaysApply?: boolean;
}
export interface CompleteOnboardingPayload {
mode: OnboardingModes;
provider?: string;

View file

@ -63,13 +63,12 @@ export async function* chunkDocument({
resolve({
...chunkWithoutId,
digest,
index,
index: index++,
filepath,
});
})();
}),
);
index++;
}
for await (const chunk of chunkPromises) {
if (!chunk) {

View file

@ -29,7 +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",
],
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

@ -1,5 +1,5 @@
const DEFAULT_MAX_TOKENS = 4096;
const DEFAULT_CONTEXT_LENGTH = 8192;
const DEFAULT_CONTEXT_LENGTH = 32_768;
const DEFAULT_TEMPERATURE = 0.5;
const DEFAULT_ARGS = {

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

@ -1,6 +1,10 @@
import { ChatMessage, LLMOptions } from "..";
import { allModelProviders } from "@continuedev/llm-info";
import { LlmInfo } from "@continuedev/llm-info/dist/types";
import { BaseLLM } from ".";
import { DEFAULT_CONTEXT_LENGTH } from "./constants";
import { LLMClasses } from "./llms";
import { LLMLogger } from "./logger";
class DummyLLM extends BaseLLM {
@ -140,4 +144,31 @@ describe("BaseLLM", () => {
describe("*streamChat", () => {
// TODO: Implement tests for *streamChat method
});
describe("default context length", () => {
allModelProviders.map((modelProvider) => {
const LLMClass = LLMClasses.find(
(llm) => llm.providerName === modelProvider.id,
);
if (!LLMClass) {
throw new Error(`did not find LLM provider for ${modelProvider.id}`);
}
const testContextLength = (llmInfo: LlmInfo) => () => {
const llm = new LLMClass({ model: llmInfo.model });
if (llmInfo.contextLength) {
expect(llm.contextLength).toEqual(llmInfo.contextLength);
} else {
expect(llm.contextLength).toEqual(DEFAULT_CONTEXT_LENGTH);
}
};
describe(`${modelProvider.id}`, () => {
modelProvider.models.forEach((llmInfo) => {
test(
`should have correct context length for ${llmInfo.model}`,
testContextLength(llmInfo),
);
});
});
});
});
});

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

@ -8,7 +8,6 @@ class Anthropic extends BaseLLM {
static providerName = "anthropic";
static defaultOptions: Partial<LLMOptions> = {
model: "claude-3-5-sonnet-latest",
contextLength: 200_000,
completionOptions: {
model: "claude-3-5-sonnet-latest",
maxTokens: 8192,

View file

@ -48,7 +48,6 @@ class Bedrock extends BaseLLM {
static defaultOptions: Partial<LLMOptions> = {
region: "us-east-1",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
contextLength: 200_000,
profile: "bedrock",
};

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

@ -7,7 +7,9 @@ import {
} from "../..";
import { renderChatMessage } from "../../util/messageContent";
import { getCleanUriPath } from "../../util/uri";
import { extractContentFromCodeBlock } from "../utils/extractContentFromCodeBlocks";
import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
import { RulePolicies } from "./types";
/**
* Checks if a path matches any of the provided globs
@ -51,6 +53,47 @@ const matchesGlobs = (
return false;
};
/**
* Checks if file content matches any of the provided regex regex
*
* @param fileContent - The content of the file to check
* @param regex - A single regex pattern string or array of regex pattern strings
* @returns true if the content matches any pattern (or if no regex is provided), false otherwise
*/
const contentMatchesRegex = (
fileContent: string,
regex: string | string[],
): boolean => {
// Handle single string pattern
if (typeof regex === "string") {
try {
const expression = new RegExp(regex);
return expression.test(fileContent);
} catch (e) {
console.error(`Invalid regex pattern: ${regex}`, e);
return false;
}
}
// Handle array of regex
if (Array.isArray(regex)) {
if (regex.length === 0) return true;
// Content must match at least one pattern
return regex.some((pattern) => {
try {
const regex = new RegExp(pattern);
return regex.test(fileContent);
} catch (e) {
console.error(`Invalid regex pattern: ${pattern}`, e);
return false;
}
});
}
return false;
};
/**
* Determines if a file path is within a specific directory or its subdirectories
*
@ -102,31 +145,81 @@ const isGlobalRule = (rule: RuleWithSource): boolean => {
return true;
}
// Root-level rules with no globs are implicitly global
if (isRootLevelRule(rule) && !rule.globs && rule.alwaysApply !== false) {
// Root-level rules with no globs or regex are implicitly global
if (
isRootLevelRule(rule) &&
!rule.globs &&
!rule.regex &&
rule.alwaysApply !== false
) {
return true;
}
return false;
};
const checkGlobsAndRegex = ({
rule,
filePaths,
fileContents,
}: {
rule: RuleWithSource;
filePaths: string[];
fileContents: Record<string, string>;
}) => {
const matchingFiles = rule.globs
? filePaths.filter((filePath) => matchesGlobs(filePath, rule.globs))
: filePaths;
// If no files match the globs, don't apply the rule
if (matchingFiles.length === 0) {
return false;
}
// Now check for pattern matches in file contents if regex are specified
if (rule.regex) {
// Check if any of the matching files also match the content regex
return matchingFiles.some((filePath) => {
const content = fileContents[filePath];
// If we don't have the content, we can't check regex
if (!content) return false;
return contentMatchesRegex(content, rule.regex!);
});
}
// If we have no regex or if we couldn't check regex (no content),
// just go with the glob matches
return matchingFiles.length > 0;
};
/**
* Determines if a rule should be applied based on its alwaysApply property and file path matching
* Determines if a rule should be applied based on its properties and file matching
*
* @param rule - The rule to check
* @param filePaths - Array of file paths to check against the rule's globs
* @param fileContents - Map of file paths to their contents for pattern matching
* @param rulePolicies - Optional policies that can override normal rule behavior
* @returns true if the rule should be applied, false otherwise
*/
export const shouldApplyRule = (
rule: RuleWithSource,
filePaths: string[],
rulePolicies: RulePolicies = {},
fileContents: Record<string, string> = {},
): 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) {
@ -148,40 +241,27 @@ export const shouldApplyRule = (
isFileInDirectory(filePath, ruleDirPath),
);
// If no files are in this directory, don't apply the rule
if (filesInRuleDirectory.length === 0) {
return false;
}
// If we have globs, check if any files in this directory match them
if (rule.globs) {
return filesInRuleDirectory.some((filePath) =>
matchesGlobs(filePath, rule.globs),
);
}
// No globs but files are in this directory, so apply the rule
return true;
return checkGlobsAndRegex({
filePaths: filesInRuleDirectory,
fileContents,
rule,
});
}
// For root-level rules:
// If alwaysApply is explicitly false, only apply if there are globs AND they match
if (rule.alwaysApply === false) {
if (!rule.globs) {
return false;
}
return filePaths.some((path) => matchesGlobs(path, rule.globs));
// If alwaysApply is explicitly false, we need to check globs and/or regex
if (
rule.alwaysApply === false &&
rule.globs === undefined &&
rule.regex === undefined
) {
return false;
}
// Default behavior for root rules with globs:
// - Only apply if they match the globs
if (rule.globs) {
return filePaths.some((path) => matchesGlobs(path, rule.globs));
}
// This point should not be reached as we've handled all cases above
return false;
return checkGlobsAndRegex({
filePaths,
fileContents,
rule,
});
};
/**
@ -196,11 +276,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 +291,58 @@ 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;
// Create a map of file paths to their contents for pattern matching
const fileContents: Record<string, string> = {};
// Extract contents from context items with file URIs
contextItems.forEach((item) => {
if (item.uri?.type === "file" && item.uri?.value) {
fileContents[item.uri.value] = item.content;
}
});
// Extract contents from code blocks in the message for paths that don't have content yet
if (userMessage) {
const messageContent = renderChatMessage(userMessage);
filePathsFromMessage.forEach((path) => {
// Only extract content if we don't already have it from context items
if (!fileContents[path]) {
const blockContent = extractContentFromCodeBlock(messageContent, path);
if (blockContent) {
fileContents[path] = blockContent;
}
}
});
}
// 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));
// 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, fileContents),
);
// 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,15 @@
import { describe, expect, it } from "vitest";
import { RuleWithSource } from "../..";
import { shouldApplyRule } from "./getSystemMessageWithRules";
import {
ContextItemId,
ContextItemWithId,
RuleWithSource,
UserChatMessage,
} from "../..";
import {
getApplicableRules,
shouldApplyRule,
} from "./getSystemMessageWithRules";
import { RulePolicies } from "./types";
describe("Rule colocation glob matching", () => {
// This test file demonstrates the expected behavior after our fix
@ -132,3 +141,339 @@ 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);
});
});
describe("Content pattern matching", () => {
it("should apply rules when file content matches pattern", () => {
// Rule with pattern to match React component files
const reactComponentRule: RuleWithSource = {
name: "React Component Rule",
rule: "Follow React component standards",
regex: "export (function|const) \\w+.*\\(",
source: "rules-block",
ruleFile: "src/components/rules.md",
};
// File that matches the pattern
const filePath = "src/components/Button.tsx";
const fileContents = {
[filePath]:
"export function Button() { return <button>Click me</button> }",
};
expect(
shouldApplyRule(reactComponentRule, [filePath], {}, fileContents),
).toBe(true);
// File that doesn't match the pattern
const nonMatchingContents = {
[filePath]:
"import React from 'react'; // Just an import, not a component",
};
expect(
shouldApplyRule(reactComponentRule, [filePath], {}, nonMatchingContents),
).toBe(false);
});
it("should support multiple regex regex as an array", () => {
// Rule with multiple regex
const multiPatternRule: RuleWithSource = {
name: "Multi-Pattern Rule",
rule: "Apply to functions or classes",
regex: ["function\\s+\\w+", "class\\s+\\w+"],
source: "rules-block",
ruleFile: "src/utils/rules.md",
};
const filePath = "src/utils/helper.ts";
// Content with function - should match
const functionContent = {
[filePath]: "function formatDate(date) { return date.toISOString(); }",
};
expect(
shouldApplyRule(multiPatternRule, [filePath], {}, functionContent),
).toBe(true);
// Content with class - should match
const classContent = {
[filePath]:
"class DateFormatter { format(date) { return date.toISOString(); } }",
};
expect(
shouldApplyRule(multiPatternRule, [filePath], {}, classContent),
).toBe(true);
// Content with neither - should not match
const nonMatchingContent = {
[filePath]: "const PI = 3.14159;",
};
expect(
shouldApplyRule(multiPatternRule, [filePath], {}, nonMatchingContent),
).toBe(false);
});
it("should apply rules based on both globs and regex when both are specified", () => {
// Rule with both glob and pattern restrictions
const typescriptClassRule: RuleWithSource = {
name: "TypeScript Class Rule",
rule: "Follow class standards in TypeScript",
globs: "**/*.ts",
regex: "class\\s+\\w+",
source: "rules-block",
ruleFile: "src/models/rules.md",
};
const tsFilePath = "src/models/User.ts";
const jsFilePath = "src/models/Product.js";
// TypeScript file with class - should match
const tsClassContent = {
[tsFilePath]: "export class User { constructor(public name: string) {} }",
};
expect(
shouldApplyRule(typescriptClassRule, [tsFilePath], {}, tsClassContent),
).toBe(true);
// TypeScript file without class - should not match
const tsNonClassContent = {
[tsFilePath]: "export const createUser = (name: string) => ({ name });",
};
expect(
shouldApplyRule(typescriptClassRule, [tsFilePath], {}, tsNonClassContent),
).toBe(false);
// JavaScript file with class - should not match due to glob
const jsClassContent = {
[jsFilePath]:
"export class Product { constructor(name) { this.name = name; } }",
};
expect(
shouldApplyRule(typescriptClassRule, [jsFilePath], {}, jsClassContent),
).toBe(false);
});
it("should extract file content from messages for pattern matching", () => {
// Rule with pattern
const arrowFunctionRule: RuleWithSource = {
name: "Arrow Function Rule",
rule: "Use arrow functions for better this binding",
regex: "const\\s+\\w+\\s*=\\s*\\(",
source: "rules-block",
ruleFile: "src/utils/rules.md",
};
// Message with code block containing a matching pattern
const messageWithArrowFn: UserChatMessage = {
role: "user",
content:
"Can you check this code?\n```typescript src/utils/formatter.ts\nconst format = (date) => {\n return date.toISOString();\n};\n```",
};
// Create context item to match the file in the message
const contextItem: ContextItemWithId = {
id: { providerTitle: "file", itemId: "formatter" } as ContextItemId,
uri: { type: "file", value: "src/utils/formatter.ts" },
content: "const format = (date) => {\n return date.toISOString();\n};",
name: "formatter.ts",
description: "Utility formatter",
};
// Should match the pattern
const applicableRules = getApplicableRules(
messageWithArrowFn,
[arrowFunctionRule],
[contextItem],
);
expect(applicableRules).toHaveLength(1);
expect(applicableRules[0].name).toBe("Arrow Function Rule");
// Message with code block that doesn't match the pattern
const messageWithoutArrowFn: UserChatMessage = {
role: "user",
content:
"Can you check this code?\n```typescript src/utils/formatter.ts\nfunction format(date) {\n return date.toISOString();\n}\n```",
};
// Context item with non-matching content
const nonMatchingContextItem: ContextItemWithId = {
id: { providerTitle: "file", itemId: "formatter2" } as ContextItemId,
uri: { type: "file", value: "src/utils/formatter.ts" },
content: "function format(date) {\n return date.toISOString();\n}",
name: "formatter.ts",
description: "Utility formatter",
};
// Should not match the pattern
const nonApplicableRules = getApplicableRules(
messageWithoutArrowFn,
[arrowFunctionRule],
[nonMatchingContextItem],
);
expect(nonApplicableRules).toHaveLength(0);
});
it("should handle invalid regex regex gracefully", () => {
// Rule with invalid regex pattern
const invalidRegexRule: RuleWithSource = {
name: "Invalid Regex Rule",
rule: "This rule has an invalid regex pattern",
regex: "([unclosed parenthesis",
source: "rules-block",
ruleFile: "src/utils/rules.md",
};
const filePath = "src/utils/helper.ts";
const fileContents = {
[filePath]: "function helper() { return true; }",
};
// Should not throw an error but gracefully not apply the rule
expect(
shouldApplyRule(invalidRegexRule, [filePath], {}, fileContents),
).toBe(false);
});
it("should respect directory restrictions for pattern rules", () => {
// Rule with pattern in a nested directory
const nestedPatternRule: RuleWithSource = {
name: "Nested Pattern Rule",
rule: "Apply only to model files with interfaces",
regex: "interface\\s+\\w+",
source: "rules-block",
ruleFile: "src/models/rules.md",
};
// File in the correct directory with matching content
const modelFilePath = "src/models/User.ts";
const modelContents = {
[modelFilePath]: "export interface User { id: string; name: string; }",
};
expect(
shouldApplyRule(nestedPatternRule, [modelFilePath], {}, modelContents),
).toBe(true);
// File outside the directory with matching content - should not match
const utilFilePath = "src/utils/types.ts";
const utilContents = {
[utilFilePath]:
"export interface Config { apiUrl: string; timeout: number; }",
};
expect(
shouldApplyRule(nestedPatternRule, [utilFilePath], {}, utilContents),
).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

@ -85,6 +85,7 @@ export async function* llmStreamChat(
config.requestOptions,
),
completionOptions,
abortController,
});
let next = await gen.next();
while (!next.done) {

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

@ -0,0 +1,94 @@
import { extractContentFromCodeBlock } from "./extractContentFromCodeBlocks";
describe("extractContentFromCodeBlock", () => {
it("should extract content from code block with language and filepath", () => {
const content = "```typescript src/main.ts\nconst x = 1;\n```";
expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe(
"const x = 1;",
);
});
it("should extract content from code block with filepath only (no language)", () => {
const content = "```test.js\nclass Calculator { }\n```";
expect(extractContentFromCodeBlock(content, "test.js")).toBe(
"class Calculator { }",
);
});
it("should extract content from code block with line ranges", () => {
const content = "```js test.js (19-25)\nfunction test() {}\n```";
expect(extractContentFromCodeBlock(content, "test.js")).toBe(
"function test() {}",
);
});
it("should handle multiple code blocks and find the right one", () => {
const content =
"```typescript src/main.ts\nconst x = 1;\n```\n" +
"```test.js\nclass Calculator { }\n```\n" +
"```js utils.js (19-25)\nfunction test() {}\n```";
expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe(
"const x = 1;",
);
expect(extractContentFromCodeBlock(content, "test.js")).toBe(
"class Calculator { }",
);
expect(extractContentFromCodeBlock(content, "utils.js")).toBe(
"function test() {}",
);
});
it("should handle paths with special regex characters", () => {
const content =
"```typescript src/special+chars.ts[123]\nconst special = true;\n```";
expect(
extractContentFromCodeBlock(content, "src/special+chars.ts[123]"),
).toBe("const special = true;");
});
it("should handle multiline content", () => {
const content =
"```typescript src/multi-line.ts\n" +
"function example() {\n" +
" const x = 1;\n" +
" return x + 2;\n" +
"}\n" +
"```";
const expected =
"function example() {\n" + " const x = 1;\n" + " return x + 2;\n" + "}";
expect(extractContentFromCodeBlock(content, "src/multi-line.ts")).toBe(
expected,
);
});
it("should return undefined when path doesn't exist in any code block", () => {
const content = "```typescript src/main.ts\nconst x = 1;\n```";
expect(
extractContentFromCodeBlock(content, "nonexistent.ts"),
).toBeUndefined();
});
it("should extract content when the path has directory structure", () => {
const content =
"```js src/components/Button.jsx\nconst Button = () => <button>Click me</button>;\n```";
expect(
extractContentFromCodeBlock(content, "src/components/Button.jsx"),
).toBe("const Button = () => <button>Click me</button>;");
});
it("should match exact paths only", () => {
const content =
"```typescript src/utils.ts\nconst util = {};\n```\n" +
"```typescript src/utils/index.ts\nconst index = {};\n```";
expect(extractContentFromCodeBlock(content, "src/utils.ts")).toBe(
"const util = {};",
);
expect(extractContentFromCodeBlock(content, "src/utils/index.ts")).toBe(
"const index = {};",
);
});
});

View file

@ -0,0 +1,33 @@
/**
* Extracts content from code blocks with given path
* @param content The full message content
* @param path The file path to look for
* @returns The content of the code block if found, undefined otherwise
*/
export function extractContentFromCodeBlock(
content: string,
path: string,
): string | undefined {
// Escape special characters in the path for regex
const escapedPath = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
// Match the code block with this path
// This regex looks for:
// 1. Code block start with the path (```[language] path)
// 2. The content until the closing ```
// The path can be:
// - With language: ```typescript src/main.ts
// - Without language: ```src/main.ts
// - With line ranges: ```js src/main.ts (1-10)
const regex = new RegExp(
`\`\`\`[^\\n]*\\b${escapedPath}(?:\\s+\\([\\d-]+\\))?[^\\n]*\\n([\\s\\S]*?)\\n\`\`\``,
"m",
);
const match = content.match(regex);
if (match && match[1]) {
return match[1];
}
return undefined;
}

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

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

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

@ -0,0 +1,11 @@
import fs from "fs";
import path from "path";
// Sets up the GLOBAL directory for testing - equivalent to ~/.continue
// IMPORTANT: the CONTINUE_GLOBAL_DIR environment variable is used in utils/paths for getting all local paths
export default async function () {
process.env.CONTINUE_GLOBAL_DIR = path.join(__dirname, ".continue-test");
if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR)) {
fs.rmdirSync(process.env.CONTINUE_GLOBAL_DIR, { recursive: true });
}
}

16
core/test/vitest.setup.ts Normal file
View file

@ -0,0 +1,16 @@
import { TextDecoder, TextEncoder } from "util";
import fetch, { Request, Response } from "node-fetch";
import { beforeAll } from "vitest";
beforeAll(() => {
// @ts-ignore
globalThis.fetch = fetch;
// @ts-ignore
globalThis.Request = Request;
// @ts-ignore
globalThis.Response = Response;
globalThis.TextEncoder = TextEncoder;
// @ts-ignore
globalThis.TextDecoder = TextDecoder;
});

View file

@ -13,7 +13,7 @@ export const createRuleBlock: Tool = {
function: {
name: BuiltInToolNames.CreateRuleBlock,
description:
"Creates a persistent rule for all future conversations. For establishing code standards or preferences that should be applied consistently. To modify existing rules, use the edit tool instead.",
'Creates a "rule" that can be referenced in future conversations. This should be used whenever you want to establish code standards / preferences that should be applied consistently, or when you want to avoid making a mistake again. To modify existing rules, use the edit tool instead.',
parameters: {
type: "object",
required: ["name", "rule", "alwaysApply", "description"],
@ -37,6 +37,11 @@ export const createRuleBlock: Tool = {
description:
"Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])",
},
regex: {
type: "string",
description:
"Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)",
},
},
},
},

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,21 +1,30 @@
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>,
"rule" | "description" | "alwaysApply" | "name"
> &
Pick<RuleWithSource, "globs">;
Pick<RuleWithSource, "globs" | "regex">;
export const createRuleBlockImpl: ToolImpl = async (
args: CreateRuleBlockArgs,
extras,
) => {
const fileContent = createRuleMarkdown(args.name, args.rule, {
// Create options object with the fields that createRuleMarkdown expects
const options: any = {
description: args.description,
globs: args.globs,
});
};
// Add regex if provided
if (args.regex) {
options.regex = args.regex;
}
const fileContent = createRuleMarkdown(args.name, args.rule, options);
const [localContinueDir] = await extras.ide.getWorkspaceDirs();
const ruleFilePath = createRuleFilePath(localContinueDir, args.name);

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

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

View file

@ -0,0 +1,217 @@
import { expect, test } from "vitest";
import { formatGrepSearchResults } from "./grepSearch";
// Sample grep output mimicking what would come from ripgrep with the params:
// ripgrep -i --ignore-file .continueignore --ignore-file .gitignore -C 2 --heading -m 100 -e <query> .
const sampleGrepOutput = `./program.cs
Console.WriteLine("Hello World!");
Calculator calc = new Calculator();
calc.Add(5).Subtract(3);
Console.WriteLine("Result: " + calc.GetResult());
}
--
}
public Calculator Subtract(double number)
{
result -= number;
./test.kt
}
fun subtract(number: Double): Test {
result -= number
return this
./test.php
}
public function subtract($number) {
$this->result -= $number;
return $this;
--
$calc = new Calculator();
$calc->add(10)->subtract(5);
echo "Result: " . $calc->getResult() . "\n";
./Calculator.java
}
public Calculator subtract(double number) {
result -= number;
return this;
--
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.add(10).subtract(5);
System.out.println("Result: " + calc.getResult());
}
./calculator_test/Calculator.java
}
public int subtract(int a, int b) {
return a - b;
}
./test.rb
end
def subtract(number)
@result -= number
self
--
calc = Calculator.new
calc.add(5).subtract(3)
puts "Result: #{calc.get_result}"
./test.js
return this;
}
subtract(number) {
return this;
}
./test.py
return self
def subtract(self, number):
self.result -= number
return self
./test.ts
}
subtract(number: number): Calculator {
this.result -= number;
return this;`;
test("formats grep search results correctly", () => {
const result = formatGrepSearchResults(sampleGrepOutput);
expect(result.numResults).toBe(13); // 4 file paths in the sample
expect(result.truncated).toBe(false);
// Check that all file paths are preserved
expect(result.formatted).toContain("./program.cs");
expect(result.formatted).toContain("./test.kt");
expect(result.formatted).toContain("./test.php");
expect(result.formatted).toContain("./Calculator.java");
// Check that content is preserved and properly indented
expect(result.formatted).toContain('Console.WriteLine("Hello World!");');
expect(result.formatted).toContain("fun subtract(number: Double): Test {");
expect(result.formatted).toContain("public function subtract($number) {");
expect(result.formatted).toContain(
"public Calculator subtract(double number) {",
);
});
test("handles empty input", () => {
const result = formatGrepSearchResults("");
expect(result.numResults).toBe(0);
expect(result.truncated).toBe(false);
expect(result.formatted).toBe("");
});
test("handles input with only file paths (no content) - lines should be skipped", () => {
const input =
"./empty-file.ts\n./another-empty.js\n./has-content.ts\n searchMatch";
const result = formatGrepSearchResults(input);
expect(result.numResults).toBe(3);
expect(result.formatted).toBe("./has-content.ts\n searchMatch");
});
test("truncates output when exceeding maxChars", () => {
const maxChars = 50;
const result = formatGrepSearchResults(sampleGrepOutput, maxChars);
expect(result.truncated).toBe(true);
expect(result.formatted.length).toBe(maxChars);
});
test("normalizes indentation to 2 spaces", () => {
const input = `./file.ts
function test() {
const x = 1;
console.log(x);
}`;
const result = formatGrepSearchResults(input);
// The function should normalize the indentation to 2 spaces
expect(result.formatted).toContain("./file.ts");
expect(result.formatted).toContain(" function test() {");
expect(result.formatted).toContain(" const x = 1;");
expect(result.formatted).toContain(" console.log(x);");
expect(result.formatted).toContain(" }");
});
test("skips leading single-char or empty lines after file paths", () => {
const input = `./file.ts
function test() {
console.log("test");
}`;
const result = formatGrepSearchResults(input);
expect(result.formatted).toContain("./file.ts");
expect(result.formatted).not.toContain("\n \n"); // The single space line should be skipped
expect(result.formatted).toContain("function test() {");
});
test("processes separator lines correctly", () => {
const input = `./file1.ts
function one() {
return 1;
}
--
function two() {
return 2;
}
./file2.ts
class Test {
method() {}
}`;
const result = formatGrepSearchResults(input);
expect(result.numResults).toBe(3);
expect(result.formatted).toContain("./file1.ts");
expect(result.formatted).toContain("--");
expect(result.formatted).toContain("function two() {");
expect(result.formatted).toContain("./file2.ts");
});
test("increases indentation when original is less than 2 spaces", () => {
const input = `./minimal-indent.ts
function test() {
singleSpaceIndent();
}`;
const result = formatGrepSearchResults(input);
expect(result.formatted).toContain(" function test() {");
expect(result.formatted).toContain(" singleSpaceIndent();");
expect(result.formatted).toContain(" }");
});
test("decreases indentation when original is more than 2 spaces", () => {
const input = `./excessive-indent.ts
function test() {
tooMuchIndent();
}`;
const result = formatGrepSearchResults(input);
expect(result.formatted).toContain(" function test() {");
expect(result.formatted).toContain(" tooMuchIndent();");
expect(result.formatted).toContain(" }");
});

View file

@ -4,6 +4,7 @@ import { TeamAnalytics } from "../control-plane/TeamAnalytics.js";
import { IdeInfo } from "../index.js";
import type { PostHog as PostHogType } from "posthog-node";
import { extractMinimalStackTraceInfo } from "./extractMinimalStackTraceInfo.js";
export enum PosthogFeatureFlag {
AutocompleteTimeout = "autocomplete-timeout",
@ -37,6 +38,24 @@ export class Telemetry {
static os: string | undefined = undefined;
static ideInfo: IdeInfo | undefined = undefined;
/**
* Convenience method for capturing errors in a single event
*/
static async captureError(errorName: string, error: unknown) {
if (!(error instanceof Error)) {
return;
}
await Telemetry.capture(
"extension_error_caught",
{
errorName,
message: error.message,
stack: extractMinimalStackTraceInfo(error.stack),
},
false,
);
}
static async capture(
event: string,
properties: { [key: string]: any },

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