Merge branch 'main' into pe/tsc-fix-find-widget

This commit is contained in:
Test 2024-11-13 11:24:56 -08:00
commit 84932774ee
382 changed files with 6630 additions and 940 deletions

View file

@ -1,17 +1,19 @@
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";
import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js";
import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js";
import { constructAutocompletePrompt } from "./constructPrompt.js";
import { AutocompleteSnippet } from "./context/ranking/index.js";
import { postprocessCompletion } from "./postprocessing/index.js";
// @prettier-ignore
import { TRIAL_FIM_MODEL } from "../config/onboarding.js";
import OpenAI from "../llm/llms/OpenAI.js";
import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js";
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
import { AutocompleteSnippet } from "./context/ranking/index.js";
import { BracketMatchingService } from "./filtering/BracketMatchingService.js";
import { CompletionStreamer } from "./generation/CompletionStreamer.js";
import { postprocessCompletion } from "./postprocessing/index.js";
import { shouldPrefilter } from "./prefiltering/index.js";
import { renderPrompt } from "./templating/index.js";
import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js";
@ -259,13 +261,10 @@ export class CompletionProvider {
//////////
// Do some stuff later so as not to block return. Latency matters
const completionToCache = outcome.completion;
setTimeout(async () => {
if (!outcome.cacheHit) {
(await this.autocompleteCache).put(outcome.prefix, completionToCache);
}
}, 100);
// Save to cache
if (!outcome.cacheHit) {
(await this.autocompleteCache).put(outcome.prefix, outcome.completion);
}
// When using the JetBrains extension, Mark as displayed
const ideType = (await this.ide.getIdeInfo()).ideType;

View file

@ -28,7 +28,7 @@ export const Python = {
name: "Python",
// """"#" is for .ipynb files, where we add '"""' surrounding markdown blocks.
// This stops the model from trying to complete the start of a new markdown block
topLevelKeywords: ["def", "class", '"""#'],
topLevelKeywords: ["def", "class", "\"\"\"#"],
singleLineComment: "#",
endOfLine: [],
};

View file

@ -1,4 +1,5 @@
import { Position, Range } from "../index.js";
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
import {
fillPromptWithSnippets,

View file

@ -1,6 +1,7 @@
import { IDE } from "../..";
import { HelperVars } from "../util/HelperVars";
import { RecentlyEditedRange } from "../util/types";
import { ImportDefinitionsService } from "./ImportDefinitionsService";
import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking";
import { RootPathContextService } from "./root-path-context/RootPathContextService";

View file

@ -1,5 +1,6 @@
import { IDE, Location } from "../..";
import { LANGUAGES } from "../constants/AutocompleteLanguageInfo";
import { getSymbolsForSnippet } from "./ranking";
interface FileInfo {

View file

@ -1,4 +1,5 @@
import { RangeInFileWithContents } from "../../../commands/util.js";
import { AutocompleteSnippet, jaccardSimilarity } from "./index.js";
function* slidingWindow(

View file

@ -1,97 +0,0 @@
import fs from "fs";
import path from "path";
import { Range } from "../../..";
import { testIde } from "../../../test/util/fixtures";
import { getAst, getTreePathAtCursor } from "../../util/ast";
import { ImportDefinitionsService } from "../ImportDefinitionsService";
import { RootPathContextService } from "./RootPathContextService";
function splitTextAtRange(fileContent: string, range: Range): [string, string] {
const lines = fileContent.split("\n");
let currentPos = 0;
if (range.start.line === range.end.line) {
// If range is on the same line, calculate position once
for (let i = 0; i < range.start.line; i++) {
currentPos += lines[i].length + 1; // +1 for the newline character
}
const startPos = currentPos + range.start.character;
const endPos = currentPos + range.end.character;
return [fileContent.slice(0, startPos), fileContent.slice(endPos)];
}
// Calculate position of range start
for (let i = 0; i < range.start.line; i++) {
currentPos += lines[i].length + 1;
}
const startPos = currentPos + range.start.character;
// Calculate position of range end
currentPos = 0;
for (let i = 0; i < range.end.line; i++) {
currentPos += lines[i].length + 1;
}
const endPos = currentPos + range.end.character;
return [fileContent.slice(0, startPos), fileContent.slice(endPos)];
}
export async function testRootPathContext(
folderName: string,
relativeFilepath: string,
rangeToFill: Range,
expectedSnippets: string[],
) {
const ide = testIde;
const importDefinitionsService = new ImportDefinitionsService(ide);
const service = new RootPathContextService(importDefinitionsService, ide);
// Copy the folder to the test directory
const folderPath = path.join(
__dirname,
"autocomplete",
"context",
"root-path-context",
"test",
folderName,
);
const workspaceDir = (await ide.getWorkspaceDirs())[0];
const testFolderPath = path.join(workspaceDir, folderName);
fs.cpSync(folderPath, testFolderPath, {
recursive: true,
force: true,
});
// Get results of root path context
const startPath = path.join(testFolderPath, relativeFilepath);
const [prefix, suffix] = splitTextAtRange(
fs.readFileSync(startPath, "utf8"),
rangeToFill,
);
const fileContents = prefix + suffix;
const ast = await getAst(startPath, fileContents);
if (!ast) {
throw new Error("AST is undefined");
}
const treePath = await getTreePathAtCursor(ast, prefix.length);
const snippets = await service.getContextForPath(startPath, treePath);
expectedSnippets.forEach((expectedSnippet) => {
const found = snippets.find((snippet) =>
snippet.contents.includes(expectedSnippet),
);
expect(found).toBeDefined();
});
}
describe("RootPathContextService", () => {
it.skip("should be true", async () => {
await testRootPathContext(
"typescript",
"file1.ts",
{ start: { line: 3, character: 2 }, end: { line: 3, character: 24 } },
["export interface Person", "export interface Address"],
);
});
});

View file

@ -1,8 +1,10 @@
import { createHash } from "crypto";
import { LRUCache } from "lru-cache";
import Parser from "web-tree-sitter";
import { IDE } from "../../..";
import { getQueryForFile, TSQueryType } from "../../../util/treeSitter";
import { getQueryForFile } from "../../../util/treeSitter";
import { AstPath } from "../../util/ast";
import { ImportDefinitionsService } from "../ImportDefinitionsService";
import { AutocompleteSnippet } from "../ranking";
@ -24,7 +26,10 @@ export class RootPathContextService {
private static TYPES_TO_USE = new Set([
"program",
"function_declaration",
"function_definition",
"method_definition",
"class_declaration",
"class_definition",
]);
/**
@ -52,23 +57,12 @@ export class RootPathContextService {
case "program":
this.importDefinitionsService.get(filepath);
break;
case "function_declaration":
default:
query = await getQueryForFile(
filepath,
TSQueryType.FunctionDeclaration,
`root-path-context-queries/${node.type}`,
);
break;
case "method_definition":
query = await getQueryForFile(filepath, TSQueryType.MethodDefinition);
break;
case "function_definition":
query = await getQueryForFile(filepath, TSQueryType.FunctionDefinition);
break;
case "method_declaration":
query = await getQueryForFile(filepath, TSQueryType.MethodDeclaration);
break;
default:
break;
}
if (!query) {
@ -77,28 +71,38 @@ export class RootPathContextService {
await Promise.all(
query.matches(node).map(async (match) => {
const startPosition = match.captures[0].node.startPosition;
const endPosition = match.captures[0].node.endPosition;
const definitions = await this.ide.gotoDefinition({
filepath,
position: {
line: endPosition.row,
character: endPosition.column,
},
});
const newSnippets = await Promise.all(
definitions.map(async (def) => ({
...def,
contents: await this.ide.readRangeInFile(def.filepath, def.range),
})),
);
snippets.push(...newSnippets);
for (const item of match.captures) {
const endPosition = item.node.endPosition;
const newSnippets = await this.getSnippets(filepath, endPosition);
snippets.push(...newSnippets);
}
}),
);
return snippets;
}
private async getSnippets(
filepath: string,
endPosition: Parser.Point,
): Promise<AutocompleteSnippet[]> {
const definitions = await this.ide.gotoDefinition({
filepath,
position: {
line: endPosition.row,
character: endPosition.column,
},
});
const newSnippets = await Promise.all(
definitions.map(async (def) => ({
...def,
contents: await this.ide.readRangeInFile(def.filepath, def.range),
})),
);
return newSnippets;
}
async getContextForPath(
filepath: string,
astPath: AstPath,

View file

@ -0,0 +1,63 @@
import { testRootPathContext } from "./testUtils";
const TEST_CASES = [
{
nodeType: "function_declaration",
fileName: "file1.ts",
language: "TypeScript",
cursorPosition: { line: 10, character: 24 },
definitionPositions: [
{ row: 9, column: 34 }, // Person
{ row: 9, column: 44 }, // Address
],
},
{
nodeType: "method_declaration",
fileName: "file1.ts",
language: "TypeScript",
cursorPosition: { line: 22, character: 30 },
definitionPositions: [
{ row: 13, column: 29 }, // BaseClass
{ row: 13, column: 55 }, // FirstInterface
{ row: 13, column: 72 }, // SecondInterface
{ row: 21, column: 33 }, // Person
{ row: 21, column: 43 }, // Address
],
},
{
nodeType: "function_definition",
fileName: "file1.py",
language: "Python",
cursorPosition: { line: 4, character: 25 },
definitionPositions: [
{ row: 3, column: 30 }, // Person
{ row: 3, column: 42 }, // Address
],
},
{
nodeType: "function_definition (inside a class)",
fileName: "file1.py",
language: "Python",
cursorPosition: { line: 12, character: 33 },
definitionPositions: [
{ row: 6, column: 21 }, // BaseClass
{ row: 6, column: 33 }, // Collection
{ row: 11, column: 47 }, // Person
{ row: 11, column: 59 }, // Address
],
},
];
describe("RootPathContextService", () => {
test.each(TEST_CASES)(
"Should look for correct type definitions when editing inside a $nodeType in $language",
async ({ fileName, cursorPosition, definitionPositions }) => {
await testRootPathContext(
"files",
fileName,
cursorPosition,
definitionPositions,
);
},
);
});

View file

@ -0,0 +1,26 @@
# File: base_module.py
class BaseClass:
def __init__(self):
print("BaseClass initialized")
class Collection:
def __init__(self):
print("Collection initialized")
class Address:
def __init__(self, street: str, city: str, zip_code: str):
self.street = street
self.city = city
self.zip_code = zip_code
def __str__(self):
return f"{self.street}, {self.city}, {self.zip_code}"
class Person:
def __init__(self, name: str, address: Address):
self.name = name
self.address = address
def __str__(self):
return f"{self.name} lives at {self.address}"

View file

@ -0,0 +1,13 @@
from .base_module import BaseClass, Collection, Person, Address
from typing import List
def get_address(person: Person) -> Address:
return person.address
class Group(BaseClass, Collection):
def __init__(self, people: List[Person]) -> None:
super().__init__()
self.people = people
def get_person_address(self, person: Person) -> Address:
return get_address(person)

View file

@ -0,0 +1,25 @@
import {
Address,
Person,
BaseClass,
FirstInterface,
SecondInterface,
// @ts-ignore
} from "./types";
function getAddress(person: Person): Address {
return person.address;
}
class Group extends BaseClass implements FirstInterface, SecondInterface {
people: Person[];
constructor(people: Person[]) {
super();
this.people = people;
}
getPersonAddress(person: Person): Address {
return getAddress(person);
}
}

View file

@ -0,0 +1,89 @@
import { jest } from "@jest/globals";
import fs from "fs";
import path from "path";
import Parser from "web-tree-sitter";
import { Position } from "../../../..";
import { testIde } from "../../../../test/util/fixtures";
import { getAst, getTreePathAtCursor } from "../../../util/ast";
import { ImportDefinitionsService } from "../../ImportDefinitionsService";
import { RootPathContextService } from "../RootPathContextService";
function splitTextAtPosition(
fileContent: string,
position: Position,
): [string, string] {
const lines = fileContent.split("\n");
let currentPos = 0;
// Calculate position based on the provided line and character
for (let i = 0; i < position.line; i++) {
currentPos += lines[i].length + 1; // +1 for the newline character
}
const splitPos = currentPos + position.character;
return [fileContent.slice(0, splitPos), fileContent.slice(splitPos)];
}
export async function testRootPathContext(
folderName: string,
relativeFilepath: string,
position: Position,
expectedDefinitionPositions: Parser.Point[],
) {
// Create a mocked instance of RootPathContextService
const ide = testIde;
const importDefinitionsService = new ImportDefinitionsService(ide);
const service = new RootPathContextService(importDefinitionsService, ide);
const getSnippetsMock = jest
// @ts-ignore
.spyOn(service, "getSnippets")
// @ts-ignore
.mockImplementation(async (_filepath, _endPosition) => {
return [];
});
// Copy the folder to the test directory
const folderPath = path.join(
__dirname,
"autocomplete",
"context",
"root-path-context",
"test",
folderName,
);
const workspaceDir = (await ide.getWorkspaceDirs())[0];
const testFolderPath = path.join(workspaceDir, folderName);
fs.cpSync(folderPath, testFolderPath, {
recursive: true,
force: true,
});
// Get results of root path context
const startPath = path.join(testFolderPath, relativeFilepath);
const [prefix, suffix] = splitTextAtPosition(
fs.readFileSync(startPath, "utf8"),
position,
);
const fileContents = prefix + suffix;
const ast = await getAst(startPath, fileContents);
if (!ast) {
throw new Error("AST is undefined");
}
const treePath = await getTreePathAtCursor(ast, prefix.length);
await service.getContextForPath(startPath, treePath);
expect(getSnippetsMock).toHaveBeenCalledTimes(
expectedDefinitionPositions.length,
);
expectedDefinitionPositions.forEach((position, index) => {
expect(getSnippetsMock).toHaveBeenNthCalledWith(
index + 1,
expect.any(String), // filepath argument
position,
);
});
}

View file

@ -1,13 +0,0 @@
import { Address, Person } from "./types";
function getAddress(person: Person): Address {
return person.address;
}
class Group {
people: Person[];
constructor(people: Person[]) {
this.people = people;
}
}

View file

@ -1,11 +0,0 @@
export interface Person {
firstName: string;
lastName: string;
age: number;
address: Address;
}
export interface Address {
street: string;
city: string;
}

View file

@ -1,6 +1,7 @@
import { streamLines } from "../../../diff/util";
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../../util/parameters";
import { HelperVars } from "../../util/HelperVars";
import { stopAtStopTokens } from "./charStream";
import {
avoidEmptyComments,

View file

@ -1,4 +1,5 @@
import { jest } from "@jest/globals";
import * as lineStream from "./lineStream";
describe("lineStream", () => {

View file

@ -1,4 +1,5 @@
import { distance } from "fastest-levenshtein";
import { DiffLine } from "../../..";
import { LineStream } from "../../../diff/util";

View file

@ -1,9 +1,10 @@
import { setUpTestDir, tearDownTestDir } from "../../../test/util/testDir";
import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases";
import {
AutocompleteFileringTestInput,
testAutocompleteFiltering,
} from "./util";
import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases";
import { setUpTestDir, tearDownTestDir } from "../../../test/util/testDir";
const filterTestCases = (tests: AutocompleteFileringTestInput[]) => {
if (tests.some((test) => test.options?.only)) {
@ -13,7 +14,7 @@ const filterTestCases = (tests: AutocompleteFileringTestInput[]) => {
return tests;
};
describe("llms/Mock", () => {
describe("Autocomplete filtering tests", () => {
beforeAll(async () => {
tearDownTestDir();
setUpTestDir();
@ -23,27 +24,25 @@ describe("llms/Mock", () => {
tearDownTestDir();
});
describe("Autocomplete Filtering Tests", () => {
beforeEach(async () => {
await new Promise((resolve) => setTimeout(resolve, 50));
});
beforeEach(async () => {
await new Promise((resolve) => setTimeout(resolve, 50));
});
describe("Should return unmodified LLM output", () => {
it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))(
"$description",
async (testCase) => {
await testAutocompleteFiltering(testCase);
},
);
});
describe("Should return unmodified LLM output", () => {
it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))(
"$description",
async (testCase) => {
await testAutocompleteFiltering(testCase);
},
);
});
describe("Should return modified LLM output", () => {
it.each(filterTestCases(TEST_CASES_WITH_DIFF))(
"$description",
async (testCase) => {
await testAutocompleteFiltering(testCase);
},
);
});
describe("Should return modified LLM output", () => {
it.each(filterTestCases(TEST_CASES_WITH_DIFF))(
"$description",
async (testCase) => {
await testAutocompleteFiltering(testCase);
},
);
});
});

View file

@ -1,4 +1,5 @@
import { dedent } from "../../../util";
import { AutocompleteFileringTestInput } from "./util";
export const TEST_CASES_WITH_DIFF: AutocompleteFileringTestInput[] = [
@ -62,7 +63,7 @@ function sayHello() {
`,
llmOutput: `world!");
`,
expectedCompletion: `world!");`,
expectedCompletion: "world!\");",
},
{
description: "Should autocomplete Java when inside a block",
@ -375,8 +376,8 @@ button {
border: 2px solid #000;
border-radius<|fim|>
}`,
llmOutput: `: 5px;`,
expectedCompletion: `: 5px;`,
llmOutput: ": 5px;",
expectedCompletion: ": 5px;",
},
{
@ -391,8 +392,8 @@ button {
border-bottom-right-radius: 8px;
}
`,
llmOutput: `8`,
expectedCompletion: `8`,
llmOutput: "8",
expectedCompletion: "8",
},
{
@ -404,8 +405,8 @@ input:focus {
border: 2px solid <|fim|>;
}
`,
llmOutput: `#4CAF50;`,
expectedCompletion: `#4CAF50;`,
llmOutput: "#4CAF50;",
expectedCompletion: "#4CAF50;",
},
{
@ -422,8 +423,8 @@ input:focus {
padding: var(--padding);
}
`,
llmOutput: `--primary-color`,
expectedCompletion: `--primary-color`,
llmOutput: "--primary-color",
expectedCompletion: "--primary-color",
},
{
description: "Should complete CSS grid template columns",
@ -435,8 +436,8 @@ input:focus {
grid-gap: 10px;
}
`,
llmOutput: `3, 1fr`,
expectedCompletion: `3, 1fr`,
llmOutput: "3, 1fr",
expectedCompletion: "3, 1fr",
},
{
@ -476,8 +477,8 @@ function calculateArea($length, $width) {
}
echo calculateArea(5, 3);`,
llmOutput: `return $length * $width;`,
expectedCompletion: `return $length * $width;`,
llmOutput: "return $length * $width;",
expectedCompletion: "return $length * $width;",
filename: "areaCalculator.php",
},
@ -488,8 +489,8 @@ echo calculateArea(5, 3);`,
$colors = array("Red", "Green", <|fim|>);
echo "First color is: " . $colors[0];`,
llmOutput: `"Blue"`,
expectedCompletion: `"Blue"`,
llmOutput: "\"Blue\"",
expectedCompletion: "\"Blue\"",
filename: "colors.php",
},
{
@ -529,8 +530,8 @@ export const Counter = () => {
</div>
);
};`,
llmOutput: `0`,
expectedCompletion: `0`,
llmOutput: "0",
expectedCompletion: "0",
filename: "Counter.tsx",
},
@ -557,8 +558,8 @@ export const Timer = () => {
</div>
);
};`,
llmOutput: `return () => clearInterval(interval);`,
expectedCompletion: `return () => clearInterval(interval);`,
llmOutput: "return () => clearInterval(interval);",
expectedCompletion: "return () => clearInterval(interval);",
filename: "Timer.tsx",
},
@ -593,8 +594,8 @@ class Form extends React.Component {
);
}
}`,
llmOutput: `this.setState({ name: event.target.value });`,
expectedCompletion: `this.setState({ name: event.target.value });`,
llmOutput: "this.setState({ name: event.target.value });",
expectedCompletion: "this.setState({ name: event.target.value });",
filename: "Form.tsx",
},
{
@ -646,8 +647,8 @@ print(even_squares)
odd_squares = [<|fim|>
print(odd_squares)
`,
llmOutput: `x for x in squares if x % 2 != 0`,
expectedCompletion: `x for x in squares if x % 2 != 0`,
llmOutput: "x for x in squares if x % 2 != 0",
expectedCompletion: "x for x in squares if x % 2 != 0",
},
{
description: "Should autocomplete a simple Go function declaration",
@ -731,8 +732,8 @@ func main() {
WHERE release_year > 2000 AND director = 'Christopher Nolan'
GROUP BY name
HAVING avg_rating > <|fim|>`,
llmOutput: `8.5)`,
expectedCompletion: `8.5)`,
llmOutput: "8.5)",
expectedCompletion: "8.5)",
},
{
description:
@ -774,8 +775,8 @@ func main() {
FROM users u
WHERE u.active = 1
<|fim|>`,
llmOutput: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`,
expectedCompletion: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`,
llmOutput: " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
expectedCompletion: " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
},
{
description:
@ -790,8 +791,8 @@ func main() {
ELSE 'Unknown'
END as order_status
FROM orders`,
llmOutput: `WHEN status = 'cancelled' THEN 'Cancelled'`,
expectedCompletion: `WHEN status = 'cancelled' THEN 'Cancelled'`,
llmOutput: "WHEN status = 'cancelled' THEN 'Cancelled'",
expectedCompletion: "WHEN status = 'cancelled' THEN 'Cancelled'",
},
{
description: "Should autocomplete HTML paragraph content",
@ -803,8 +804,8 @@ func main() {
<p><|fim|></p>
</body>
</html>`,
llmOutput: `This is a paragraph with some sample text.`,
expectedCompletion: `This is a paragraph with some sample text.`,
llmOutput: "This is a paragraph with some sample text.",
expectedCompletion: "This is a paragraph with some sample text.",
filename: "test.html",
},
{
@ -816,8 +817,8 @@ func main() {
<p>Description text.</p>
</div>
</div>`,
llmOutput: `alt="Description of image"`,
expectedCompletion: `alt="Description of image"`,
llmOutput: "alt=\"Description of image\"",
expectedCompletion: "alt=\"Description of image\"",
filename: "test.html",
},
{
@ -827,8 +828,8 @@ func main() {
<li>Item 2</li>
<li>Item 3</li>
<li<|fim|></ul>`,
llmOutput: `>Item 4</li>`,
expectedCompletion: `>Item 4</li>`,
llmOutput: ">Item 4</li>",
expectedCompletion: ">Item 4</li>",
filename: "test.html",
},
@ -874,8 +875,8 @@ end
numbers = [1, 2, 3, 4, 5]
squared_numbers = numbers.<|fim|>
`,
llmOutput: `map { |n| n ** 2 }`,
expectedCompletion: `map { |n| n ** 2 }`,
llmOutput: "map { |n| n ** 2 }",
expectedCompletion: "map { |n| n ** 2 }",
filename: "array_methods.rb",
},
{
@ -888,8 +889,8 @@ public class App {
System.out.println(message);
}
}`,
llmOutput: `World`,
expectedCompletion: `World`,
llmOutput: "World",
expectedCompletion: "World",
},
{
description:
@ -929,8 +930,8 @@ public class App {
<|fim|>
]
}`,
llmOutput: `, { "id": 3, "name": "Charlie" }`,
expectedCompletion: `, { "id": 3, "name": "Charlie" }`,
llmOutput: ", { \"id\": 3, \"name\": \"Charlie\" }",
expectedCompletion: ", { \"id\": 3, \"name\": \"Charlie\" }",
},
{
description: "Should autocomplete within a CSV record",
@ -938,8 +939,8 @@ public class App {
input: `Name, Age, City
John Doe, 30, New York
Jane Smith<|fim|>`,
llmOutput: `, 25, Los Angeles`,
expectedCompletion: `, 25, Los Angeles`,
llmOutput: ", 25, Los Angeles",
expectedCompletion: ", 25, Los Angeles",
},
{
description:
@ -948,8 +949,8 @@ Jane Smith<|fim|>`,
input: `Product, Price, Quantity
Laptop, 1200, 5
Smart<|fim|>`,
llmOutput: `phone, 800, 10`,
expectedCompletion: `phone, 800, 10`,
llmOutput: "phone, 800, 10",
expectedCompletion: "phone, 800, 10",
},
{
description: "Should complete CSV structure adding closing brackets",
@ -957,8 +958,8 @@ Smart<|fim|>`,
input: `ID, Name, JoiningDate
1, Alice, 2023-01-10
2, B<|fim|>`,
llmOutput: `ob, 2023-02-10`,
expectedCompletion: `ob, 2023-02-10`,
llmOutput: "ob, 2023-02-10",
expectedCompletion: "ob, 2023-02-10",
},
{
description: "Should complete YAML list item and preserve structure",
@ -1125,8 +1126,8 @@ sumTree (Node left right) =
let leftSum = <|fim|>
rightSum = sumTree right
in leftSum + rightSum`,
llmOutput: `sumTree left`,
expectedCompletion: `sumTree left`,
llmOutput: "sumTree left",
expectedCompletion: "sumTree left",
},
{
description: "Haskell: Complex function with where clause and guards",
@ -1142,8 +1143,8 @@ solveQuadratic a b c
sqrtD = sqrt discriminant
x1 = (-b + sqrtD) / (2*a)
<|fim|> = (-b - sqrtD) / (2*a)`,
llmOutput: `x2`,
expectedCompletion: `x2`,
llmOutput: "x2",
expectedCompletion: "x2",
},
{
description: "Haskell: List comprehension with complex filter",
@ -1153,8 +1154,8 @@ solveQuadratic a b c
primesUpTo :: Int -> [Int]
primesUpTo n = [x | x <- [2..n], isPrime x]
where isPrime num = <|fim|> && all (\d -> num \`mod\` d /= 0) [2..(floor . sqrt $ fromIntegral num)]`,
llmOutput: `num > 1`,
expectedCompletion: `num > 1`,
llmOutput: "num > 1",
expectedCompletion: "num > 1",
},
{
description: "Should autocomplete Dart class methods",
@ -1192,8 +1193,8 @@ void main() {
var name = "World";
print('Hello, <|fim|>!');
}`,
llmOutput: `\${name}`,
expectedCompletion: `\${name}`,
llmOutput: "${name}",
expectedCompletion: "${name}",
},
{
description: "Should autocomplete within a Dart function body",
@ -1213,8 +1214,8 @@ class Counter {
count = 0;
}
}`,
llmOutput: `count--;`,
expectedCompletion: `count--;`,
llmOutput: "count--;",
expectedCompletion: "count--;",
},
{
description:
@ -1223,8 +1224,8 @@ class Counter {
(let [sum (+ a b)]
(println "The sum is" sum)
sum<|fim|>`,
llmOutput: `))`,
expectedCompletion: `))`,
llmOutput: "))",
expectedCompletion: "))",
filename: "test.clj",
},
{
@ -1236,8 +1237,8 @@ class Counter {
:age 30
<|fim|>
(println "User information loaded"))`,
llmOutput: `:location "Unknown"}`,
expectedCompletion: `:location "Unknown"}`,
llmOutput: ":location \"Unknown\"}",
expectedCompletion: ":location \"Unknown\"}",
filename: "test.clj",
},
{
@ -1248,8 +1249,8 @@ class Counter {
(when (seq nums)
(println (first nums))
(recur (rest nums)))))`,
llmOutput: ` 7,`,
expectedCompletion: ` 7,`,
llmOutput: " 7,",
expectedCompletion: " 7,",
filename: "test.clj",
},
{
@ -1273,8 +1274,8 @@ numbers <- c(1, 2, 3, 4, 5)
for (number in numbers) {
print(<|fim|>)
}`,
llmOutput: `number)`,
expectedCompletion: `number)`,
llmOutput: "number)",
expectedCompletion: "number)",
},
{
description: "Should autocomplete R data frame creation",
@ -1285,8 +1286,8 @@ data <- data.frame(
Age = c(25, 30, 35),
<|fim|>
)`,
llmOutput: `Height = c(165, 180, 175)`,
expectedCompletion: `Height = c(165, 180, 175)`,
llmOutput: "Height = c(165, 180, 175)",
expectedCompletion: "Height = c(165, 180, 175)",
},
{
description: "Should autocomplete R if-else statement",
@ -1300,8 +1301,8 @@ if (grade >= 90) {
} else {
print("C")
}`,
llmOutput: `print("B")`,
expectedCompletion: `print("B")`,
llmOutput: "print(\"B\")",
expectedCompletion: "print(\"B\")",
},
{
description: "Should autocomplete R ggplot2 plot structure",
@ -1312,8 +1313,8 @@ library(ggplot2)
ggplot(data=mtcars, aes(x=wt, y=mpg)) +
geom_point() +
<|fim|>`,
llmOutput: `geom_smooth(method='lm', se=FALSE)`,
expectedCompletion: `geom_smooth(method='lm', se=FALSE)`,
llmOutput: "geom_smooth(method='lm', se=FALSE)",
expectedCompletion: "geom_smooth(method='lm', se=FALSE)",
},
{
description: "Should autocomplete Scala class with a method",
@ -1323,8 +1324,8 @@ ggplot(data=mtcars, aes(x=wt, y=mpg)) +
<|fim|>
}
}`,
llmOutput: `s"Hello, my name is $name and I am $age years old."`,
expectedCompletion: `s"Hello, my name is $name and I am $age years old."`,
llmOutput: "s\"Hello, my name is $name and I am $age years old.\"",
expectedCompletion: "s\"Hello, my name is $name and I am $age years old.\"",
},
{
@ -1334,8 +1335,8 @@ ggplot(data=mtcars, aes(x=wt, y=mpg)) +
case class Person(name: String, age: Int, address: Address)
val alice = Person("Alice", 30, Address("Wonderland", <|fim|>))`,
llmOutput: `"12345")`,
expectedCompletion: `"12345")`,
llmOutput: "\"12345\")",
expectedCompletion: "\"12345\")",
},
{
@ -1380,8 +1381,8 @@ int main() {
printf("Result: %d", add(2, 3));
return 0;
}`,
llmOutput: `return a - b;`,
expectedCompletion: `return a - b;`,
llmOutput: "return a - b;",
expectedCompletion: "return a - b;",
},
{
@ -1400,8 +1401,8 @@ int main() {
printf("Name: %s, Age: %d, Height: %.2f", alice.name, alice.age, alice.height);
return 0;
}`,
llmOutput: `5.5`,
expectedCompletion: `5.5`,
llmOutput: "5.5",
expectedCompletion: "5.5",
},
{
@ -1453,8 +1454,8 @@ data class User(
val email: String,
<|fim|>
)`,
llmOutput: `val age: Int`,
expectedCompletion: `val age: Int`,
llmOutput: "val age: Int",
expectedCompletion: "val age: Int",
},
{
description:
@ -1490,8 +1491,8 @@ contract SimpleStorage {
}
}
`,
llmOutput: `return data;`,
expectedCompletion: `return data;`,
llmOutput: "return data;",
expectedCompletion: "return data;",
},
{
@ -1508,8 +1509,8 @@ contract EventExample {
}
}
`,
llmOutput: `id, content`,
expectedCompletion: `id, content`,
llmOutput: "id, content",
expectedCompletion: "id, content",
},
{
@ -1582,8 +1583,8 @@ const multiplyNumbers = (a: number, b: number): number => {
console.log(multiplyNumbers(2, 3));
`,
llmOutput: `turn a * b;`,
expectedCompletion: `turn a * b;`,
llmOutput: "turn a * b;",
expectedCompletion: "turn a * b;",
},
// TODO
@ -1677,8 +1678,8 @@ public class Person
{
void <|fim|>
}`,
llmOutput: `Greet();`,
expectedCompletion: `Greet();`,
llmOutput: "Greet();",
expectedCompletion: "Greet();",
},
{
description: "Should autocomplete inside C# method with if condition",
@ -1696,8 +1697,8 @@ public class Calculator
return 0;
}
}`,
llmOutput: `a > 0 && b > 0`,
expectedCompletion: `a > 0 && b > 0`,
llmOutput: "a > 0 && b > 0",
expectedCompletion: "a > 0 && b > 0",
},
{
description: "Should complete a simple Julia function",
@ -1706,8 +1707,8 @@ public class Calculator
<|fim|>
end
`,
llmOutput: `return length * width`,
expectedCompletion: `return length * width`,
llmOutput: "return length * width",
expectedCompletion: "return length * width",
},
{
description: "Should autocomplete Julia for loop",
@ -1721,8 +1722,8 @@ end
println(squared_numbers)
`,
llmOutput: `push!(squared_numbers, num^2)`,
expectedCompletion: `push!(squared_numbers, num^2)`,
llmOutput: "push!(squared_numbers, num^2)",
expectedCompletion: "push!(squared_numbers, num^2)",
},
{
description: "Should complete a Julia struct definition",
@ -1756,8 +1757,8 @@ end
println(get_grade("Alice")) # Should print 90
`,
llmOutput: `student_name`,
expectedCompletion: `student_name`,
llmOutput: "student_name",
expectedCompletion: "student_name",
},
{
description: "Should complete a Julia module declaration",
@ -1776,8 +1777,8 @@ end
<|fim|>
`,
llmOutput: `end`,
expectedCompletion: `end`,
llmOutput: "end",
expectedCompletion: "end",
},
{
description: "Should complete F# let-binding with function definition",
@ -1786,8 +1787,8 @@ end
let calculateArea length width =
<|fim|>`,
llmOutput: `length * width`,
expectedCompletion: `length * width`,
llmOutput: "length * width",
expectedCompletion: "length * width",
},
{
@ -1828,8 +1829,8 @@ let john = { FirstName = "John"; LastName = "Doe"; Age = 30 }`,
input: `let squares = [ for x in 1..10 -> x * x ]
let evenSquares = [ for x in squares do if x % 2 = 0 then yield x ]
let oddSquares = [<|fim|>]`,
llmOutput: ` for x in squares do if x % 2 <> 0 then yield x ]`,
expectedCompletion: ` for x in squares do if x % 2 <> 0 then yield x ]`,
llmOutput: " for x in squares do if x % 2 <> 0 then yield x ]",
expectedCompletion: " for x in squares do if x % 2 <> 0 then yield x ]",
},
{
description: "Should complete an F# recursive function",
@ -1837,8 +1838,8 @@ let oddSquares = [<|fim|>]`,
input: `let rec factorial n =
if n <= 1 then 1
else n <|fim|> factorial (n - 1)`,
llmOutput: `*`,
expectedCompletion: `*`,
llmOutput: "*",
expectedCompletion: "*",
},
{
description: "Should complete F# member method inside a class type",
@ -1919,8 +1920,8 @@ let oddSquares = [<|fim|>]`,
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
}`,
llmOutput: ` transition(all 0.3s ease);`,
expectedCompletion: ` transition(all 0.3s ease);`,
llmOutput: " transition(all 0.3s ease);",
expectedCompletion: " transition(all 0.3s ease);",
},
{
@ -1937,8 +1938,8 @@ $secondary-color: #6c757d;
color: #fff;
border-radius: 4px;
}`,
llmOutput: `$primary-`,
expectedCompletion: `$primary-`,
llmOutput: "$primary-",
expectedCompletion: "$primary-",
},
{
description: "Should autocomplete Vue component method",
@ -2027,8 +2028,8 @@ export default {
};
</script>
`,
llmOutput: `this.completed`,
expectedCompletion: `this.completed`,
llmOutput: "this.completed",
expectedCompletion: "this.completed",
},
{
description: "Should autocomplete Svelte reactive statement",
@ -2048,8 +2049,8 @@ export default {
Clicked {count} times
</button>
`,
llmOutput: `doubledCount = count * 2`,
expectedCompletion: `doubledCount = count * 2`,
llmOutput: "doubledCount = count * 2",
expectedCompletion: "doubledCount = count * 2",
},
{
@ -2065,8 +2066,8 @@ export default {
<ChildComponent <|fim|> />
</main>
`,
llmOutput: `name="World"`,
expectedCompletion: `name="World"`,
llmOutput: "name=\"World\"",
expectedCompletion: "name=\"World\"",
},
{
@ -2083,7 +2084,7 @@ export default {
{/each<|fim|>
</ul>
`,
llmOutput: `}`,
expectedCompletion: `}`,
llmOutput: "}",
expectedCompletion: "}",
},
];

View file

@ -1,5 +1,6 @@
import fs from "node:fs";
import path from "node:path";
import Mock from "../../../llm/llms/Mock";
import { testConfigHandler, testIde } from "../../../test/util/fixtures";
import { CompletionProvider } from "../../CompletionProvider";

View file

@ -1,6 +1,7 @@
import { CompletionOptions, ILLM } from "../..";
import { StreamTransformPipeline } from "../filtering/streamTransforms/StreamTransformPipeline";
import { HelperVars } from "../util/HelperVars";
import { GeneratorReuseManager } from "./GeneratorReuseManager";
export class CompletionStreamer {

View file

@ -1,7 +1,8 @@
import type { ILLM } from "../../index.js";
import { longestCommonSubsequence } from "../../util/lcs.js";
import { lineIsRepeated } from "../filtering/streamTransforms/lineStream.js";
import type { ILLM } from "../../index.js";
function rewritesLineAbove(completion: string, prefix: string): boolean {
const lineAbove = prefix
.split("\n")

View file

@ -1,4 +1,5 @@
import path from "node:path";
import { IDE } from "../..";
import { getBasename } from "../../util";
import { getConfigJsonPath } from "../../util/paths";

View file

@ -1,7 +1,6 @@
import { IDE } from "../..";
import { getRangeInString } from "../../util/ranges";
import { languageForFilepath } from "../constants/AutocompleteLanguageInfo";
import { AutocompleteInput } from "../util/types";
/**

View file

@ -1,9 +1,11 @@
import Handlebars from "handlebars";
import { CompletionOptions } from "../..";
import { getBasename, getLastNPathParts } from "../../util";
import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo";
import { AutocompleteSnippet } from "../context/ranking";
import { HelperVars } from "../util/HelperVars";
import {
AutocompleteTemplate,
getTemplateForModel,

View file

@ -1,6 +1,7 @@
import { logDevData } from "../../util/devdata";
import { COUNT_COMPLETION_REJECTED_AFTER } from "../../util/parameters";
import { Telemetry } from "../../util/posthog";
import { AutocompleteOutcome } from "./types";
export class AutocompleteLoggingService {

View file

@ -1,6 +1,7 @@
import { Mutex } from "async-mutex";
import { open } from "sqlite";
import sqlite3 from "sqlite3";
import {
DatabaseConnection,
truncateSqliteLikePattern,

View file

@ -9,6 +9,7 @@ import {
languageForFilepath,
} from "../constants/AutocompleteLanguageInfo";
import { constructInitialPrefixSuffix } from "../templating/constructPrefixSuffix";
import { AstPath, getAst, getTreePathAtCursor } from "./ast";
import { AutocompleteInput } from "./types";
@ -38,7 +39,7 @@ export class HelperVars {
private async init() {
// Don't do anything if already initialized
if (this._fileContents !== undefined) return;
if (this._fileContents !== undefined) {return;}
this._fileContents =
this.input.manuallyPassFileContents ??

View file

@ -1,4 +1,5 @@
import Parser from "web-tree-sitter";
import { RangeInFileWithContents } from "../../commands/util.js";
import { getParserForFile } from "../../util/treeSitter.js";

View file

@ -1,6 +1,7 @@
import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
import { stripImages } from "../llm/images";
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
import SlashCommands from "./slash";
export function slashFromCustomCommand(

View file

@ -1,4 +1,5 @@
import { SlashCommand } from "../../";
import EditSlashCommand from "./edit";
const CommentSlashCommand: SlashCommand = {

View file

@ -1,13 +1,15 @@
import { IDE, SlashCommand } from "../..";
import * as fs from "fs/promises";
import * as path from "path";
import { stripImages } from "../../llm/images";
import ignore from "ignore";
import { IDE, SlashCommand } from "../..";
import {
defaultIgnoreDir,
defaultIgnoreFile,
gitIgArrayFromFile,
} from "../../indexing/ignore";
import { stripImages } from "../../llm/images";
const LANGUAGE_DEP_MGMT_FILENAMES = [
"package.json", // JavaScript (Node.js)

View file

@ -1,6 +1,7 @@
import * as fs from "node:fs";
import { homedir } from "node:os";
import path from "path";
import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js";
import { SlashCommand } from "../../index.js";
import { stripImages } from "../../llm/images.js";

View file

@ -1,8 +1,10 @@
import fs from "node:fs";
import path from "node:path";
import { testConfigHandler } from "../test/util/fixtures";
import { TEST_DIR } from "../test/util/testDir";
import { getConfigTsPath } from "../util/paths";
import { defaultConfig } from "./default";
describe.skip("Test the ConfigHandler and E2E config loading", () => {

View file

@ -12,6 +12,7 @@ import {
} from "../index.js";
import Ollama from "../llm/llms/Ollama.js";
import { GlobalContext } from "../util/GlobalContext.js";
import { ConfigResult } from "./load.js";
import {
LOCAL_ONBOARDING_CHAT_MODEL,
@ -19,7 +20,6 @@ import {
} from "./onboarding.js";
import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js";
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
import {
ProfileDescription,
ProfileLifecycleManager,

View file

@ -1,4 +1,5 @@
import { config } from "dotenv";
import {
BrowserSerializedContinueConfig,
ContinueConfig,
@ -6,7 +7,6 @@ import {
} from "../index.js";
import { ConfigResult, finalToBrowserConfig } from "./load.js";
import { IProfileLoader } from "./profile/IProfileLoader.js";
export interface ProfileDescription {

View file

@ -3,6 +3,7 @@ import * as JSONC from "comment-json";
import * as fs from "fs";
import os from "os";
import path from "path";
import * as tar from "tar";
import {
BrowserSerializedContinueConfig,
@ -32,6 +33,7 @@ import ContinueProxyContextProvider from "../context/providers/ContinueProxyCont
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import FileContextProvider from "../context/providers/FileContextProvider";
import { contextProviderClassFromName } from "../context/providers/index";
import PromptFilesContextProvider from "../context/providers/PromptFilesContextProvider";
import { AllRerankers } from "../context/rerankers/index";
import { LLMReranker } from "../context/rerankers/llm";
import { allEmbeddingsProviders } from "../indexing/embeddings";
@ -42,6 +44,7 @@ import CustomLLMClass from "../llm/llms/CustomLLM";
import FreeTrial from "../llm/llms/FreeTrial";
import { copyOf } from "../util";
import { fetchwithRequestOptions } from "../util/fetchWithOptions";
import { GlobalContext } from "../util/GlobalContext";
import mergeJson from "../util/merge";
import {
DEFAULT_CONFIG_TS_CONTENTS,
@ -54,6 +57,7 @@ import {
getEsbuildBinaryPath,
readAllGlobalPromptFiles,
} from "../util/paths";
import {
defaultContextProvidersJetBrains,
defaultContextProvidersVsCode,
@ -67,9 +71,6 @@ import {
} from "./promptFile.js";
import { ConfigValidationError, validateConfig } from "./validation.js";
import PromptFilesContextProvider from "../context/providers/PromptFilesContextProvider";
import { GlobalContext } from "../util/GlobalContext";
export interface ConfigResult<T> {
config: T | undefined;
errors: ConfigValidationError[] | undefined;
@ -135,6 +136,13 @@ function loadSerializedConfig(
config.allowAnonymousTelemetry = true;
}
if (config.ui?.getChatTitles === undefined) {
config.ui = {
...config.ui,
getChatTitles: true,
};
}
if (ideSettings.remoteConfigServerUrl) {
try {
const remoteConfigJson = resolveSerializedConfig(
@ -207,7 +215,10 @@ async function serializedToIntermediateConfig(
promptFiles.push(...readAllGlobalPromptFiles());
for (const file of promptFiles) {
slashCommands.push(slashCommandFromPromptFile(file.path, file.content));
const slashCommand = slashCommandFromPromptFile(file.path, file.content);
if (slashCommand) {
slashCommands.push(slashCommand);
}
}
}

View file

@ -1,4 +1,5 @@
import { SerializedContinueConfig } from "../";
import { FREE_TRIAL_MODELS } from "./default";
export const TRIAL_FIM_MODEL = "codestral-latest";

View file

@ -1,4 +1,5 @@
import { ConfigJson } from "@continuedev/config-types";
import { ControlPlaneClient } from "../../control-plane/client.js";
import {
ContinueConfig,
@ -7,8 +8,9 @@ import {
SerializedContinueConfig,
} from "../../index.js";
import { ConfigResult } from "../load.js";
import { IProfileLoader } from "./IProfileLoader.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";
export default class ControlPlaneProfileLoader implements IProfileLoader {
private static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes

View file

@ -1,6 +1,7 @@
import { ControlPlaneClient } from "../../control-plane/client.js";
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
import { ConfigResult } from "../load.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";

View file

@ -1,12 +1,21 @@
import Handlebars from "handlebars";
import path from "path";
import Handlebars from "handlebars";
import * as YAML from "yaml";
import type { ChatHistory, ChatHistoryItem, ChatMessage, ContextItem, ContinueSDK, IContextProvider, IDE, SlashCommand } from "..";
import { walkDir } from "../indexing/walkDir";
import { stripImages } from "../llm/images";
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
import { getBasename } from "../util/index";
import { BaseContextProvider } from "../context";
import type {
ChatMessage,
ContextItem,
ContinueSDK,
IContextProvider,
IDE,
SlashCommand,
} from "..";
export const DEFAULT_PROMPTS_FOLDER = ".prompts";
@ -90,12 +99,16 @@ export async function createNewPromptFile(
export function slashCommandFromPromptFile(
path: string,
content: string,
): SlashCommand {
const { name, description, systemMessage, prompt } = parsePromptFile(
): SlashCommand | null {
const { name, description, systemMessage, prompt, version } = parsePromptFile(
path,
content,
);
if (version !== 1) {
return null;
}
return {
name,
description,
@ -131,6 +144,7 @@ function parsePromptFile(path: string, content: string) {
const preamble = YAML.parse(preambleRaw) ?? {};
const name = preamble.name ?? getBasename(path).split(".prompt")[0];
const description = preamble.description ?? name;
const version = preamble.version ?? 2;
let systemMessage: string | undefined = undefined;
if (prompt.includes("<system>")) {
@ -138,7 +152,7 @@ function parsePromptFile(path: string, content: string) {
prompt = prompt.split("</system>")[1].trim();
}
return { name, description, systemMessage, prompt };
return { name, description, systemMessage, prompt, version };
}
function extractUserInput(input: string, commandName: string): string {
@ -148,7 +162,11 @@ function extractUserInput(input: string, commandName: string): string {
return input;
}
async function renderPrompt(prompt: string, context: ContinueSDK, userInput: string) {
async function renderPrompt(
prompt: string,
context: ContinueSDK,
userInput: string,
) {
const helpers = getContextProviderHelpers(context);
// A few context providers that don't need to be in config.json to work in .prompt files

View file

@ -628,6 +628,11 @@ declare global {
| "mistral-large-latest"
| "mistral-7b"
| "mistral-8x7b"
| "mistral-8x22b"
| "mistral-tiny"
| "mistral-small"
| "mistral-medium"
| "mistral-nemo"
// Llama 2
| "llama2-7b"
| "llama2-13b"
@ -641,6 +646,8 @@ declare global {
| "llama3-70b"
// Other Open-source
| "phi2"
| "phi-3-mini"
| "phi-3-medium"
| "phind-codellama-34b"
| "wizardcoder-7b"
| "wizardcoder-13b"
@ -649,9 +656,12 @@ declare global {
| "codeup-13b"
| "deepseek-7b"
| "deepseek-33b"
| "deepseek-2-lite"
| "neural-chat-7b"
| "gemma-7b-it"
| "gemma2-2b-it"
| "gemma2-9b-it"
| "olmo-7b"
// Anthropic
| "claude-3-5-sonnet-latest"
| "claude-3-5-sonnet-20240620"
@ -669,10 +679,6 @@ declare global {
| "gemini-1.5-pro"
| "gemini-1.5-flash-latest"
| "gemini-1.5-flash"
// Mistral
| "mistral-tiny"
| "mistral-small"
| "mistral-medium"
// Tab autocomplete
| "deepseek-1b"
| "starcoder-1b"

View file

@ -1,9 +1,9 @@
import { BaseContextProvider } from "../";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
} from "../../";
import { BaseContextProvider } from "../";
import { retrieveContextItemsFromEmbeddings } from "../retrieval/retrieval";
class CodebaseContextProvider extends BaseContextProvider {

View file

@ -1,10 +1,10 @@
import { BaseContextProvider } from "../";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
} from "../../";
import { getBasename } from "../../util/";
import { BaseContextProvider } from "../";
class CurrentFileContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {

View file

@ -1,3 +1,5 @@
import { getDatabaseAdapter } from "dbinfoz";
import {
ContextItem,
ContextProviderDescription,
@ -6,7 +8,6 @@ import {
LoadSubmenuItemsArgs,
} from "../../index.js";
import { BaseContextProvider } from "../index.js";
import { getDatabaseAdapter } from "dbinfoz";
class DatabaseContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {

View file

@ -1,4 +1,3 @@
import { INSTRUCTIONS_BASE_ITEM } from "./utils";
import { BaseContextProvider } from "../";
import {
Chunk,
@ -12,6 +11,8 @@ import DocsService from "../../indexing/docs/DocsService";
import preIndexedDocs from "../../indexing/docs/preIndexedDocs";
import { Telemetry } from "../../util/posthog";
import { INSTRUCTIONS_BASE_ITEM } from "./utils";
class DocsContextProvider extends BaseContextProvider {
static nRetrieve = 30;
static nFinal = 15;

View file

@ -1,4 +1,5 @@
import { AxiosError, AxiosInstance } from "axios";
import {
ContextItem,
ContextProviderDescription,

View file

@ -1,12 +1,14 @@
import { execSync } from "child_process";
import * as fs from "fs";
import * as path from "path";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
} from "../../index.js";
import { BaseContextProvider } from "../index.js";
import { execSync } from "child_process";
import * as path from "path";
import * as fs from "fs";
class GreptileContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
@ -35,7 +37,7 @@ import {
throw new Error("Failed to determine the workspace directory.");
}
var remoteUrl = getRemoteUrl(absPath)
var remoteUrl = getRemoteUrl(absPath);
remoteUrl = getRemoteUrl(absPath);
const repoName = extractRepoName(remoteUrl);
const branch = getCurrentBranch(absPath);
@ -46,11 +48,11 @@ import {
}
const options = {
method: 'POST',
method: "POST",
headers: {
Authorization: `Bearer ${greptileToken}`,
'X-GitHub-Token': githubToken,
'Content-Type': 'application/json',
"X-GitHub-Token": githubToken,
"Content-Type": "application/json",
},
body: JSON.stringify({
messages: [{ id: "<string>", content: query, role: "user" }],
@ -66,7 +68,7 @@ import {
};
try {
const response = await extras.fetch('https://api.greptile.com/v2/query', options);
const response = await extras.fetch("https://api.greptile.com/v2/query", options);
const rawText = await response.text();
// Check for HTTP errors
@ -84,7 +86,7 @@ import {
}));
} catch (error) {
console.error("Error getting context items from Greptile:", error);
throw new Error(`Error getting context items from Greptile`);
throw new Error("Error getting context items from Greptile");
}
}
@ -102,34 +104,34 @@ import {
if (workspaceDirs && workspaceDirs.length > 0) {
return workspaceDirs[0];
} else {
console.warn(`extras.ide.getWorkspaceDirs() returned undefined or empty array.`);
console.warn("extras.ide.getWorkspaceDirs() returned undefined or empty array.");
}
} catch (err) {
console.warn(`Failed to get workspace directories from extras.ide.getWorkspaceDirs():`);
console.warn("Failed to get workspace directories from extras.ide.getWorkspaceDirs():");
}
// Fallback to using Git commands
try {
const currentDir = process.cwd();
if (this.isGitRepository(currentDir)) {
const workspaceDir = execSync('git rev-parse --show-toplevel').toString().trim();
const workspaceDir = execSync("git rev-parse --show-toplevel").toString().trim();
return workspaceDir;
} else {
console.warn(`Current directory is not a Git repository: ${currentDir}`);
return null;
}
} catch (err) {
console.warn(`Failed to get workspace directory using Git commands: `);
console.warn("Failed to get workspace directory using Git commands: ");
return null;
}
}
private isGitRepository(dir: string): boolean {
try {
const gitDir = path.join(dir, '.git');
const gitDir = path.join(dir, ".git");
return fs.existsSync(gitDir);
} catch (err) {
console.warn(`Failed to check if directory is a Git repository:`);
console.warn("Failed to check if directory is a Git repository:");
return false;
}
}
@ -141,7 +143,7 @@ import {
const remote = execSync(`git -C ${absPath} remote get-url origin`).toString().trim();
return remote;
} catch (err) {
console.warn(`Failed to get remote URL`);
console.warn("Failed to get remote URL");
return "";
}
}
@ -151,7 +153,7 @@ import {
const branch = execSync(`git -C ${absPath} rev-parse --abbrev-ref HEAD`).toString().trim();
return branch;
} catch (err) {
console.warn(`Failed to get current branch`);
console.warn("Failed to get current branch");
return "master"; // Default to 'master' if the current branch cannot be determined
}
}

View file

@ -1,7 +1,8 @@
import { RequestOptions } from "../../../";
// @ts-ignore
import adf2md from "adf-to-md";
import { RequestOptions } from "../../../";
interface JiraClientOptions {
domain: string;
username: string;

View file

@ -6,6 +6,7 @@ import {
LoadSubmenuItemsArgs,
} from "../../../index.js";
import { BaseContextProvider } from "../../index.js";
import { JiraClient } from "./JiraClient.js";
class JiraIssuesContextProvider extends BaseContextProvider {

View file

@ -1,4 +1,5 @@
import os from "os";
import {
ContextItem,
ContextProviderDescription,

View file

@ -1,6 +1,7 @@
import { Readability } from "@mozilla/readability";
import { JSDOM } from "jsdom";
import { NodeHtmlMarkdown } from "node-html-markdown";
import { BaseContextProvider } from "../";
import {
ContextItem,

View file

@ -1,5 +1,6 @@
import { BaseContextProvider } from "../";
import { ContextProviderName } from "../../";
import CodeContextProvider from "./CodeContextProvider";
import ContinueProxyContextProvider from "./ContinueProxyContextProvider";
import CurrentFileContextProvider from "./CurrentFileContextProvider";
@ -16,8 +17,8 @@ import GoogleContextProvider from "./GoogleContextProvider";
import GreptileContextProvider from "./GreptileContextProvider";
import HttpContextProvider from "./HttpContextProvider";
import JiraIssuesContextProvider from "./JiraIssuesContextProvider/";
import OSContextProvider from "./OSContextProvider";
import OpenFilesContextProvider from "./OpenFilesContextProvider";
import OSContextProvider from "./OSContextProvider";
import PostgresContextProvider from "./PostgresContextProvider";
import ProblemsContextProvider from "./ProblemsContextProvider";
import RepoMapContextProvider from "./RepoMapContextProvider";

View file

@ -1,4 +1,5 @@
import fetch from "node-fetch";
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
import { Chunk, Reranker } from "../../index.js";

View file

@ -1,4 +1,5 @@
import fetch from "node-fetch";
import { Chunk, Reranker } from "../../index.js";
export class CohereReranker implements Reranker {

View file

@ -1,4 +1,5 @@
import fetch from "node-fetch";
import { getHeaders } from "../../continueServer/stubs/headers.js";
import { TRIAL_PROXY_URL } from "../../control-plane/client.js";
import { Chunk, Reranker } from "../../index.js";

View file

@ -1,4 +1,5 @@
import { RerankerName } from "../../index.js";
import { CohereReranker } from "./cohere.js";
import { ContinueProxyReranker } from "./ContinueProxyReranker.js";
import { FreeTrialReranker } from "./freeTrial.js";

View file

@ -1,4 +1,5 @@
import fetch from "node-fetch";
import { Chunk, Reranker } from "../../index.js";
export class HuggingFaceTEIReranker implements Reranker {

View file

@ -1,4 +1,5 @@
import fetch from "node-fetch";
import { Chunk, Reranker } from "../../index.js";
export class VoyageReranker implements Reranker {

View file

@ -1,4 +1,5 @@
import QuickLRU from "quick-lru";
import { ToWebviewOrCoreFromIdeProtocol } from "../../protocol/ide.js";
// The cache key and value are both a filepath string

View file

@ -1,5 +1,7 @@
import { Analytics } from "@continuedev/config-types";
import os from "node:os";
import { Analytics } from "@continuedev/config-types";
import ContinueProxyAnalyticsProvider from "./analytics/ContinueProxyAnalyticsProvider.js";
import {
ControlPlaneProxyInfo,

View file

@ -1,6 +1,8 @@
import { Analytics } from "@continuedev/config-types";
import fetch from "node-fetch";
import { ControlPlaneClient } from "../client.js";
import {
ControlPlaneProxyInfo,
IAnalyticsProvider,

View file

@ -1,5 +1,7 @@
import { Analytics } from "@continuedev/config-types";
import net from "node:net";
import { Analytics } from "@continuedev/config-types";
import {
ControlPlaneProxyInfo,
IAnalyticsProvider,

View file

@ -1,4 +1,5 @@
import { Analytics } from "@continuedev/config-types";
import {
ControlPlaneProxyInfo,
IAnalyticsProvider,

View file

@ -1,6 +1,8 @@
import { ConfigJson } from "@continuedev/config-types";
import fetch, { RequestInit, Response } from "node-fetch";
import { ModelDescription } from "../index.js";
import { controlPlaneEnv } from "./env.js";
export interface ControlPlaneSessionInfo {

View file

@ -1,7 +1,8 @@
import ignore from "ignore";
import path from "path";
import ignore from "ignore";
import { v4 as uuidv4 } from "uuid";
import type { ContextItemId, IDE, IndexingProgressUpdate } from ".";
import { CompletionProvider } from "./autocomplete/CompletionProvider";
import { ConfigHandler } from "./config/ConfigHandler";
import {
@ -21,18 +22,20 @@ import DocsService from "./indexing/docs/DocsService";
import { defaultIgnoreFile } from "./indexing/ignore.js";
import Ollama from "./llm/llms/Ollama";
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import { GlobalContext } from "./util/GlobalContext";
import { ChatDescriber } from "./util/chatDescriber";
import { logDevData } from "./util/devdata";
import { DevDataSqliteDb } from "./util/devdataSqlite";
import { fetchwithRequestOptions } from "./util/fetchWithOptions";
import { GlobalContext } from "./util/GlobalContext";
import historyManager from "./util/history";
import type { IMessenger, Message } from "./util/messenger";
import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths";
import { Telemetry } from "./util/posthog";
import { TTS } from "./util/tts";
import type { ContextItemId, IDE, IndexingProgressUpdate } from ".";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./util/messenger";
export class Core {
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
configHandler: ConfigHandler;

View file

@ -1,4 +1,5 @@
import { dedent } from "../util";
import { myersDiff } from "./myers";
describe("Test myers diff function", () => {

View file

@ -1,4 +1,5 @@
import { diffLines, type Change } from "diff";
import { DiffLine } from "..";
export function convertMyersChangeToDiffLines(change: Change): DiffLine[] {

View file

@ -1,9 +1,10 @@
import fs from "node:fs";
import { streamDiff } from "../diff/streamDiff.js";
import { DiffLine, DiffLineType } from "../index.js";
import path from "node:path";
// @ts-ignore no typings available
import { changed, diff as myersDiff } from "myers-diff";
import path from "node:path";
import { streamDiff } from "../diff/streamDiff.js";
import { DiffLine, DiffLineType } from "../index.js";
import { generateLines } from "./util.js";
// "modification" is an extra type used to represent an "old" + "new" diff line

View file

@ -1,4 +1,5 @@
import { DiffLine, DiffLineType } from "../index.js";
import { LineStream, matchLine } from "./util.js";
/**

View file

@ -1,4 +1,5 @@
import { distance } from "fastest-levenshtein";
import { ChatMessage } from "../index.js";
import { stripImages } from "../llm/images.js";

View file

@ -1,7 +1,9 @@
import path from "path";
import { DiffLine, ILLM } from "../..";
import { generateLines } from "../../diff/util";
import { supportedLanguages } from "../../util/treeSitter";
import { deterministicApplyLazyEdit } from "./deterministic";
import { streamLazyApply } from "./streamLazyApply";

View file

@ -1,8 +1,8 @@
import fs from "node:fs";
import path from "node:path";
// @ts-ignore no typings available
import { diff as myersDiff } from "myers-diff";
import path from "node:path";
import { DiffLine } from "../..";
import { myersDiff as continueMyersDiff } from "../../diff/myers";
import { dedent } from "../../util";

View file

@ -1,10 +1,13 @@
import { distance } from "fastest-levenshtein";
import path from "path";
import { distance } from "fastest-levenshtein";
import Parser from "web-tree-sitter";
import { DiffLine } from "../..";
import { LANGUAGES } from "../../autocomplete/constants/AutocompleteLanguageInfo";
import { myersDiff } from "../../diff/myers";
import { getParserForFile } from "../../util/treeSitter";
import { findInAst } from "./findInAst";
type AstReplacements = Array<{

View file

@ -6,6 +6,7 @@ import {
import { streamDiff } from "../../diff/streamDiff.js";
import { LineStream, streamLines } from "../../diff/util.js";
import { DiffLine, ILLM } from "../../index.js";
import { lazyApplyPromptForModel, UNCHANGED_CODE } from "./prompts.js";
import { BUFFER_LINES_BELOW, getReplacementWithLlm } from "./replace.js";

26
core/index.d.ts vendored
View file

@ -45,12 +45,12 @@ export interface IndexingProgressUpdate {
debugInfo?: string;
}
export type PromptTemplate =
| string
| ((
history: ChatMessage[],
otherData: Record<string, string>,
) => string | ChatMessage[]);
export type PromptTemplateFunction = (
history: ChatMessage[],
otherData: Record<string, string>,
) => string | ChatMessage[];
export type PromptTemplate = string | PromptTemplateFunction;
export interface ILLM extends LLMOptions {
get providerName(): ModelProvider;
@ -685,10 +685,12 @@ export type ModelName =
| "mistral-large-latest"
| "mistral-7b"
| "mistral-8x7b"
| "mistral-8x22b"
| "mistral-tiny"
| "mistral-small"
| "mistral-medium"
| "mistral-embed"
| "mistral-nemo"
// Llama 2
| "llama2-7b"
| "llama2-13b"
@ -713,6 +715,8 @@ export type ModelName =
| "grok-beta"
// Other Open-source
| "phi2"
| "phi-3-mini"
| "phi-3-medium"
| "phind-codellama-34b"
| "wizardcoder-7b"
| "wizardcoder-13b"
@ -721,9 +725,13 @@ export type ModelName =
| "codeup-13b"
| "deepseek-7b"
| "deepseek-33b"
| "deepseek-2-lite"
| "neural-chat-7b"
| "gemma-7b-it"
| "gemma2-2b-it"
| "gemma2-9b-it"
| "olmo-7b"
| "qwen-coder2.5-7b"
// Anthropic
| "claude-3-5-sonnet-latest"
| "claude-3-5-sonnet-20240620"
@ -941,6 +949,7 @@ export interface ContinueUIConfig {
fontSize?: number;
displayRawMarkdown?: boolean;
showChatScrollbar?: boolean;
getChatTitles?: boolean;
}
interface ContextMenuConfig {
@ -1003,11 +1012,6 @@ interface ExperimentalConfig {
*/
readResponseTTS?: boolean;
/**
* Prompt the user's LLM for a title given the current chat content
*/
getChatTitles?: boolean;
/**
* If set to true, we will attempt to pull down and install an instance of Chromium
* that is compatible with the current version of Puppeteer.

View file

@ -1,10 +1,12 @@
import { jest } from "@jest/globals";
import { testIde } from "../test/util/fixtures";
import {
insertMockChunks,
mockPathAndCacheKey,
updateIndexAndAwaitGenerator,
} from "../test/util/indexing";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import { IndexResultType } from "./types";

View file

@ -1,4 +1,21 @@
import Parser from "web-tree-sitter";
import { getBasename, getLastNPathParts } from "../util/";
import { migrate } from "../util/paths";
import {
TSQueryType,
getParserForFile,
getQueryForFile,
} from "../util/treeSitter";
import { DatabaseConnection, SqliteDb, tagToString, truncateSqliteLikePattern } from "./refreshIndex";
import {
IndexResultType,
MarkCompleteCallback,
RefreshIndexResults,
type CodebaseIndex,
} from "./types";
import type {
ChunkWithoutID,
ContextItem,
@ -7,20 +24,6 @@ import type {
IndexTag,
IndexingProgressUpdate,
} from "../";
import { getBasename, getLastNPathParts } from "../util/";
import { migrate } from "../util/paths";
import {
TSQueryType,
getParserForFile,
getQueryForFile,
} from "../util/treeSitter";
import { DatabaseConnection, SqliteDb, tagToString, truncateSqliteLikePattern } from "./refreshIndex";
import {
IndexResultType,
MarkCompleteCallback,
RefreshIndexResults,
type CodebaseIndex,
} from "./types";
type SnippetChunk = ChunkWithoutID & { title: string; signature: string };

View file

@ -1,7 +1,9 @@
import { jest } from "@jest/globals";
import { execSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { jest } from "@jest/globals";
import { ContinueServerClient } from "../continueServer/stubs/client.js";
import { testConfigHandler, testIde } from "../test/util/fixtures.js";
import {
@ -11,6 +13,7 @@ import {
TEST_DIR,
} from "../test/util/testDir.js";
import { getIndexSqlitePath } from "../util/paths.js";
import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js";
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
@ -73,8 +76,8 @@ describe("CodebaseIndexer", () => {
setUpTestDir();
execSync("git init", { cwd: TEST_DIR });
execSync('git config user.email "test@example.com"', { cwd: TEST_DIR });
execSync('git config user.name "Test"', { cwd: TEST_DIR });
execSync("git config user.email \"test@example.com\"", { cwd: TEST_DIR });
execSync("git config user.name \"Test\"", { cwd: TEST_DIR });
});
afterAll(async () => {

View file

@ -1,9 +1,11 @@
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 { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";

View file

@ -1,9 +1,11 @@
import { jest } from "@jest/globals";
import {
insertMockChunks,
mockPathAndCacheKey,
updateIndexAndAwaitGenerator,
} from "../test/util/indexing";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import { IndexResultType } from "./types";

View file

@ -1,5 +1,6 @@
import { jest } from "@jest/globals";
import lance from "vectordb";
import { testConfigHandler, testIde } from "../test/util/fixtures";
import {
mockPathAndCacheKey,
@ -8,6 +9,7 @@ import {
updateIndexAndAwaitGenerator,
} from "../test/util/indexing";
import { getLanceDbPath } from "../util/paths";
import { LanceDbIndex } from "./LanceDbIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import { IndexResultType } from "./types";

View file

@ -2,6 +2,7 @@
import { RunResult } from "sqlite3";
import { v4 as uuidv4 } from "uuid";
import lance, { Table } from "vectordb";
import { IContinueServerClient } from "../continueServer/interface.js";
import {
BranchAndDir,
@ -12,6 +13,7 @@ import {
} from "../index.js";
import { getBasename } from "../util/index.js";
import { getLanceDbPath, migrate } from "../util/paths.js";
import { chunkDocument, shouldChunk } from "./chunk/chunk.js";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js";
import {

View file

@ -1,4 +1,3 @@
import type { IndexTag, IndexingProgressUpdate } from "../index.js";
import { DatabaseConnection, SqliteDb } from "./refreshIndex.js";
import {
IndexResultType,
@ -7,6 +6,8 @@ import {
type CodebaseIndex,
} from "./types.js";
import type { IndexTag, IndexingProgressUpdate } from "../index.js";
/**
* This is a CodebaseIndex used for testing which files get indexed.
* It maintains a SQLite database of all file/tag pairs

View file

@ -1,4 +1,5 @@
import { jest } from "@jest/globals";
import { testIde } from "../../test/util/fixtures";
import {
mockFileContents,
@ -10,6 +11,7 @@ import {
import { addToTestDir } from "../../test/util/testDir";
import { DatabaseConnection, SqliteDb } from "../refreshIndex";
import { IndexResultType } from "../types";
import { ChunkCodebaseIndex } from "./ChunkCodebaseIndex";
jest.useFakeTimers();

View file

@ -1,5 +1,7 @@
import * as path from "path";
import { RunResult } from "sqlite3";
import { IContinueServerClient } from "../../continueServer/interface.js";
import { Chunk, IndexTag, IndexingProgressUpdate } from "../../index.js";
import { getBasename } from "../../util/index.js";
@ -11,6 +13,7 @@ import {
RefreshIndexResults,
type CodebaseIndex,
} from "../types.js";
import { chunkDocument, shouldChunk } from "./chunk.js";
export class ChunkCodebaseIndex implements CodebaseIndex {

View file

@ -1,4 +1,5 @@
import path from "path";
import { shouldChunk } from "./chunk";
describe("shouldChunk", () => {

View file

@ -3,6 +3,7 @@ import { countTokensAsync } from "../../llm/countTokens.js";
import { extractMinimalStackTraceInfo } from "../../util/extractMinimalStackTraceInfo.js";
import { Telemetry } from "../../util/posthog.js";
import { supportedLanguages } from "../../util/treeSitter.js";
import { basicChunker } from "./basic.js";
import { codeChunker } from "./code.js";

View file

@ -1,4 +1,5 @@
import { ChunkWithoutID } from "../..";
import { codeChunker } from "./code";
async function genToArr<T>(generator: AsyncGenerator<T>): Promise<T[]> {

View file

@ -1,4 +1,5 @@
import { SyntaxNode } from "web-tree-sitter";
import { ChunkWithoutID } from "../../index.js";
import { countTokensAsync } from "../../llm/countTokens.js";
import { getParserForFile } from "../../util/treeSitter.js";

View file

@ -1,5 +1,6 @@
import { ChunkWithoutID } from "../../";
import { countTokens } from "../../llm/countTokens";
import { basicChunker } from "./basic";
export function cleanFragment(

View file

@ -1,10 +1,13 @@
import os from "os";
import { jest } from "@jest/globals";
import { ContinueConfig } from "../..";
import { testConfigHandler } from "../../test/util/fixtures";
import FileSystemIde from "../../util/filesystem";
import DocsCrawler, { ChromiumInstaller, type PageData } from "./DocsCrawler";
import preIndexedDocs from "./preIndexedDocs";
import { jest } from "@jest/globals";
import FileSystemIde from "../../util/filesystem";
import { testConfigHandler } from "../../test/util/fixtures";
import os from "os";
import { ContinueConfig } from "../..";
// Temporary workaround until we have better caching of Chromium
// download between test runs

View file

@ -1,7 +1,9 @@
import { URL } from "node:url";
// @ts-ignore
// @prettier-ignore
import { ContinueConfig, IDE } from "../..";
import CheerioCrawler from "./crawlers/CheerioCrawler";
import { ChromiumCrawler, ChromiumInstaller } from "./crawlers/ChromiumCrawler";
import { DefaultCrawler } from "./crawlers/DefaultCrawler";

View file

@ -7,6 +7,7 @@ import { SiteIndexingConfig } from "../../index.js";
import FileSystemIde from "../../util/filesystem.js";
import { editConfigJson } from "../../util/paths.js";
import FreeTrialEmbeddingsProvider from "../embeddings/FreeTrialEmbeddingsProvider.js";
import DocsService from "./DocsService.js";
import preIndexedDocs from "./preIndexedDocs.js";

View file

@ -1,6 +1,7 @@
import { open, type Database } from "sqlite";
import sqlite3 from "sqlite3";
import lancedb, { Connection } from "vectordb";
import {
Chunk,
ContinueConfig,
@ -13,6 +14,7 @@ import { ConfigHandler } from "../../config/ConfigHandler";
import { addContextProvider } from "../../config/util";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
import { FromCoreProtocol, ToCoreProtocol } from "../../protocol";
import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon";
import { GlobalContext } from "../../util/GlobalContext";
import { IMessenger } from "../../util/messenger";
import {
@ -22,6 +24,7 @@ import {
} from "../../util/paths";
import { Telemetry } from "../../util/posthog";
import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider";
import { Article, chunkArticle, pageToArticle } from "./article";
import DocsCrawler from "./DocsCrawler";
import { runLanceMigrations, runSqliteMigrations } from "./migrations";
@ -32,7 +35,6 @@ import {
SiteIndexingResults,
} from "./preIndexed";
import preIndexedDocs from "./preIndexedDocs";
import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon";
// Purposefully lowercase because lancedb converts
export interface LanceDbDocsRow {
@ -360,11 +362,16 @@ export default class DocsService {
isPreIndexedDoc: !!preIndexedDocs[startUrl],
});
const docs: LanceDbDocsRow[] = await table
.search(vector)
.limit(nRetrieve)
.where(`starturl = '${startUrl}'`)
.execute();
let docs: LanceDbDocsRow[] = [];
try {
docs = await table
.search(vector)
.limit(nRetrieve)
.where(`starturl = '${startUrl}'`)
.execute();
} catch (e: any) {
console.error("Error retrieving chunks from LanceDB", e);
}
const hasIndexedDoc = await this.hasIndexedDoc(startUrl);
@ -551,9 +558,8 @@ export default class DocsService {
private async getLanceTableNameFromEmbeddingsProvider(
isPreIndexedDoc: boolean,
) {
const embeddingsProvider = await this.getEmbeddingsProvider(
isPreIndexedDoc,
);
const embeddingsProvider =
await this.getEmbeddingsProvider(isPreIndexedDoc);
const tableName = this.sanitizeLanceTableName(
`${DocsService.lanceTableName}${embeddingsProvider.id}`,

View file

@ -1,7 +1,9 @@
import { Readability } from "@mozilla/readability";
import { JSDOM } from "jsdom";
import { Chunk } from "../../";
import { cleanFragment, cleanHeader } from "../chunk/markdown";
import { type PageData } from "./DocsCrawler";
export type ArticleComponent = {

View file

@ -1,5 +1,7 @@
import * as cheerio from "cheerio";
import { URL } from "node:url";
import * as cheerio from "cheerio";
import { PageData } from "../DocsCrawler";
export default class CheerioCrawler {

View file

@ -1,15 +1,18 @@
import * as fs from "fs";
import { URL } from "node:url";
import { Handler, HTTPResponse, Page } from "puppeteer";
// @ts-ignore
// @prettier-ignore
import PCR from "puppeteer-chromium-resolver";
import { ContinueConfig, IDE } from "../../..";
import {
editConfigJson,
getChromiumPath,
getContinueUtilsPath,
} from "../../../util/paths";
// @ts-ignore
// @prettier-ignore
import PCR from "puppeteer-chromium-resolver";
import { ContinueConfig, IDE } from "../../..";
import { PageData } from "../DocsCrawler";
export class ChromiumCrawler {

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