Merge branch 'main' into watsonx-vi

This commit is contained in:
Nate 2025-06-05 10:46:48 -07:00
commit fae5c5db4d
346 changed files with 57449 additions and 54187 deletions

View file

@ -0,0 +1,79 @@
name: Update LLM Info
description: Updates Gemini blocks with latest information
version: 2
---
I need you to update this repo with the latest information about large language models from certain providers.
The information is stored in the `packages/llm-info` directory, which operates as its own npm package.
Information is stored in a simple JSON format, with one file of models per "provider" (e.g. gemini, ollama, openai, etc).
For example, Gemini model information is stored in `packages/llm-info/src/providers/gemini.ts`.
To make these updates for a given provider, perform the following steps one at a time:
1. VIEW CURRENT INFORMATION
To view the current llm info, read the file (e.g. `packages/llm-info/src/providers/gemini.ts`) using the read_file tool.
If you do not see a tool for reading files, let me know.
For reference, here is the LLMInfo interface used to store the information:
```typescript
export interface LlmInfo {
model: string; // the model name used to distinguish the model at the API layer, e.g. "gemini-2.5-pro-preview-05-06"
displayName?: string; // A fitting display name, e.g. "Gemini 2.5 Pro Preview"
description?: string; // A short description of the model, as similar as possible to descriptions found on the provider's website
contextLength?: number; // The size of the context window in tokens, often called "max input tokens" or "context length"
maxCompletionTokens?: number; // The maximum number of tokens the model can output
regex?: RegExp; // A regex expression to uniquely match the model name if it had some slight modifications/upgrades, e.g. /gemini-2\.5-pro-preview/i
mediaTypes?: MediaType[]; // Input/output types supported by the model, e.g. [MediaType.Text, MediaType.Image]
}
export enum MediaType {
Text = "text",
Image = "image",
Audio = "audio",
Video = "video",
}
export const AllMediaTypes = [
MediaType.Text,
MediaType.Image,
MediaType.Audio,
MediaType.Video,
];
```
2. EXTRACT NEW INFORMATION
New information will be pulled from the internet.
If you do not see a web search tool, let me know.
Retrieve the following sites per these providers, and consider these notes on how to extract the information:
- "gemini": https://ai.google.dev/gemini-api/docs/models - maxCompletionTokens is called "Output token limit", contextLength is called "Input token limit"
// TODO: add info for openai, ollama, etc
For any other providers, search the web for "latest [provider] models" and find the most relevant model information using your best judgement.
Generally, ignore models that do not support text output. These models will be used in a coding assistant client that only supports text/image input and text/output, so extraneous capabilities can be ignored.
Sometimes, "Experimental", "Preview", or similar versions of models are available. The latest-date version of each should have its own information maintained.
3. UPDATE THE INFORMATION
Use the edit file tool to submit updates to the relevant provider file (e.g. `packages/llm-info/src/providers/gemini.ts`).
Let me know if you do not see a tool for editing files.
Generally, avoid making changes to existing information, as it is probably up to date.
Primarily, focus on adding new models or adding missing information to existing models.
NEVER delete any existing models, but let me know if you think one should be removed.
Stop to ask me if you are unsure about any changes, and let me know if there are updates that seem nuanced, complex, or extremely notable.
Provide a summary of changes after the fact.
4. ASK IF I WANT TO PUBLISH TO NPM
After you are done updating everything, remind me that I need to publish the changes to npm.
// TODO too sensitive for now
// If yes, update `packages/llm-info/package.json` with the new version number and then
// - use the terminal tool to commit the changes
// - use the terminal tool to publish changes to npm
// If you do not see a tool for running terminal commands, let me know.
// User input
Please update LLM Info for the following providers. If "all", update all providers mentioned above:

View file

@ -0,0 +1,9 @@
---
globs: /**/*.
description: General questions about code completion should be answered specific to Continue
---
# Continue Specificity
- In chat mode, if the user asks generally about code completion or developer tools, answer specifically regarding Continue and not other similar software.
- Keep all suggestions and comments concentrated on Continue, unless the user asks otherwise. If the user does this, answer with no particular specificity to Continue.

View file

@ -13,4 +13,4 @@ description: Standards for writing and maintaining Continue Docs
- Include cross-references to related documentation
- Reference other docs with relative paths
- Keep paragraphs concise and scannable
- Use code blocks with appropriate language tags
- Use code blocks with appropriate language tags

View file

@ -6,6 +6,7 @@
},
"plugins": ["@typescript-eslint", "import"],
"rules": {
"no-negated-condition": "warn",
"@typescript-eslint/naming-convention": "off",
"@typescript-eslint/no-floating-promises": "warn",
"@typescript-eslint/semi": "warn",

View file

@ -30,6 +30,24 @@ jobs:
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm ci
prettier-check:
needs: install-root
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
- name: Check code formatting with Prettier
run: npx prettier --check "**/*.{js,jsx,ts,tsx,json,css,md}" --ignore-path .gitignore --ignore-path .prettierignore
install-config-yaml:
needs: install-root
runs-on: ubuntu-latest
@ -408,6 +426,7 @@ jobs:
run: |
cd core
npm test
npm run vitest
env:
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
@ -859,6 +878,7 @@ jobs:
runs-on: ubuntu-latest
needs:
- install-root
- prettier-check
- install-core
- core-checks
- install-gui

View file

@ -15,4 +15,11 @@ gui/dist
CHANGELOG.md
**/continue_tutorial.py
**/node_modules
**/CODEOWNERS
**/CODEOWNERS
core/vendor
coverage
e2e
extensions/vscode/gui
extensions/vscode/models
extensions/intellij/src/main/resources
packages/continue-sdk

View file

@ -14,21 +14,21 @@ religion, or sexual identity and orientation.
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
- The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities

View file

@ -58,7 +58,6 @@ file
![edit](docs/static/img/edit.gif)
</div>
## Getting Started

View file

@ -1,6 +1,10 @@
const path = require('path');
const path = require("path");
process.env.CONTINUE_DEVELOPMENT = true;
process.env.CONTINUE_GLOBAL_DIR = path.join(process.env.PROJECT_DIR, 'extensions', '.continue-debug');
process.env.CONTINUE_GLOBAL_DIR = path.join(
process.env.PROJECT_DIR,
"extensions",
".continue-debug",
);
require('./out/index.js');
require("./out/index.js");

View file

@ -1,7 +1,13 @@
const fs = require('fs');
const path = require('path');
const fs = require("fs");
const path = require("path");
const logDirPath = path.join(__dirname, '..', 'extensions', '.continue-debug', 'logs');
const logDirPath = path.join(
__dirname,
"..",
"extensions",
".continue-debug",
"logs",
);
const logFilePath = path.join(logDirPath, "prompt.log");
// Ensure the log directory exists
@ -12,7 +18,7 @@ if (!fs.existsSync(logDirPath)) {
// Create the log file if it doesn't exist
if (!fs.existsSync(logFilePath)) {
fs.writeFileSync(logFilePath, ''); // Create an empty file synchronously
fs.writeFileSync(logFilePath, ""); // Create an empty file synchronously
console.log("Created empty log file at " + logFilePath);
}
@ -25,14 +31,16 @@ try {
// console.clear();
const stream = fs.createReadStream(logFilePath);
stream.pipe(process.stdout);
stream.on('error', (err) => {
console.error('Error reading log file:', err.message);
stream.on("error", (err) => {
console.error("Error reading log file:", err.message);
});
} catch (err) {
console.error('Error while handling file change:', err.message);
console.error("Error while handling file change:", err.message);
}
});
} catch (err) {
console.error('Error setting up file watcher:', err.message);
console.log('You may need to restart the script after the extension generates the first log entry.');
}
console.error("Error setting up file watcher:", err.message);
console.log(
"You may need to restart the script after the extension generates the first log entry.",
);
}

View file

@ -39,4 +39,4 @@ module.exports = {
TARGET_TO_RIPGREP_RELEASE,
TARGET_TO_LANCEDB,
RIPGREP_VERSION,
};
};

View file

@ -1,5 +1,4 @@
import { ConfigHandler } from "../config/ConfigHandler.js";
import { TRIAL_FIM_MODEL } from "../config/onboarding.js";
import { IDE, ILLM } from "../index.js";
import OpenAI from "../llm/llms/OpenAI.js";
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
@ -75,11 +74,6 @@ export class CompletionProvider {
if (llm instanceof OpenAI) {
llm.useLegacyCompletionsEndpoint = true;
} else if (
llm.providerName === "free-trial" &&
llm.model !== TRIAL_FIM_MODEL
) {
llm.model = TRIAL_FIM_MODEL;
}
return llm;

View file

@ -74,7 +74,6 @@ export class StreamTransformPipeline {
const timeoutValue = helper.options.modelTimeout;
lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!);
const finalGenerator = streamWithNewLines(lineGenerator);

View file

@ -215,21 +215,47 @@ describe("lineStream", () => {
});
it("should handle unfenced code with a code block", async () => {
const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```"]);
const linesGenerator = await getLineGenerator([
"const x = 5;",
"```bash",
"ls -al",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"ls -al",
"```",
]);
});
it("should handle unfenced code with two code blocks", async () => {
const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]);
const linesGenerator = await getLineGenerator([
"const x = 5;",
"```bash",
"ls -al",
"```",
"```bash",
"ls -al",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"ls -al",
"```",
"```bash",
"ls -al",
"```",
]);
});
it("should remove lines before the first valid line", async () => {
@ -242,7 +268,11 @@ describe("lineStream", () => {
});
it("should remove outer blocks", async () => {
const linesGenerator = await getLineGenerator(["```ts", "const x = 5;","```"]);
const linesGenerator = await getLineGenerator([
"```ts",
"const x = 5;",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
@ -251,48 +281,119 @@ describe("lineStream", () => {
});
it("should leave inner blocks intact", async () => {
const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```"]);
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"ls -al",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"ls -al",
"```",
]);
});
it("should handle included inner ticks", async () => {
const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","echo ```test```","```","```"]);
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"echo ```test```",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","echo ```test```","```"]);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"echo ```test```",
"```",
]);
});
it("should leave single inner blocks intact but not return trailing text", async () => {
const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```","trailing text"]);
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"ls -al",
"```",
"```",
"trailing text",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"ls -al",
"```",
]);
});
it("should leave double inner blocks intact but not return trailing text", async () => {
const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","const y = 10;","```sh","echo `hello world`","```","```","trailing text"]);
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"ls -al",
"```",
"const y = 10;",
"```sh",
"echo `hello world`",
"```",
"```",
"trailing text",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```","const y = 10;","```sh","echo `hello world`","```"]);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"ls -al",
"```",
"const y = 10;",
"```sh",
"echo `hello world`",
"```",
]);
});
it("should leave inner blocks intact but not return trailing or leading text", async () => {
const linesGenerator = await getLineGenerator(["[CODE]", "const x = 5;", "```bash","ls -al","```","[/CODE]","trailing text"]);
const linesGenerator = await getLineGenerator([
"[CODE]",
"const x = 5;",
"```bash",
"ls -al",
"```",
"[/CODE]",
"trailing text",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"ls -al",
"```",
]);
});
});

View file

@ -350,12 +350,10 @@ export async function* filterCodeBlockLines(rawLines: LineStream): LineStream {
let nestCount = 0;
for await (const line of rawLines) {
if (!seenFirstFence) {
if (shouldRemoveLineBeforeStart(line)) {
// Filter out starting ``` or START block
continue
continue;
}
// Regardless of a fence or START block start tracking the nesting level
seenFirstFence = true;

View file

@ -14,7 +14,11 @@ export class GeneratorReuseManager {
) {
this.currentGenerator?.cancel();
const listenableGen = new ListenableGenerator(gen, this.onError, abortController);
const listenableGen = new ListenableGenerator(
gen,
this.onError,
abortController,
);
listenableGen.listen((chunk) => (this.pendingCompletion += chunk ?? ""));
this.pendingGeneratorPrefix = prefix;
@ -43,7 +47,11 @@ export class GeneratorReuseManager {
if (!this.shouldReuseExistingGenerator(prefix)) {
// Create a wrapper over the current generator to fix the prompt
const abortController = new AbortController();
this._createListenableGenerator(abortController, newGenerator(abortController.signal), prefix);
this._createListenableGenerator(
abortController,
newGenerator(abortController.signal),
prefix,
);
}
// Already typed characters are those that are new in the prefix from the old generator

View file

@ -1,8 +1,9 @@
import { IDE, IdeInfo } from "../../index";
import { IDE } from "../../index";
import { findUriInDirs } from "../../util/uri";
import { ContextRetrievalService } from "../context/ContextRetrievalService";
import { GetLspDefinitionsFunction } from "../types";
import { HelperVars } from "../util/HelperVars";
import { getDiffsFromCache } from "./gitDiffCache";
import {
AutocompleteClipboardSnippet,
@ -23,35 +24,14 @@ export interface SnippetPayload {
clipboardSnippets: AutocompleteClipboardSnippet[];
}
function racePromise<T>(promise: Promise<T[]>): Promise<T[]> {
function racePromise<T>(promise: Promise<T[]>, timeout = 100): Promise<T[]> {
const timeoutPromise = new Promise<T[]>((resolve) => {
setTimeout(() => resolve([]), 100);
setTimeout(() => resolve([]), timeout);
});
return Promise.race([promise, timeoutPromise]);
}
class DiffSnippetsCache {
private cache: Map<number, any> = new Map();
private lastTimestamp: number = 0;
public set<T>(timestamp: number, value: T): T {
// Clear old cache entry if exists
if (this.lastTimestamp !== timestamp) {
this.cache.clear();
}
this.lastTimestamp = timestamp;
this.cache.set(timestamp, value);
return value;
}
public get(timestamp: number): any | undefined {
return this.cache.get(timestamp);
}
}
const diffSnippetsCache = new DiffSnippetsCache();
// Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems,
// or they might separately track recently edited ranges)
async function getIdeSnippets(
@ -112,43 +92,15 @@ const getClipboardSnippets = async (
const getDiffSnippets = async (
ide: IDE,
ideInfo: IdeInfo | undefined,
): Promise<AutocompleteDiffSnippet[]> => {
if (ideInfo?.ideType !== "vscode") {
// Disabling for non-vscode IDEs for now
// See https://github.com/continuedev/continue/issues/4130
// https://github.com/continuedev/continue/issues/5819
return [];
}
const currentTimestamp = ide.getLastFileSaveTimestamp
? ide.getLastFileSaveTimestamp()
: Math.floor(Date.now() / 10000) * 10000; // Defaults to update once in every 10 seconds
const diffs = await getDiffsFromCache(ide);
// Check cache first
const cached = diffSnippetsCache.get(
currentTimestamp,
) as AutocompleteDiffSnippet[];
if (cached) {
return cached;
}
let diff: string[] = [];
try {
diff = await ide.getDiff(true);
} catch (e) {
console.error("Error getting diff for autocomplete", e);
}
return diffSnippetsCache.set(
currentTimestamp,
diff.map((item) => {
return {
content: item,
type: AutocompleteSnippetType.Diff,
};
}),
);
return diffs.map((item) => {
return {
content: item,
type: AutocompleteSnippetType.Diff,
};
});
};
export const getAllSnippets = async ({
@ -179,7 +131,7 @@ export const getAllSnippets = async ({
IDE_SNIPPETS_ENABLED
? racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp))
: [],
racePromise(getDiffSnippets(ide, helper.ideInfo)),
[], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
racePromise(getClipboardSnippets(ide)),
]);

View file

@ -0,0 +1,84 @@
import { GitDiffCache } from "./gitDiffCache";
beforeEach(() => {
// Add this line to GitDiffCache class to make instance accessible
(GitDiffCache as any).instance = null;
});
test("GitDiffCache returns cached results within cache time", async () => {
const mockDiff = ["file1.ts", "file2.ts"];
const getDiffFn = jest.fn().mockResolvedValue(mockDiff);
const cache = GitDiffCache.getInstance(getDiffFn, 1); // 1 second cache
const result1 = await cache.get();
const result2 = await cache.get();
expect(result1).toEqual(mockDiff);
expect(result2).toEqual(mockDiff);
expect(getDiffFn).toHaveBeenCalledTimes(1);
});
test("GitDiffCache refreshes cache after expiration", async () => {
const mockDiff = ["file1.ts"];
const getDiffFn = jest.fn().mockResolvedValue(mockDiff);
const cache = GitDiffCache.getInstance(getDiffFn, 0.1); // 100ms cache
const result1 = await cache.get();
await new Promise((resolve) => setTimeout(resolve, 200)); // Wait for cache to expire
const result2 = await cache.get();
expect(getDiffFn).toHaveBeenCalledTimes(2);
});
test("GitDiffCache returns empty array on error", async () => {
const getDiffFn = jest.fn().mockRejectedValue(new Error("Git error"));
const cache = GitDiffCache.getInstance(getDiffFn);
const result = await cache.get();
expect(result).toEqual([]);
});
test("GitDiffCache reuses pending request", async () => {
const mockDiff = ["file1.ts"];
let resolvePromise: (value: string[]) => void;
const getDiffFn = jest.fn().mockImplementation(() => {
return new Promise((resolve) => {
resolvePromise = resolve;
});
});
const cache = GitDiffCache.getInstance(getDiffFn);
const promise1 = cache.get();
const promise2 = cache.get();
resolvePromise!(mockDiff);
const [result1, result2] = await Promise.all([promise1, promise2]);
expect(result1).toEqual(mockDiff);
expect(result2).toEqual(mockDiff);
expect(getDiffFn).toHaveBeenCalledTimes(1);
});
test("GitDiffCache invalidate clears cache", async () => {
const mockDiff = ["file1.ts"];
const getDiffFn = jest.fn().mockResolvedValue(mockDiff);
const cache = GitDiffCache.getInstance(getDiffFn);
await cache.get();
cache.invalidate();
await cache.get();
expect(getDiffFn).toHaveBeenCalledTimes(2);
});
test("GitDiffCache maintains singleton instance", () => {
const getDiffFn1 = jest.fn();
const getDiffFn2 = jest.fn();
const instance1 = GitDiffCache.getInstance(getDiffFn1);
const instance2 = GitDiffCache.getInstance(getDiffFn2);
expect(instance1).toBe(instance2);
});

View file

@ -0,0 +1,73 @@
import { IDE } from "../..";
type GetDiffFn = () => Promise<string[]>;
export class GitDiffCache {
private static instance: GitDiffCache | null = null;
private cachedDiff: string[] | undefined = undefined;
private lastFetchTime: number = 0;
private pendingRequest: Promise<string[]> | null = null;
private getDiffFn: GetDiffFn;
private cacheTimeMs: number;
private constructor(getDiffFn: GetDiffFn, cacheTimeSeconds: number = 60) {
this.getDiffFn = getDiffFn;
this.cacheTimeMs = cacheTimeSeconds * 1000;
}
public static getInstance(
getDiffFn: GetDiffFn,
cacheTimeSeconds?: number,
): GitDiffCache {
if (!GitDiffCache.instance) {
GitDiffCache.instance = new GitDiffCache(getDiffFn, cacheTimeSeconds);
}
return GitDiffCache.instance;
}
private async getDiffPromise(): Promise<string[]> {
try {
const diff = await this.getDiffFn();
this.cachedDiff = diff;
this.lastFetchTime = Date.now();
return this.cachedDiff;
} catch (e) {
console.error("Error fetching git diff:", e);
return [];
} finally {
this.pendingRequest = null;
}
}
public async get(): Promise<string[]> {
if (
this.cachedDiff !== undefined &&
Date.now() - this.lastFetchTime < this.cacheTimeMs
) {
return this.cachedDiff;
}
// If there's already a request in progress, return that instead of starting a new one
if (this.pendingRequest) {
return this.pendingRequest;
}
this.pendingRequest = this.getDiffPromise();
return this.pendingRequest;
}
public invalidate(): void {
this.cachedDiff = undefined;
this.pendingRequest = null;
}
}
// factory to make diff cache more testable
export function getDiffFn(ide: IDE): GetDiffFn {
return () => ide.getDiff(true);
}
export async function getDiffsFromCache(ide: IDE): Promise<string[]> {
const diffCache = GitDiffCache.getInstance(getDiffFn(ide));
return await diffCache.get();
}

View file

@ -72,7 +72,8 @@ const qwenCoderFimTemplate: AutocompleteTemplate = {
};
const seedCoderFimTemplate: AutocompleteTemplate = {
template: "<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>",
template:
"<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>",
completionOptions: {
stop: [
"<[end▁of▁sentence]>",

View file

@ -42,17 +42,18 @@ export const getSnippets = (
helper: HelperVars,
payload: SnippetPayload,
): AutocompleteSnippet[] => {
const snippets = {
"clipboard": payload.clipboardSnippets,
"recentlyVisitedRanges": payload.recentlyVisitedRangesSnippets,
"recentlyEditedRanges": payload.recentlyEditedRangeSnippets,
"diff": payload.diffSnippets,
"base": shuffleArray(filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
helper.prunedCaretWindow,
)),
}
clipboard: payload.clipboardSnippets,
recentlyVisitedRanges: payload.recentlyVisitedRangesSnippets,
recentlyEditedRanges: payload.recentlyEditedRangeSnippets,
diff: payload.diffSnippets,
base: shuffleArray(
filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
helper.prunedCaretWindow,
),
),
};
// Define snippets with their priorities
const snippetConfigs: {
@ -61,53 +62,60 @@ export const getSnippets = (
defaultPriority: number;
snippets: AutocompleteSnippet[];
}[] = [
{
key: "clipboard",
enabledOrPriority: helper.options.experimental_includeClipboard,
defaultPriority: 1,
snippets: payload.clipboardSnippets,
},
{
key: "recentlyVisitedRanges",
enabledOrPriority: helper.options.experimental_includeRecentlyVisitedRanges,
defaultPriority: 2,
snippets: payload.recentlyVisitedRangesSnippets,
/* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output
{
key: "clipboard",
enabledOrPriority: helper.options.experimental_includeClipboard,
defaultPriority: 1,
snippets: payload.clipboardSnippets,
},
{
key: "recentlyVisitedRanges",
enabledOrPriority:
helper.options.experimental_includeRecentlyVisitedRanges,
defaultPriority: 2,
snippets: payload.recentlyVisitedRangesSnippets,
/* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output
if they are visible. We should handle them separately so that we can control their priority
and whether they should be included or not. */
},
{
key: "recentlyEditedRanges",
enabledOrPriority: helper.options.experimental_includeRecentlyEditedRanges,
defaultPriority: 3,
snippets: payload.recentlyEditedRangeSnippets,
},
{
key: "diff",
enabledOrPriority: helper.options.experimental_includeDiff,
defaultPriority: 4,
snippets: payload.diffSnippets,
// TODO: diff is commonly too large, thus anything lower in priority is not included.
},
{
key: "base",
enabledOrPriority: true,
defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
snippets: shuffleArray(filterSnippetsAlreadyInCaretWindow(
},
{
key: "recentlyEditedRanges",
enabledOrPriority:
helper.options.experimental_includeRecentlyEditedRanges,
defaultPriority: 3,
snippets: payload.recentlyEditedRangeSnippets,
},
{
key: "diff",
enabledOrPriority: helper.options.experimental_includeDiff,
defaultPriority: 4,
snippets: payload.diffSnippets,
// TODO: diff is commonly too large, thus anything lower in priority is not included.
},
{
key: "base",
enabledOrPriority: true,
defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
snippets: shuffleArray(
filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
helper.prunedCaretWindow,
)),
// TODO: Add this too to experimental config, maybe move upper in the order, since it's almost
// always not inlucded due to diff being commonly large
},
];
),
),
// TODO: Add this too to experimental config, maybe move upper in the order, since it's almost
// always not inlucded due to diff being commonly large
},
];
// Create a readable order of enabled snippets
const snippetOrder = snippetConfigs
.filter(({ enabledOrPriority }) => enabledOrPriority)
.map(({ key, enabledOrPriority, defaultPriority }) => ({
key,
priority: typeof enabledOrPriority === 'number' ? enabledOrPriority : defaultPriority,
priority:
typeof enabledOrPriority === "number"
? enabledOrPriority
: defaultPriority,
}))
.sort((a, b) => a.priority - b.priority);
@ -121,15 +129,19 @@ export const getSnippets = (
// Convert configs to prioritized snippets
let prioritizedSnippets = snippetOrder
.flatMap(({ key, priority }) =>
snippets[key].map(snippet => ({ snippet, priority }))
snippets[key].map((snippet) => ({ snippet, priority })),
)
.sort((a, b) => a.priority - b.priority)
.map(({ snippet }) => snippet);
// Exclude Continue's own output as it makes it super-hard for users to test the autocomplete feature
// while looking at the prompts in the Continue's output
prioritizedSnippets = prioritizedSnippets.filter((snippet) =>
!(snippet as AutocompleteCodeSnippet).filepath?.startsWith("output:extension-output-Continue.continue"));
prioritizedSnippets = prioritizedSnippets.filter(
(snippet) =>
!(snippet as AutocompleteCodeSnippet).filepath?.startsWith(
"output:extension-output-Continue.continue",
),
);
const finalSnippets = [];
let remainingTokenCount = getRemainingTokenCount(helper);

View file

@ -8,23 +8,23 @@ export class AutocompleteDebouncer {
// Generate a unique ID for this request
const requestId = uuidv4();
this.currentRequestId = requestId;
// Clear any existing timeout
if (this.debounceTimeout) {
clearTimeout(this.debounceTimeout);
}
// Create a new promise that resolves after the debounce delay
return new Promise<boolean>((resolve) => {
this.debounceTimeout = setTimeout(() => {
// When the timeout completes, check if this is still the most recent request
const shouldDebounce = this.currentRequestId !== requestId;
// If this is the most recent request, it shouldn't be debounced
if (!shouldDebounce) {
this.currentRequestId = undefined;
}
resolve(shouldDebounce);
}, debounceDelay);
});

View file

@ -1,4 +1,4 @@
import { IDE, IdeInfo, TabAutocompleteOptions } from "../..";
import { IDE, TabAutocompleteOptions } from "../..";
import {
countTokens,
pruneLinesFromBottom,
@ -21,7 +21,6 @@ export class HelperVars {
lang: AutocompleteLanguageInfo;
treePath: AstPath | undefined;
workspaceUris: string[] = [];
ideInfo: IdeInfo | undefined;
private _fileContents: string | undefined;
private _fileLines: string[] | undefined;
@ -44,7 +43,6 @@ export class HelperVars {
if (this._fileContents !== undefined) {
return;
}
this.ideInfo = await this.ide.getIdeInfo();
this.workspaceUris = await this.ide.getWorkspaceDirs();
this._fileContents =

View file

@ -1,65 +1,65 @@
import {
processTestCase,
type CompletionTestCase,
processTestCase,
type CompletionTestCase,
} from "./completionTestUtils";
describe("processTestCase utility", () => {
it("processes simple console.log completion", () => {
const testCase: CompletionTestCase = {
original: "console.log(|cur||till|)",
completion: "\"foo,\", bar",
};
it("processes simple console.log completion", () => {
const testCase: CompletionTestCase = {
original: "console.log(|cur||till|)",
completion: '"foo,", bar',
};
expect(processTestCase(testCase)).toEqual({
input: {
lastLineOfCompletionText: "\"foo,\", bar",
currentText: ")",
cursorPosition: "console.log(".length,
},
expectedResult: {
completionText: "\"foo,\", bar",
},
});
expect(processTestCase(testCase)).toEqual({
input: {
lastLineOfCompletionText: '"foo,", bar',
currentText: ")",
cursorPosition: "console.log(".length,
},
expectedResult: {
completionText: '"foo,", bar',
},
});
});
it("processes simple console.log completion with overwriting", () => {
const testCase: CompletionTestCase = {
original: "console.log(|cur|)|till|",
completion: "\"foo,\", bar);",
};
it("processes simple console.log completion with overwriting", () => {
const testCase: CompletionTestCase = {
original: "console.log(|cur|)|till|",
completion: '"foo,", bar);',
};
expect(processTestCase(testCase)).toEqual({
input: {
lastLineOfCompletionText: "\"foo,\", bar);",
currentText: ")",
cursorPosition: "console.log(".length,
},
expectedResult: {
completionText: "\"foo,\", bar);",
range: {
start: "console.log(".length,
end: "console.log()".length,
},
},
});
expect(processTestCase(testCase)).toEqual({
input: {
lastLineOfCompletionText: '"foo,", bar);',
currentText: ")",
cursorPosition: "console.log(".length,
},
expectedResult: {
completionText: '"foo,", bar);',
range: {
start: "console.log(".length,
end: "console.log()".length,
},
},
});
});
it("partially applying completion", () => {
const testCase: CompletionTestCase = {
original: "|cur||till|fetch(\"https://example.com\");",
completion: "await fetch(\"https://example.com\");",
appliedCompletion: "await ",
};
it("partially applying completion", () => {
const testCase: CompletionTestCase = {
original: '|cur||till|fetch("https://example.com");',
completion: 'await fetch("https://example.com");',
appliedCompletion: "await ",
};
expect(processTestCase(testCase)).toEqual({
input: {
lastLineOfCompletionText: "await fetch(\"https://example.com\");",
currentText: "fetch(\"https://example.com\");",
cursorPosition: 0,
},
expectedResult: {
completionText: "await ",
},
});
expect(processTestCase(testCase)).toEqual({
input: {
lastLineOfCompletionText: 'await fetch("https://example.com");',
currentText: 'fetch("https://example.com");',
cursorPosition: 0,
},
expectedResult: {
completionText: "await ",
},
});
});
});

View file

@ -1,91 +1,94 @@
export interface CompletionTestCase {
original: string; // Text with |cur| and |till| markers
completion: string; // Text to insert/overwrite
appliedCompletion?: string | null;
cursorMarker?: string;
tillMarker?: string;
original: string; // Text with |cur| and |till| markers
completion: string; // Text to insert/overwrite
appliedCompletion?: string | null;
cursorMarker?: string;
tillMarker?: string;
}
export interface ProcessedTestCase {
input: {
lastLineOfCompletionText: string;
currentText: string;
cursorPosition: number;
};
expectedResult: {
completionText: string;
range?: {
start: number;
end: number;
};
input: {
lastLineOfCompletionText: string;
currentText: string;
cursorPosition: number;
};
expectedResult: {
completionText: string;
range?: {
start: number;
end: number;
};
};
}
/**
* Transforms human-readable test case into input and expected results.
*
*
* - `original`: Your original text with |cur| marking where the cursor is before completion,
* and |till| marking where the cursor should be after accepting completion (and this is
* the end of the actual applied completion)
* - `completion`: LLM completion output
* - `appliedCompletion` (optional): part of the LLM completion output that is actually applied
* (written between |cur| and |till| in the original)
*
*
* For example, you have this line:
*
*
* console.log("<cursor here>");
*
*
* and expect it to be completed this way:
*
*
* console.log("foo: ", bar<cursor here>);
*
*
* with your completion coming from LLM being: `'foo: ", bar<cursor here>);'`
*
*
* Your input to this function should be:
* - original: `'console.log("|cur|"|till|);'`
* - completion: `'foo: ", bar);'`
* - appliedCompletion: `'foo: ", bar'`
*
*
* Output: input and expected output of {@link core/autocomplete/util/processSingleLineCompletion/processSingleLineCompletion|processSingleLineCompletion()}
*
*
*/
export function processTestCase({
original,
completion,
appliedCompletion = null,
cursorMarker = "|cur|",
tillMarker = "|till|",
original,
completion,
appliedCompletion = null,
cursorMarker = "|cur|",
tillMarker = "|till|",
}: CompletionTestCase): ProcessedTestCase {
// Validate cursor marker
if (!original.includes(cursorMarker)) {
throw new Error("Cursor marker not found in original text");
}
// Validate cursor marker
if (!original.includes(cursorMarker)) {
throw new Error("Cursor marker not found in original text");
}
const cursorPos = original.indexOf(cursorMarker);
original = original.replace(cursorMarker, "");
const cursorPos = original.indexOf(cursorMarker);
original = original.replace(cursorMarker, "");
let tillPos = original.indexOf(tillMarker);
if (tillPos < 0) {
tillPos = cursorPos;
} else {
original = original.replace(tillMarker, "")
}
let tillPos = original.indexOf(tillMarker);
if (tillPos < 0) {
tillPos = cursorPos;
} else {
original = original.replace(tillMarker, "");
}
// Calculate currentText based on what's between cursor and till marker
const currentText = original.substring(cursorPos);
// Calculate currentText based on what's between cursor and till marker
const currentText = original.substring(cursorPos);
return {
input: {
lastLineOfCompletionText: completion,
currentText,
cursorPosition: cursorPos,
},
expectedResult: {
completionText: appliedCompletion || completion,
range: cursorPos === tillPos ? undefined : {
start: cursorPos,
end: tillPos,
return {
input: {
lastLineOfCompletionText: completion,
currentText,
cursorPosition: cursorPos,
},
expectedResult: {
completionText: appliedCompletion || completion,
range:
cursorPos === tillPos
? undefined
: {
start: cursorPos,
end: tillPos,
},
},
};
}
},
};
}

View file

@ -2,96 +2,94 @@ import { processTestCase } from "./completionTestUtils";
import { processSingleLineCompletion } from "./processSingleLineCompletion";
describe("processSingleLineCompletion", () => {
it("should handle simple end of line completion", () => {
const testCase = processTestCase({
original: "console.log(|cur|",
completion: "\"Hello, world!\")",
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
it("should handle simple end of line completion", () => {
const testCase = processTestCase({
original: "console.log(|cur|",
completion: '"Hello, world!")',
});
it("should handle midline insert repeating the end of line", () => {
const testCase = processTestCase({
original: "console.log(|cur|);|till|",
completion: "\"Hello, world!\");",
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition,
);
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
expect(result).toEqual(testCase.expectedResult);
it("should handle midline insert repeating the end of line", () => {
const testCase = processTestCase({
original: "console.log(|cur|);|till|",
completion: '"Hello, world!");',
});
it("should handle midline insert repeating the end of line plus adding a semicolon", () => {
const testCase = processTestCase({
original: "console.log(|cur|)|till|",
completion: "\"Hello, world!\");",
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition,
);
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
expect(result).toEqual(testCase.expectedResult);
it("should handle midline insert repeating the end of line plus adding a semicolon", () => {
const testCase = processTestCase({
original: "console.log(|cur|)|till|",
completion: '"Hello, world!");',
});
it("should handle simple midline insert", () => {
const testCase = processTestCase({
original: "console.log(|cur|)",
completion: "\"Hello, world!\"",
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition,
);
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
expect(result).toEqual(testCase.expectedResult);
it("should handle simple midline insert", () => {
const testCase = processTestCase({
original: "console.log(|cur|)",
completion: '"Hello, world!"',
});
it("should handle complex dif with addition in the beginning", () => {
const testCase = processTestCase({
original: "console.log(|cur||till|, \"param1\", )", // TODO
completion: "\"Hello world!\", \"param1\", param1);",
appliedCompletion: "\"Hello world!\""
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition,
);
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
expect(result).toEqual(testCase.expectedResult);
it("should handle complex dif with addition in the beginning", () => {
const testCase = processTestCase({
original: 'console.log(|cur||till|, "param1", )', // TODO
completion: '"Hello world!", "param1", param1);',
appliedCompletion: '"Hello world!"',
});
it("should handle simple insertion even with random equality", () => {
const testCase = processTestCase({
original: "print(f\"Foobar length: |cur||till|\")",
completion: "{len(foobar)}",
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition,
);
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
expect(result).toEqual(testCase.expectedResult);
it("should handle simple insertion even with random equality", () => {
const testCase = processTestCase({
original: 'print(f"Foobar length: |cur||till|")',
completion: "{len(foobar)}",
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition,
);
expect(result).toEqual(testCase.expectedResult);
});
});

View file

@ -1,92 +1,93 @@
import * as Diff from "diff";
interface SingleLineCompletionResult {
completionText: string;
range?: {
start: number;
end: number;
};
completionText: string;
range?: {
start: number;
end: number;
};
}
interface DiffType {
count?: number;
added?: boolean;
removed?: boolean;
value: string;
count?: number;
added?: boolean;
removed?: boolean;
value: string;
}
function diffPatternMatches(
diffs: DiffType[],
pattern: DiffPartType[],
diffs: DiffType[],
pattern: DiffPartType[],
): boolean {
if (diffs.length !== pattern.length) {
return false;
if (diffs.length !== pattern.length) {
return false;
}
for (let i = 0; i < diffs.length; i++) {
const diff = diffs[i];
const diffPartType: DiffPartType =
!diff.added && !diff.removed ? "=" : diff.added ? "+" : "-";
if (diffPartType !== pattern[i]) {
return false;
}
}
for (let i = 0; i < diffs.length; i++) {
const diff = diffs[i];
const diffPartType: DiffPartType =
!diff.added && !diff.removed ? "=" : diff.added ? "+" : "-";
if (diffPartType !== pattern[i]) {
return false;
}
}
return true;
return true;
}
type DiffPartType = "+" | "-" | "=";
export function processSingleLineCompletion(
lastLineOfCompletionText: string,
currentText: string,
cursorPosition: number
lastLineOfCompletionText: string,
currentText: string,
cursorPosition: number,
): SingleLineCompletionResult | undefined {
const diffs: DiffType[] = Diff.diffWords(currentText, lastLineOfCompletionText);
const diffs: DiffType[] = Diff.diffWords(
currentText,
lastLineOfCompletionText,
);
if (diffPatternMatches(diffs, ["+"])) {
// Just insert, we're already at the end of the line
return {
completionText: lastLineOfCompletionText,
};
}
if (
diffPatternMatches(diffs, ["+", "="]) ||
diffPatternMatches(diffs, ["+", "=", "+"])
) {
// The model repeated the text after the cursor to the end of the line
return {
completionText: lastLineOfCompletionText,
range: {
start: cursorPosition,
end: currentText.length + cursorPosition,
},
};
}
if (
diffPatternMatches(diffs, ["+", "-"]) ||
diffPatternMatches(diffs, ["-", "+"])
) {
// We are midline and the model just inserted without repeating to the end of the line
return {
completionText: lastLineOfCompletionText,
};
}
// For any other diff pattern, just use the first added part if available
if (diffs[0]?.added) {
return {
completionText: diffs[0].value,
};
}
// Default case: treat as simple insertion
if (diffPatternMatches(diffs, ["+"])) {
// Just insert, we're already at the end of the line
return {
completionText: lastLineOfCompletionText,
completionText: lastLineOfCompletionText,
};
}
if (
diffPatternMatches(diffs, ["+", "="]) ||
diffPatternMatches(diffs, ["+", "=", "+"])
) {
// The model repeated the text after the cursor to the end of the line
return {
completionText: lastLineOfCompletionText,
range: {
start: cursorPosition,
end: currentText.length + cursorPosition,
},
};
}
if (
diffPatternMatches(diffs, ["+", "-"]) ||
diffPatternMatches(diffs, ["-", "+"])
) {
// We are midline and the model just inserted without repeating to the end of the line
return {
completionText: lastLineOfCompletionText,
};
}
// For any other diff pattern, just use the first added part if available
if (diffs[0]?.added) {
return {
completionText: diffs[0].value,
};
}
// Default case: treat as simple insertion
return {
completionText: lastLineOfCompletionText,
};
}

View file

@ -19,14 +19,14 @@ const GenerateTerminalCommand: SlashCommand = {
return;
}
const gen =
llm.streamComplete(`The user has made a request to run a shell command. Their description of what it should do is:
const gen = llm.streamComplete(
`The user has made a request to run a shell command. Their description of what it should do is:
"${input}"
Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`,
new AbortController().signal
);
new AbortController().signal,
);
const lines = streamLines(gen);
let cmd = "";

View file

@ -46,7 +46,6 @@ import { useHub } from "../control-plane/env";
import { BaseLLM } from "../llm";
import { LLMClasses, llmFromDescription } from "../llm/llms";
import CustomLLMClass from "../llm/llms/CustomLLM";
import FreeTrial from "../llm/llms/FreeTrial";
import { LLMReranker } from "../llm/llms/llm";
import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider";
import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
@ -244,7 +243,6 @@ async function intermediateToFinalConfig({
llmLogger,
workOsAccessToken,
loadPromptFiles = true,
allowFreeTrial = true,
}: {
config: Config;
ide: IDE;
@ -254,7 +252,6 @@ async function intermediateToFinalConfig({
llmLogger: ILLMLogger;
workOsAccessToken: string | undefined;
loadPromptFiles?: boolean;
allowFreeTrial?: boolean;
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
const errors: ConfigValidationError[] = [];
@ -343,56 +340,43 @@ async function intermediateToFinalConfig({
"summarize",
]); // Default to chat role if not specified
if (allowFreeTrial) {
// Obtain auth token (iff free trial being used)
const freeTrialModels = models.filter(
(model) => model.providerName === "free-trial",
);
if (freeTrialModels.length > 0) {
const ghAuthToken = await ide.getGitHubAuthToken({});
for (const model of freeTrialModels) {
(model as FreeTrial).setupGhAuthToken(ghAuthToken);
}
}
} else {
// Remove free trial models
models = models.filter((model) => model.providerName !== "free-trial");
// Free trial provider will be completely ignored
let warnAboutFreeTrial = false;
models = models.filter((model) => model.providerName !== "free-trial");
if (models.filter((m) => m.providerName === "free-trial").length) {
warnAboutFreeTrial = true;
}
// Tab autocomplete model
let tabAutocompleteModels: BaseLLM[] = [];
const tabAutocompleteModels: BaseLLM[] = [];
if (config.tabAutocompleteModel) {
tabAutocompleteModels = (
await Promise.all(
(Array.isArray(config.tabAutocompleteModel)
? config.tabAutocompleteModel
: [config.tabAutocompleteModel]
).map(async (desc) => {
if ("title" in desc) {
const llm = await llmFromDescription(
desc,
ide.readFile.bind(ide),
uniqueId,
ideSettings,
llmLogger,
config.completionOptions,
);
const autocompleteConfigs = Array.isArray(config.tabAutocompleteModel)
? config.tabAutocompleteModel
: [config.tabAutocompleteModel];
if (llm?.providerName === "free-trial") {
if (!allowFreeTrial) {
// This shouldn't happen
throw new Error("Free trial cannot be used with control plane");
}
const ghAuthToken = await ide.getGitHubAuthToken({});
(llm as FreeTrial).setupGhAuthToken(ghAuthToken);
await Promise.all(
autocompleteConfigs.map(async (desc) => {
if ("title" in desc) {
const llm = await llmFromDescription(
desc,
ide.readFile.bind(ide),
uniqueId,
ideSettings,
llmLogger,
config.completionOptions,
);
if (llm) {
if (llm.providerName === "free-trial") {
warnAboutFreeTrial = true;
} else {
tabAutocompleteModels.push(llm);
}
return llm;
} else {
return new CustomLLMClass(desc);
}
}),
)
).filter((x) => x !== undefined) as BaseLLM[];
} else {
tabAutocompleteModels.push(new CustomLLMClass(desc));
}
}),
);
}
applyRequestOptionsToModels(tabAutocompleteModels, config);
@ -458,7 +442,10 @@ async function intermediateToFinalConfig({
return embedConfig;
}
const { provider, ...options } = embedConfig;
if (provider === "transformers.js") {
if (provider === "transformers.js" || provider === "free-trial") {
if (provider === "free-trial") {
warnAboutFreeTrial = true;
}
return new TransformersJsEmbeddingsProvider();
} else {
const cls = LLMClasses.find((c) => c.providerName === provider);
@ -495,7 +482,10 @@ async function intermediateToFinalConfig({
return rerankingConfig;
}
const { name, params } = config.reranker as RerankerDescription;
if (name === "free-trial") {
warnAboutFreeTrial = true;
return null;
}
if (name === "llm") {
const llm = models.find((model) => model.title === params?.modelTitle);
if (!llm) {
@ -526,6 +516,14 @@ async function intermediateToFinalConfig({
}
const newReranker = getRerankingILLM(config.reranker);
if (warnAboutFreeTrial) {
errors.push({
fatal: false,
message:
"Model provider 'free-trial' is no longer supported, will be ignored",
});
}
const continueConfig: ContinueConfig = {
...config,
contextProviders,

View file

@ -1,6 +1,5 @@
import { ConfigYaml } from "@continuedev/config-yaml";
export const TRIAL_FIM_MODEL = "codestral-latest";
export const LOCAL_ONBOARDING_PROVIDER_TITLE = "Ollama";
export const LOCAL_ONBOARDING_FIM_MODEL = "qwen2.5-coder:1.5b-base";
export const LOCAL_ONBOARDING_FIM_TITLE = "Qwen2.5-Coder 1.5B";

View file

@ -743,8 +743,6 @@ declare global {
getLastModified(files: string[]): Promise<{ [path: string]: number }>;
getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined>;
// LSP
gotoDefinition(location: Location): Promise<RangeInFile[]>;

View file

@ -17,12 +17,16 @@ export class LocalPlatformClient implements PlatformClient {
private readonly ide: IDE,
) {}
/**
* searches for the first valid secret file in order of ~/.continue/.env, <workspace>/.continue/.env, <workspace>/.env
*/
private async findSecretInEnvFiles(
fqsn: FQSN,
): Promise<SecretResult | undefined> {
const secretValue =
this.findSecretInLocalEnvFile(fqsn) ??
(await this.findSecretInWorkspaceEnvFiles(fqsn));
(await this.findSecretInWorkspaceEnvFiles(fqsn, true)) ??
(await this.findSecretInWorkspaceEnvFiles(fqsn, false));
if (secretValue) {
return {
@ -52,12 +56,16 @@ export class LocalPlatformClient implements PlatformClient {
private async findSecretInWorkspaceEnvFiles(
fqsn: FQSN,
insideContinue: boolean,
): Promise<string | undefined> {
try {
const workspaceDirs = await this.ide.getWorkspaceDirs();
for (const folder of workspaceDirs) {
const envFilePath = joinPathsToUri(folder, ".env");
const envFilePath = joinPathsToUri(
folder,
insideContinue ? ".continue" : "",
".env",
);
try {
const fileExists = await this.ide.fileExists(envFilePath);
if (fileExists) {

View file

@ -0,0 +1,233 @@
import { FQSN, SecretResult, SecretType } from "@continuedev/config-yaml";
import {
afterEach,
beforeEach,
describe,
expect,
Mock,
test,
vi,
} from "vitest";
import { IDE } from "../..";
import { ControlPlaneClient } from "../../control-plane/client";
import { LocalPlatformClient } from "./LocalPlatformClient";
vi.mock("../../util/paths", { spy: true });
describe("LocalPlatformClient", () => {
const testFQSN: FQSN = {
packageSlugs: [
{
ownerSlug: "test-owner-slug",
packageSlug: "test-package-slug",
},
],
secretName: "TEST_CONTINUE_SECRET_KEY",
};
const testFQSN2: FQSN = {
packageSlugs: [
{
ownerSlug: "test-owner-slug-2",
packageSlug: "test-package-slug-2",
},
],
secretName: "TEST_WORKSPACE_SECRET_KEY",
};
const testResolvedFQSN: SecretResult = {
found: true,
fqsn: testFQSN,
secretLocation: {
secretName: testFQSN.secretName,
secretType: SecretType.Organization,
orgSlug: "test-org-slug",
},
};
let testControlPlaneClient: ControlPlaneClient;
let testIde: IDE;
beforeEach(
/**dynamic import before each test for test isolation */
async () => {
const testFixtures = await import("../../test/fixtures");
testControlPlaneClient = testFixtures.testControlPlaneClient;
testIde = testFixtures.testIde;
},
);
let secretValue: string;
let envKeyValues: Record<string, unknown>;
let envKeyValuesString: string;
beforeEach(
/**generate unique env key value pairs for each test */
() => {
secretValue = Math.floor(Math.random() * 100) + "";
envKeyValues = {
TEST_CONTINUE_SECRET_KEY: secretValue,
TEST_WORKSPACE_SECRET_KEY: secretValue + "-workspace",
};
envKeyValuesString = Object.entries(envKeyValues)
.map(([key, value]) => `${key}=${value}`)
.join("\n");
},
);
afterEach(() => {
vi.resetAllMocks();
vi.restoreAllMocks();
vi.resetModules(); // clear dynamic imported module cache
});
test("should not be able to resolve FQSNs if they do not exist", async () => {
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
expect(resolvedFQSNs.length).toBeGreaterThan(0);
expect(resolvedFQSNs[0]?.found).toBe(false);
});
test("should be able to resolve FQSNs if they exist", async () => {
testControlPlaneClient.resolveFQSNs = vi.fn(async () => [testResolvedFQSN]);
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
expect(testControlPlaneClient.resolveFQSNs).toHaveBeenCalled();
expect(resolvedFQSNs).toEqual([testResolvedFQSN]);
expect(resolvedFQSNs[0]?.found).toBe(true);
});
describe("searches for secrets in local .env files", () => {
let getContinueDotEnv: Mock;
beforeEach(async () => {
const utilPaths = await import("../../util/paths");
getContinueDotEnv = vi.fn(() => envKeyValues);
utilPaths.getContinueDotEnv = getContinueDotEnv;
});
test("should be able to get secrets from ~/.continue/.env files", async () => {
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
expect(getContinueDotEnv).toHaveBeenCalled();
expect(resolvedFQSNs.length).toBe(1);
expect(
(resolvedFQSNs[0] as SecretResult & { value: unknown })?.value,
).toBe(secretValue);
console.log("debug1 resolved fqsn", resolvedFQSNs);
});
});
describe("should be able to get secrets from workspace .env files", () => {
test("should get secrets from <workspace>/.continue/.env and <workspace>/.env", async () => {
const originalIdeFileExists = testIde.fileExists;
testIde.fileExists = vi.fn(async (fileUri: string) =>
fileUri.includes(".env") ? true : originalIdeFileExists(fileUri),
);
const originalIdeReadFile = testIde.readFile;
const randomValueForContinueDirDotEnv =
"continue-dir-" + Math.floor(Math.random() * 100);
const randomValueForWorkspaceDotEnv =
"dotenv-" + Math.floor(Math.random() * 100);
testIde.readFile = vi.fn(async (fileUri: string) => {
// fileUri should contain .continue/.env and not .env
if (fileUri.match(/.*\.continue\/\.env.*/gi)?.length) {
return (
envKeyValuesString.split("\n")[0] + randomValueForContinueDirDotEnv
);
}
// filUri should contain .env and not .continue/.env
else if (fileUri.match(/.*(?<!\.continue\/)\.env.*/gi)?.length) {
return (
envKeyValuesString.split("\n")[1] + randomValueForWorkspaceDotEnv
);
}
return originalIdeReadFile(fileUri);
});
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([
testFQSN,
testFQSN2,
]);
// both the secrets should be present as they are retrieved from different files
expect(resolvedFQSNs.length).toBe(2);
const continueDirSecretValue = (
resolvedFQSNs[0] as SecretResult & { value: unknown }
)?.value;
const dotEnvSecretValue = (
resolvedFQSNs[1] as SecretResult & { value: unknown }
)?.value;
expect(continueDirSecretValue).toContain(secretValue);
expect(continueDirSecretValue).toContain(randomValueForContinueDirDotEnv);
expect(dotEnvSecretValue).toContain(secretValue + "-workspace");
expect(dotEnvSecretValue).toContain(randomValueForWorkspaceDotEnv);
});
test("should first get secrets from <workspace>/.continue/.env and then <workspace>/.env", async () => {
const originalIdeFileExists = testIde.fileExists;
testIde.fileExists = vi.fn(async (fileUri: string) =>
fileUri.includes(".env") ? true : originalIdeFileExists(fileUri),
);
const randomValueForContinueDirDotEnv =
"continue-dir-" + Math.floor(Math.random() * 100);
const randomValueForWorkspaceDotEnv =
"dotenv-" + Math.floor(Math.random() * 100);
const originalIdeReadFile = testIde.readFile;
testIde.readFile = vi.fn(async (fileUri: string) => {
// fileUri should contain .continue/.env and not .env
if (fileUri.match(/.*\.continue\/\.env.*/gi)?.length) {
return (
envKeyValuesString.split("\n")[0] + randomValueForContinueDirDotEnv
);
}
// filUri should contain .env and not .continue/.env
else if (fileUri.match(/.*(?<!\.continue\/)\.env.*/gi)?.length) {
return (
envKeyValuesString.split("\n")[0] + randomValueForWorkspaceDotEnv
);
}
return originalIdeReadFile(fileUri);
});
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
expect(resolvedFQSNs.length).toBe(1);
expect(
(resolvedFQSNs[0] as SecretResult & { value: unknown })?.value,
).toContain(secretValue);
// we check that workspace <workspace>.continue/.env does not override the <workspace>/.env secret
expect(
(resolvedFQSNs[0] as SecretResult & { value: unknown })?.value,
).toContain(randomValueForContinueDirDotEnv);
expect(
(resolvedFQSNs[0] as SecretResult & { value: unknown })?.value,
).not.toContain(randomValueForWorkspaceDotEnv);
});
});
});

View file

@ -32,7 +32,6 @@ import DocsContextProvider from "../../context/providers/DocsContextProvider";
import FileContextProvider from "../../context/providers/FileContextProvider";
import { contextProviderClassFromName } from "../../context/providers/index";
import { ControlPlaneClient } from "../../control-plane/client";
import FreeTrial from "../../llm/llms/FreeTrial";
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile";
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
@ -176,18 +175,8 @@ async function configYamlToContinueConfig(options: {
uniqueId: string;
llmLogger: ILLMLogger;
workOsAccessToken: string | undefined;
allowFreeTrial?: boolean;
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
let {
config,
ide,
ideSettings,
ideInfo,
uniqueId,
llmLogger,
allowFreeTrial,
} = options;
allowFreeTrial = allowFreeTrial ?? true;
let { config, ide, ideSettings, ideInfo, uniqueId, llmLogger } = options;
const localErrors: ConfigValidationError[] = [];
@ -302,9 +291,14 @@ async function configYamlToContinueConfig(options: {
});
// Models
let warnAboutFreeTrial = false;
const defaultModelRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
for (const model of config.models ?? []) {
model.roles = model.roles ?? defaultModelRoles; // Default to all 4 chat-esque roles if not specified
if (model.provider === "free-trial") {
warnAboutFreeTrial = true;
}
try {
const llms = await llmsFromModelConfig({
model,
@ -376,34 +370,12 @@ async function configYamlToContinueConfig(options: {
);
}
if (allowFreeTrial) {
// Obtain auth token (iff free trial being used)
const freeTrialModels = continueConfig.modelsByRole.chat.filter(
(model) => model.providerName === "free-trial",
);
if (freeTrialModels.length > 0) {
try {
const ghAuthToken = await ide.getGitHubAuthToken({});
for (const model of freeTrialModels) {
(model as FreeTrial).setupGhAuthToken(ghAuthToken);
}
} catch (e) {
localErrors.push({
fatal: false,
message: `Failed to obtain GitHub auth token for free trial:\n${e instanceof Error ? e.message : e}`,
});
// Remove free trial models
continueConfig.modelsByRole.chat =
continueConfig.modelsByRole.chat.filter(
(model) => model.providerName !== "free-trial",
);
}
}
} else {
// Remove free trial models
continueConfig.modelsByRole.chat = continueConfig.modelsByRole.chat.filter(
(model) => model.providerName !== "free-trial",
);
if (warnAboutFreeTrial) {
localErrors.push({
fatal: false,
message:
"Model provider 'free-trial' is no longer supported, will be ignored.",
});
}
// Context providers

View file

@ -24,7 +24,7 @@ class ContinueProxyContextProvider extends BaseContextProvider {
this.options.title || ContinueProxyContextProvider.description.title,
displayTitle:
this.options.displayTitle ||
this.options.name ||
this.options.name ||
ContinueProxyContextProvider.description.displayTitle,
description:
this.options.description ||

View file

@ -17,16 +17,15 @@ class DiffContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const diff = await extras.ide.getDiff(
this.options?.includeUnstaged ?? true,
);
const includeUnstaged = this.options?.includeUnstaged ?? true;
const diffs = await extras.ide.getDiff(includeUnstaged); // TODO use diff cache (currently cache always includes unstaged)
return [
{
description: "The current git diff",
content:
diff.length === 0
diffs.length === 0
? "Git shows no current changes."
: `\`\`\`git diff\n${diff.join("\n")}\n\`\`\``,
: `\`\`\`git diff\n${diffs.join("\n")}\n\`\`\``,
name: "Git Diff",
},
];

View file

@ -124,10 +124,10 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
let urlMatches: RegExpExecArray | null;
if (/https?.*/.test(remoteUrl)) {
const pathname = new URL(remoteUrl).pathname;
urlMatches = /\/(?<projectPath>.*?)(?:(?=\.git)|$)/.exec(pathname)
urlMatches = /\/(?<projectPath>.*?)(?:(?=\.git)|$)/.exec(pathname);
} else {
// ssh
urlMatches = /:(?<projectPath>.*).git/.exec(remoteUrl)
urlMatches = /:(?<projectPath>.*).git/.exec(remoteUrl);
}
const project = urlMatches?.groups?.projectPath ?? null;

View file

@ -20,10 +20,11 @@ class HttpContextProvider extends BaseContextProvider {
try {
const currentFile = await ide.getCurrentFile();
// `isLocalhost` actually also returns true for other local addresses, not just localhost
return await isLocalhost(url.hostname) ?
(await ide.getWorkspaceDirs()).find(workspaceDirectory => {
return currentFile?.path.startsWith(workspaceDirectory)
}) : undefined
return (await isLocalhost(url.hostname))
? (await ide.getWorkspaceDirs()).find((workspaceDirectory) => {
return currentFile?.path.startsWith(workspaceDirectory);
})
: undefined;
} catch (e) {
return undefined;
}
@ -44,12 +45,12 @@ class HttpContextProvider extends BaseContextProvider {
HttpContextProvider.description.renderInlineAs,
};
}
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const parsedUrl = new URL(this.options.url)
const parsedUrl = new URL(this.options.url);
const response = await extras.fetch(parsedUrl, {
method: "POST",
headers: {

View file

@ -25,7 +25,7 @@ class JiraIssuesContextProvider extends BaseContextProvider {
issueQuery: this.options.issueQuery,
apiVersion: this.options.apiVersion,
requestOptions: this.options.requestOptions,
maxResults: this.options.maxResults
maxResults: this.options.maxResults,
});
}

View file

@ -7,6 +7,7 @@ import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
FetchFunction,
} from "../../index.js";
import { fetchFavicon } from "../../util/fetchFavicon";
@ -22,42 +23,49 @@ class URLContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
try {
const url = new URL(query);
const icon = await fetchFavicon(url);
const resp = await extras.fetch(url);
const html = await resp.text();
const dom = new JSDOM(html);
let reader = new Readability(dom.window.document);
let article = reader.parse();
const content = article?.content || "";
const markdown = NodeHtmlMarkdown.translate(
content,
{},
undefined,
undefined,
);
const title = article?.title || url.pathname;
return [
{
icon,
description: url.toString(),
content: markdown,
name: title,
uri: {
type: "url",
value: url.toString(),
},
},
];
} catch (e) {
console.log(e);
return [];
}
return await getUrlContextItems(query, extras.fetch);
}
}
export default URLContextProvider;
export async function getUrlContextItems(
query: string,
fetchFn: FetchFunction,
): Promise<ContextItem[]> {
try {
const url = new URL(query);
const icon = await fetchFavicon(url);
const resp = await fetchFn(url);
const html = await resp.text();
const dom = new JSDOM(html);
let reader = new Readability(dom.window.document);
let article = reader.parse();
const content = article?.content || "";
const markdown = NodeHtmlMarkdown.translate(
content,
{},
undefined,
undefined,
);
const title = article?.title || url.pathname;
return [
{
icon,
description: url.toString(),
content: markdown,
name: title,
uri: {
type: "url",
value: url.toString(),
},
},
];
} catch (e) {
console.log(e);
return [];
}
}

View file

@ -85,7 +85,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
}
const tokens = this.getCleanedTrigrams(args.query).join(" OR ");
return await this.ftsIndex.retrieve({
n,
text: tokens,

View file

@ -23,6 +23,14 @@ export interface ControlPlaneWorkspace {
export interface ControlPlaneModelDescription extends ModelDescription {}
export interface FreeTrialStatus {
optedInToFreeTrial: boolean;
chatCount?: number;
autocompleteCount?: number;
chatLimit: number;
autocompleteLimit: number;
}
export const TRIAL_PROXY_URL =
"https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
@ -159,4 +167,19 @@ export class ControlPlaneClient {
return null;
}
}
public async getFreeTrialStatus(): Promise<FreeTrialStatus | null> {
if (!(await this.isSignedIn())) {
return null;
}
try {
const resp = await this.request("ide/free-trial-status", {
method: "GET",
});
return (await resp.json()) as FreeTrialStatus;
} catch (e) {
return null;
}
}
}

View file

@ -5,7 +5,7 @@ import {
getStagingEnvironmentDotFilePath,
} from "../util/paths";
import { AuthType, ControlPlaneEnv } from "./AuthTypes";
import { getMdmKeys } from "./mdm";
import { getLicenseKeyData } from "./mdm/mdm";
export const EXTENSION_NAME = "continue";
@ -59,9 +59,9 @@ export function getControlPlaneEnvSync(
ideTestEnvironment: IdeSettings["continueTestEnvironment"],
): ControlPlaneEnv {
// MDM override
const mdmKeys = getMdmKeys();
if (mdmKeys) {
const { apiUrl } = mdmKeys;
const licenseKeyData = getLicenseKeyData();
if (licenseKeyData?.unsignedData?.apiUrl) {
const { apiUrl } = licenseKeyData.unsignedData;
return {
AUTH_TYPE: AuthType.OnPrem,
DEFAULT_CONTROL_PLANE_PROXY_URL: apiUrl,

View file

@ -1,127 +0,0 @@
import * as crypto from "crypto";
import { LicenseData, validateLicenseKey } from "./mdm";
// We'll create a real key pair once for all tests
const testKeyPair = crypto.generateKeyPairSync("rsa", {
modulusLength: 2048,
publicKeyEncoding: {
type: "spki",
format: "pem",
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem",
},
});
// Custom function to create test licenses (replaces the original mock-dependent one)
function createTestLicense(
licenseData: LicenseData,
useValidSignature: boolean = true,
): string {
// Convert license data to a string
const licenseDataStr = JSON.stringify(licenseData);
// Create a signature with our generated private key
const sign = crypto.createSign("SHA256");
sign.update(licenseDataStr);
sign.end();
let signature: string;
if (useValidSignature) {
signature = sign.sign(testKeyPair.privateKey, "base64");
} else {
// For invalid tests, create an intentionally wrong signature by signing different data
const wrongSign = crypto.createSign("SHA256");
wrongSign.update(licenseDataStr + "tampered");
wrongSign.end();
signature = wrongSign.sign(testKeyPair.privateKey, "base64");
}
// Combine data and signature into a license key
const licenseKeyObj = {
data: licenseDataStr,
signature: signature,
};
return Buffer.from(JSON.stringify(licenseKeyObj)).toString("base64");
}
// We need to test the actual implementation - which we can't mock with ESM
// Instead, we'll have tests that bypass validation or are expected to fail
// depending on what we're testing
test("validateLicenseKey returns false for malformed license key", () => {
// Test with a completely invalid license key
const invalidLicenseKey = "not-a-valid-license-key";
// Test - no mocks, real validation
const result = validateLicenseKey(invalidLicenseKey);
// Assert
expect(result).toBe(false);
});
test("validateLicenseKey returns false for invalid JSON in license key", () => {
// Create a malformed but base64-encoded string
const malformedLicenseKey = Buffer.from("this is not valid JSON").toString(
"base64",
);
// Test - no mocks, real validation
const result = validateLicenseKey(malformedLicenseKey);
// Assert
expect(result).toBe(false);
});
test("validateLicenseKey returns false for expired license", () => {
// Without mocking, we expect this to fail signature verification
// We're testing the date logic by itself
const licenseData: LicenseData = {
customerId: "customer123",
createdAt: new Date(Date.now() - 2000 * 60 * 60 * 24).toISOString(), // Created 2 days ago
expiresAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(), // Expired 1 day ago
};
// Create a license key - will fail verification but test logic still works
const expiredLicenseKey = createTestLicense(licenseData);
// Test - expect false, either due to signature or expiration - both are valid test cases
const result = validateLicenseKey(expiredLicenseKey);
// Assert
expect(result).toBe(false);
});
test("validateLicenseKey returns false for invalid signature", () => {
// Create license data with valid dates
const licenseData: LicenseData = {
customerId: "customer123",
createdAt: new Date().toISOString(),
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), // Valid for 1 day
};
// Create a license with an invalid signature
const invalidSignatureKey = createTestLicense(licenseData, false);
// Test - no mocks, real validation
const result = validateLicenseKey(invalidSignatureKey);
// Assert
expect(result).toBe(false);
});
test("validateLicenseKey handles JSON parsing errors gracefully", () => {
// Create a base64 string that decodes to valid JSON but lacks required fields
const invalidStructureKey = Buffer.from(
JSON.stringify({
notTheRightField: "wrong structure",
}),
).toString("base64");
// Test - no mocks, real validation
const result = validateLicenseKey(invalidStructureKey);
// Assert
expect(result).toBe(false);
});

View file

@ -0,0 +1,210 @@
import * as crypto from "crypto";
import { LicenseKeyData, validateLicenseKey } from "./mdm";
// We'll create a real key pair once for all tests
const testKeyPair = crypto.generateKeyPairSync("rsa", {
modulusLength: 2048,
publicKeyEncoding: {
type: "spki",
format: "pem",
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem",
},
});
// Custom function to create test licenses with the new structure including unsignedData
function createTestLicense(
licenseData: LicenseKeyData,
apiUrl: string = "https://api.continue.dev",
useValidSignature: boolean = true,
): string {
// Convert license data to a string
const licenseDataStr = JSON.stringify(licenseData);
// Create a signature with our generated private key
const sign = crypto.createSign("SHA256");
sign.update(licenseDataStr);
sign.end();
let signature: string;
if (useValidSignature) {
signature = sign.sign(testKeyPair.privateKey, "base64");
} else {
// For invalid tests, create an intentionally wrong signature by signing different data
const wrongSign = crypto.createSign("SHA256");
wrongSign.update(licenseDataStr + "tampered");
wrongSign.end();
signature = wrongSign.sign(testKeyPair.privateKey, "base64");
}
// Combine data, signature, and unsigned data into a license key
const licenseKeyObj = {
data: licenseDataStr,
signature: signature,
unsignedData: {
apiUrl: apiUrl,
},
};
return Buffer.from(JSON.stringify(licenseKeyObj)).toString("base64");
}
// We need to test the actual implementation - which we can't mock with ESM
// Instead, we'll have tests that bypass validation or are expected to fail
// depending on what we're testing
test("validateLicenseKey returns false for malformed license key", () => {
// Test with a completely invalid license key
const invalidLicenseKey = "not-a-valid-license-key";
// Test - no mocks, real validation
const result = validateLicenseKey(invalidLicenseKey);
// Assert
expect(result.isValid).toBe(false);
expect(result.licenseKeyData).toBeUndefined();
});
test("validateLicenseKey returns false for invalid JSON in license key", () => {
// Create a malformed but base64-encoded string
const malformedLicenseKey = Buffer.from("this is not valid JSON").toString(
"base64",
);
// Test - no mocks, real validation
const result = validateLicenseKey(malformedLicenseKey);
// Assert
expect(result.isValid).toBe(false);
expect(result.licenseKeyData).toBeUndefined();
});
test("validateLicenseKey returns false for expired license", () => {
// Without mocking, we expect this to fail signature verification
// We're testing the date logic by itself
const licenseData: LicenseKeyData = {
customerId: "customer123",
createdAt: new Date(Date.now() - 2000 * 60 * 60 * 24).toISOString(), // Created 2 days ago
expiresAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(), // Expired 1 day ago
};
// Create a license key with apiUrl in unsignedData - will fail verification but test logic still works
const expiredLicenseKey = createTestLicense(
licenseData,
"https://api.continue.dev",
);
// Test - expect false, either due to signature or expiration - both are valid test cases
const result = validateLicenseKey(expiredLicenseKey);
// Assert
expect(result.isValid).toBe(false);
expect(result.licenseKeyData).toBeUndefined();
});
test("validateLicenseKey returns false for invalid signature", () => {
// Create license data with valid dates
const licenseData: LicenseKeyData = {
customerId: "customer123",
createdAt: new Date().toISOString(),
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), // Valid for 1 day
};
// Create a license with an invalid signature but valid unsignedData structure
const invalidSignatureKey = createTestLicense(
licenseData,
"https://api.continue.dev",
false,
);
// Test - no mocks, real validation
const result = validateLicenseKey(invalidSignatureKey);
// Assert
expect(result.isValid).toBe(false);
expect(result.licenseKeyData).toBeUndefined();
});
test("validateLicenseKey handles JSON parsing errors gracefully", () => {
// Create a base64 string that decodes to valid JSON but lacks required fields
const invalidStructureKey = Buffer.from(
JSON.stringify({
notTheRightField: "wrong structure",
}),
).toString("base64");
// Test - no mocks, real validation
const result = validateLicenseKey(invalidStructureKey);
// Assert
expect(result.isValid).toBe(false);
expect(result.licenseKeyData).toBeUndefined();
});
test("validateLicenseKey handles missing unsignedData gracefully", () => {
// Create a license key structure without unsignedData field
const licenseData: LicenseKeyData = {
customerId: "customer123",
createdAt: new Date().toISOString(),
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(),
};
const licenseDataStr = JSON.stringify(licenseData);
const sign = crypto.createSign("SHA256");
sign.update(licenseDataStr);
sign.end();
const signature = sign.sign(testKeyPair.privateKey, "base64");
// Create license key without unsignedData
const licenseKeyObj = {
data: licenseDataStr,
signature: signature,
// Missing unsignedData field
};
const licenseKey = Buffer.from(JSON.stringify(licenseKeyObj)).toString(
"base64",
);
// Test - no mocks, real validation
const result = validateLicenseKey(licenseKey);
// Assert - should fail due to signature verification with wrong public key
expect(result.isValid).toBe(false);
expect(result.licenseKeyData).toBeUndefined();
});
test("validateLicenseKey handles invalid unsignedData structure", () => {
// Create license data with valid dates
const licenseData: LicenseKeyData = {
customerId: "customer123",
createdAt: new Date().toISOString(),
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(),
};
const licenseDataStr = JSON.stringify(licenseData);
const sign = crypto.createSign("SHA256");
sign.update(licenseDataStr);
sign.end();
const signature = sign.sign(testKeyPair.privateKey, "base64");
// Create license key with invalid unsignedData structure
const licenseKeyObj = {
data: licenseDataStr,
signature: signature,
unsignedData: "not an object", // Should be an object with apiUrl
};
const licenseKey = Buffer.from(JSON.stringify(licenseKeyObj)).toString(
"base64",
);
// Test - no mocks, real validation
const result = validateLicenseKey(licenseKey);
// Assert - should fail due to signature verification with wrong public key
expect(result.isValid).toBe(false);
expect(result.licenseKeyData).toBeUndefined();
});

View file

@ -6,7 +6,6 @@ import * as plist from "plist";
export interface MdmKeys {
licenseKey: string;
apiUrl: string;
}
const CONTINUE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
@ -19,17 +18,30 @@ LXSsjLbeWHifRrQ18wj/PC990E33QaFGNFp0NcBXMPbq5eKYKEzKZ0GsxtLoGxar
FQIDAQAB
-----END PUBLIC KEY-----`;
export interface LicenseData {
interface LicenseKeyUnsignedData {
apiUrl: string;
}
export interface LicenseKey {
signature: string;
data: string;
unsignedData: LicenseKeyUnsignedData;
}
export interface LicenseKeyData {
customerId: string;
createdAt: string;
expiresAt: string;
}
export function validateLicenseKey(licenseKey: string): boolean {
export function validateLicenseKey(licenseKey: string): {
isValid: boolean;
licenseKeyData?: LicenseKey;
} {
try {
// Decode the base64 license key
const decodedString = Buffer.from(licenseKey, "base64").toString("utf8");
const { data, signature } = JSON.parse(decodedString);
const { data, signature, unsignedData } = JSON.parse(decodedString);
// Verify the signature
const verify = crypto.createVerify("SHA256");
@ -38,36 +50,31 @@ export function validateLicenseKey(licenseKey: string): boolean {
const isValid = verify.verify(CONTINUE_PUBLIC_KEY, signature, "base64");
if (!isValid) return false;
if (!isValid) return { isValid: false };
// Check license expiration
const licenseData: LicenseData = JSON.parse(data);
const licenseData: LicenseKeyData = JSON.parse(data);
const expirationDate = new Date(licenseData.expiresAt);
const now = new Date();
return expirationDate > now;
const isNotExpired = expirationDate > now;
if (!isNotExpired) return { isValid: false };
// Return both validation result and license key data
const licenseKeyData: LicenseKey = {
signature,
data,
unsignedData,
};
return { isValid: true, licenseKeyData };
} catch (error) {
console.error("License validation error:", error);
return false;
return { isValid: false };
}
}
function extractConfigFromArray(config: any[]): Record<string, string> {
const configObj: Record<string, string> = {};
for (let i = 0; i < config.length; i += 2) {
if (i + 1 < config.length) {
const key = config[i];
const value = config[i + 1];
if (typeof key === "string") {
configObj[key] = value as string;
}
}
}
return configObj;
}
const MACOS_MDM_PATHS = [
// Organization-specific MDM plist
"/Library/Managed Preferences/dev.continue.app.plist",
@ -88,20 +95,15 @@ function readMdmKeysMacOS(): MdmKeys | undefined {
try {
// Parse the plist file using the plist package
const config = plist.parse(fileContent);
const config = plist.parse(fileContent) as
| { licenseKey: string | undefined }
| undefined;
// Extract the relevant fields from the config
// Config is an array of alternating keys and values
if (Array.isArray(config)) {
const configObj = extractConfigFromArray(config);
// Check if required keys are present
if (configObj.licenseKey && configObj.apiUrl) {
return {
licenseKey: configObj.licenseKey,
apiUrl: configObj.apiUrl,
};
}
if (config && config?.licenseKey) {
// Extract the license key from the configuration
return { licenseKey: config?.licenseKey };
} else {
console.error("Invalid MDM configuration format");
}
} catch (parseError) {
console.error(`Error parsing MDM configuration: ${parseError}`);
@ -130,17 +132,11 @@ function readMdmKeysWindows(): MdmKeys | undefined {
try {
// Use REG QUERY command to read registry values
const licenseKeyCmd = `reg query "${regPath}" /v licenseKey`;
const apiUrlCmd = `reg query "${regPath}" /v apiUrl`;
const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
const apiUrlOutput = execSync(apiUrlCmd, { encoding: "utf8" });
// Extract values from command output
const licenseKey = extractRegValue(licenseKeyOutput);
const apiUrl = extractRegValue(apiUrlOutput);
if (licenseKey && apiUrl) {
return { licenseKey, apiUrl };
if (licenseKey) {
return { licenseKey };
}
} catch (error) {
// Registry key might not exist, fallback to HKEY_CURRENT_USER
@ -149,17 +145,11 @@ function readMdmKeysWindows(): MdmKeys | undefined {
// Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE
try {
const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`;
const apiUrlCmd = `reg query "${userRegPath}" /v apiUrl`;
const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
const apiUrlOutput = execSync(apiUrlCmd, { encoding: "utf8" });
// Extract values from command output
const licenseKey = extractRegValue(licenseKeyOutput);
const apiUrl = extractRegValue(apiUrlOutput);
if (licenseKey && apiUrl) {
return { licenseKey, apiUrl };
if (licenseKey) {
return { licenseKey };
}
} catch (error) {
// Registry key might not exist in HKCU either
@ -199,11 +189,10 @@ function readMdmKeysLinux(): MdmKeys | undefined {
// Parse the JSON configuration file
const config = JSON.parse(fileContent);
// Check if required keys are present
if (config.licenseKey && config.apiUrl) {
// Check if required key is present
if (config.licenseKey) {
return {
licenseKey: config.licenseKey,
apiUrl: config.apiUrl,
};
}
} catch (parseError) {
@ -241,17 +230,20 @@ function readMdmKeys(): MdmKeys | undefined {
/**
* Read and validate MDM keys from the operating system's configuration files or registry.
*/
export function getMdmKeys(): MdmKeys | undefined {
export function getLicenseKeyData(): LicenseKey | undefined {
try {
const mdmKeys = readMdmKeys();
if (mdmKeys) {
if (!validateLicenseKey(mdmKeys.licenseKey)) {
const { isValid, licenseKeyData } = validateLicenseKey(
mdmKeys.licenseKey,
);
if (!isValid) {
console.error("Invalid license key found: ", mdmKeys.licenseKey);
return undefined;
}
return mdmKeys;
return licenseKeyData;
}
return undefined;
@ -260,3 +252,113 @@ export function getMdmKeys(): MdmKeys | undefined {
return undefined;
}
}
function writeMdmKeysMacOS(licenseKey: string): boolean {
try {
// Write to user-specific MDM plist
const userMdmPath = path.join(
os.homedir(),
"Library/Managed Preferences/dev.continue.app.plist",
);
const config = {
licenseKey,
};
// Ensure directory exists
fs.mkdirSync(path.dirname(userMdmPath), { recursive: true });
// Write the plist file
const plistContent = plist.build(config);
fs.writeFileSync(userMdmPath, plistContent, "utf8");
return true;
} catch (error) {
console.error("Error writing macOS MDM keys:", error);
return false;
}
}
function writeMdmKeysWindows(licenseKey: string): boolean {
try {
const { execSync } = require("child_process");
// Use HKEY_CURRENT_USER to avoid needing admin privileges
const userRegPath = "HKCU\\Software\\Continue\\MDM";
// Create the registry key if it doesn't exist
try {
execSync(`reg add "${userRegPath}" /f`);
} catch (error) {
// Key might already exist
}
// Set the license key and API URL
execSync(
`reg add "${userRegPath}" /v licenseKey /t REG_SZ /d "${licenseKey}" /f`,
);
return true;
} catch (error) {
console.error("Error writing Windows MDM keys:", error);
return false;
}
}
function writeMdmKeysLinux(licenseKey: string): boolean {
try {
// Write to user-specific configuration
const userMdmPath = path.join(os.homedir(), ".config/continue/mdm.json");
const config = {
licenseKey,
};
// Ensure directory exists
fs.mkdirSync(path.dirname(userMdmPath), { recursive: true });
// Write the JSON configuration file
fs.writeFileSync(userMdmPath, JSON.stringify(config, null, 2), "utf8");
return true;
} catch (error) {
console.error("Error writing Linux MDM keys:", error);
return false;
}
}
/**
* Store the license key in the appropriate OS-specific location.
* For now, we'll use a default API URL since it's not provided in the command.
*/
export function setMdmLicenseKey(licenseKey: string): boolean {
try {
// Validate the license key first
const { isValid } = validateLicenseKey(licenseKey);
if (!isValid) {
return false;
}
const platform = os.platform();
switch (platform) {
case "darwin":
return writeMdmKeysMacOS(licenseKey);
case "win32":
return writeMdmKeysWindows(licenseKey);
case "linux":
return writeMdmKeysLinux(licenseKey);
default:
console.error(
`Setting MDM keys not supported on platform: ${platform}`,
);
return false;
}
} catch (error) {
console.error("Error setting MDM license key:", error);
return false;
}
}

View file

@ -20,7 +20,7 @@ const modelDescriptionSchema = z.object({
"nebius",
"siliconflow",
"scaleway",
"watsonx"
"watsonx",
]),
model: z.string(),
apiKey: z.string().optional(),
@ -88,13 +88,12 @@ const embeddingsProviderSchema = z.object({
"ollama",
"openai",
"cohere",
"free-trial",
"gemini",
"ovhcloud",
"nebius",
"siliconflow",
"scaleway",
"watsonx"
"watsonx",
]),
apiBase: z.string().optional(),
apiKey: z.string().optional(),

View file

@ -14,7 +14,7 @@ import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
import { getControlPlaneEnv } from "./control-plane/env";
import { DevDataSqliteDb } from "./data/devdataSqlite";
import { DataLogger } from "./data/log";
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { countTokens } from "./llm/countTokens";
import Ollama from "./llm/llms/Ollama";
@ -41,10 +41,10 @@ import {
type ContextItem,
type ContextItemId,
type IDE,
type IndexingProgressUpdate,
} from ".";
import { ConfigYaml } from "@continuedev/config-yaml";
import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
import { isLocalAssistantFile } from "./config/loadLocalAssistants";
import {
setupBestConfig,
@ -53,10 +53,10 @@ import {
} from "./config/onboarding";
import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks";
import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
import { setMdmLicenseKey } from "./control-plane/mdm/mdm";
import { streamDiffLines } from "./edit/streamDiffLines";
import { shouldIgnore } from "./indexing/shouldIgnore";
import { walkDirCache } from "./indexing/walkDir";
import { LLMError } from "./llm";
import { LLMLogger } from "./llm/logger";
import { llmStreamChat } from "./llm/streamChat";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
@ -65,18 +65,12 @@ import { StreamAbortManager } from "./util/abortManager";
export class Core {
configHandler: ConfigHandler;
codebaseIndexerPromise: Promise<CodebaseIndexer>;
codeBaseIndexer: CodebaseIndexer;
completionProvider: CompletionProvider;
continueServerClientPromise: Promise<ContinueServerClient>;
codebaseIndexingState: IndexingProgressUpdate;
private docsService: DocsService;
private globalContext = new GlobalContext();
llmLogger = new LLMLogger();
private readonly indexingPauseToken = new PauseToken(
this.globalContext.get("indexingPaused") === true,
);
private messageAbortControllers = new Map<string, AbortController>();
private addMessageAbortController(id: string): AbortController {
const controller = new AbortController();
@ -114,12 +108,6 @@ export class Core {
// Ensure .continue directory is created
migrateV1DevDataFiles();
this.codebaseIndexingState = {
status: "loading",
desc: "loading",
progress: 0,
};
const ideInfoPromise = messenger.request("getIdeInfo", undefined);
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", {
@ -144,6 +132,13 @@ export class Core {
await this.configHandler.reloadConfig();
};
this.codeBaseIndexer = new CodebaseIndexer(
this.configHandler,
this.ide,
this.messenger,
this.globalContext.get("indexingPaused"),
);
this.configHandler.onConfigUpdate(async (result) => {
const serializedResult = await this.configHandler.getSerializedConfig();
this.messenger.send("configUpdate", {
@ -170,38 +165,17 @@ export class Core {
dataLogger.ideInfoPromise = ideInfoPromise;
dataLogger.ideSettingsPromise = ideSettingsPromise;
// Codebase Indexer and ContinueServerClient depend on IdeSettings
let codebaseIndexerResolve: (_: any) => void | undefined;
this.codebaseIndexerPromise = new Promise(
async (resolve) => (codebaseIndexerResolve = resolve),
);
let continueServerClientResolve: (_: any) => void | undefined;
this.continueServerClientPromise = new Promise(
(resolve) => (continueServerClientResolve = resolve),
);
void ideSettingsPromise.then((ideSettings) => {
const continueServerClient = new ContinueServerClient(
ideSettings.remoteConfigServerUrl,
ideSettings.userToken,
);
continueServerClientResolve(continueServerClient);
codebaseIndexerResolve(
new CodebaseIndexer(
this.configHandler,
this.ide,
this.indexingPauseToken,
continueServerClient,
),
);
// Index on initialization
void this.ide.getWorkspaceDirs().then(async (dirs) => {
// Respect pauseCodebaseIndexOnStart user settings
if (ideSettings.pauseCodebaseIndexOnStart) {
this.indexingPauseToken.paused = true;
this.codeBaseIndexer.paused = true;
void this.messenger.request("indexProgress", {
progress: 0,
desc: "Initial Indexing Skipped",
@ -210,7 +184,7 @@ export class Core {
return;
}
void this.refreshCodebaseIndex(dirs);
void this.codeBaseIndexer.refreshCodebaseIndex(dirs);
});
});
@ -362,6 +336,10 @@ export class Core {
await this.messenger.request("openUrl", url);
});
on("controlPlane/getFreeTrialStatus", async (msg) => {
return this.configHandler.controlPlaneClient.getFreeTrialStatus();
});
on("mcp/reloadServer", async (msg) => {
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
});
@ -551,25 +529,24 @@ export class Core {
}
walkDirCache.invalidate();
if (data?.shouldClearIndexes) {
const codebaseIndexer = await this.codebaseIndexerPromise;
await codebaseIndexer.clearIndexes();
await this.codeBaseIndexer.clearIndexes();
}
const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs());
await this.refreshCodebaseIndex(dirs);
await this.codeBaseIndexer.refreshCodebaseIndex(dirs);
});
on("index/setPaused", (msg) => {
this.globalContext.update("indexingPaused", msg.data);
this.indexingPauseToken.paused = msg.data;
// Update using the new setter instead of token
this.codeBaseIndexer.paused = msg.data;
});
on("index/indexingProgressBarInitialized", async (msg) => {
// Triggered when progress bar is initialized.
// If a non-default state has been stored, update the indexing display to that state
if (this.codebaseIndexingState.status !== "loading") {
void this.messenger.request(
"indexProgress",
this.codebaseIndexingState,
);
const currentState = this.codeBaseIndexer.currentIndexingState;
if (currentState.status !== "loading") {
void this.messenger.request("indexProgress", currentState);
}
});
@ -589,7 +566,7 @@ export class Core {
});
const { config } = await this.configHandler.loadConfig();
if (config && !config.disableIndexing) {
await this.refreshCodebaseIndexFiles(toRefresh);
await this.codeBaseIndexer.refreshCodebaseIndexFiles(toRefresh);
}
}
};
@ -750,6 +727,11 @@ export class Core {
return isBackgrounded; // Return true to indicate the message was handled successfully
},
);
on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
const isValid = setMdmLicenseKey(licenseKey);
return isValid;
});
}
private async isItemTooBig(item: ContextItemWithId) {
@ -809,6 +791,8 @@ export class Core {
uris?: string[];
}>) {
if (data?.uris?.length) {
const diffCache = GitDiffCache.getInstance(getDiffFn(this.ide));
diffCache.invalidate();
walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes
for (const uri of data.uris) {
const currentProfileUri =
@ -853,7 +837,7 @@ export class Core {
// Reindex the file
const ignore = await shouldIgnore(uri, this.ide);
if (!ignore) {
await this.refreshCodebaseIndexFiles([uri]);
await this.codeBaseIndexer.refreshCodebaseIndexFiles([uri]);
}
}
}
@ -1024,100 +1008,4 @@ export class Core {
return [];
}
};
private indexingCancellationController: AbortController | undefined;
private async sendIndexingErrorTelemetry(update: IndexingProgressUpdate) {
console.debug(
"Indexing failed with error: ",
update.desc,
update.debugInfo,
);
void Telemetry.capture(
"indexing_error",
{
error: update.desc,
stack: update.debugInfo,
},
false,
);
}
private async refreshCodebaseIndex(paths: string[]) {
if (this.indexingCancellationController) {
this.indexingCancellationController.abort();
}
this.indexingCancellationController = new AbortController();
try {
for await (const update of (
await this.codebaseIndexerPromise
).refreshDirs(paths, this.indexingCancellationController.signal)) {
let updateToSend = { ...update };
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
}
}
} catch (e: any) {
console.log(`Failed refreshing codebase index directories : ${e}`);
this.handleIndexingError(e);
}
this.messenger.send("refreshSubmenuItems", {
providers: "dependsOnIndexing",
});
this.indexingCancellationController = undefined;
}
private async refreshCodebaseIndexFiles(files: string[]) {
// Can be cancelled by codebase index but not vice versa
if (
this.indexingCancellationController &&
!this.indexingCancellationController.signal.aborted
) {
return;
}
this.indexingCancellationController = new AbortController();
try {
for await (const update of (
await this.codebaseIndexerPromise
).refreshFiles(files)) {
let updateToSend = { ...update };
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
}
}
} catch (e: any) {
console.log(`Failed refreshing codebase index files : ${e}`);
this.handleIndexingError(e);
}
this.messenger.send("refreshSubmenuItems", {
providers: "dependsOnIndexing",
});
this.indexingCancellationController = undefined;
}
// private
handleIndexingError(e: any) {
if (e instanceof LLMError) {
// Need to report this specific error to the IDE for special handling
void this.messenger.request("reportError", e);
}
// broadcast indexing error
let updateToSend: IndexingProgressUpdate = {
progress: 0,
status: "failed",
desc: e.message,
};
void this.messenger.request("indexProgress", updateToSend);
this.codebaseIndexingState = updateToSend;
void this.sendIndexingErrorTelemetry(updateToSend);
}
}

View file

@ -83,10 +83,13 @@ export async function* getReplacementWithLlm(
\`\`\`
`;
const completion = await llm.streamChat([
{ role: "user", content: userPrompt },
{ role: "assistant", content: assistantPrompt },
], new AbortController().signal);
const completion = await llm.streamChat(
[
{ role: "user", content: userPrompt },
{ role: "assistant", content: assistantPrompt },
],
new AbortController().signal,
);
let lines = streamLines(completion);
lines = filterLeadingNewline(lines);

View file

@ -43,7 +43,7 @@ describe("isUnifiedDiffFormat", () => {
expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true);
});
it("should return true in case of empty lines", () => {
it("should return true in case of empty lines", () => {
const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@
line1
@ -83,16 +83,25 @@ describe("applyUnifiedDiff", () => {
const expected = [
{ type: "same", line: "func main() {" },
{ type: "same", line: " scanner := bufio.NewScanner(os.Stdin)" },
{ type: "same", line: " fmt.Println(\"Calculator started! Available operations:\")" },
{ type: "same", line: " fmt.Println(\" + : Addition\")" },
{ type: "same", line: " fmt.Println(\" - : Subtraction\")" },
{ type: "same", line: " fmt.Println(\" * : Multiplication\")" },
{ type: "same", line: " fmt.Println(\" / : Division\")" },
{ type: "same", line: " fmt.Println(\" ^ : Power\")" },
{ type: "same", line: " fmt.Println(\" √ : Square root (use only one number)\")" },
{ type: "new", line: " fmt.Println(\" log: Logarithm (use 'log base number')\")" },
{
type: "same",
line: ' fmt.Println("Calculator started! Available operations:")',
},
{ type: "same", line: ' fmt.Println(" + : Addition")' },
{ type: "same", line: ' fmt.Println(" - : Subtraction")' },
{ type: "same", line: ' fmt.Println(" * : Multiplication")' },
{ type: "same", line: ' fmt.Println(" / : Division")' },
{ type: "same", line: ' fmt.Println(" ^ : Power")' },
{
type: "same",
line: ' fmt.Println(" √ : Square root (use only one number)")',
},
{
type: "new",
line: " fmt.Println(\" log: Logarithm (use 'log base number')\")",
},
{ type: "same", line: "}" },
{ type: "same", line: "// End of file" }
{ type: "same", line: "// End of file" },
];
expect(result).toEqual(expected);
@ -130,18 +139,18 @@ func main() {
const expected = [
{ type: "same", line: "package main" },
{ type: "same", line: "" },
{ type: "old", line: "import \"fmt\"" },
{ type: "old", line: 'import "fmt"' },
{ type: "new", line: "import (" },
{ type: "new", line: " \"fmt\"" },
{ type: "new", line: " \"time\"" },
{ type: "new", line: ' "fmt"' },
{ type: "new", line: ' "time"' },
{ type: "new", line: ")" },
{ type: "same", line: "" },
{ type: "same", line: "func main() {" },
{ type: "old", line: " fmt.Println(\"Hello\")" },
{ type: "new", line: " fmt.Printf(\"The time is: %v\\n\", time.Now())" },
{ type: "old", line: " fmt.Println(\"World\")" },
{ type: "new", line: " fmt.Println(\"Goodbye!\")" },
{ type: "same", line: "}" }
{ type: "old", line: ' fmt.Println("Hello")' },
{ type: "new", line: ' fmt.Printf("The time is: %v\\n", time.Now())' },
{ type: "old", line: ' fmt.Println("World")' },
{ type: "new", line: ' fmt.Println("Goodbye!")' },
{ type: "same", line: "}" },
];
expect(result).toEqual(expected);
@ -379,29 +388,47 @@ func TestLargeNumbers(t *testing.T) {
expect(result[0].line).toEqual("package main");
// 1st block
expect(result[18].line).toEqual("\tfmt.Println(\" √ : Square root (use only one number)\")");
expect(result[19].line).toEqual(" fmt.Println(\" log: Logarithm (use 'log base number')\")");
expect(result[20].line).toEqual(" fmt.Println(\" Base must be > 0 and != 1, number must be > 0\")");
// 2nd block
expect(result[56]).toEqual({type: "same", line: "\t}"});
expect(result[57]).toEqual({type: "new", line: "\t"});
expect(result[58]).toEqual({type: "new", line: "\t// Handle logarithmic operations"});
expect(result[73]).toEqual({type: "new", line: ""});
expect(result[74]).toEqual({type: "same", line: "\tif len(parts) != 3 {"});
// 3rd block
expect(result[140]).toEqual({type: "same", line: "}"});
expect(result[141]).toEqual({type: "new", line: ""});
expect(result[142]).toEqual({type: "new", line: "func TestLogarithmicCases(t *testing.T) {"});
expect(result[153]).toEqual({type: "new", line: "\t}"});
expect(result[154]).toEqual({type: "same", line: "func TestSpecialCases(t *testing.T) {"});
});
expect(result[18].line).toEqual(
'\tfmt.Println(" √ : Square root (use only one number)")',
);
expect(result[19].line).toEqual(
" fmt.Println(\" log: Logarithm (use 'log base number')\")",
);
expect(result[20].line).toEqual(
' fmt.Println(" Base must be > 0 and != 1, number must be > 0")',
);
// 2nd block
expect(result[56]).toEqual({ type: "same", line: "\t}" });
expect(result[57]).toEqual({ type: "new", line: "\t" });
expect(result[58]).toEqual({
type: "new",
line: "\t// Handle logarithmic operations",
});
expect(result[73]).toEqual({ type: "new", line: "" });
expect(result[74]).toEqual({
type: "same",
line: "\tif len(parts) != 3 {",
});
// 3rd block
expect(result[140]).toEqual({ type: "same", line: "}" });
expect(result[141]).toEqual({ type: "new", line: "" });
expect(result[142]).toEqual({
type: "new",
line: "func TestLogarithmicCases(t *testing.T) {",
});
expect(result[153]).toEqual({ type: "new", line: "\t}" });
expect(result[154]).toEqual({
type: "same",
line: "func TestSpecialCases(t *testing.T) {",
});
});
it("should throw error when hunk cannot be matched to source", () => {
const sourceCode = `line1
it("should throw error when hunk cannot be matched to source", () => {
const sourceCode = `line1
line2
line3`;
const diffText = `--- a.txt
const diffText = `--- a.txt
+++ b.txt
@@ -1,3 +1,4 @@
missing1
@ -409,7 +436,8 @@ missing1
+newline2
missing3`;
expect(() => applyUnifiedDiff(sourceCode, diffText))
.toThrow("Hunk could not be applied cleanly to source code.");
});
expect(() => applyUnifiedDiff(sourceCode, diffText)).toThrow(
"Hunk could not be applied cleanly to source code.",
);
});
});

View file

@ -8,7 +8,9 @@ import { DiffLine } from "../../index";
export function isUnifiedDiffFormat(diff: string): boolean {
const lines = diff.trim().split("\n");
if (lines.length < 3) {return false;}
if (lines.length < 3) {
return false;
}
let hasHunkHeader = false;
let hasValidContent = false;
@ -35,10 +37,13 @@ function extractBeforeLines(hunkLines: string[]): string[] {
/**
* Applies a unified diff to source code and returns an array of DiffLine objects.
* Each DiffLine contains a type ("same", "new", or "old") and the line content.
*
*
* @throws Error if the diff cannot be cleanly applied to the source
*/
export function applyUnifiedDiff(sourceCode: string, unifiedDiffText: string): DiffLine[] {
export function applyUnifiedDiff(
sourceCode: string,
unifiedDiffText: string,
): DiffLine[] {
const sourceLines = sourceCode.split(/\r?\n/);
const hunks = parseUnifiedDiff(unifiedDiffText);
const diffResult: DiffLine[] = [];
@ -46,7 +51,11 @@ export function applyUnifiedDiff(sourceCode: string, unifiedDiffText: string): D
for (const hunk of hunks) {
const hunkBeforeLines = extractBeforeLines(hunk.lines);
const hunkStart = findHunkInSource(sourceLines, hunkBeforeLines, currentPos);
const hunkStart = findHunkInSource(
sourceLines,
hunkBeforeLines,
currentPos,
);
if (hunkStart === -1) {
// All hunks must be found in the source code. If not, throw an error.
throw new Error("Hunk could not be applied cleanly to source code.");
@ -124,8 +133,16 @@ function parseUnifiedDiff(diffText: string): Hunk[] {
*
* Returns the index in sourceLines where the block begins, or -1 if no match is found.
*/
function findHunkInSource(sourceLines: string[], hunkBeforeLines: string[], startIndex: number): number {
for (let i = startIndex; i <= sourceLines.length - hunkBeforeLines.length; i++) {
function findHunkInSource(
sourceLines: string[],
hunkBeforeLines: string[],
startIndex: number,
): number {
for (
let i = startIndex;
i <= sourceLines.length - hunkBeforeLines.length;
i++
) {
let match = true;
for (let j = 0; j < hunkBeforeLines.length; j++) {
const sl = sourceLines[i + j];

7
core/index.d.ts vendored
View file

@ -5,7 +5,6 @@ import {
} from "@continuedev/config-yaml";
import Parser from "web-tree-sitter";
import { LLMConfigurationStatuses } from "./llm/constants";
import { GetGhTokenArgs } from "./protocol/ide";
declare global {
interface Window {
@ -776,10 +775,6 @@ export interface IDE {
}
>;
getLastFileSaveTimestamp?(): number;
updateLastFileSaveTimestamp?(): void;
getPinnedFiles(): Promise<string[]>;
getSearchResults(query: string): Promise<string>;
@ -808,8 +803,6 @@ export interface IDE {
getFileStats(files: string[]): Promise<FileStatsMap>;
getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined>;
// Secret Storage
readSecrets(keys: string[]): Promise<Record<string, string>>;

View file

@ -3,7 +3,7 @@ import { execSync } from "node:child_process";
import fs from "node:fs";
import path from "path";
import { ContinueServerClient } from "../continueServer/stubs/client.js";
import { LLMError } from "../llm/index.js";
import { testConfigHandler, testIde } from "../test/fixtures.js";
import {
addToTestDir,
@ -59,16 +59,34 @@ class TestCodebaseIndexer extends CodebaseIndexer {
}
}
// Create a mock messenger type that doesn't require actual protocol imports
type MockMessengerType = {
send: jest.Mock;
request: jest.Mock;
invoke: jest.Mock;
on: jest.Mock;
onError: jest.Mock;
};
// These are more like integration tests, whereas we should separately test
// the individual CodebaseIndex classes
describe("CodebaseIndexer", () => {
const pauseToken = new PauseToken(false);
const continueServerClient = new ContinueServerClient(undefined, undefined);
// Replace mockProgressReporter with mockMessenger
const mockMessenger: MockMessengerType = {
send: jest.fn(),
request: jest.fn(async () => {}),
invoke: jest.fn(),
on: jest.fn(),
onError: jest.fn(),
};
const codebaseIndexer = new TestCodebaseIndexer(
testConfigHandler,
testIde,
pauseToken,
continueServerClient,
mockMessenger as any,
false,
);
const testIndex = new TestCodebaseIndex();
@ -89,6 +107,7 @@ describe("CodebaseIndexer", () => {
afterEach(() => {
walkDirCache.invalidate();
jest.clearAllMocks();
});
async function refreshIndex() {
@ -241,4 +260,155 @@ describe("CodebaseIndexer", () => {
execSync(`cd ${TEST_DIR_PATH} && git checkout main`);
await expectPlan(0, 0, 0, 0);
});
// New tests for the methods added from Core.ts
describe("New methods from Core.ts", () => {
// Simplified tests to focus on behavior, not implementation details
test("should call messenger with progress updates when refreshing codebase index", async () => {
jest
.spyOn(codebaseIndexer as any, "refreshDirs")
.mockImplementation(async function* () {
yield { status: "done", progress: 1, desc: "Completed" };
});
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
expect(mockMessenger.request).toHaveBeenCalledWith(
"indexProgress",
expect.anything(),
);
expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", {
providers: "dependsOnIndexing",
});
});
test("should call messenger with progress updates when refreshing specific files", async () => {
jest
.spyOn(codebaseIndexer as any, "refreshFiles")
.mockImplementation(async function* () {
yield { status: "done", progress: 1, desc: "Completed" };
});
await codebaseIndexer.refreshCodebaseIndexFiles(["/test/file.ts"]);
expect(mockMessenger.request).toHaveBeenCalledWith(
"indexProgress",
expect.anything(),
);
expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", {
providers: "all",
});
});
test("should abort previous indexing when starting a new one", async () => {
// Set up a situation where indexingCancellationController exists
const mockAbort = jest.fn();
const controller = { abort: mockAbort, signal: { aborted: false } };
// Access the private property in a type-safe way for testing
(codebaseIndexer as any).indexingCancellationController = controller;
// Mock refreshDirs to return immediately
jest
.spyOn(codebaseIndexer as any, "refreshDirs")
.mockImplementation(async function* () {
yield { status: "done", progress: 1, desc: "Completed" };
});
// Start indexing - this should call abort on the existing controller
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
// Verify abort was called
expect(mockAbort).toHaveBeenCalled();
});
test("should handle errors properly during indexing", async () => {
const testError = new Error("Test indexing error");
// Mock console.log to avoid printing errors
const consoleLogSpy = jest
.spyOn(console, "log")
.mockImplementation(() => {});
// Mock refreshDirs to throw an error
jest
.spyOn(codebaseIndexer as any, "refreshDirs")
.mockImplementation(() => {
throw testError;
});
// We don't need to mock AbortController because we're mocking the entire refreshDirs call
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
// Use the first argument only for the assertion since the second argument doesn't match exactly
expect(consoleLogSpy).toHaveBeenCalledWith(
`Failed refreshing codebase index directories: Error: ${testError.message}`,
);
expect(mockMessenger.request).toHaveBeenCalledWith(
"indexProgress",
expect.objectContaining({
status: "failed",
}),
);
consoleLogSpy.mockRestore();
});
test("should handle LLMError specially during indexing", async () => {
// Create a mock LLM
const mockLlm: any = {
providerName: "test-provider",
model: "test-model",
};
// Create a real LLMError
const llmError = new LLMError("Test LLM error", mockLlm);
// Mock console.log to avoid printing errors
jest.spyOn(console, "log").mockImplementation(() => {});
// Mock refreshDirs to throw an LLMError
jest
.spyOn(codebaseIndexer as any, "refreshDirs")
.mockImplementation(() => {
throw llmError;
});
// We don't need to mock AbortController because we're mocking the entire refreshDirs call
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
expect(mockMessenger.request).toHaveBeenCalledWith(
"reportError",
llmError,
);
expect(mockMessenger.request).toHaveBeenCalledWith(
"indexProgress",
expect.objectContaining({
status: "failed",
desc: "Test LLM error",
}),
);
});
test("should provide access to current indexing state", async () => {
const testState = {
progress: 0.5,
status: "indexing" as const,
desc: "Test state",
};
// Mock refreshDirs to set a specific state
jest
.spyOn(codebaseIndexer as any, "refreshDirs")
.mockImplementation(async function* () {
yield testState;
});
// We don't need to mock AbortController because we're mocking the entire refreshDirs call
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
// Check that the state was updated
expect(codebaseIndexer.currentIndexingState).toEqual(testState);
});
});
});

View file

@ -3,10 +3,14 @@ import * as fs from "fs/promises";
import { ConfigHandler } from "../config/ConfigHandler.js";
import { IContinueServerClient } from "../continueServer/interface.js";
import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js";
import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
import type { IMessenger } from "../protocol/messenger";
import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
import { Telemetry } from "../util/posthog.js";
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
import { ContinueServerClient } from "../continueServer/stubs/client";
import { LLMError } from "../llm/index.js";
import { getRootCause } from "../util/errors.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
@ -41,6 +45,9 @@ export class CodebaseIndexer {
* - To make as few requests as possible to the embeddings providers
*/
filesPerBatch = 500;
private indexingCancellationController: AbortController | undefined;
private codebaseIndexingState: IndexingProgressUpdate;
private readonly pauseToken: PauseToken;
// Note that we exclude certain Sqlite errors that we do not want to clear the indexes on,
// e.g. a `SQLITE_BUSY` error.
@ -56,9 +63,32 @@ export class CodebaseIndexer {
constructor(
private readonly configHandler: ConfigHandler,
protected readonly ide: IDE,
private readonly pauseToken: PauseToken,
private readonly continueServerClient: IContinueServerClient,
) {}
private readonly messenger?: IMessenger<ToCoreProtocol, FromCoreProtocol>,
initialPaused: boolean = false,
) {
this.codebaseIndexingState = {
status: "loading",
desc: "loading",
progress: 0,
};
// Initialize pause token
this.pauseToken = new PauseToken(initialPaused);
}
/**
* Set the paused state of the indexer
*/
set paused(value: boolean) {
this.pauseToken.paused = value;
}
/**
* Get the current paused state of the indexer
*/
get paused(): boolean {
return this.pauseToken.paused;
}
async clearIndexes() {
const sqliteFilepath = getIndexSqlitePath();
@ -88,10 +118,22 @@ export class CodebaseIndexer {
return [];
}
const ideSettings = await this.ide.getIdeSettings();
if (!ideSettings) {
return [];
}
const continueServerClient = new ContinueServerClient(
ideSettings.remoteConfigServerUrl,
ideSettings.userToken,
);
if (!continueServerClient) {
return [];
}
const indexes: CodebaseIndex[] = [
new ChunkCodebaseIndex(
this.ide.readFile.bind(this.ide),
this.continueServerClient,
continueServerClient,
embeddingsModel.maxEmbeddingChunkSize,
), // Chunking must come first
];
@ -504,4 +546,109 @@ export class CodebaseIndexer {
completedIndexCount += 1;
}
}
// New methods using messenger directly
private async updateProgress(update: IndexingProgressUpdate) {
this.codebaseIndexingState = update;
if (this.messenger) {
await this.messenger.request("indexProgress", update);
}
}
private async sendIndexingErrorTelemetry(update: IndexingProgressUpdate) {
console.debug(
"Indexing failed with error: ",
update.desc,
update.debugInfo,
);
void Telemetry.capture(
"indexing_error",
{
error: update.desc,
stack: update.debugInfo,
},
false,
);
}
public async refreshCodebaseIndex(paths: string[]) {
if (this.indexingCancellationController) {
this.indexingCancellationController.abort();
}
this.indexingCancellationController = new AbortController();
try {
for await (const update of this.refreshDirs(
paths,
this.indexingCancellationController.signal,
)) {
await this.updateProgress(update);
if (update.status === "failed") {
await this.sendIndexingErrorTelemetry(update);
}
}
} catch (e: any) {
console.log(`Failed refreshing codebase index directories: ${e}`);
await this.handleIndexingError(e);
}
// Directly refresh submenu items
if (this.messenger) {
this.messenger.send("refreshSubmenuItems", {
providers: "dependsOnIndexing",
});
}
this.indexingCancellationController = undefined;
}
public async refreshCodebaseIndexFiles(files: string[]) {
// Can be cancelled by codebase index but not vice versa
if (
this.indexingCancellationController &&
!this.indexingCancellationController.signal.aborted
) {
return;
}
this.indexingCancellationController = new AbortController();
try {
for await (const update of this.refreshFiles(files)) {
await this.updateProgress(update);
if (update.status === "failed") {
await this.sendIndexingErrorTelemetry(update);
}
}
} catch (e: any) {
console.log(`Failed refreshing codebase index files: ${e}`);
await this.handleIndexingError(e);
}
// Directly refresh submenu items
if (this.messenger) {
this.messenger.send("refreshSubmenuItems", { providers: "all" });
}
this.indexingCancellationController = undefined;
}
public async handleIndexingError(e: any) {
if (e instanceof LLMError && this.messenger) {
// Need to report this specific error to the IDE for special handling
await this.messenger.request("reportError", e);
}
// broadcast indexing error
const updateToSend: IndexingProgressUpdate = {
progress: 0,
status: "failed",
desc: e.message,
};
await this.updateProgress(updateToSend);
void this.sendIndexingErrorTelemetry(updateToSend);
}
public get currentIndexingState(): IndexingProgressUpdate {
return this.codebaseIndexingState;
}
}

View file

@ -14,12 +14,14 @@ export async function* basicChunker(
let startLine = 0;
let currLine = 0;
const lineTokens = await Promise.all(contents.split("\n").map(async l => {
return {
line: l,
tokenCount: await countTokensAsync(l),
};
}));
const lineTokens = await Promise.all(
contents.split("\n").map(async (l) => {
return {
line: l,
tokenCount: await countTokensAsync(l),
};
}),
);
for (const lt of lineTokens) {
if (chunkTokens + lt.tokenCount > maxChunkSize - 5) {

View file

@ -30,7 +30,7 @@ describe.skip("codeChunker", () => {
test("should capture small class and function from large python file", async () => {
const extraLine = "# This is a comment";
const myClass = "class MyClass:\n def __init__(self):\n pass";
const myFunction = "def my_function():\n return \"Hello, World!\"";
const myFunction = 'def my_function():\n return "Hello, World!"';
const file =
Array(100).fill(extraLine).join("\n") +
@ -67,7 +67,7 @@ describe.skip("codeChunker", () => {
chunks[0].startsWith("class MyClass:\n def method1():\n ..."),
).toBe(true);
// The extra spaces seem to be a bug with tree-sitter-python
expect(chunks).toContain("def method1():\n return \"Hello, 1!\"");
expect(chunks).toContain("def method20():\n return \"Hello, 20!\"");
expect(chunks).toContain('def method1():\n return "Hello, 1!"');
expect(chunks).toContain('def method20():\n return "Hello, 20!"');
});
});

View file

@ -101,23 +101,7 @@
// // const originalEmbeddingsProvider =
// // await docsService.getEmbeddingsProvider();
// // // Change embeddings provider
// // editConfigJson((config) => ({
// // ...config,
// // embeddingsProvider: {
// // provider: FreeTrial.providerName,
// // },
// // }));
// // await getReloadedConfig();
// // const { provider, isPreindexed} = await docsService.getEmbeddingsProvider();
// // // Verify reindexing
// // const [originalVector] = await originalEmbeddingsProvider.embed(["test"]);
// // const [newMockVector] = await provider.embed(["test"]);
// // expect(originalVector).not.toEqual(newMockVector);
// // TODO removed this test when free trial provider was removed
// // });
// test("Handles pulling down and adding pre-indexed docs", async () => {

View file

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

View file

@ -66,7 +66,6 @@ const PROVIDER_SUPPORTS_IMAGES: string[] = [
"openai",
"ollama",
"gemini",
"free-trial",
"msty",
"anthropic",
"bedrock",
@ -148,7 +147,6 @@ const PARALLEL_PROVIDERS: string[] = [
"huggingface-tgi",
"mistral",
"moonshot",
"free-trial",
"replicate",
"together",
"novita",
@ -389,6 +387,5 @@ export {
autodetectTemplateType,
llmCanGenerateInParallel,
modelSupportsImages,
modelSupportsTools
modelSupportsTools,
};

View file

@ -46,6 +46,39 @@ describe.skip("pruneLinesFromTop", () => {
const pruned = pruneLinesFromTop(prompt, 5, "gpt-4");
expect(pruned.split("\n").length).toBeLessThan(prompt.split("\n").length);
});
it("should return the original prompt if it's within max tokens", () => {
const prompt = "Line 1\nLine 2";
const pruned = pruneLinesFromTop(prompt, 10, "gpt-4");
expect(pruned).toEqual(prompt);
});
it("should return an empty string if maxTokens is 0", () => {
const prompt = "Line 1\nLine 2\nLine 3\nLine 4";
const pruned = pruneLinesFromTop(prompt, 0, "gpt-4");
expect(pruned).toEqual("");
});
it("should handle an empty prompt string", () => {
const prompt = "";
const pruned = pruneLinesFromTop(prompt, 5, "gpt-4");
expect(pruned).toEqual("");
});
it("should handle a prompt with a single line that exceeds maxTokens", () => {
const prompt =
"This is a single long line that will exceed the token limit";
const pruned = pruneLinesFromTop(prompt, 5, "gpt-4");
expect(pruned).toEqual("");
});
it("should correctly prune when all lines together exceed maxTokens but individual lines do not", () => {
const prompt = "L1\nL2\nL3\nL4";
const pruned = pruneLinesFromTop(prompt, 5, "gpt-4");
expect(pruned).toEqual("L3\nL4");
});
});
describe.skip("pruneLinesFromBottom", () => {
@ -54,6 +87,39 @@ describe.skip("pruneLinesFromBottom", () => {
const pruned = pruneLinesFromBottom(prompt, 5, "gpt-4");
expect(pruned.split("\n").length).toBeLessThan(prompt.split("\n").length);
});
it("should return the original prompt if it's within max tokens", () => {
const prompt = "Line 1\nLine 2";
const pruned = pruneLinesFromBottom(prompt, 10, "gpt-4");
expect(pruned).toEqual(prompt);
});
it("should return an empty string if maxTokens is 0", () => {
const prompt = "Line 1\nLine 2\nLine 3\nLine 4";
const pruned = pruneLinesFromBottom(prompt, 0, "gpt-4");
expect(pruned).toEqual("");
});
it("should handle an empty prompt string", () => {
const prompt = "";
const pruned = pruneLinesFromBottom(prompt, 5, "gpt-4");
expect(pruned).toEqual("");
});
it("should handle a prompt with a single line that exceeds maxTokens", () => {
const prompt =
"This is a single long line that will exceed the token limit";
const pruned = pruneLinesFromBottom(prompt, 5, "gpt-4");
expect(pruned).toEqual("");
});
it("should correctly prune when all lines together exceed maxTokens but individual lines do not", () => {
const prompt = "L1\nL2\nL3\nL4";
const pruned = pruneLinesFromBottom(prompt, 5, "gpt-4");
expect(pruned).toEqual("L1\nL2");
});
});
describe.skip("pruneRawPromptFromTop", () => {

View file

@ -215,13 +215,28 @@ function pruneLinesFromTop(
maxTokens: number,
modelName: string,
): string {
let totalTokens = countTokens(prompt, modelName);
const lines = prompt.split("\n");
while (totalTokens > maxTokens && lines.length > 0) {
totalTokens -= countTokens(lines.shift()!, modelName);
// Preprocess tokens for all lines and cache them.
const lineTokens = lines.map((line) => countTokens(line, modelName));
let totalTokens = lineTokens.reduce((sum, tokens) => sum + tokens, 0);
let start = 0;
let currentLines = lines.length;
// Calculate initial token count including newlines
totalTokens += Math.max(0, currentLines - 1); // Add tokens for joining newlines
// Using indexes instead of array modifications.
// Remove lines from the top until the token count is within the limit.
while (totalTokens > maxTokens && start < currentLines) {
totalTokens -= lineTokens[start];
// Decrement token count for the removed line and its preceding/joining newline (if not the last line)
if (currentLines - start > 1) {
totalTokens--;
}
start++;
}
return lines.join("\n");
return lines.slice(start).join("\n");
}
function pruneLinesFromBottom(
@ -229,13 +244,26 @@ function pruneLinesFromBottom(
maxTokens: number,
modelName: string,
): string {
let totalTokens = countTokens(prompt, modelName);
const lines = prompt.split("\n");
while (totalTokens > maxTokens && lines.length > 0) {
totalTokens -= countTokens(lines.pop()!, modelName);
const lineTokens = lines.map((line) => countTokens(line, modelName));
let totalTokens = lineTokens.reduce((sum, tokens) => sum + tokens, 0);
let end = lines.length;
// Calculate initial token count including newlines
totalTokens += Math.max(0, end - 1); // Add tokens for joining newlines
// Reverse traversal to avoid array modification
// Remove lines from the bottom until the token count is within the limit.
while (totalTokens > maxTokens && end > 0) {
end--;
totalTokens -= lineTokens[end];
// Decrement token count for the removed line and its following/joining newline (if not the first line)
if (end > 0) {
totalTokens--;
}
}
return lines.join("\n");
return lines.slice(0, end).join("\n");
}
function pruneStringFromBottom(

View file

@ -1,11 +1,20 @@
export declare class LlamaTokenizer {
vocabById: string[];
vocabByString: Map<string, number>;
merges: Map<string, number>;
constructor(vocab_base64?: string, merges_binary?: string);
encode(prompt: string, add_bos_token?: boolean, add_preceding_space?: boolean, log_performance?: boolean): number[];
decode(tokenIds: number[], add_bos_token?: boolean, add_preceding_space?: boolean): string;
runTests(tests?: (tokenizer: LlamaTokenizer) => boolean): void
vocabById: string[];
vocabByString: Map<string, number>;
merges: Map<string, number>;
constructor(vocab_base64?: string, merges_binary?: string);
encode(
prompt: string,
add_bos_token?: boolean,
add_preceding_space?: boolean,
log_performance?: boolean,
): number[];
decode(
tokenIds: number[],
add_bos_token?: boolean,
add_preceding_space?: boolean,
): string;
runTests(tests?: (tokenizer: LlamaTokenizer) => boolean): void;
}
declare const llamaTokenizer: LlamaTokenizer;
export default llamaTokenizer;
export default llamaTokenizer;

File diff suppressed because one or more lines are too long

View file

@ -1,7 +1,12 @@
import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
import Bedrock from "./Bedrock.js";
import { ChatMessage, Chunk, CompletionOptions, UserChatMessage } from "../../index.js";
import {
ChatMessage,
Chunk,
CompletionOptions,
UserChatMessage,
} from "../../index.js";
// Mock AWS SDK
jest.mock("@aws-sdk/client-bedrock-runtime", () => ({
@ -34,7 +39,7 @@ class TestBedrock extends Bedrock {
public async *streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: TestCompletionOptions
options: TestCompletionOptions,
): AsyncGenerator<ChatMessage> {
if (options.mockError) {
throw new Error(options.mockError);
@ -44,14 +49,16 @@ class TestBedrock extends Bedrock {
yield {
role: "assistant",
content: "",
toolCalls: [{
id: "tool-1",
type: "function",
function: {
name: "test_tool",
arguments: '{"arg1":"value1"}'
}
}],
toolCalls: [
{
id: "tool-1",
type: "function",
function: {
name: "test_tool",
arguments: '{"arg1":"value1"}',
},
},
],
};
return;
}
@ -97,7 +104,9 @@ describe("Bedrock", () => {
expect(bedrock.region).toBe("us-east-1");
expect(bedrock.profile).toBe("bedrock");
expect(bedrock.apiBase).toBe("https://bedrock-runtime.us-east-1.amazonaws.com");
expect(bedrock.apiBase).toBe(
"https://bedrock-runtime.us-east-1.amazonaws.com",
);
});
it("should use custom options when provided", () => {
@ -131,14 +140,20 @@ describe("Bedrock", () => {
});
it("should handle text streaming correctly", async () => {
const messages: ChatMessage[] = [{
role: "user",
content: "Hi"
} as UserChatMessage];
const messages: ChatMessage[] = [
{
role: "user",
content: "Hi",
} as UserChatMessage,
];
const results = [];
for await (const message of bedrock.streamChat(messages, mockAbortSignal, defaultOptions)) {
for await (const message of bedrock.streamChat(
messages,
mockAbortSignal,
defaultOptions,
)) {
results.push(message);
}
@ -149,18 +164,24 @@ describe("Bedrock", () => {
});
it("should handle tool use streaming correctly", async () => {
const messages: ChatMessage[] = [{
role: "user",
content: "Use a tool"
} as UserChatMessage];
const messages: ChatMessage[] = [
{
role: "user",
content: "Use a tool",
} as UserChatMessage,
];
const results = [];
const options: TestCompletionOptions = {
...defaultOptions,
mockToolUse: true
mockToolUse: true,
};
for await (const message of bedrock.streamChat(messages, mockAbortSignal, options)) {
for await (const message of bedrock.streamChat(
messages,
mockAbortSignal,
options,
)) {
results.push(message);
}
@ -168,31 +189,39 @@ describe("Bedrock", () => {
{
role: "assistant",
content: "",
toolCalls: [{
id: "tool-1",
type: "function",
function: {
name: "test_tool",
arguments: '{"arg1":"value1"}'
}
}],
toolCalls: [
{
id: "tool-1",
type: "function",
function: {
name: "test_tool",
arguments: '{"arg1":"value1"}',
},
},
],
},
]);
});
it("should handle API errors", async () => {
const messages: ChatMessage[] = [{
role: "user",
content: "Hi"
} as UserChatMessage];
const messages: ChatMessage[] = [
{
role: "user",
content: "Hi",
} as UserChatMessage,
];
const options: TestCompletionOptions = {
...defaultOptions,
mockError: "API Error"
mockError: "API Error",
};
await expect(async () => {
for await (const _ of bedrock.streamChat(messages, mockAbortSignal, options)) {
for await (const _ of bedrock.streamChat(
messages,
mockAbortSignal,
options,
)) {
// consume generator
}
}).rejects.toThrow("API Error");
@ -239,7 +268,7 @@ describe("Bedrock", () => {
filepath: "file1",
index: 0,
startLine: 1,
endLine: 1
endLine: 1,
},
{
content: "doc2",
@ -247,8 +276,8 @@ describe("Bedrock", () => {
filepath: "file2",
index: 1,
startLine: 1,
endLine: 1
}
endLine: 1,
},
];
const result = await bedrock.rerank("query", chunks);
@ -262,16 +291,18 @@ describe("Bedrock", () => {
filepath: "file1",
index: 0,
startLine: 1,
endLine: 1
endLine: 1,
};
await expect(
bedrock.rerank("error", [chunk])
).rejects.toThrow("Reranking Error");
await expect(bedrock.rerank("error", [chunk])).rejects.toThrow(
"Reranking Error",
);
});
it("should throw error for empty input", async () => {
await expect(bedrock.rerank("", [])).rejects.toThrow("Query and chunks must not be empty");
await expect(bedrock.rerank("", [])).rejects.toThrow(
"Query and chunks must not be empty",
);
});
});
@ -289,7 +320,7 @@ describe("Bedrock", () => {
it("should convert text messages correctly", () => {
const message: ChatMessage = {
role: "user",
content: "Hello"
content: "Hello",
} as UserChatMessage;
const converted = bedrock["_convertMessage"](message);
expect(converted).toEqual({
@ -307,12 +338,14 @@ describe("Bedrock", () => {
const converted = bedrock["_convertMessage"](message);
expect(converted).toEqual({
role: "user",
content: [{
toolResult: {
toolUseId: "tool-1",
content: [{ text: "Tool result" }],
content: [
{
toolResult: {
toolUseId: "tool-1",
content: [{ text: "Tool result" }],
},
},
}],
],
});
});
@ -320,25 +353,29 @@ describe("Bedrock", () => {
const message: ChatMessage = {
role: "assistant",
content: "",
toolCalls: [{
id: "tool-1",
type: "function" as const,
function: {
name: "test_tool",
arguments: '{"arg":"value"}',
toolCalls: [
{
id: "tool-1",
type: "function" as const,
function: {
name: "test_tool",
arguments: '{"arg":"value"}',
},
},
}],
],
};
const converted = bedrock["_convertMessage"](message);
expect(converted).toEqual({
role: "assistant",
content: [{
toolUse: {
toolUseId: "tool-1",
name: "test_tool",
input: { arg: "value" },
content: [
{
toolUse: {
toolUseId: "tool-1",
name: "test_tool",
input: { arg: "value" },
},
},
}],
],
});
});

View file

@ -292,9 +292,12 @@ class Bedrock extends BaseLLM {
const convertedMessages = this._convertMessages(messages);
const shouldCacheSystemMessage =
!!systemMessage && this.cacheBehavior?.cacheSystemMessage || this.completionOptions.promptCaching;
(!!systemMessage && this.cacheBehavior?.cacheSystemMessage) ||
this.completionOptions.promptCaching;
const enablePromptCaching =
shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation || this.completionOptions.promptCaching;
shouldCacheSystemMessage ||
this.cacheBehavior?.cacheConversation ||
this.completionOptions.promptCaching;
const shouldCacheToolsConfig = this.completionOptions.promptCaching;
// Add header for prompt caching
@ -306,21 +309,24 @@ class Bedrock extends BaseLLM {
}
const supportsTools =
(this.capabilities?.tools || PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? false;
(this.capabilities?.tools ||
PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ??
false;
let toolConfig = supportsTools && options.tools
? {
tools: options.tools.map((tool) => ({
toolSpec: {
name: tool.function.name,
description: tool.function.description,
inputSchema: {
json: tool.function.parameters,
},
},
})),
} as ToolConfiguration
: undefined;
let toolConfig =
supportsTools && options.tools
? ({
tools: options.tools.map((tool) => ({
toolSpec: {
name: tool.function.name,
description: tool.function.description,
inputSchema: {
json: tool.function.parameters,
},
},
})),
} as ToolConfiguration)
: undefined;
if (toolConfig?.tools && shouldCacheToolsConfig) {
toolConfig.tools.push({ cachePoint: { type: "default" } });

View file

@ -1,6 +1,6 @@
import {
BedrockRuntimeClient,
InvokeModelWithResponseStreamCommand,
BedrockRuntimeClient,
InvokeModelWithResponseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";

View file

@ -12,7 +12,7 @@ class Cerebras extends OpenAI {
private static modelConversion: { [key: string]: string } = {
"llama3.1-8b": "llama3.1-8b",
"llama3.1-70b": "llama3.1-70b",
"llama-4-scout-17b-16e-instruct": "llama-4-scout-17b-16e-instruct"
"llama-4-scout-17b-16e-instruct": "llama-4-scout-17b-16e-instruct",
};
protected _convertModelName(model: string): string {
return Cerebras.modelConversion[model] ?? model;

View file

@ -1,270 +0,0 @@
import { streamResponse } from "@continuedev/fetch";
import { TRIAL_FIM_MODEL } from "../../config/onboarding.js";
import { getHeaders } from "../../continueServer/stubs/headers.js";
import { TRIAL_PROXY_URL } from "../../control-plane/client.js";
import {
ChatMessage,
Chunk,
CompletionOptions,
LLMOptions,
} from "../../index.js";
import { BaseLLM } from "../index.js";
class FreeTrial extends BaseLLM {
static providerName = "free-trial";
static defaultOptions: Partial<LLMOptions> | undefined = {
maxEmbeddingBatchSize: 128,
model: "voyage-code-2",
};
private ghAuthToken: string | undefined = undefined;
constructor(options: LLMOptions) {
super(options);
this.embeddingId = `${this.constructor.name}::${this.model}`;
}
setupGhAuthToken(ghAuthToken: string | undefined) {
this.ghAuthToken = ghAuthToken;
}
private async _getHeaders() {
if (!this.ghAuthToken) {
throw new Error(
"Please sign in with GitHub in order to use the free trial. If you'd like to use Continue without signing in, you can set up your own local model or API key.",
);
}
return {
"Content-Type": "application/json",
Authorization: `Bearer ${this.ghAuthToken}`,
...(await getHeaders()),
};
}
private async _countTokens(prompt: string, model: string, isPrompt: boolean) {
// Removed to reduce PostHog bill
// if (!Telemetry.client) {
// throw new Error(
// "In order to use the free trial, telemetry must be enabled so that we can monitor abuse. To enable telemetry, set \"allowAnonymousTelemetry\": true in config.json and make sure the box is checked in IDE settings. If you use your own model (local or API key), telemetry will never be required.",
// );
// }
// const event = isPrompt
// ? "free_trial_prompt_tokens"
// : "free_trial_completion_tokens";
// Telemetry.capture(event, {
// tokens: this.countTokens(prompt),
// model,
// });
}
private _convertArgs(options: CompletionOptions): any {
return {
model: options.model,
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
max_tokens: options.maxTokens,
stop:
options.model === TRIAL_FIM_MODEL
? options.stop
: options.stop?.slice(0, 2),
temperature: options.temperature,
top_p: options.topP,
};
}
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const args = this._convertArgs(this.collectArgs(options));
await this._countTokens(prompt, args.model, true);
const response = await this.fetch(`${TRIAL_PROXY_URL}/stream_complete`, {
method: "POST",
headers: await this._getHeaders(),
body: JSON.stringify({
prompt,
...args,
}),
signal,
});
let completion = "";
for await (const value of streamResponse(response)) {
yield value;
completion += value;
}
void this._countTokens(completion, args.model, false);
}
protected _convertMessage(message: ChatMessage) {
if (message.role === "tool") {
return {
role: "tool",
content: message.content,
tool_call_id: message.toolCallId,
};
}
if (typeof message.content === "string") {
return message;
}
const parts = message.content.map((part) => {
if (part.type === "imageUrl") {
return {
type: "image_url",
image_url: {
url: part.imageUrl.url,
detail: "low",
},
};
}
return {
type: "text",
text: part.text,
};
});
return {
...message,
content: parts,
};
}
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const args = this._convertArgs(this.collectArgs(options));
await this._countTokens(
messages.map((m) => m.content).join("\n"),
args.model,
true,
);
const response = await this.fetch(`${TRIAL_PROXY_URL}/stream_chat`, {
method: "POST",
headers: await this._getHeaders(),
body: JSON.stringify({
messages: messages.map(this._convertMessage),
...args,
}),
signal,
});
let completion = "";
for await (const chunk of streamResponse(response)) {
yield {
role: "assistant",
content: chunk,
};
completion += chunk;
}
await this._countTokens(completion, args.model, false);
}
supportsFim(): boolean {
return this.model === "codestral-latest";
}
async *_streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const args = this._convertArgs(this.collectArgs(options));
try {
const resp = await this.fetch(`${TRIAL_PROXY_URL}/stream_fim`, {
method: "POST",
headers: await this._getHeaders(),
body: JSON.stringify({
prefix,
suffix,
...args,
}),
signal,
});
let completion = "";
for await (const value of streamResponse(resp)) {
yield value;
completion += value;
}
await this._countTokens(completion, args.model, false);
} catch (e: any) {
if (e.message.startsWith("HTTP 429")) {
throw new Error(
"You have reached the 2000 request limit for the autocomplete free trial. To continue using autocomplete, please set up a local model or your own Codestral API key.",
);
}
throw e;
}
}
async listModels(): Promise<string[]> {
return [
"codestral-latest",
"claude-3-5-sonnet-latest",
"llama3.1-405b",
"llama3.1-70b",
"gpt-4o",
"gpt-3.5-turbo",
"claude-3-5-haiku-latest",
"gemini-1.5-pro-latest",
];
}
protected async _embed(chunks: string[]): Promise<number[][]> {
const resp = await this.fetch(new URL("embeddings", TRIAL_PROXY_URL), {
method: "POST",
body: JSON.stringify({
input: chunks,
model: this.model,
}),
headers: {
"Content-Type": "application/json",
...(await getHeaders()),
},
});
if (resp.status !== 200) {
throw new Error(`Failed to embed: ${resp.status} ${await resp.text()}`);
}
const data = (await resp.json()) as any;
return data.embeddings;
}
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
if (chunks.length === 0) {
return [];
}
const resp = await this.fetch(new URL("rerank", TRIAL_PROXY_URL), {
method: "POST",
headers: {
"Content-Type": "application/json",
...(await getHeaders()),
},
body: JSON.stringify({
query,
documents: chunks.map((chunk) => chunk.content),
}),
});
if (!resp.ok) {
throw new Error(await resp.text());
}
const data = (await resp.json()) as any;
const results = data.sort((a: any, b: any) => a.index - b.index);
return results.map((result: any) => result.relevance_score);
}
}
export default FreeTrial;

View file

@ -342,13 +342,13 @@ class Gemini extends BaseLLM {
throw new Error(data.error.message);
}
// Check for existence of each level before accessing the final 'text' property
const content = data?.candidates?.[0]?.content;
if (content) {
// In case of max tokens reached, gemini will sometimes return content with no parts, even though that doesn't match the API spec
const contentParts = data?.candidates?.[0]?.content?.parts;
if (contentParts) {
const textParts: MessagePart[] = [];
const toolCalls: ToolCallDelta[] = [];
for (const part of content.parts) {
for (const part of contentParts) {
if ("text" in part) {
textParts.push({ type: "text", text: part.text });
} else if ("functionCall" in part) {

View file

@ -38,11 +38,11 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (this.apiKey) {
headers["Authorization"] = `Bearer ${this.apiKey}`;
}
const resp = await this.fetch(new URL("embed", this.apiBase), {
method: "POST",
body: JSON.stringify({

View file

@ -35,7 +35,7 @@ class LlamaCpp extends BaseLLM {
...this.requestOptions?.headers,
};
const resp = await this.fetch(new URL("completions", this.apiBase), {
const resp = await this.fetch(new URL("completion", this.apiBase), {
method: "POST",
headers,
body: JSON.stringify({

View file

@ -6,9 +6,9 @@ import OpenAI from "./OpenAI.js";
class NCompass extends OpenAI {
static providerName = "ncompass";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.ncompass.tech/v1"
apiBase: "https://api.ncompass.tech/v1",
};
static embeddingsApiEndpoint: "https://api.gcp.ncompass.tech/v1/embeddings"
static embeddingsApiEndpoint: "https://api.gcp.ncompass.tech/v1/embeddings";
private static modelConversion: { [key: string]: string } = {
"qwen2.5-coder-7b": "Qwen/Qwen2.5-Coder-7B-Instruct",
@ -30,7 +30,12 @@ class NCompass extends OpenAI {
}
protected _getHeaders() {
const headers = super._getHeaders() as { "Content-Type": string; Authorization: string; "api-key": string; Accept?: string };
const headers = super._getHeaders() as {
"Content-Type": string;
Authorization: string;
"api-key": string;
Accept?: string;
};
headers["Accept"] = "text/event-stream";
return headers;
}
@ -56,7 +61,6 @@ class NCompass extends OpenAI {
const data = (await resp.json()) as any;
return data.data.map((result: { embedding: number[] }) => result.embedding);
}
}
export default NCompass;

View file

@ -10,7 +10,7 @@ class Novita extends OpenAI {
private static MODEL_IDS: { [name: string]: string } = {
"deepseek-r1": "deepseek/deepseek-r1",
"deepseek_v3": "deepseek/deepseek_v3",
deepseek_v3: "deepseek/deepseek_v3",
"llama3-8b": "meta-llama/llama-3-8b-instruct",
"llama3-70b": "meta-llama/llama-3-70b-instruct",
"llama3.1-8b": "meta-llama/llama-3.1-8b-instruct",

View file

@ -20,20 +20,23 @@ export class OVHcloud extends OpenAI {
"mistral-7b": "Mistral-7B-Instruct-v0.3",
"mistral-8x7b": "Mixtral-8x7B-Instruct-v0.1",
"mistral-nemo": "Mistral-Nemo-Instruct-2407",
"DeepSeek-R1-Distill-Llama-70B": "DeepSeek-R1-Distill-Llama-70B"
"DeepSeek-R1-Distill-Llama-70B": "DeepSeek-R1-Distill-Llama-70B",
};
protected _convertModelName(model: string) {
return OVHcloud.MODEL_IDS[model] || this.model;
}
protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]): ChatCompletionCreateParams {
protected _convertArgs(
options: CompletionOptions,
messages: ChatMessage[],
): ChatCompletionCreateParams {
const modifiedOptions = {
...options,
model: this._convertModelName(options.model)
model: this._convertModelName(options.model),
};
return super._convertArgs(modifiedOptions, messages);
}
}
export default OVHcloud;
export default OVHcloud;

View file

@ -1,7 +1,7 @@
import {
InvokeEndpointCommand,
InvokeEndpointWithResponseStreamCommand,
SageMakerRuntimeClient,
InvokeEndpointCommand,
InvokeEndpointWithResponseStreamCommand,
SageMakerRuntimeClient,
} from "@aws-sdk/client-sagemaker-runtime";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";

View file

@ -3,7 +3,6 @@ import OpenAI from "./OpenAI";
import { LLMOptions, CompletionOptions, ChatMessage } from "../../index.js";
import { ChatCompletionCreateParams } from "openai/resources/index";
class Scaleway extends OpenAI {
static providerName = "scaleway";
static defaultOptions: Partial<LLMOptions> = {
@ -17,17 +16,20 @@ class Scaleway extends OpenAI {
"llama3.1-70b": "llama-3.1-70b-instruct",
"mistral-nemo": "mistral-nemo-instruct-2407",
"qwen2.5-coder-32b": "qwen2.5-coder-32b-instruct",
"pixtral": "pixtral-12b-2409",
pixtral: "pixtral-12b-2409",
};
protected _convertModelName(model: string) {
return Scaleway.MODEL_IDS[model] || this.model;
}
protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]): ChatCompletionCreateParams {
protected _convertArgs(
options: CompletionOptions,
messages: ChatMessage[],
): ChatCompletionCreateParams {
// Convert model name in the options before passing to parent
const modifiedOptions = {
...options,
model: this._convertModelName(options.model)
model: this._convertModelName(options.model),
};
return super._convertArgs(modifiedOptions, messages);
}

View file

@ -9,14 +9,22 @@ class Venice extends OpenAI {
apiBase: "https://api.venice.ai/api/v1",
};
protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]): ChatCompletionCreateParams {
const finalOptions = super._convertArgs(options, messages) as ChatCompletionCreateParams & { venice_parameters?: any };
if ("venice_parameters" in options && typeof options.venice_parameters === "object") {
protected _convertArgs(
options: CompletionOptions,
messages: ChatMessage[],
): ChatCompletionCreateParams {
const finalOptions = super._convertArgs(
options,
messages,
) as ChatCompletionCreateParams & { venice_parameters?: any };
if (
"venice_parameters" in options &&
typeof options.venice_parameters === "object"
) {
finalOptions.venice_parameters = { ...options.venice_parameters };
}
return finalOptions;
}
}
export default Venice;
export default Venice;

View file

@ -23,7 +23,6 @@ import Deepseek from "./Deepseek";
import Docker from "./Docker";
import Fireworks from "./Fireworks";
import Flowise from "./Flowise";
import FreeTrial from "./FreeTrial";
import FunctionNetwork from "./FunctionNetwork";
import Gemini from "./Gemini";
import Groq from "./Groq";
@ -67,7 +66,6 @@ import xAI from "./xAI";
export const LLMClasses = [
Anthropic,
Cohere,
FreeTrial,
FunctionNetwork,
Gemini,
Llamafile,

View file

@ -85,6 +85,12 @@ class ContinueProxy extends OpenAI {
}
supportsCompletions(): boolean {
// This was a hotfix and contains duplicate logic from class-specific completion support methods
if (this.underlyingProviderName === "vllm") {
return true;
}
// other providers that don't support completions include groq, mistral, nvidia, deepseek, etc.
// For now disabling all except vllm
return false;
}

View file

@ -1,6 +1,9 @@
/* eslint-disable max-lines-per-function */
import { ContextItemWithId, RuleWithSource, UserChatMessage } from "../..";
import { getSystemMessageWithRules, shouldApplyRule } from "./getSystemMessageWithRules";
import {
getSystemMessageWithRules,
shouldApplyRule,
} from "./getSystemMessageWithRules";
describe("getSystemMessageWithRules", () => {
const baseSystemMessage = "Base system message";
@ -450,7 +453,8 @@ describe("getSystemMessageWithRules", () => {
it("should include rules with alwaysApply: false when globs match", () => {
const userMessage: UserChatMessage = {
role: "user",
content: "```tsx Component.tsx\nexport const Component = () => <div>Hello</div>;\n```",
content:
"```tsx Component.tsx\nexport const Component = () => <div>Hello</div>;\n```",
};
const result = getSystemMessageWithRules({
@ -701,14 +705,18 @@ describe("shouldApplyRule", () => {
it("should return true when alwaysApply is true, regardless of file paths", () => {
expect(shouldApplyRule(ruleAlwaysApplyTrue, [])).toBe(true);
expect(shouldApplyRule(ruleAlwaysApplyTrue, ["src/main.js"])).toBe(true);
expect(shouldApplyRule(ruleAlwaysApplyTrue, ["Component.tsx"])).toBe(true);
expect(shouldApplyRule(ruleAlwaysApplyTrue, ["Component.tsx"])).toBe(
true,
);
});
it("should use glob matching when alwaysApply is false", () => {
// Should apply when globs match
expect(shouldApplyRule(ruleAlwaysApplyFalse, ["src/main.ts"])).toBe(true);
expect(shouldApplyRule(ruleAlwaysApplyFalse, ["Component.tsx"])).toBe(true);
expect(shouldApplyRule(ruleAlwaysApplyFalse, ["Component.tsx"])).toBe(
true,
);
// Should not apply when globs don't match
expect(shouldApplyRule(ruleAlwaysApplyFalse, ["script.py"])).toBe(false);
expect(shouldApplyRule(ruleAlwaysApplyFalse, [])).toBe(false);
@ -716,7 +724,9 @@ describe("shouldApplyRule", () => {
it("should return false when alwaysApply is false and no globs specified", () => {
expect(shouldApplyRule(ruleAlwaysApplyFalseNoGlobs, [])).toBe(false);
expect(shouldApplyRule(ruleAlwaysApplyFalseNoGlobs, ["any-file.js"])).toBe(false);
expect(
shouldApplyRule(ruleAlwaysApplyFalseNoGlobs, ["any-file.js"]),
).toBe(false);
});
});
@ -724,7 +734,9 @@ describe("shouldApplyRule", () => {
it("should return true for rules without globs regardless of file paths", () => {
expect(shouldApplyRule(ruleWithoutGlobs, [])).toBe(true);
expect(shouldApplyRule(ruleWithoutGlobs, ["src/main.js"])).toBe(true);
expect(shouldApplyRule(ruleWithoutGlobs, ["Component.tsx", "utils.py"])).toBe(true);
expect(
shouldApplyRule(ruleWithoutGlobs, ["Component.tsx", "utils.py"]),
).toBe(true);
});
it("should return false for rules with globs when no file paths are provided", () => {
@ -734,12 +746,16 @@ describe("shouldApplyRule", () => {
it("should return true for rules with globs when matching file paths are provided", () => {
expect(shouldApplyRule(ruleWithGlobs, ["Component.tsx"])).toBe(true);
expect(shouldApplyRule(ruleWithGlobs, ["src/main.ts"])).toBe(true);
expect(shouldApplyRule(ruleWithGlobs, ["utils.js", "Component.tsx"])).toBe(true);
expect(
shouldApplyRule(ruleWithGlobs, ["utils.js", "Component.tsx"]),
).toBe(true);
});
it("should return false for rules with globs when no matching file paths are provided", () => {
expect(shouldApplyRule(ruleWithGlobs, ["utils.py"])).toBe(false);
expect(shouldApplyRule(ruleWithGlobs, ["main.js", "script.rb"])).toBe(false);
expect(shouldApplyRule(ruleWithGlobs, ["main.js", "script.rb"])).toBe(
false,
);
});
});
@ -760,19 +776,39 @@ describe("shouldApplyRule", () => {
it("should handle array of glob patterns", () => {
expect(shouldApplyRule(ruleWithArrayGlobs, ["src/main.ts"])).toBe(true);
expect(shouldApplyRule(ruleWithArrayGlobs, ["tests/unit.test.js"])).toBe(true);
expect(shouldApplyRule(ruleWithArrayGlobs, ["config/settings.json"])).toBe(false);
expect(shouldApplyRule(ruleWithArrayGlobs, ["tests/unit.test.js"])).toBe(
true,
);
expect(
shouldApplyRule(ruleWithArrayGlobs, ["config/settings.json"]),
).toBe(false);
});
it("should handle string glob patterns", () => {
expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.py"])).toBe(true);
expect(shouldApplyRule(ruleWithSpecificPattern, ["src/models/user.py"])).toBe(true);
expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.js"])).toBe(false);
expect(
shouldApplyRule(ruleWithSpecificPattern, ["src/models/user.py"]),
).toBe(true);
expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.js"])).toBe(
false,
);
});
it("should return true if any file path matches when multiple paths provided", () => {
expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.js", "models.py", "config.json"])).toBe(true);
expect(shouldApplyRule(ruleWithGlobs, ["utils.py", "Component.tsx", "script.rb"])).toBe(true);
expect(
shouldApplyRule(ruleWithSpecificPattern, [
"utils.js",
"models.py",
"config.json",
]),
).toBe(true);
expect(
shouldApplyRule(ruleWithGlobs, [
"utils.py",
"Component.tsx",
"script.rb",
]),
).toBe(true);
});
});
@ -784,7 +820,7 @@ describe("shouldApplyRule", () => {
globs: [],
source: "rules-block",
};
// Empty array should be treated as "no globs" (truthy check fails)
expect(shouldApplyRule(ruleWithEmptyGlobs, ["any-file.js"])).toBe(false);
});
@ -796,7 +832,7 @@ describe("shouldApplyRule", () => {
globs: undefined,
source: "rules-block",
};
expect(shouldApplyRule(ruleUndefinedGlobs, ["any-file.js"])).toBe(true);
expect(shouldApplyRule(ruleUndefinedGlobs, [])).toBe(true);
});

View file

@ -95,11 +95,11 @@ function llama2TemplateMessages(msgs: ChatMessage[]): string {
// Llama2 template with added \n to prevent Codestral from continuing user message
function codestralTemplateMessages(msgs: ChatMessage[]): string {
let template = llama2TemplateMessages(msgs);
if (template.length === 0) {
return template;
}
return template + "\n";
let template = llama2TemplateMessages(msgs);
if (template.length === 0) {
return template;
}
return template + "\n";
}
function anthropicTemplateMessages(messages: ChatMessage[]): string {

View file

@ -1,13 +1,13 @@
import { getSecureID } from '../getSecureID';
import { getSecureID } from "../getSecureID";
// Mock the crypto.randomUUID function
const mockRandomUUID = jest.fn();
global.crypto = {
...global.crypto,
randomUUID: mockRandomUUID
randomUUID: mockRandomUUID,
};
describe('getSecureID', () => {
describe("getSecureID", () => {
beforeEach(() => {
// Reset the static property before each test
(getSecureID as any).uuid = undefined;
@ -15,16 +15,16 @@ describe('getSecureID', () => {
// Reset the mock implementation
mockRandomUUID.mockReset();
// Setup a mock implementation that returns a fixed value for testing
mockRandomUUID.mockReturnValue('test-uuid-1234');
mockRandomUUID.mockReturnValue("test-uuid-1234");
});
test('should generate a UUID on first call', () => {
test("should generate a UUID on first call", () => {
const result = getSecureID();
expect(mockRandomUUID).toHaveBeenCalledTimes(1);
expect(result).toBe('<!-- SID: test-uuid-1234 -->');
expect(result).toBe("<!-- SID: test-uuid-1234 -->");
});
test('should reuse the same UUID on subsequent calls', () => {
test("should reuse the same UUID on subsequent calls", () => {
const firstResult = getSecureID();
const secondResult = getSecureID();
@ -33,17 +33,17 @@ describe('getSecureID', () => {
// Both results should be identical
expect(firstResult).toBe(secondResult);
expect(firstResult).toBe('<!-- SID: test-uuid-1234 -->');
expect(firstResult).toBe("<!-- SID: test-uuid-1234 -->");
});
test('should maintain the same UUID across different test cases if not reset', () => {
test("should maintain the same UUID across different test cases if not reset", () => {
// Don't reset the UUID here to test persistence
(getSecureID as any).uuid = 'persistent-uuid';
(getSecureID as any).uuid = "persistent-uuid";
const result = getSecureID();
// No new UUID should be generated
expect(mockRandomUUID).not.toHaveBeenCalled();
expect(result).toBe('<!-- SID: persistent-uuid -->');
expect(result).toBe("<!-- SID: persistent-uuid -->");
});
});
});

View file

@ -17,7 +17,7 @@ describe("extractPathsFromCodeBlocks", () => {
});
it("should handle multiple code blocks with different formats", () => {
const content =
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```";
@ -32,4 +32,4 @@ describe("extractPathsFromCodeBlocks", () => {
const content = "```typescript\nconst x = 1;\n```";
expect(extractPathsFromCodeBlocks(content)).toEqual([]);
});
});
});

View file

@ -0,0 +1,286 @@
import { ConfigHandler } from "../config/ConfigHandler.js";
import { IDE, ILLM } from "../index.js";
import OpenAI from "../llm/llms/OpenAI.js";
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
import { shouldCompleteMultiline } from "../autocomplete/classification/shouldCompleteMultiline.js";
import { ContextRetrievalService } from "../autocomplete/context/ContextRetrievalService.js";
import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js";
import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js";
import { postprocessCompletion } from "../autocomplete/postprocessing/index.js";
import { shouldPrefilter } from "../autocomplete/prefiltering/index.js";
import { getAllSnippets } from "../autocomplete/snippets/index.js";
import { renderPrompt } from "../autocomplete/templating/index.js";
import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebouncer.js";
import { AutocompleteLoggingService } from "../autocomplete/util/AutocompleteLoggingService.js";
import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js";
import { HelperVars } from "../autocomplete/util/HelperVars.js";
import {
AutocompleteInput,
AutocompleteOutcome,
} from "../autocomplete/util/types.js";
const autocompleteCache = AutocompleteLruCache.get();
// Errors that can be expected on occasion even during normal functioning should not be shown.
// Not worth disrupting the user to tell them that a single autocomplete request didn't go through
const ERRORS_TO_IGNORE = [
// From Ollama
"unexpected server status",
"operation was aborted",
];
export class NextEditProvider {
private autocompleteCache = AutocompleteLruCache.get();
public errorsShown: Set<string> = new Set();
private bracketMatchingService = new BracketMatchingService();
private debouncer = new AutocompleteDebouncer();
private completionStreamer: CompletionStreamer;
private loggingService = new AutocompleteLoggingService();
private contextRetrievalService: ContextRetrievalService;
constructor(
private readonly configHandler: ConfigHandler,
private readonly ide: IDE,
private readonly _injectedGetLlm: () => Promise<ILLM | undefined>,
private readonly _onError: (e: any) => void,
private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction,
) {
this.completionStreamer = new CompletionStreamer(this.onError.bind(this));
this.contextRetrievalService = new ContextRetrievalService(this.ide);
}
private async _prepareLlm(): Promise<ILLM | undefined> {
const llm = await this._injectedGetLlm();
if (!llm) {
return undefined;
}
// Temporary fix for JetBrains autocomplete bug as described in https://github.com/continuedev/continue/pull/3022
if (llm.model === undefined && llm.completionOptions?.model !== undefined) {
llm.model = llm.completionOptions.model;
}
// Ignore empty API keys for Mistral since we currently write
// a template provider without one during onboarding
if (llm.providerName === "mistral" && llm.apiKey === "") {
return undefined;
}
// Set temperature (but don't override)
if (llm.completionOptions.temperature === undefined) {
llm.completionOptions.temperature = 0.01;
}
if (llm instanceof OpenAI) {
llm.useLegacyCompletionsEndpoint = true;
}
// TODO: Resolve import error with TRIAL_FIM_MODEL
// else if (
// llm.providerName === "free-trial" &&
// llm.model !== TRIAL_FIM_MODEL
// ) {
// llm.model = TRIAL_FIM_MODEL;
// }
return llm;
}
private onError(e: any) {
if (
ERRORS_TO_IGNORE.some((err) =>
typeof e === "string" ? e.includes(err) : e?.message?.includes(err),
)
) {
return;
}
console.warn("Error generating autocompletion: ", e);
if (!this.errorsShown.has(e.message)) {
this.errorsShown.add(e.message);
this._onError(e);
}
}
public cancel() {
this.loggingService.cancel();
}
public accept(completionId: string) {
const outcome = this.loggingService.accept(completionId);
if (!outcome) {
return;
}
this.bracketMatchingService.handleAcceptedCompletion(
outcome.completion,
outcome.filepath,
);
}
public markDisplayed(completionId: string, outcome: AutocompleteOutcome) {
this.loggingService.markDisplayed(completionId, outcome);
}
private async _getAutocompleteOptions() {
const { config } = await this.configHandler.loadConfig();
const options = {
...DEFAULT_AUTOCOMPLETE_OPTS,
...config?.tabAutocompleteOptions,
};
return options;
}
public async provideInlineCompletionItems(
input: AutocompleteInput,
token: AbortSignal | undefined,
): Promise<AutocompleteOutcome | undefined> {
try {
// Create abort signal if not given
if (!token) {
const controller = this.loggingService.createAbortController(
input.completionId,
);
token = controller.signal;
}
const startTime = Date.now();
const options = await this._getAutocompleteOptions();
// Debounce
if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) {
return undefined;
}
const llm = await this._prepareLlm();
if (!llm) {
return undefined;
}
if (llm.promptTemplates?.autocomplete) {
options.template = llm.promptTemplates.autocomplete as string;
}
const helper = await HelperVars.create(
input,
options,
llm.model,
this.ide,
);
if (await shouldPrefilter(helper, this.ide)) {
return undefined;
}
const [snippetPayload, workspaceDirs] = await Promise.all([
getAllSnippets({
helper,
ide: this.ide,
getDefinitionsFromLsp: this.getDefinitionsFromLsp,
contextRetrievalService: this.contextRetrievalService,
}),
this.ide.getWorkspaceDirs(),
]);
const { prompt, prefix, suffix, completionOptions } = renderPrompt({
snippetPayload,
workspaceDirs,
helper,
});
// Completion
let completion: string | undefined = "";
const cache = await autocompleteCache;
const cachedCompletion = helper.options.useCache
? await cache.get(helper.prunedPrefix)
: undefined;
let cacheHit = false;
if (cachedCompletion) {
// Cache
cacheHit = true;
completion = cachedCompletion;
} else {
const multiline =
!helper.options.transform || shouldCompleteMultiline(helper);
const completionStream =
this.completionStreamer.streamCompletionWithFilters(
token,
llm,
prefix,
suffix,
prompt,
multiline,
completionOptions,
helper,
);
for await (const update of completionStream) {
completion += update;
}
// Don't postprocess if aborted
if (token.aborted) {
return undefined;
}
const processedCompletion = helper.options.transform
? postprocessCompletion({
completion,
prefix: helper.prunedPrefix,
suffix: helper.prunedSuffix,
llm,
})
: completion;
completion = processedCompletion;
}
if (!completion) {
return undefined;
}
const outcome: AutocompleteOutcome = {
time: Date.now() - startTime,
completion,
prefix,
suffix,
prompt,
modelProvider: llm.underlyingProviderName,
modelName: llm.model,
completionOptions,
cacheHit,
filepath: helper.filepath,
numLines: completion.split("\n").length,
completionId: helper.input.completionId,
gitRepo: await this.ide.getRepoName(helper.filepath),
uniqueId: await this.ide.getUniqueId(),
timestamp: Date.now(),
...helper.options,
};
//////////
// Save to cache
if (!outcome.cacheHit && helper.options.useCache) {
(await this.autocompleteCache)
.put(outcome.prefix, outcome.completion)
.catch((e) => console.warn(`Failed to save to cache: ${e.message}`));
}
// When using the JetBrains extension, Mark as displayed
const ideType = (await this.ide.getIdeInfo()).ideType;
if (ideType === "jetbrains") {
this.markDisplayed(input.completionId, outcome);
}
return outcome;
} catch (e: any) {
this.onError(e);
} finally {
this.loggingService.deleteAbortController(input.completionId);
}
}
}

View file

@ -0,0 +1 @@
export const IS_NEXT_EDIT_ACTIVE = false;

1786
core/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -4,6 +4,7 @@
"description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js",
"scripts": {
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest",
"vitest": "vitest run LocalPlatformClient",
"test:coverage": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --coverage && open ./coverage/lcov-report/index.html",
"tsc:check": "tsc -p ./ --noEmit",
"build:npm": "tsc -p ./tsconfig.npm.json",
@ -41,7 +42,8 @@
"onnxruntime-common": "1.14.0",
"onnxruntime-web": "1.14.0",
"ts-jest": "^29.1.1",
"typescript": "^5.6.3"
"typescript": "^5.6.3",
"vitest": "^3.1.4"
},
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
@ -49,7 +51,7 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.10",
"@continuedev/fetch": "^1.0.13",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.32",
"@modelcontextprotocol/sdk": "^1.12.0",

View file

@ -1,4 +1,5 @@
import { ContinueSDK, SlashCommand } from "../..";
import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache";
import { renderChatMessage } from "../../util/messageContent";
import { getLastNPathParts } from "../../util/uri";
import { parsePromptFileV1V2 } from "../v2/parsePromptFileV1V2";
@ -12,13 +13,6 @@ export function extractName(preamble: { name?: string }, path: string): string {
return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
}
export function extractUserInput(input: string, commandName: string): string {
if (input.startsWith(`/${commandName}`)) {
return input.slice(commandName.length + 1).trimStart();
}
return input;
}
async function renderPromptV1(
prompt: string,
context: ContinueSDK,
@ -32,8 +26,8 @@ async function renderPromptV1(
// A few context providers that don't need to be in config.json to work in .prompt files
if (helpers?.find((helper) => helper[0] === "diff")) {
const diff = await context.ide.getDiff(true);
inputData.diff = diff.join("\n");
const diffs = await getDiffsFromCache(context.ide);
inputData.diff = diffs.join("\n");
}
if (helpers?.find((helper) => helper[0] === "currentFile")) {
const currentFile = await context.ide.getCurrentFile();
@ -65,10 +59,9 @@ export function slashCommandFromPromptFileV1(
prompt,
promptFile: path,
run: async function* (context) {
const userInput = extractUserInput(context.input, name);
const [_, renderedPrompt] = await renderPromptFileV2(prompt, {
config: context.config,
fullInput: userInput,
fullInput: context.input,
embeddingsProvider: context.config.modelsByRole.embed[0],
reranker: context.config.modelsByRole.rerank[0],
llm: context.llm,
@ -84,18 +77,6 @@ export function slashCommandFromPromptFileV1(
systemMessage,
);
if (systemMessage) {
const currentSystemMsg = messages.find((msg) => msg.role === "system");
if (currentSystemMsg) {
currentSystemMsg.content = systemMessage;
} else {
messages.unshift({
role: "system",
content: systemMessage,
});
}
}
for await (const chunk of context.llm.streamChat(
messages,
new AbortController().signal,

View file

@ -1,6 +1,6 @@
import { ContextItem, ContextProviderExtras } from "../..";
import { contextProviderClassFromName } from "../../context/providers";
import URLContextProvider from "../../context/providers/URLContextProvider";
import { getUrlContextItems } from "../../context/providers/URLContextProvider";
import { resolveRelativePathInDir } from "../../util/ideUtils";
import { getUriPathBasename } from "../../util/uri";
@ -33,7 +33,7 @@ async function resolveAttachment(
if (name.endsWith(".prompt")) {
// Recurse
const [items, _] = await renderPromptFileV2(
await extras.ide.readFile(name),
await extras.ide.readFile(resolvedFileUri),
extras,
);
subItems.push(...items);
@ -52,10 +52,7 @@ async function resolveAttachment(
// URLs
if (name.startsWith("http")) {
const items = await new URLContextProvider({}).getContextItems(
name,
extras,
);
const items = getUrlContextItems(name, extras.fetch);
return items;
}
@ -75,10 +72,13 @@ export async function renderPromptFileV2(
});
const contextItems = (await Promise.all(contextItemsPromises)).flat();
const renderedPrompt =
contextItems.map((item) => item.content).join("\n\n") +
"\n\n" +
renderedBody;
const renderedPrompt = [
...contextItems.map((item) => item.content),
renderedBody,
extras.fullInput,
]
.join("\n\n")
.trim();
return [contextItems, renderedPrompt];
}

View file

@ -0,0 +1,175 @@
import { ContextProviderExtras, ILLM, RangeInFile } from "../..";
import { testConfigHandler, testIde } from "../../test/fixtures";
import {
addToTestDir,
setUpTestDir,
tearDownTestDir,
} from "../../test/testDir";
import { renderPromptFileV2 } from "./renderPromptFile";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock(
import("../../context/providers/URLContextProvider"),
async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
getUrlContextItems: vi.fn().mockResolvedValue([
{
description: "https://example.com",
content: "Example Content",
name: "Example site",
uri: {
type: "url",
value: "https://example.com",
},
},
]),
};
},
);
describe("renderPromptFileV2", () => {
let extras: ContextProviderExtras;
const mockGetContextItems = vi.fn().mockResolvedValue([
{
name: "custom",
content: "Custom provider content",
description: "Custom provider",
},
]);
beforeEach(async () => {
const { config } = await testConfigHandler.loadConfig();
// Setup mock extras
extras = {
config: {
...config!,
contextProviders: [
{
description: {
type: "normal",
title: "CustomProvider",
displayTitle: "Custom Provider",
description: "A custom context provider",
},
loadSubmenuItems: vi.fn().mockResolvedValue([]),
getContextItems: mockGetContextItems,
},
],
},
fullInput: "User input",
embeddingsProvider: null,
reranker: null,
llm: {} as ILLM,
ide: testIde,
selectedCode: [] as RangeInFile[],
fetch: vi.fn(),
};
// Clear all mocks
vi.clearAllMocks();
setUpTestDir();
});
afterEach(() => {
tearDownTestDir();
});
it("should render a prompt file with no attachments", async () => {
const rawContent = "Simple prompt with no attachments";
const [contextItems, renderedPrompt] = await renderPromptFileV2(
rawContent,
extras,
);
expect(contextItems).toHaveLength(0);
expect(renderedPrompt).toBe(
"Simple prompt with no attachments\n\nUser input",
);
});
it("should handle URL attachments", async () => {
const rawContent = "Content with URL @https://example.com";
const [contextItems, renderedPrompt] = await renderPromptFileV2(
rawContent,
extras,
);
expect(contextItems).toHaveLength(1);
expect(renderedPrompt).toContain("Example Content");
});
it("should resolve file attachments", async () => {
const rawContent = "Content with file attachment @test.txt";
addToTestDir([["test.txt", "File content"]]);
const [contextItems, renderedPrompt] = await renderPromptFileV2(
rawContent,
extras,
);
expect(contextItems).toHaveLength(1);
expect(renderedPrompt).toContain("```test.txt\nFile content\n```");
expect(renderedPrompt).toContain("Content with file attachment @test.txt");
});
it("should handle nested prompt files", async () => {
const rawContent = "Main prompt with nested @nested.prompt";
addToTestDir([
["nested.prompt", "Nested prompt content with @CustomProvider"],
]);
const [contextItems, renderedPrompt] = await renderPromptFileV2(
rawContent,
extras,
);
expect(renderedPrompt).toContain("Custom provider content");
});
it("should handle custom context providers", async () => {
const rawContent = "Content with custom provider @CustomProvider";
const [contextItems, renderedPrompt] = await renderPromptFileV2(
rawContent,
extras,
);
expect(contextItems).toHaveLength(1);
expect(renderedPrompt).toContain("Custom provider content");
expect(mockGetContextItems).toHaveBeenCalled();
});
it("should handle multiple attachments", async () => {
const rawContent = "Content with @file1.txt and @file2.txt";
addToTestDir([
["file1.txt", "Content 1"],
["file2.txt", "Content 2"],
]);
const [contextItems, renderedPrompt] = await renderPromptFileV2(
rawContent,
extras,
);
expect(contextItems).toHaveLength(2);
expect(renderedPrompt).toContain("```file1.txt\nContent 1\n```");
expect(renderedPrompt).toContain("```file2.txt\nContent 2\n```");
});
it("should handle failed attachment resolutions gracefully", async () => {
const rawContent = "Content with @nonexistent";
const [contextItems, renderedPrompt] = await renderPromptFileV2(
rawContent,
extras,
);
expect(contextItems).toHaveLength(0);
expect(renderedPrompt).toBe("Content with @nonexistent\n\nUser input");
});
});

View file

@ -34,6 +34,7 @@ import {
} from "../";
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager";
import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes";
import { FreeTrialStatus } from "../control-plane/client";
export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart";
@ -198,6 +199,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
];
"clipboardCache/add": [{ content: string }, void];
"controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void];
"controlPlane/getFreeTrialStatus": [undefined, FreeTrialStatus | null];
isItemTooBig: [{ item: ContextItemWithId }, boolean];
didChangeControlPlaneSessionInfo: [
{ sessionInfo: ControlPlaneSessionInfo | undefined },
@ -205,4 +207,5 @@ export type ToCoreFromIdeOrWebviewProtocol = {
];
"process/markAsBackgrounded": [{ toolCallId: string }, void];
"process/isBackgrounded": [{ toolCallId: string }, boolean];
"mdm/setLicenseKey": [{ licenseKey: string }, boolean];
};

View file

@ -92,7 +92,6 @@ export type ToIdeFromWebviewOrCoreProtocol = {
gotoDefinition: [{ location: Location }, RangeInFile[]];
getGitHubAuthToken: [GetGhTokenArgs, string | undefined];
getControlPlaneSessionInfo: [
{ silent: boolean; useOnboarding: boolean },
ControlPlaneSessionInfo | undefined,

View file

@ -44,7 +44,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
];
"jetbrains/getColors": [undefined, Record<string, string | null | undefined>];
"vscode/openMoveRightMarkdown": [undefined, void];
setGitHubAuthToken: [{ token: string }, void];
acceptDiff: [AcceptOrRejectDiffPayload, void];
rejectDiff: [AcceptOrRejectDiffPayload, void];
"edit/sendPrompt": [

View file

@ -1,5 +1,5 @@
import { FromIdeProtocol } from "..";
import { GetGhTokenArgs, ToIdeFromWebviewOrCoreProtocol } from "../ide";
import { ToIdeFromWebviewOrCoreProtocol } from "../ide";
import type {
ContinueRcJson,
@ -50,9 +50,6 @@ export class MessageIde implements IDE {
getIdeSettings(): Promise<IdeSettings> {
return this.request("getIdeSettings", undefined);
}
getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined> {
return this.request("getGitHubAuthToken", args);
}
getFileStats(files: string[]): Promise<FileStatsMap> {
return this.request("getFileStats", { files });
}

View file

@ -34,10 +34,6 @@ export class ReverseMessageIde {
}
private initializeListeners() {
this.on("getGitHubAuthToken", (data) => {
return this.ide.getGitHubAuthToken(data);
});
this.on("getFileStats", (data) => {
return this.ide.getFileStats(data.files);
});

View file

@ -1,7 +1,7 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import os from 'os';
import os from "os";
/**
* Get the preferred shell for the current platform
@ -10,17 +10,17 @@ import os from 'os';
export function getPreferredShell(): string {
const platform = os.platform();
if (platform === 'win32') {
return process.env.COMSPEC || 'cmd.exe';
} else if (platform === 'darwin') {
return process.env.SHELL || '/bin/zsh';
if (platform === "win32") {
return process.env.COMSPEC || "cmd.exe";
} else if (platform === "darwin") {
return process.env.SHELL || "/bin/zsh";
} else {
// Linux and other Unix-like systems
return process.env.SHELL || '/bin/bash';
return process.env.SHELL || "/bin/bash";
}
}
export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform} and ${os.arch} and shell ${getPreferredShell()}.`
export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform} and ${os.arch} and shell ${getPreferredShell()}.`;
export const runTerminalCommandTool: Tool = {
type: "function",
@ -32,28 +32,27 @@ export const runTerminalCommandTool: Tool = {
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.RunTerminalCommand,
description:
`Run a terminal command in the current directory.\
description: `Run a terminal command in the current directory.\
The shell is not stateful and will not remember any previous commands.\
When a command is run in the background ALWAYS suggest using shell commands to stop it; NEVER suggest using Ctrl+C.\
When suggesting subsequent shell commands ALWAYS format them in shell command blocks.\
Do NOT perform actions requiring special/admin privileges.\
${PLATFORM_INFO}`,
parameters: {
type: "object",
required: ["command"],
properties: {
command: {
type: "string",
description:
"The command to run. This will be passed directly into the IDE shell.",
},
waitForCompletion: {
type: "boolean",
description:
"Whether to wait for the command to complete before returning. Default is true. Set to false to run the command in the background. Set to true to run the command in the foreground and wait to collect the output.",
},
parameters: {
type: "object",
required: ["command"],
properties: {
command: {
type: "string",
description:
"The command to run. This will be passed directly into the IDE shell.",
},
waitForCompletion: {
type: "boolean",
description:
"Whether to wait for the command to complete before returning. Default is true. Set to false to run the command in the background. Set to true to run the command in the foreground and wait to collect the output.",
},
},
},
},
};

View file

@ -17,26 +17,31 @@ describe("runTerminalCommandImpl", () => {
const mockGetWorkspaceDirs = jest.fn();
const mockOnPartialOutput = jest.fn();
const mockRunCommand = jest.fn();
// Use a simple approach to ensure background processes are terminated
let testPid: number | null = null;
// Create a temp directory for our tests
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'terminal-command-test-'));
const tempDir = fs.mkdtempSync(
path.join(os.tmpdir(), "terminal-command-test-"),
);
beforeEach(() => {
jest.resetAllMocks();
// Setup backgrounded processes handling - don't mock, just make sure it's empty
// Get any processes that might be already tracked and clear them
const processMap = (processBackgroundStates as any).processTerminalBackgroundStates;
if (processMap && typeof processMap.clear === 'function') {
const processMap = (processBackgroundStates as any)
.processTerminalBackgroundStates;
if (processMap && typeof processMap.clear === "function") {
processMap.clear();
}
// Setup IDE mocks
mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" }));
mockGetWorkspaceDirs.mockReturnValue(Promise.resolve([`file://${tempDir}`]));
mockGetWorkspaceDirs.mockReturnValue(
Promise.resolve([`file://${tempDir}`]),
);
});
afterEach(async () => {
@ -44,9 +49,11 @@ describe("runTerminalCommandImpl", () => {
if (testPid !== null) {
try {
// Platform-independent way to kill a process
if (process.platform === 'win32') {
await new Promise(resolve => {
childProcess.exec(`taskkill /F /PID ${testPid}`, () => resolve(null));
if (process.platform === "win32") {
await new Promise((resolve) => {
childProcess.exec(`taskkill /F /PID ${testPid}`, () =>
resolve(null),
);
});
} else {
process.kill(testPid);
@ -57,20 +64,24 @@ describe("runTerminalCommandImpl", () => {
testPid = null;
}
});
afterAll(() => {
// Clean up the temp directory after tests
fs.rmSync(tempDir, { recursive: true, force: true });
});
// Helper function to create a ToolExtras object
const createMockExtras = (overrides: Partial<{
onPartialOutput?: jest.Mock;
remoteName?: string;
}> = {}): ToolExtras => {
const createMockExtras = (
overrides: Partial<{
onPartialOutput?: jest.Mock;
remoteName?: string;
}> = {},
): ToolExtras => {
// Update IDE info if remoteName is provided
if (overrides.remoteName) {
mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: overrides.remoteName }));
mockGetIdeInfo.mockReturnValue(
Promise.resolve({ remoteName: overrides.remoteName }),
);
}
// Create a minimally compliant IDE mock
@ -97,7 +108,7 @@ describe("runTerminalCommandImpl", () => {
llm: {} as any,
fetch: {} as any,
tool: {} as any,
toolCallId: "test-tool-call"
toolCallId: "test-tool-call",
} as ToolExtras;
// Apply overrides
@ -115,7 +126,7 @@ describe("runTerminalCommandImpl", () => {
const extras = createMockExtras();
const result = await runTerminalCommandImpl(args, extras);
// Verify real command output
expect(result).toHaveLength(1);
expect(result[0].name).toBe("Terminal");
@ -134,27 +145,27 @@ describe("runTerminalCommandImpl", () => {
console.error('error output');
}, 50);
"`;
const args = { command, waitForCompletion: true };
const mockOutputFn = jest.fn();
const extras = createMockExtras({ onPartialOutput: mockOutputFn });
// Execute the command with streaming
const result = await runTerminalCommandImpl(args, extras);
// Verify onPartialOutput was called with increasing content
expect(mockOutputFn).toHaveBeenCalled();
// Verify final result has all output
expect(result[0].content).toContain('first output');
expect(result[0].content).toContain('second output');
expect(result[0].content).toContain('error output');
expect(result[0].content).toContain("first output");
expect(result[0].content).toContain("second output");
expect(result[0].content).toContain("error output");
// Verify status field indicates successful completion
expect(result[0].status).toBe("Command completed");
// Verify that initial streaming updates have empty status for regular commands
const firstCall = mockOutputFn.mock.calls[0][0];
if (firstCall && typeof firstCall === 'object') {
if (firstCall && typeof firstCall === "object") {
const contextItems = (firstCall as any).contextItems;
if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
// For commands with waitForCompletion=true, status should be empty while streaming
@ -166,8 +177,8 @@ describe("runTerminalCommandImpl", () => {
it("should run commands in background when waitForCompletion is false", async () => {
// Create a self-identifying background process that writes its PID
// to a file we can access to kill it later
const pidFile = path.join(tempDir, 'test-pid.txt');
const pidFile = path.join(tempDir, "test-pid.txt");
// This script creates a long-running process and writes its PID to our file
// Using a fixed duration timeout so we can be sure to clean it up
const command = `node -e "
@ -178,59 +189,66 @@ describe("runTerminalCommandImpl", () => {
console.log('background process completed');
}, 500);
"`;
const args = { command, waitForCompletion: false };
const mockOutputFn = jest.fn();
const extras = createMockExtras({ onPartialOutput: mockOutputFn });
const result = await runTerminalCommandImpl(args, extras);
// Result should indicate background running in either content or status
expect(result[0].content || result[0].status).toContain("running in the background");
expect(result[0].content || result[0].status).toContain(
"running in the background",
);
// Verify status field indicates background running
expect(result[0].status).toBe("Command is running in the background...");
// Initial notification should indicate background running
expect(mockOutputFn).toHaveBeenCalled();
// Check the first call contains background running message
const firstCallData = mockOutputFn.mock.calls[0][0];
if (firstCallData && typeof firstCallData === 'object') {
if (firstCallData && typeof firstCallData === "object") {
const contextItems = (firstCallData as any).contextItems;
if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
expect(contextItems[0].content).toContain("");
expect(contextItems[0].status).toMatch(/Command is running in the background.../);
expect(contextItems[0].status).toMatch(
/Command is running in the background.../,
);
}
}
// Wait a bit to make sure the PID file is written
await new Promise(resolve => setTimeout(resolve, 100));
await new Promise((resolve) => setTimeout(resolve, 100));
// Read the PID file to get the process ID so we can kill it later
if (fs.existsSync(pidFile)) {
testPid = Number(fs.readFileSync(pidFile, 'utf-8'));
testPid = Number(fs.readFileSync(pidFile, "utf-8"));
}
// Wait a bit longer for the process to complete and onPartialOutput to be called again
await new Promise(resolve => setTimeout(resolve, 400));
await new Promise((resolve) => setTimeout(resolve, 400));
// Check for background process completion message in mockOutputFn calls
// Note: This is optional and depends on timing, so we don't want to strictly enforce it
let foundCompletionMessage = false;
for (let i = 0; i < mockOutputFn.mock.calls.length; i++) {
const call = mockOutputFn.mock.calls[i][0];
if (call && typeof call === 'object') {
if (call && typeof call === "object") {
const contextItems = (call as any).contextItems;
if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
if (contextItems[0].status === "\nBackground command completed" ||
(contextItems[0].status && contextItems[0].status.includes("Background command"))) {
if (
contextItems[0].status === "\nBackground command completed" ||
(contextItems[0].status &&
contextItems[0].status.includes("Background command"))
) {
foundCompletionMessage = true;
break;
}
}
}
}
// If we found any completion message in the output, great!
// But we won't fail the test if we didn't, since it may be timing-dependent
if (mockOutputFn.mock.calls.length > 1) {
@ -244,7 +262,7 @@ describe("runTerminalCommandImpl", () => {
const extras = createMockExtras({ remoteName: "ssh" });
const result = await runTerminalCommandImpl(args, extras);
// In remote environments, it should use the IDE's runCommand
expect(mockRunCommand).toHaveBeenCalledWith("echo 'test'");
// Match the actual output message
@ -256,23 +274,26 @@ describe("runTerminalCommandImpl", () => {
it("should handle errors when executing invalid commands", async () => {
// Use a command that should fail on any platform
const args = { command: "non-existent-command-xyz", waitForCompletion: true };
const args = {
command: "non-existent-command-xyz",
waitForCompletion: true,
};
const extras = createMockExtras();
const result = await runTerminalCommandImpl(args, extras);
expect(result[0].name).toBe("Terminal");
expect(result[0].description).toBe("Terminal command output");
// The exact error message varies by platform, but should contain error information
const errorContent = result[0].content;
expect(
errorContent.includes("Command failed") ||
errorContent.includes("not found") ||
errorContent.includes("recognized") ||
/error/i.test(errorContent)
errorContent.includes("Command failed") ||
errorContent.includes("not found") ||
errorContent.includes("recognized") ||
/error/i.test(errorContent),
).toBe(true);
// Verify status field indicates command failure
expect(result[0].status).toContain("Command failed with:");
});
@ -284,23 +305,23 @@ describe("runTerminalCommandImpl", () => {
const extras = createMockExtras();
const result = await runTerminalCommandImpl(args, extras);
// Verify we still get a result with a name and description
expect(result).toHaveLength(1);
expect(result[0].name).toBe("Terminal");
expect(result[0].description).toBe("Terminal command output");
// The command should have executed and returned content
expect(result[0].content).toBeDefined();
// We should see the error message we wrote to stderr
expect(result[0].content).toContain("This is an error message");
// Verify status field indicates command failure - the exact message format can vary
// between different node versions and platforms
expect(result[0].status).toContain("Command failed");
});
it("should set appropriate status when a command completes successfully", async () => {
// Use a simple command that will succeed
const command = `node -e "console.log('success test')"`;
@ -308,14 +329,14 @@ describe("runTerminalCommandImpl", () => {
const extras = createMockExtras();
const result = await runTerminalCommandImpl(args, extras);
expect(result).toHaveLength(1);
expect(result[0].name).toBe("Terminal");
expect(result[0].content).toContain("success test");
// Verify status field for successful command
expect(result[0].status).toBe("Command completed");
});
it("should include status info for background commands in non-streaming mode", async () => {
// Use a simple background command
const command = `node -e "setTimeout(() => console.log('done'), 300)"`;
@ -324,7 +345,7 @@ describe("runTerminalCommandImpl", () => {
const extras = createMockExtras();
const result = await runTerminalCommandImpl(args, extras);
expect(result).toHaveLength(1);
expect(result[0].name).toBe("Terminal");
// Verify both content and status fields for background commands

View file

@ -3,17 +3,32 @@ import util from "node:util";
import { fileURLToPath } from "node:url";
import { ToolImpl } from ".";
import { isProcessBackgrounded, removeBackgroundedProcess } from "../../util/processTerminalBackgroundStates";
import {
isProcessBackgrounded,
removeBackgroundedProcess,
} from "../../util/processTerminalBackgroundStates";
const asyncExec = util.promisify(childProcess.exec);
const ENABLED_FOR_REMOTES = [
"",
"local",
"wsl",
"dev-container",
"devcontainer",
"ssh-remote",
"attached-container",
"codespaces",
"tunnel",
];
export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
// Default to waiting for completion if not specified
const waitForCompletion = args.waitForCompletion !== false;
const ideInfo = await extras.ide.getIdeInfo();
const toolCallId = extras.toolCallId || "";
if (ideInfo.remoteName === "local" || ideInfo.remoteName === "") {
if (ENABLED_FOR_REMOTES.includes(ideInfo.remoteName)) {
// For streaming output
if (extras.onPartialOutput) {
return new Promise((resolve, reject) => {
@ -56,7 +71,9 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
// Send partial output to UI
if (extras.onPartialOutput) {
const status = waitForCompletion ? "" : "Command is running in the background...";
const status = waitForCompletion
? ""
: "Command is running in the background...";
extras.onPartialOutput({
toolCallId,
contextItems: [
@ -116,9 +133,10 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
if (!waitForCompletion) {
// Already resolved, just update the UI with final output
if (extras.onPartialOutput) {
const status = (code === 0 || !code
? "\nBackground command completed"
: `\nBackground command failed with exit code ${code}`)
const status =
code === 0 || !code
? "\nBackground command completed"
: `\nBackground command failed with exit code ${code}`;
extras.onPartialOutput({
toolCallId,
contextItems: [
@ -140,7 +158,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
name: "Terminal",
description: "Terminal command output",
content: terminalOutput,
status: status
status: status,
},
]);
} else {
@ -149,9 +167,8 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
{
name: "Terminal",
description: "Terminal command output",
content:
terminalOutput,
status: status,
content: terminalOutput,
status: status,
},
]);
}
@ -191,7 +208,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
// Detach the process so it's not tied to the parent
detached: true,
// Redirect to /dev/null equivalent (works cross-platform)
stdio: 'ignore',
stdio: "ignore",
});
// Even for detached processes, add event handlers to clean up the background process map
@ -225,7 +242,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
name: "Terminal",
description: "Terminal command output",
content: status,
status: status
status: status,
},
];
}
@ -269,4 +286,4 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
status: "Command failed",
},
];
}
};

View file

@ -1,12 +1,15 @@
import { ToolImpl } from ".";
import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache";
export const viewDiffImpl: ToolImpl = async (args, extras) => {
const diff = await extras.ide.getDiff(true);
const diffs = await getDiffsFromCache(extras.ide); // const diffs = await extras.ide.getDiff(true);
// TODO includeUnstaged should be an option
return [
{
name: "Diff",
description: "The current git diff",
content: diff.join("\n"),
content: diffs.join("\n"),
},
];
};

View file

@ -1,4 +1,3 @@
/**
* Recursively retrieves the root cause of an error by traversing through its `cause` property.
*
@ -6,8 +5,8 @@
* @returns The root cause of the error, or the original error if no further cause is found.
*/
export function getRootCause(err: any): any {
if (err.cause) {
return getRootCause(err.cause);
}
return err;
}
if (err.cause) {
return getRootCause(err.cause);
}
return err;
}

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