This commit is contained in:
Nate Sesti 2024-06-12 09:25:40 -07:00
commit 13bb578e3e
70 changed files with 2588 additions and 21628 deletions

5
.gitignore vendored
View file

@ -163,4 +163,7 @@ continue_server.dist
Icon
Icon?
.continue
.continue
# Sandbox env default file
extensions/vscode/manual-testing-sandbox/example.ts

1
.vscode/launch.json vendored
View file

@ -56,6 +56,7 @@
"${workspaceFolder}/extensions/vscode/manual-testing-sandbox/test.js",
"--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode"
],
"pauseForSourceMap": false,
"outFiles": [
"${workspaceFolder}/extensions/vscode/out/extension.js",
"/Users/natesesti/.continue/config.ts"

View file

@ -79,7 +79,7 @@ nvm use
1. The new VS Code window with the extension is referred to as the _Host VS Code_
2. The window you started debugging from is referred to as the _Main VS Code_
4. To package the extension, run `npm package` in the `extensions/vscode` directory. This will generate `extensions/vscode/build/continue-patch.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX".
4. To package the extension, run `npm run package` in the `extensions/vscode` directory. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX".
##### Debugging

View file

@ -3,7 +3,11 @@ const fs = require("fs");
const path = require("path");
const ncp = require("ncp").ncp;
const { rimrafSync } = require("rimraf");
const { validateFilesPresent, execCmdSync } = require("../scripts/util");
const {
validateFilesPresent,
execCmdSync,
autodetectPlatformAndArch,
} = require("../scripts/util");
// Clean slate
const bin = path.join(__dirname, "bin");
@ -23,6 +27,8 @@ let targets = [
"win32-x64",
];
const [currentPlatform, currentArch] = autodetectPlatformAndArch();
const assetBackups = [
"node_modules/win-ca/lib/crypt32-ia32.node.bak",
"node_modules/win-ca/lib/crypt32-x64.node.bak",
@ -51,7 +57,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
console.log(`Copying ${packageName} to ${toCopy}`);
// This is a way to install only one package without npm trying to install all the dependencies
// Create a temporary directory for installing the package
const adjustedName = toCopy.replace(/^@/, "").replace("/", "-");
const adjustedName = packageName.replace(/@/g, "").replace("/", "-");
const tempDir = path.join(
__dirname,
"tmp",
@ -78,7 +84,6 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
);
// Without this it seems the file isn't completely written to disk
// Ideally we validate file integrity in the validation at the end
await new Promise((resolve) => setTimeout(resolve, 2000));
// Copy the installed package back to the current directory
@ -169,7 +174,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
entryPoints: ["src/index.ts"],
bundle: true,
outfile: esbuildOutputFile,
external: ["esbuild", "./xhr-sync-worker.js", "vscode"],
external: ["esbuild", "./xhr-sync-worker.js", "vscode", "./index.node"],
format: "cjs",
platform: "node",
sourcemap: true,
@ -214,6 +219,16 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
`${targetDir}/build/Release/node_sqlite3.node`,
`${targetDir}/node_sqlite3.node`,
);
// Copy to build directory for testing
const [platform, arch] = target.split("-");
if (platform === currentPlatform && arch === currentArch) {
fs.copyFileSync(
`${targetDir}/node_sqlite3.node`,
`build/node_sqlite3.node`,
);
}
fs.unlinkSync(`${targetDir}/build.tar.gz`);
fs.rmSync(`${targetDir}/build`, {
recursive: true,

View file

@ -86,6 +86,7 @@
},
"devDependencies": {
"@biomejs/biome": "1.6.4",
"@google/generative-ai": "^0.11.4",
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.11",
"@types/jquery": "^3.5.29",

View file

@ -1,27 +1,30 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"extends": ["plugin:require-extensions/recommended"],
"plugins": ["@typescript-eslint", "import", "require-extensions"],
"rules": {
"quotes": ["warn", "double", {}],
"import/extensions": ["error", "always", {
"js": "never",
"jsx": "never",
"ts": "never",
"tsx": "never"
}],
"@typescript-eslint/naming-convention": "warn",
"@typescript-eslint/semi": "warn",
"curly": "warn",
"eqeqeq": "warn",
"no-throw-literal": "warn",
"semi": "off"
},
"ignorePatterns": ["out", "dist", "**/*.d.ts"]
}
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"extends": ["plugin:require-extensions/recommended"],
"plugins": ["@typescript-eslint", "import", "require-extensions"],
"rules": {
"quotes": ["warn", "double", {}],
"import/extensions": [
"error",
"always",
{
"js": "never",
"jsx": "never",
"ts": "never",
"tsx": "never"
}
],
"@typescript-eslint/naming-convention": "warn",
"@typescript-eslint/semi": "warn",
"curly": "warn",
"eqeqeq": "warn",
"no-throw-literal": "warn",
"semi": "off"
},
"ignorePatterns": ["out", "dist", "**/*.d.ts"]
}

View file

@ -29,36 +29,43 @@ export class AutocompleteLruCache {
return new AutocompleteLruCache(db);
}
async get(key: string): Promise<string | undefined> {
async get(prefix: string): Promise<string | undefined> {
// NOTE: Right now prompts with different suffixes will be considered the same
// If the query is "co" and we have "c" -> "ontinue" in the cache,
// we should return "ntinue" as the completion.
// Have to make sure we take the key with shortest length
const result = await this.db.get(
"SELECT value FROM cache WHERE key = ?",
key,
"SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1",
prefix,
);
if (result) {
// Validate that the cached compeltion is a valid completion for the prefix
if (result && result.value.startsWith(prefix.slice(result.key.length))) {
await this.db.run(
"UPDATE cache SET timestamp = ? WHERE key = ?",
Date.now(),
key,
prefix,
);
return result.value;
// And then truncate so we aren't writing something that's already there
return result.value.slice(prefix.length - result.key.length);
}
return undefined;
}
async put(key: string, value: string) {
async put(prefix: string, completion: string) {
const result = await this.db.get(
"SELECT key FROM cache WHERE key = ?",
key,
prefix,
);
if (result) {
await this.db.run(
"UPDATE cache SET value = ?, timestamp = ? WHERE key = ?",
value,
completion,
Date.now(),
key,
prefix,
);
} else {
const count = await this.db.get("SELECT COUNT(*) as count FROM cache");
@ -71,8 +78,8 @@ export class AutocompleteLruCache {
await this.db.run(
"INSERT INTO cache (key, value, timestamp) VALUES (?, ?, ?)",
key,
value,
prefix,
completion,
Date.now(),
);
}

View file

@ -1,6 +1,7 @@
export async function* onlyWhitespaceAfterEndOfLine(
stream: AsyncGenerator<string>,
endOfLine: string[],
fullStop: () => void,
): AsyncGenerator<string> {
let pending = "";
for await (let chunk of stream) {
@ -12,6 +13,7 @@ export async function* onlyWhitespaceAfterEndOfLine(
chunk[i + 1].trim() === chunk[i + 1]
) {
yield chunk.slice(0, i + 1);
fullStop();
return;
}
}
@ -30,7 +32,7 @@ export async function* noFirstCharNewline(stream: AsyncGenerator<string>) {
for await (const char of stream) {
if (first) {
first = false;
if (char === "\n") {
if (char.startsWith("\n") || char.startsWith("\r")) {
return;
}
}

View file

@ -16,7 +16,7 @@ import {
} from "../index.js";
import OpenAI from "../llm/llms/OpenAI.js";
import { logDevData } from "../util/devdata.js";
import { getBasename } from "../util/index.js";
import { getBasename, getLastNPathParts } from "../util/index.js";
import {
COUNT_COMPLETION_REJECTED_AFTER,
DEFAULT_AUTOCOMPLETE_OPTS,
@ -43,6 +43,7 @@ import {
stopAtSimilarLine,
streamWithNewLines,
} from "./lineStream.js";
import { postprocessCompletion } from "./postprocessing.js";
import { AutocompleteSnippet } from "./ranking.js";
import { RecentlyEditedRange } from "./recentlyEdited.js";
import { getTemplateForModel } from "./templates.js";
@ -69,6 +70,8 @@ export interface AutocompleteInput {
export interface AutocompleteOutcome extends TabAutocompleteOptions {
accepted?: boolean;
time: number;
prefix: string;
suffix: string;
prompt: string;
completion: string;
modelProvider: string;
@ -76,6 +79,9 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions {
completionOptions: any;
cacheHit: boolean;
filepath: string;
gitRepo?: string;
completionId: string;
uniqueId: string;
}
const autocompleteCache = AutocompleteLruCache.get();
@ -103,7 +109,7 @@ function formatExternalSnippet(
snippet: string,
language: AutocompleteLanguageInfo,
) {
const comment = language.comment;
const comment = language.singleLineComment;
const lines = [
`${comment} Path: ${getBasename(filepath)}`,
...snippet
@ -199,8 +205,8 @@ export async function getTabCompletion(
if (input.injectDetails) {
const lines = fullPrefix.split("\n");
fullPrefix = `${lines.slice(0, -1).join("\n")}\n${
lang.comment
} ${input.injectDetails.split("\n").join(`\n${lang.comment} `)}\n${
lang.singleLineComment
} ${input.injectDetails.split("\n").join(`\n${lang.singleLineComment} `)}\n${
lines[lines.length - 1]
}`;
}
@ -265,13 +271,30 @@ export async function getTabCompletion(
}
// Template prompt
const { template, completionOptions } = options.template
const {
template,
completionOptions,
compilePrefixSuffix = undefined,
} = options.template
? { template: options.template, completionOptions: {} }
: getTemplateForModel(llm.model);
let prompt: string;
const filename = getBasename(filepath);
const reponame = getBasename(workspaceDirs[0] ?? "myproject");
// Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix
// into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint
if (compilePrefixSuffix) {
[prefix, suffix] = compilePrefixSuffix(
prefix,
suffix,
filepath,
reponame,
snippets,
);
}
if (typeof template === "string") {
const compiledTemplate = Handlebars.compile(template);
@ -283,6 +306,9 @@ export async function getTabCompletion(
.join("\n");
if (formattedSnippets.length > 0) {
prefix = `${formattedSnippets}\n\n${prefix}`;
} else if (prefix.trim().length === 0 && suffix.trim().length === 0) {
// If it's an empty file, include the file name as a comment
prefix = `${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n${prefix}`;
}
prompt = compiledTemplate({
@ -293,7 +319,7 @@ export async function getTabCompletion(
});
} else {
// Let the template function format snippets
prompt = template(prefix, suffix, filename, reponame, snippets);
prompt = template(prefix, suffix, filepath, reponame, snippets);
}
// Completion
@ -301,7 +327,7 @@ export async function getTabCompletion(
const cache = await autocompleteCache;
const cachedCompletion = options.useCache
? await cache.get(prompt)
? await cache.get(prefix)
: undefined;
let cacheHit = false;
if (cachedCompletion) {
@ -316,7 +342,8 @@ export async function getTabCompletion(
...(llm.model.toLowerCase().includes("starcoder2")
? STARCODER2_T_ARTIFACTS
: []),
...lang.stopWords.map((word) => `\n${word}`),
...(lang.stopWords ?? []),
...lang.topLevelKeywords.map((word) => `\n${word}`),
];
const multiline =
@ -341,6 +368,9 @@ export async function getTabCompletion(
multiline,
);
// Full stop means to stop the LLM's generation, instead of just truncating the displayed completion
const fullStop = () => generatorReuseManager.currentGenerator?.cancel();
// LLM
let cancelled = false;
const generatorWithCancellation = async function* () {
@ -354,7 +384,11 @@ export async function getTabCompletion(
};
let charGenerator = generatorWithCancellation();
charGenerator = noFirstCharNewline(charGenerator);
charGenerator = onlyWhitespaceAfterEndOfLine(charGenerator, lang.endOfLine);
charGenerator = onlyWhitespaceAfterEndOfLine(
charGenerator,
lang.endOfLine,
fullStop,
);
charGenerator = bracketMatchingService.stopOnUnmatchedClosingBracket(
charGenerator,
suffix,
@ -362,13 +396,26 @@ export async function getTabCompletion(
);
let lineGenerator = streamLines(charGenerator);
lineGenerator = stopAtLines(lineGenerator);
lineGenerator = stopAtRepeatingLines(lineGenerator);
lineGenerator = avoidPathLine(lineGenerator, lang.comment);
lineGenerator = noTopLevelKeywordsMidline(lineGenerator, lang.stopWords);
lineGenerator = stopAtLines(lineGenerator, fullStop);
lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop);
lineGenerator = avoidPathLine(lineGenerator, lang.singleLineComment);
lineGenerator = noTopLevelKeywordsMidline(
lineGenerator,
lang.topLevelKeywords,
fullStop,
);
for (const lineFilter of lang.lineFilters ?? []) {
lineGenerator = lineFilter({ lines: lineGenerator, fullStop });
}
lineGenerator = streamWithNewLines(lineGenerator);
const finalGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor);
const finalGenerator = stopAtSimilarLine(
lineGenerator,
lineBelowCursor,
fullStop,
);
try {
for await (const update of finalGenerator) {
@ -385,33 +432,34 @@ export async function getTabCompletion(
return undefined;
}
// Don't return empty
if (completion.trim().length <= 0) {
const processedCompletion = postprocessCompletion({
completion,
prefix,
suffix,
llm,
});
if (!processedCompletion) {
return undefined;
}
// Post-processing
completion = completion.trimEnd();
if (llm.model.includes("codestral")) {
// Codestral sometimes starts with an extra space
if (completion[0] === " " && completion[1] !== " ") {
if (prefix.endsWith(" ") && suffix.startsWith("\n")) {
completion = completion.slice(1);
}
}
}
completion = processedCompletion;
}
const time = Date.now() - startTime;
return {
time,
completion,
prefix,
suffix,
prompt,
modelProvider: llm.providerName,
modelName: llm.model,
completionOptions,
cacheHit,
filepath: input.filepath,
completionId: input.completionId,
gitRepo: await ide.getRepoName(input.filepath),
uniqueId: await ide.getUniqueId(),
...options,
};
}
@ -589,7 +637,10 @@ export class CompletionProvider {
"llamafile",
"text-gen-webui",
];
if (LOCAL_PROVIDERS.includes(llm.providerName)) {
if (
!config.tabAutocompleteOptions?.maxPromptTokens &&
LOCAL_PROVIDERS.includes(llm.providerName)
) {
options.maxPromptTokens = 500;
}
@ -617,7 +668,7 @@ export class CompletionProvider {
const completionToCache = outcome.completion;
setTimeout(async () => {
if (!outcome.cacheHit) {
(await this.autocompleteCache).put(outcome.prompt, completionToCache);
(await this.autocompleteCache).put(outcome.prefix, completionToCache);
}
}, 100);

View file

@ -68,7 +68,7 @@ async function shouldCompleteMultiline(
.split("\n")
.slice(-1)[0]
?.trimStart()
.startsWith(language.comment)
.startsWith(language.singleLineComment)
) {
return false;
}

View file

@ -1,13 +1,17 @@
import { LineFilter } from "./lineStream";
export interface AutocompleteLanguageInfo {
stopWords: string[];
comment: string;
topLevelKeywords: string[];
singleLineComment: string;
endOfLine: string[];
stopWords?: string[];
lineFilters?: LineFilter[];
}
// TypeScript
export const Typescript = {
stopWords: ["function", "class", "module", "export", "import"],
comment: "//",
topLevelKeywords: ["function", "class", "module", "export", "import"],
singleLineComment: "//",
endOfLine: [";"],
};
@ -15,63 +19,63 @@ export const Typescript = {
export const 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
stopWords: ["def", "class", "\"\"\"#"],
comment: "#",
topLevelKeywords: ["def", "class", '"""#'],
singleLineComment: "#",
endOfLine: [],
};
// Java
export const Java = {
stopWords: ["class", "function"],
comment: "//",
topLevelKeywords: ["class", "function"],
singleLineComment: "//",
endOfLine: [";"],
};
// C++
export const Cpp = {
stopWords: ["class", "namespace", "template"],
comment: "//",
topLevelKeywords: ["class", "namespace", "template"],
singleLineComment: "//",
endOfLine: [";"],
};
// C#
export const CSharp = {
stopWords: ["class", "namespace", "void"],
comment: "//",
topLevelKeywords: ["class", "namespace", "void"],
singleLineComment: "//",
endOfLine: [";"],
};
// C
export const C = {
stopWords: ["if", "else", "while", "for", "switch", "case"],
comment: "//",
topLevelKeywords: ["if", "else", "while", "for", "switch", "case"],
singleLineComment: "//",
endOfLine: [";"],
};
// Scala
export const Scala = {
stopWords: ["def", "val", "var", "class", "object", "trait"],
comment: "//",
topLevelKeywords: ["def", "val", "var", "class", "object", "trait"],
singleLineComment: "//",
endOfLine: [";"],
};
// Go
export const Go = {
stopWords: ["func", "package", "import", "type"],
comment: "//",
topLevelKeywords: ["func", "package", "import", "type"],
singleLineComment: "//",
endOfLine: [],
};
// Rust
export const Rust = {
stopWords: ["fn", "mod", "pub", "struct", "enum", "trait"],
comment: "//",
topLevelKeywords: ["fn", "mod", "pub", "struct", "enum", "trait"],
singleLineComment: "//",
endOfLine: [";"],
};
// Haskell
export const Haskell = {
stopWords: [
topLevelKeywords: [
"data",
"type",
"newtype",
@ -81,55 +85,55 @@ export const Haskell = {
"in",
"where",
],
comment: "--",
singleLineComment: "--",
endOfLine: [],
};
// PHP
export const PHP = {
stopWords: ["function", "class", "namespace", "use"],
comment: "//",
topLevelKeywords: ["function", "class", "namespace", "use"],
singleLineComment: "//",
endOfLine: [";"],
};
// Ruby on Rails
export const RubyOnRails = {
stopWords: ["def", "class", "module"],
comment: "#",
topLevelKeywords: ["def", "class", "module"],
singleLineComment: "#",
endOfLine: [],
};
// Swift
export const Swift = {
stopWords: ["func", "class", "struct", "import"],
comment: "//",
topLevelKeywords: ["func", "class", "struct", "import"],
singleLineComment: "//",
endOfLine: [";"],
};
// Kotlin
export const Kotlin = {
stopWords: ["fun", "class", "package", "import"],
comment: "//",
topLevelKeywords: ["fun", "class", "package", "import"],
singleLineComment: "//",
endOfLine: [";"],
};
// Ruby
export const Ruby = {
stopWords: ["class", "module", "def"],
comment: "#",
topLevelKeywords: ["class", "module", "def"],
singleLineComment: "#",
endOfLine: [],
};
// Clojure
export const Clojure = {
stopWords: ["def", "fn", "let", "do", "if", "defn", "ns", "defmacro"],
comment: ";",
topLevelKeywords: ["def", "fn", "let", "do", "if", "defn", "ns", "defmacro"],
singleLineComment: ";",
endOfLine: [],
};
// Julia
export const Julia = {
stopWords: [
topLevelKeywords: [
"function",
"macro",
"if",
@ -141,13 +145,13 @@ export const Julia = {
"end",
"module",
],
comment: "#",
singleLineComment: "#",
endOfLine: [";"],
};
// F#
export const FSharp = {
stopWords: [
topLevelKeywords: [
"let",
"type",
"module",
@ -159,13 +163,13 @@ export const FSharp = {
"match",
"with",
],
comment: "//",
singleLineComment: "//",
endOfLine: [],
};
// R
export const R = {
stopWords: [
topLevelKeywords: [
"function",
"if",
"else",
@ -175,20 +179,20 @@ export const R = {
"library",
"require",
],
comment: "#",
singleLineComment: "#",
endOfLine: [],
};
// Dart
export const Dart = {
stopWords: ["class", "import", "void", "enum"],
comment: "//",
topLevelKeywords: ["class", "import", "void", "enum"],
singleLineComment: "//",
endOfLine: [";"],
};
// Solidity
export const Solidity = {
stopWords: [
topLevelKeywords: [
"contract",
"event",
"modifier",
@ -204,10 +208,51 @@ export const Solidity = {
"enum",
"type",
],
comment: "//",
singleLineComment: "//",
endOfLine: [";"],
};
// YAML
export const YAML: AutocompleteLanguageInfo = {
topLevelKeywords: [],
singleLineComment: "#",
endOfLine: [],
lineFilters: [
// Only display one list item at a time
async function* ({ lines, fullStop }) {
let seenListItem = false;
for await (const line of lines) {
if (line.trim().startsWith("- ")) {
if (seenListItem) {
fullStop();
break;
} else {
seenListItem = true;
}
yield line;
} else {
yield line;
}
}
},
// Don't allow consecutive lines of same key
async function* ({ lines }) {
let lastKey = undefined;
for await (const line of lines) {
if (line.includes(":")) {
const key = line.split(":")[0];
if (key !== lastKey) {
yield line;
lastKey = key;
} else {
break;
}
}
}
},
],
};
export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
ts: Typescript,
js: Typescript,
@ -245,4 +290,5 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
R: R,
dart: Dart,
sol: Solidity,
yaml: YAML,
};

View file

@ -2,15 +2,22 @@ import { distance } from "fastest-levenshtein";
import { LineStream } from "../diff/util.js";
import { DiffLine } from "../index.js";
export type LineFilter = (args: {
lines: LineStream;
fullStop: () => void;
}) => LineStream;
export async function* noTopLevelKeywordsMidline(
lines: LineStream,
topLevelKeywords: string[],
fullStop: () => void,
): LineStream {
for await (const line of lines) {
for (const keyword of topLevelKeywords) {
const indexOf = line.indexOf(`${keyword} `);
if (indexOf >= 0 && line.slice(indexOf - 1, indexOf).trim() !== "") {
yield line.slice(0, indexOf);
fullStop();
break;
}
}
@ -63,11 +70,13 @@ function commonPrefixLength(a: string, b: string): number {
export async function* stopAtSimilarLine(
stream: LineStream,
line: string,
fullStop: () => void,
): AsyncGenerator<string> {
const trimmedLine = line.trim();
const lineIsBracketEnding = isBracketEnding(trimmedLine);
for await (const nextLine of stream) {
if (nextLine === line) {
fullStop();
break;
}
@ -79,9 +88,10 @@ export async function* stopAtSimilarLine(
let lineQualifies = nextLine.length > 4 && trimmedLine.length > 4;
if (
lineQualifies &&
(commonPrefixLength(nextLine.trim(), trimmedLine.trim()) > 8 ||
(commonPrefixLength(nextLine.trim(), trimmedLine.trim()) > 12 ||
distance(nextLine.trim(), trimmedLine) / trimmedLine.length < 0.1)
) {
fullStop();
break;
}
yield nextLine;
@ -90,9 +100,13 @@ export async function* stopAtSimilarLine(
const LINES_TO_STOP_AT = ["# End of file.", "<STOP EDITING HERE"];
export async function* stopAtLines(stream: LineStream): LineStream {
export async function* stopAtLines(
stream: LineStream,
fullStop: () => void,
): LineStream {
for await (const line of stream) {
if (LINES_TO_STOP_AT.some((stopAt) => line.trim().includes(stopAt))) {
fullStop();
break;
}
yield line;
@ -279,7 +293,10 @@ export async function* filterLeadingAndTrailingNewLineInsertion(
}
}
export async function* stopAtRepeatingLines(lines: LineStream): LineStream {
export async function* stopAtRepeatingLines(
lines: LineStream,
fullStop: () => void,
): LineStream {
const repeatedLines: string[] = [];
for await (const line of lines) {
if (repeatedLines.length === 0) {
@ -295,6 +312,7 @@ export async function* stopAtRepeatingLines(lines: LineStream): LineStream {
}
} else {
yield repeatedLines[0];
fullStop();
return;
}
}

View file

@ -0,0 +1,43 @@
import { ILLM } from "..";
export function postprocessCompletion({
completion,
llm,
prefix,
suffix,
}: {
completion: string;
llm: ILLM;
prefix: string;
suffix: string;
}): string | undefined {
// Don't return empty
if (completion.trim().length <= 0) {
return undefined;
}
// Remove trailing whitespace
completion = completion.trimEnd();
if (llm.model.includes("codestral")) {
// Codestral sometimes starts with an extra space
if (completion[0] === " " && completion[1] !== " ") {
if (prefix.endsWith(" ") && suffix.startsWith("\n")) {
completion = completion.slice(1);
}
}
}
// If completion starts with multiple whitespaces, but the cursor is at the end of the line
// then it should probably be on a new line
if (
(completion.startsWith(" ") || completion.startsWith("\t")) &&
!prefix.endsWith("\n") &&
(suffix.startsWith("\n") || suffix.trim().length === 0)
) {
// completion = "\n" + completion;
return undefined;
}
return completion;
}

View file

@ -1,15 +1,23 @@
// Fill in the middle prompts
import { CompletionOptions } from "../index.js";
import { getLastNPathParts, shortestRelativePaths } from "../util/index.js";
import { AutocompleteSnippet } from "./ranking.js";
interface AutocompleteTemplate {
compilePrefixSuffix?: (
prefix: string,
suffix: string,
filepath: string,
reponame: string,
snippets: AutocompleteSnippet[],
) => [string, string];
template:
| string
| ((
prefix: string,
suffix: string,
filename: string,
filepath: string,
reponame: string,
snippets: AutocompleteSnippet[],
) => string);
@ -31,6 +39,46 @@ const codestralFimTemplate: AutocompleteTemplate = {
},
};
const codestralMultifileFimTemplate: AutocompleteTemplate = {
compilePrefixSuffix: (
prefix: string,
suffix: string,
filepath: string,
reponame: string,
snippets: AutocompleteSnippet[],
): [string, string] => {
if (snippets.length === 0) {
if (suffix.trim().length === 0 && prefix.trim().length === 0) {
return [`+++++ ${getLastNPathParts(filepath, 2)}\n${prefix}`, suffix];
}
return [prefix, suffix];
}
const relativePaths = shortestRelativePaths([
...snippets.map((snippet) => snippet.filepath),
filepath,
]);
const otherFiles = snippets
.map((snippet, i) => `+++++ ${relativePaths[i]}\n${snippet.contents}`)
.join("\n\n");
return [
`${otherFiles}\n\n+++++ ${relativePaths[relativePaths.length - 1]}\n${prefix}`,
suffix,
];
},
template: (
prefix: string,
suffix: string,
filepath: string,
reponame: string,
snippets: AutocompleteSnippet[],
): string => {
return `[SUFFIX]${suffix}[PREFIX]${prefix}`;
},
completionOptions: {
stop: ["[PREFIX]", "[SUFFIX]"],
},
};
const codegemmaFimTemplate: AutocompleteTemplate = {
template:
"<|fim_prefix|>{{{prefix}}}<|fim_suffix|>{{{suffix}}}<|fim_middle|>",
@ -235,7 +283,7 @@ export function getTemplateForModel(model: string): AutocompleteTemplate {
}
if (lowerCaseModel.includes("codestral")) {
return codestralFimTemplate;
return codestralMultifileFimTemplate;
}
if (lowerCaseModel.includes("codegemma")) {

View file

@ -487,7 +487,7 @@ const EditSlashCommand: SlashCommand = {
lineStream = filterEnglishLinesAtStart(lineStream);
lineStream = filterEnglishLinesAtEnd(filterCodeBlockLines(lineStream));
lineStream = stopAtLines(lineStream);
lineStream = stopAtLines(lineStream, () => {});
generator = streamWithNewLines(
fixCodeLlamaFirstLineIndentation(lineStream),

View file

@ -28,7 +28,7 @@ function reformatCodeBlocks(msgText: string): string {
codeBlockFenceRegex,
(match, metadata, filename, extension) => {
const lang = languageForFilepath(filename);
return `\`\`\`${extension}\n${lang.comment} ${metadata}\n`;
return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`;
},
);
// Appease the markdown linter

View file

@ -73,7 +73,7 @@ export class ConfigHandler {
const ideInfo = await this.ide.getIdeInfo();
const uniqueId = await this.ide.getUniqueId();
this.savedConfig = await loadFullConfigNode(
const newConfig = await loadFullConfigNode(
this.ide,
workspaceConfigs,
await this.ideSettingsPromise,
@ -81,22 +81,21 @@ export class ConfigHandler {
uniqueId,
this.writeLog,
);
this.savedConfig.allowAnonymousTelemetry =
this.savedConfig.allowAnonymousTelemetry &&
newConfig.allowAnonymousTelemetry =
newConfig.allowAnonymousTelemetry &&
(await this.ide.isTelemetryEnabled());
// Setup telemetry only after (and if) we know it is enabled
await Telemetry.setup(
this.savedConfig.allowAnonymousTelemetry ?? true,
newConfig.allowAnonymousTelemetry ?? true,
await this.ide.getUniqueId(),
ideInfo.extensionVersion,
);
(this.savedConfig.contextProviders ?? []).push(
...this.additionalContextProviders,
);
(newConfig.contextProviders ?? []).push(...this.additionalContextProviders);
return this.savedConfig;
this.savedConfig = newConfig;
return newConfig;
}
async llmFromTitle(title?: string): Promise<ILLM> {

View file

@ -28,7 +28,7 @@ import {
SlashCommand,
} from "../index.js";
import TransformersJsEmbeddingsProvider from "../indexing/embeddings/TransformersJsEmbeddingsProvider.js";
import { AllEmbeddingsProviders } from "../indexing/embeddings/index.js";
import { allEmbeddingsProviders } from "../indexing/embeddings/index.js";
import { BaseLLM } from "../llm/index.js";
import CustomLLMClass from "../llm/llms/CustomLLM.js";
import FreeTrial from "../llm/llms/FreeTrial.js";
@ -336,7 +336,7 @@ async function intermediateToFinalConfig(
| undefined;
if (embeddingsProviderDescription?.provider) {
const { provider, ...options } = embeddingsProviderDescription;
const embeddingsProviderClass = AllEmbeddingsProviders[provider];
const embeddingsProviderClass = allEmbeddingsProviders[provider];
if (embeddingsProviderClass) {
if (
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"

View file

@ -562,6 +562,7 @@ declare global {
// Gemini
| "gemini-pro"
| "gemini-1.5-pro-latest"
| "gemini-1.5-flash-latest"
// Mistral
| "mistral-tiny"
| "mistral-small"

View file

@ -1,5 +1,10 @@
import { v4 as uuidv4 } from "uuid";
import { ContextItemId, IDE } from ".";
import {
ContextItemId,
IDE,
IndexingProgressUpdate,
SiteIndexingConfig,
} from ".";
import { CompletionProvider } from "./autocomplete/completionProvider";
import { ConfigHandler } from "./config/handler";
import {
@ -25,7 +30,6 @@ import type { IMessenger, Message } from "./util/messenger";
import { editConfigJson, getConfigJsonPath } from "./util/paths";
import { Telemetry } from "./util/posthog";
import { streamDiffLines } from "./util/verticalEdit";
import { IndexingProgressUpdate } from ".";
export class Core {
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
@ -33,7 +37,7 @@ export class Core {
codebaseIndexerPromise: Promise<CodebaseIndexer>;
completionProvider: CompletionProvider;
continueServerClientPromise: Promise<ContinueServerClient>;
indexingState: IndexingProgressUpdate
indexingState: IndexingProgressUpdate;
private abortedMessageIds: Set<string> = new Set();
@ -61,7 +65,7 @@ export class Core {
private readonly ide: IDE,
private readonly onWrite: (text: string) => Promise<void> = async () => {},
) {
this.indexingState = { status:"loading", desc: 'loading', progress: 0 }
this.indexingState = { status: "loading", desc: "loading", progress: 0 };
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
this.configHandler = new ConfigHandler(
this.ide,
@ -214,9 +218,15 @@ export class Core {
// Context providers
on("context/addDocs", async (msg) => {
const siteIndexingConfig: SiteIndexingConfig = {
startUrl: msg.data.startUrl,
rootUrl: msg.data.rootUrl,
title: msg.data.title,
maxDepth: msg.data.maxDepth,
};
for await (const _ of indexDocs(
msg.data.title,
new URL(msg.data.url),
siteIndexingConfig,
new TransformersJsEmbeddingsProvider(),
)) {
}
@ -525,7 +535,7 @@ export class Core {
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.indexingState.status != 'loading') {
if (this.indexingState.status != "loading") {
this.messenger.request("indexProgress", this.indexingState);
}
});
@ -543,7 +553,7 @@ export class Core {
this.indexingCancellationController.signal,
)) {
this.messenger.request("indexProgress", update);
this.indexingState = update
this.indexingState = update;
}
}
}

12
core/index.d.ts vendored
View file

@ -162,6 +162,13 @@ export interface ContextSubmenuItem {
description: string;
}
export interface SiteIndexingConfig {
startUrl: string;
rootUrl: string;
title: string;
maxDepth?: number;
}
export interface IContextProvider {
get description(): ContextProviderDescription;
@ -300,6 +307,7 @@ export interface LLMOptions {
writeLog?: (str: string) => Promise<void>;
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
aiGatewaySlug?: string;
apiBase?: string;
useLegacyCompletionsEndpoint?: boolean;
@ -622,6 +630,7 @@ export interface RequestOptions {
proxy?: string;
headers?: { [key: string]: string };
extraBodyProperties?: { [key: string]: any };
noProxy?: string[];
}
export interface StepWithParams {
@ -681,7 +690,8 @@ export type EmbeddingsProviderName =
| "ollama"
| "openai"
| "cohere"
| "free-trial";
| "free-trial"
| "gemini";
export interface EmbedOptions {
apiBase?: string;

View file

@ -8,7 +8,7 @@ import type {
IndexTag,
IndexingProgressUpdate,
} from "../index.js";
import { getBasename } from "../util/index.js";
import { getBasename, getLastNPathParts } from "../util/index.js";
import {
getLanguageForFile,
getParserForFile,
@ -194,7 +194,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
return {
name: row.title,
description: getBasename(row.path, 2),
description: getLastNPathParts(row.path, 2),
content: `\`\`\`${getBasename(row.path)}\n${row.content}\n\`\`\``,
};
}
@ -214,7 +214,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
return rows.map((row) => ({
title: row.title,
description: getBasename(row.path, 2),
description: getLastNPathParts(row.path, 2),
id: row.id.toString(),
}));
} catch (e) {

View file

@ -18,6 +18,17 @@ const IGNORE_PATHS_ENDING_IN = [
const GITHUB_PATHS_TO_TRAVERSE = ["/blob/", "/tree/"];
async function getDefaultBranch(owner: string, repo: string): Promise<string> {
const octokit = new Octokit({ auth: undefined });
const repoInfo = await octokit.repos.get({
owner,
repo,
});
return repoInfo.data.default_branch;
}
async function crawlGithubRepo(baseUrl: URL) {
const octokit = new Octokit({
auth: undefined,
@ -25,17 +36,15 @@ async function crawlGithubRepo(baseUrl: URL) {
const [_, owner, repo] = baseUrl.pathname.split("/");
const dirContentsConfig = {
owner: owner,
repo: repo,
};
const branch = await getDefaultBranch(owner, repo);
console.log("Github repo detected. Crawling", branch, "branch");
const tree = await octokit.request(
"GET /repos/{owner}/{repo}/git/trees/{tree_sha}",
{
owner,
repo,
tree_sha: "main",
tree_sha: branch,
headers: {
"X-GitHub-Api-Version": "2022-11-28",
},
@ -54,6 +63,7 @@ async function getLinksFromUrl(url: string, path: string) {
const baseUrl = new URL(url);
const location = new URL(path, url);
let response;
try {
response = await fetch(location.toString());
} catch (error: unknown) {
@ -128,46 +138,69 @@ export type PageData = {
html: string;
};
export async function* crawlPage(url: URL): AsyncGenerator<PageData> {
export async function* crawlPage(
url: URL,
maxDepth: number = 3,
): AsyncGenerator<PageData> {
console.log("Starting crawl from: ", url, " - Max Depth: ", maxDepth);
const { baseUrl, basePath } = splitUrl(url);
let paths: string[] = [basePath];
let paths: { path: string; depth: number }[] = [{ path: basePath, depth: 0 }];
if (url.hostname === "github.com") {
const githubLinks = await crawlGithubRepo(url);
paths = [...paths, ...githubLinks];
const githubLinkObjects = githubLinks.map((link) => ({
path: link,
depth: 0,
}));
paths = [...paths, ...githubLinkObjects];
}
let index = 0;
while (index < paths.length) {
const promises = paths
.slice(index, index + 50)
.map((path) => getLinksFromUrl(baseUrl, path));
const batch = paths.slice(index, index + 50);
const results = await Promise.all(promises);
try {
const promises = batch.map(({ path, depth }) =>
getLinksFromUrl(baseUrl, path).then((links) => ({
links,
path,
depth,
})),
); // Adjust for depth tracking
for (const { html, links } of results) {
if (html !== "") {
yield {
url: url.toString(),
path: paths[index],
html: html,
};
}
const results = await Promise.all(promises);
for (const {
links: { html, links: linksArray },
path,
depth,
} of results) {
if (html !== "" && depth <= maxDepth) {
// Check depth
yield {
url: url.toString(),
path,
html,
};
}
for (const link of links) {
if (!paths.includes(link)) {
paths.push(link);
// Ensure we only add links if within depth limit
if (depth < maxDepth) {
for (let link of linksArray) {
if (!paths.some((p) => p.path === link)) {
paths.push({ path: link, depth: depth + 1 }); // Increment depth for new paths
}
}
}
}
index++;
} catch (e) {
if (e instanceof TypeError) {
console.warn("Error while crawling page: ", e); // Likely an invalid url, continue with process
} else {
console.error("Error while crawling page: ", e);
}
}
paths = paths.filter((path) =>
results.some(
(result) => result.html !== "" && result.links.includes(path),
),
);
index += batch.length; // Proceed to next batch
}
console.log("Crawl completed");
}

View file

@ -4,16 +4,18 @@ import {
IndexingProgressUpdate,
} from "../../index.js";
import { SiteIndexingConfig } from "../../index.js";
import { Article, chunkArticle, pageToArticle } from "./article.js";
import { crawlPage } from "./crawl.js";
import { addDocs, hasDoc } from "./db.js";
export async function* indexDocs(
title: string,
baseUrl: URL,
siteIndexingConfig: SiteIndexingConfig,
embeddingsProvider: EmbeddingsProvider,
): AsyncGenerator<IndexingProgressUpdate> {
if (await hasDoc(baseUrl.toString())) {
const startUrl = new URL(siteIndexingConfig.startUrl);
if (await hasDoc(siteIndexingConfig.startUrl.toString())) {
yield {
progress: 1,
desc: "Already indexed",
@ -30,12 +32,12 @@ export async function* indexDocs(
const articles: Article[] = [];
for await (const page of crawlPage(baseUrl)) {
// Crawl pages and retrieve info as articles
for await (const page of crawlPage(startUrl, siteIndexingConfig.maxDepth)) {
const article = pageToArticle(page);
if (!article) {
continue;
}
articles.push(article);
yield {
@ -48,6 +50,8 @@ export async function* indexDocs(
const chunks: Chunk[] = [];
const embeddings: number[][] = [];
// Create embeddings of retrieved articles
console.log("Creating Embeddings for ", articles.length, " articles");
for (const article of articles) {
yield {
progress: Math.max(1, Math.floor(100 / (articles.length + 1))),
@ -55,18 +59,24 @@ export async function* indexDocs(
status: "indexing",
};
const subpathEmbeddings = await embeddingsProvider.embed(
chunkArticle(article).map((chunk) => {
chunks.push(chunk);
try {
const subpathEmbeddings = await embeddingsProvider.embed(
chunkArticle(article).map((chunk) => {
chunks.push(chunk);
return chunk.content;
}),
);
return chunk.content;
}),
);
embeddings.push(...subpathEmbeddings);
embeddings.push(...subpathEmbeddings);
} catch (e) {
console.warn("Error chunking article: ", e);
}
}
await addDocs(title, baseUrl, chunks, embeddings);
// Add docs to databases
console.log("Adding ", embeddings.length, " embeddings to db");
await addDocs(siteIndexingConfig.title, startUrl, chunks, embeddings);
yield {
progress: 1,

View file

@ -1,8 +1,4 @@
export interface SiteIndexingConfig {
startUrl: string;
title: string;
rootUrl: string;
}
import {SiteIndexingConfig} from "../../index.js";
const configs: SiteIndexingConfig[] = [
{

View file

@ -1,24 +1,60 @@
import { EmbedOptions, EmbeddingsProvider, FetchFunction } from "../../index.js";
import {
EmbedOptions,
EmbeddingsProvider,
FetchFunction,
} from "../../index.js";
class BaseEmbeddingsProvider implements EmbeddingsProvider {
export interface IBaseEmbeddingsProvider extends EmbeddingsProvider {
options: EmbedOptions;
fetch: FetchFunction;
static defaultOptions: Partial<EmbedOptions> | undefined = undefined;
defaultOptions?: EmbedOptions;
maxBatchSize?: number;
}
get id(): string {
throw new Error("Method not implemented.");
}
abstract class BaseEmbeddingsProvider implements IBaseEmbeddingsProvider {
static maxBatchSize: IBaseEmbeddingsProvider["maxBatchSize"];
static defaultOptions: IBaseEmbeddingsProvider["defaultOptions"];
constructor(options: EmbedOptions, fetch: FetchFunction) {
options: IBaseEmbeddingsProvider["options"];
fetch: IBaseEmbeddingsProvider["fetch"];
id: IBaseEmbeddingsProvider["id"];
constructor(
options: IBaseEmbeddingsProvider["options"],
fetch: IBaseEmbeddingsProvider["fetch"],
) {
// Overwrite default options with any runtime options
this.options = {
...(this.constructor as typeof BaseEmbeddingsProvider).defaultOptions,
...options,
};
this.fetch = fetch;
this.id = this.options.model || this.constructor.name;
}
embed(chunks: string[]): Promise<number[][]> {
throw new Error("Method not implemented.");
abstract embed(chunks: string[]): Promise<number[][]>;
static getBatchedChunks(chunks: string[]): string[][] {
if (!this.maxBatchSize) {
console.warn(
`${this.getBatchedChunks.name} should only be called if 'maxBatchSize' is defined`,
);
return [chunks];
}
if (chunks.length > this.maxBatchSize) {
return [chunks];
}
const batchedChunks = [];
for (let i = 0; i < chunks.length; i += this.maxBatchSize) {
const batchSizedChunk = chunks.slice(i, i + this.maxBatchSize);
batchedChunks.push(batchSizedChunk);
}
return batchedChunks;
}
}

View file

@ -11,10 +11,6 @@ class CohereEmbeddingsProvider extends BaseEmbeddingsProvider {
model: "embed-english-v3.0",
};
get id(): string {
return this.options.model ?? "cohere";
}
async embed(chunks: string[]) {
if (!this.options.apiBase?.endsWith("/")) {
this.options.apiBase += "/";

View file

@ -7,10 +7,6 @@ class DeepInfraEmbeddingsProvider extends BaseEmbeddingsProvider {
model: "sentence-transformers/all-MiniLM-L6-v2",
};
get id(): string {
return this.options.model ?? "deepinfra";
}
async embed(chunks: string[]) {
const fetchWithBackoff = () =>
withExponentialBackoff<Response>(() =>

View file

@ -7,14 +7,11 @@ import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
class FreeTrialEmbeddingsProvider extends BaseEmbeddingsProvider {
static maxBatchSize = 128;
static defaultOptions: Partial<EmbedOptions> | undefined = {
model: "voyage-code-2",
};
get id(): string {
return FreeTrialEmbeddingsProvider.defaultOptions?.model!;
}
async embed(chunks: string[]) {
const batchedChunks = [];
for (
@ -44,6 +41,13 @@ class FreeTrialEmbeddingsProvider extends BaseEmbeddingsProvider {
}),
);
const resp = await fetchWithBackoff();
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;
}),

View file

@ -0,0 +1,72 @@
import { Response } from "node-fetch";
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
import BaseEmbeddingsProvider, {
IBaseEmbeddingsProvider,
} from "./BaseEmbeddingsProvider.js";
import {
EmbedContentRequest,
EmbedContentResponse,
} from "@google/generative-ai";
/**
* [View the Gemini Text Embedding docs.](https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding-and-embedding)
*/
class GeminiEmbeddingsProvider extends BaseEmbeddingsProvider {
static maxBatchSize = 2048;
static defaultOptions = {
apiBase: "https://generativelanguage.googleapis.com/v1/",
model: "models/text-embedding-004",
};
get urlPath(): string {
return `${this.options.model}:embedContent`;
}
async getSingleBatchEmbedding(batch: string[]) {
const body: EmbedContentRequest = {
content: {
/**
* Listed as optional in the [docs](https://ai.google.dev/api/rest/v1/Content)
* but is required in the interface.
*/
role: "user",
parts: batch.map((part) => ({ text: part })),
},
};
const fetchWithBackoff = () =>
withExponentialBackoff<Response>(() =>
this.fetch(new URL(this.urlPath, this.options.apiBase), {
method: "POST",
body: JSON.stringify(body),
headers: {
// eslint-disable-next-line @typescript-eslint/naming-convention
"x-goog-api-key": this.options.apiKey,
// eslint-disable-next-line @typescript-eslint/naming-convention
"Content-Type": "application/json",
},
}),
);
const resp = await fetchWithBackoff();
if (!resp.ok) {
throw new Error(await resp.text());
}
const data = (await resp.json()) as EmbedContentResponse;
return data.embedding.values;
}
async embed(chunks: string[]) {
const batches = GeminiEmbeddingsProvider.getBatchedChunks(chunks);
return await Promise.all(
batches.map((batch) => this.getSingleBatchEmbedding(batch)),
);
}
}
export default GeminiEmbeddingsProvider;

View file

@ -1,6 +1,8 @@
import { EmbedOptions, FetchFunction } from "../../index.js";
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
import BaseEmbeddingsProvider, {
IBaseEmbeddingsProvider,
} from "./BaseEmbeddingsProvider.js";
async function embedOne(
chunk: string,
@ -18,6 +20,7 @@ async function embedOne(
}),
);
const resp = await fetchWithBackoff();
if (!resp.ok) {
throw new Error(`Failed to embed chunk: ${await resp.text()}`);
}
@ -26,14 +29,11 @@ async function embedOne(
}
class OllamaEmbeddingsProvider extends BaseEmbeddingsProvider {
static defaultOptions: Partial<EmbedOptions> | undefined = {
static defaultOptions: IBaseEmbeddingsProvider["defaultOptions"] = {
apiBase: "http://localhost:11434/",
model: "nomic-embed-text",
};
get id(): string {
return this.options.model ?? "ollama";
}
async embed(chunks: string[]) {
const results: any = [];
for (const chunk of chunks) {

View file

@ -13,10 +13,6 @@ class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider {
model: "text-embedding-3-small",
};
get id(): string {
return this.options.model ?? "openai";
}
async embed(chunks: string[]) {
if (!this.options.apiBase?.endsWith("/")) {
this.options.apiBase += "/";

View file

@ -37,17 +37,10 @@ class EmbeddingsPipeline {
}
export class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider {
static MaxGroupSize: number = 4;
static maxGroupSize: number = 4;
constructor(modelPath?: string) {
constructor() {
super({ model: "all-MiniLM-L2-v6" }, () => Promise.resolve(null));
if (modelPath) {
// env.localModelPath = modelPath;
}
}
get id(): string {
return EmbeddingsPipeline.model;
}
async embed(chunks: string[]) {
@ -65,11 +58,11 @@ export class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider {
for (
let i = 0;
i < chunks.length;
i += TransformersJsEmbeddingsProvider.MaxGroupSize
i += TransformersJsEmbeddingsProvider.maxGroupSize
) {
const chunkGroup = chunks.slice(
i,
i + TransformersJsEmbeddingsProvider.MaxGroupSize,
i + TransformersJsEmbeddingsProvider.maxGroupSize,
);
const output = await extractor(chunkGroup, {
pooling: "mean",

View file

@ -42,11 +42,11 @@ parentPort.on("message", async (chunks) => {
for (
let i = 0;
i < chunks.length;
i += TransformersJsEmbeddingsProvider.MaxGroupSize
i += TransformersJsEmbeddingsProvider.maxGroupSize
) {
const chunkGroup = chunks.slice(
i,
i + TransformersJsEmbeddingsProvider.MaxGroupSize,
i + TransformersJsEmbeddingsProvider.maxGroupSize,
);
const output = await extractor(chunkGroup, {
pooling: "mean",

View file

@ -1,16 +1,26 @@
import { EmbeddingsProviderName } from "../../index.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
import CohereEmbeddingsProvider from "./CohereEmbeddingsProvider.js";
import FreeTrialEmbeddingsProvider from "./FreeTrialEmbeddingsProvider.js";
import OllamaEmbeddingsProvider from "./OllamaEmbeddingsProvider.js";
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js";
import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider.js";
import GeminiEmbeddingsProvider from "./GeminiEmbeddingsProvider.js";
export const AllEmbeddingsProviders: {
[key in EmbeddingsProviderName]: any;
} = {
type EmbeddingsProviderConstructor = new (
...args: any[]
) => BaseEmbeddingsProvider;
export const allEmbeddingsProviders: Record<
EmbeddingsProviderName,
EmbeddingsProviderConstructor
> = {
ollama: OllamaEmbeddingsProvider,
// eslint-disable-next-line @typescript-eslint/naming-convention
"transformers.js": TransformersJsEmbeddingsProvider,
openai: OpenAIEmbeddingsProvider,
cohere: CohereEmbeddingsProvider,
// eslint-disable-next-line @typescript-eslint/naming-convention
"free-trial": FreeTrialEmbeddingsProvider,
gemini: GeminiEmbeddingsProvider,
};

View file

@ -94,7 +94,6 @@ const PARALLEL_PROVIDERS: ModelProvider[] = [
"bedrock",
"deepinfra",
"gemini",
"gemini",
"huggingface-inference-api",
"huggingface-tgi",
"mistral",

View file

@ -100,6 +100,7 @@ export abstract class BaseLLM implements ILLM {
region?: string;
projectId?: string;
accountId?: string;
aiGatewaySlug?: string;
private _llmOptions: LLMOptions;
@ -147,6 +148,7 @@ export abstract class BaseLLM implements ILLM {
this.writeLog = options.writeLog;
this.llmRequestHook = options.llmRequestHook;
this.apiKey = options.apiKey;
this.aiGatewaySlug = options.aiGatewaySlug;
this.apiBase = options.apiBase;
if (this.apiBase && !this.apiBase.endsWith("/")) {
this.apiBase = `${this.apiBase}/`;

View file

@ -23,22 +23,19 @@ export default class Cloudflare extends BaseLLM {
Authorization: `Bearer ${this.apiKey}`,
...this.requestOptions?.headers,
};
const resp = await this.fetch(
new URL(
`https://api.cloudflare.com/client/v4/accounts/${this.accountId}/ai/v1/chat/completions`,
),
{
method: "POST",
headers,
body: JSON.stringify({
messages,
stream: true,
model: this.model,
...this._convertArgs(options),
}),
},
);
const url = this.aiGatewaySlug
? `https://gateway.ai.cloudflare.com/v1/${this.accountId}/${this.aiGatewaySlug}/workers-ai/v1/chat/completions`
: `https://api.cloudflare.com/client/v4/accounts/${this.accountId}/ai/v1/chat/completions`;
const resp = await this.fetch(new URL(url), {
method: "POST",
headers,
body: JSON.stringify({
messages,
stream: true,
model: this.model,
...this._convertArgs(options),
}),
});
for await (const value of streamSse(resp)) {
console.log(value);

View file

@ -30,10 +30,10 @@ class Ollama extends BaseLLM {
})
.then(async (response) => {
if (response.status !== 200) {
console.warn(
"Error calling Ollama /api/show endpoint: ",
await response.text(),
);
// console.warn(
// "Error calling Ollama /api/show endpoint: ",
// await response.text(),
// );
return;
}
const body = await response.json();
@ -69,7 +69,7 @@ class Ollama extends BaseLLM {
}
})
.catch((e) => {
console.warn(`Error calling Ollama /api/show endpoint: ${e}`);
// console.warn(`Error calling Ollama /api/show endpoint: ${e}`);
});
}

10
core/package-lock.json generated
View file

@ -54,6 +54,7 @@
},
"devDependencies": {
"@biomejs/biome": "1.6.4",
"@google/generative-ai": "^0.11.4",
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.11",
"@types/jquery": "^3.5.29",
@ -1895,6 +1896,15 @@
"integrity": "sha512-k2Ty1JcVojjJFwrg/ThKi2ujJ7XNLYaFGNB/bWT9wGR+oSMJHMa5w+CUq6p/pVrKeNNgA7pCqEcjSnHVoqJQFw==",
"optional": true
},
"node_modules/@google/generative-ai": {
"version": "0.11.4",
"resolved": "https://registry.npmjs.org/@google/generative-ai/-/generative-ai-0.11.4.tgz",
"integrity": "sha512-hlw+E9Prv9aUIQISRnLSXi4rukFqKe5WhxPvzBccTvIvXjw2BHMFOJWSC/Gq7WE0W+L/qRHGmYxopmx9qjrB9w==",
"dev": true,
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@huggingface/jinja": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/@huggingface/jinja/-/jinja-0.1.3.tgz",

View file

@ -12,6 +12,7 @@
"author": "Nate Sesti and Ty Dunn",
"license": "Apache-2.0",
"devDependencies": {
"@google/generative-ai": "^0.11.4",
"@biomejs/biome": "1.6.4",
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.11",
@ -37,7 +38,6 @@
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@typescript-eslint/parser": "^7.8.0",
"@xenova/transformers": "2.14.0",
"onnxruntime-node": "1.14.0",
"adf-to-md": "^1.1.0",
"axios": "^1.6.7",
"cheerio": "^1.0.0-rc.12",
@ -57,6 +57,7 @@
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",
"ollama": "^0.4.6",
"onnxruntime-node": "1.14.0",
"openai": "^4.20.1",
"pg": "^8.11.3",
"posthog-node": "^3.6.3",

View file

@ -11,6 +11,7 @@ import {
RangeInFile,
SerializedContinueConfig,
SessionInfo,
SiteIndexingConfig,
} from "..";
import { AutocompleteInput } from "../autocomplete/completionProvider";
import { IdeSettings } from "./ideWebview";
@ -58,8 +59,8 @@ export type ToCoreFromIdeOrWebviewProtocol = {
ContextItemWithId[],
];
"context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]];
"context/addDocs": [{ title: string; url: string }, void];
"autocomplete/complete": [AutocompleteInput, string[]];
"context/addDocs": [SiteIndexingConfig, void];
"autocomplete/cancel": [undefined, void];
"autocomplete/accept": [{ completionId: string }, void];
"command/run": [

View file

@ -53,11 +53,12 @@ export function fetchwithRequestOptions(
// Create agent
const protocol = url.protocol === "https:" ? https : http;
const agent = proxy
? protocol === https
? new HttpsProxyAgent(proxy, agentOptions)
: new HttpProxyAgent(proxy, agentOptions)
: new protocol.Agent(agentOptions);
const agent =
proxy && !requestOptions?.noProxy?.includes(url.hostname)
? protocol === https
? new HttpsProxyAgent(proxy, agentOptions)
: new HttpProxyAgent(proxy, agentOptions)
: new protocol.Agent(agentOptions);
let headers: { [key: string]: string } = {};
for (const [key, value] of Object.entries(init?.headers || {})) {

View file

@ -93,32 +93,82 @@ export function dedentAndGetCommonWhitespace(s: string): [string, string] {
return [lines.map((x) => x.replace(lcp, "")).join("\n"), lcp];
}
export function getBasename(filepath: string, n = 1): string {
return filepath.split(/[\\/]/).pop() ?? "";
const SEP_REGEX = /[\\/]/;
export function getBasename(filepath: string): string {
return filepath.split(SEP_REGEX).pop() ?? "";
}
export function getLastNPathParts(filepath: string, n: number): string {
return filepath.split(/[\\/]/).slice(-n).join("/");
return filepath.split(SEP_REGEX).slice(-n).join("/");
}
export function getRelativePath(filepath: string, workspaceDirs: string[]): string {
for (const workspaceDir of workspaceDirs) {
const filepathParts = splitPath(filepath);
const workspaceDirParts = splitPath(workspaceDir);
if (filepathParts.slice(0, workspaceDirParts.length).join('/') === workspaceDirParts.join('/')) {
return filepathParts.slice(workspaceDirParts.length).join('/');
}
export function getRelativePath(
filepath: string,
workspaceDirs: string[],
): string {
for (const workspaceDir of workspaceDirs) {
const filepathParts = splitPath(filepath);
const workspaceDirParts = splitPath(workspaceDir);
if (
filepathParts.slice(0, workspaceDirParts.length).join("/") ===
workspaceDirParts.join("/")
) {
return filepathParts.slice(workspaceDirParts.length).join("/");
}
return splitPath(filepath).pop() ?? ''; // If the file is not in any of the workspaces, return the plain filename
}
return splitPath(filepath).pop() ?? ""; // If the file is not in any of the workspaces, return the plain filename
}
export function shortestRelativePaths(paths: string[]): string[] {
if (paths.length === 0) return [];
const partsLengths = paths.map((x) => x.split(SEP_REGEX).length);
const currentRelativePaths = paths.map(getBasename);
const currentNumParts = paths.map(() => 1);
const isDuplicated = currentRelativePaths.map(
(x, i) =>
currentRelativePaths.filter((y, j) => y === x && paths[i] !== paths[j])
.length > 1,
);
while (isDuplicated.some(Boolean)) {
const firstDuplicatedPath = currentRelativePaths.find(
(x, i) => isDuplicated[i],
);
if (!firstDuplicatedPath) break;
currentRelativePaths.forEach((x, i) => {
if (x === firstDuplicatedPath) {
currentNumParts[i] += 1;
currentRelativePaths[i] = getLastNPathParts(
paths[i],
currentNumParts[i],
);
}
});
isDuplicated.forEach((x, i) => {
if (x) {
isDuplicated[i] =
// Once we've used up all the parts, we can't make it longer
currentNumParts[i] < partsLengths[i] &&
currentRelativePaths.filter((y) => y === currentRelativePaths[i])
.length > 1;
}
});
}
return currentRelativePaths;
}
export function splitPath(path: string, withRoot?: string): string[] {
let parts = path.includes("/") ? path.split("/") : path.split("\\");
if (withRoot !== undefined) {
const rootParts = splitPath(withRoot);
parts = parts.slice(rootParts.length - 1);
}
return parts;
let parts = path.includes("/") ? path.split("/") : path.split("\\");
if (withRoot !== undefined) {
const rootParts = splitPath(withRoot);
parts = parts.slice(rootParts.length - 1);
}
return parts;
}
export function getMarkdownLanguageTagForFile(filepath: string): string {

View file

@ -105,7 +105,7 @@ export async function* streamDiffLines(
lines = filterEnglishLinesAtStart(lines);
lines = filterCodeBlockLines(lines);
lines = stopAtLines(lines);
lines = stopAtLines(lines, () => {});
lines = skipLines(lines);
if (inept) {
// lines = fixCodeLlamaFirstLineIndentation(lines);

View file

@ -1,6 +1,6 @@
# Gemini API
The Google Gemini API is currently in beta. You can [create an API key in Google AI Studio](https://aistudio.google.com) and use `gemini-1.5-pro-latest`. Change `~/.continue/config.json` to look like this:
The Google Gemini API is currently in beta. You can [create an API key in Google AI Studio](https://aistudio.google.com) and use `gemini-1.5-pro-latest`. Change `~/.continue/config.json` to include the following entry in the "models" array:
```json title="~/.continue/config.json"
{
@ -15,4 +15,6 @@ The Google Gemini API is currently in beta. You can [create an API key in Google
}
```
Google has also released a more lightweight version of the model that still has a one-million-token context window and multimodal capabilities named Gemini Flash. It can be accessed by adding an entry in the models array similar to the above, but substituting "flash" for "pro" in the `title` and `model` values.
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Gemini.ts)

View file

@ -0,0 +1,39 @@
# IPEX-LLM
:::info
[**IPEX-LLM**](https://github.com/intel-analytics/ipex-llm) is a PyTorch library for running LLM on Intel CPU and GPU (e.g., local PC with iGPU, discrete GPU such as Arc A-Series, Flex and Max) with very low latency.
:::
IPEX-LLM supports accelerated Ollama backend to be hosted on Intel GPU. Refer to [this guide](https://ipex-llm.readthedocs.io/en/latest/doc/LLM/Quickstart/ollama_quickstart.html) from IPEX-LLM official documentation about how to install and run Ollama serve accelerated by IPEX-LLM on Intel GPU. You can then configure Continue to use the IPEX-LLM accelerated `"ollama"` provider as follows:
```json title="~/.continue/config.json"
{
"models": [
{
"title": "IPEX-LLM",
"provider": "ollama",
"model": "AUTODETECT"
}
]
}
```
If you would like to reach the Ollama service from another machine, make sure you set or export the environment variable `OLLAMA_HOST=0.0.0.0` before executing the command `ollama serve`. Then, in the Continue configuration, set `'apiBase'` to correspond with the IP address / port of the remote machine. That is, Continue can be configured to be:
```json title="~/.continue/config.json"
{
"models": [
{
"title": "IPEX-LLM",
"provider": "ollama",
"model": "AUTODETECT",
"apiBase": "http://your-ollama-service-ip:11434"
}
]
}
```
:::tip
- For more configuration options regarding completion or authentication, you could refer to [here](./ollama.md#completion-options) for Ollama provider.
- If you would like to preload the model before your first conversation with that model in Continue, you could refer to [here](https://ipex-llm.readthedocs.io/en/latest/doc/LLM/Quickstart/continue_quickstart.html#pull-and-prepare-the-model) for more information.
:::

View file

@ -43,7 +43,7 @@ _You can also use other open-source chat models by adding them to your `config.j
#### Gemini Pro from Google
- Unlimited budget: `gemini-pro-1.5-latest`
- Limited budget: `gemini-pro-1.0`
- Limited budget: `gemini-flash-1.5-latest` or `gemini-pro-1.0`
_You can also use other commercial chat models by adding them to your `config.json`._

View file

@ -20,12 +20,13 @@ You can run a model on your local computer using:
- [LM Studio](../reference/Model%20Providers/lmstudio.md)
- [Llama.cpp](../reference/Model%20Providers/llamacpp.md)
- [KoboldCpp](../reference/Model%20Providers/openai.md) (OpenAI compatible server)
- [llamafile](../reference/Model%20Providers/llamafile) ((OpenAI compatible server)
- [llamafile](../reference/Model%20Providers/llamafile) (OpenAI compatible server)
- [LocalAI](../reference/Model%20Providers/openai.md) (OpenAI compatible server)
- [Text generation web UI](../reference/Model%20Providers/openai.md) (OpenAI compatible server)
- [FastChat](../reference/Model%20Providers/openai.md) (OpenAI compatible server)
- [llama-cpp-python](../reference/Model%20Providers/openai.md) (OpenAI compatible server)
- [TensorRT-LLM](https://github.com/NVIDIA/trt-llm-as-openai-windows?tab=readme-ov-file#examples) (OpenAI compatible server)
- [IPEX-LLM](../reference/Model%20Providers/ipex_llm.md) (Local LLM on Intel GPU)
### Remote

View file

@ -34,6 +34,34 @@ If you're getting a response from the LLM that doesn't seem to make sense, you c
Open `~/.continue/core.log`. The most recent logs are found at the bottom of the file.
## Download the latest pre-release
### VS Code
We are constantly making fixes and improvements to Continue, but the latest changes remain in a "pre-release" version for roughly a week so that we can test their stability. If you are experiencing issues, you can try the pre-release by going to the Continue extension page in VS Code and selecting "Switch to Pre-Release" as shown below.
![Pre-Release](../static/img/prerelease.png)
### JetBrains
On JetBrains, the "pre-release" happens through their Early Access Program (EAP) channel. To download the latest EAP version, enable the EAP channel:
1. Open JetBrains settings (cmd/ctrl+,) and go to "Plugins"
2. Click the gear icon at the top
3. Select "Manage Plugin Repositories..."
4. Add "https://plugins.jetbrains.com/plugins/eap/list" to the list
5. You'll now always be able to download the latest EAP version from the marketplace
## Download an Older Version
If you've tried everything, reported an error, know that a previous version was working for you, and are waiting to hear back, you can try downloading an older version of the extension.
For VS Code, All versions are hosted on the Open VSX Registry [here](https://open-vsx.org/extension/Continue/continue). Once you've downloaded the extension, which will be a .vsix file, you can install it manually by following the instructions [here](https://code.visualstudio.com/docs/editor/extension-gallery#_install-from-a-vsix).
You can find older versions of the JetBrains extension on their [marketplace](https://plugins.jetbrains.com/plugin/22707-continue), which will walk you through installing from disk.
# FAQs
## Networking Issues
### Configure Certificates
@ -65,32 +93,10 @@ If you are using VS Code and require requests to be made through a proxy, you ar
Continue can be used in [code-server](https://coder.com/), but if you are running across an error in the logs that includes "This is likely because the editor is not running in a secure context", please see [their documentation on securely exposing code-server](https://coder.com/docs/code-server/latest/guide#expose-code-server).
## Download the latest pre-release
## I installed Continue, but don't see the sidebar window
### VS Code
By default the Continue window is on the left side of VS Code, but it can be dragged to right side as well, which we recommend in our tutorial. In the situation where you have previously installed Continue and moved it to the right side, it may still be there. You can reveal Continue either by using cmd/ctrl+L or by clicking the button in the top right of VS Code to open the right sidebar.
We are constantly making fixes and improvements to Continue, but the latest changes remain in a "pre-release" version for roughly a week so that we can test their stability. If you are experiencing issues, you can try the pre-release by going to the Continue extension page in VS Code and selecting "Switch to Pre-Release" as shown below.
# Still having trouble?
![Pre-Release](../static/img/prerelease.png)
### JetBrains
On JetBrains, the "pre-release" happens through their Early Access Program (EAP) channel. To download the latest EAP version, enable the EAP channel:
1. Open JetBrains settings (cmd/ctrl+,) and go to "Plugins"
2. Click the gear icon at the top
3. Select "Manage Plugin Repositories..."
4. Add "https://plugins.jetbrains.com/plugins/eap/list" to the list
5. You'll now always be able to download the latest EAP version from the marketplace
## Download an Older Version
If you've tried everything, reported an error, know that a previous version was working for you, and are waiting to hear back, you can try downloading an older version of the extension.
For VS Code, All versions are hosted on the Open VSX Registry [here](https://open-vsx.org/extension/Continue/continue). Once you've downloaded the extension, which will be a .vsix file, you can install it manually by following the instructions [here](https://code.visualstudio.com/docs/editor/extension-gallery#_install-from-a-vsix).
You can find older versions of the JetBrains extension on their [marketplace](https://plugins.jetbrains.com/plugin/22707-continue), which will walk you through installing from disk.
## Still having trouble?
Create a GitHub issue [here](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=), leaving the details of your problem, and we'll be able to more quickly help you out.
Create a GitHub issue [here](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=), leaving the details of your problem, and we'll be able to more quickly help you out.

View file

@ -103,8 +103,7 @@ Voyage AI offers the best embeddings for code with their voyage-code-2 model. Af
"embeddingsProvider": {
"provider": "openai",
"model": "voyage-code-2",
"apiBase": "
https://api.voyageai.com/v1/",
"apiBase": "https://api.voyageai.com/v1/",
"apiKey": "<VOYAGE_API_KEY>"
}
}
@ -165,13 +164,28 @@ Configuration for the `embed-english-v3.0` model. This is the default.
"embeddingsProvider": {
"provider": "cohere",
"model": "embed-english-v3.0",
"apiKey": "YOUR_API_KEY"
"apiKey": "<COHERE_API_KEY>"
}
}
```
See Cohere's [embeddings](https://docs.cohere.com/docs/embed-2) for available models. Only embedding models v3 and higher are supported.
### Gemini
Gemini's _Text Embedding_ model is optimized for creating embeddings with 768 dimensions for text of up to 2,048 tokens.
As of May 2024, the only available embedding model from Gemini is [`text-embedding-004`](https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding-and-embedding).
```json title="~/.continue/config.json"
{
"embeddingsProvider": {
"provider": "gemini",
"apiKey": "<GEMINI_API_KEY>"
}
}
```
### Writing a custom `EmbeddingsProvider`
If you have your own API capable of generating embeddings, Continue makes it easy to write a custom `EmbeddingsProvider`. All you have to do is write a function that converts strings to arrays of numbers, and add this to your config in `config.ts`. Here's an example:
@ -201,6 +215,6 @@ export function modifyConfig(config: Config): Config {
Continue respects `.gitignore` files in order to determine which files should not be indexed. If you'd like to exclude additional files, you can add them to a `.continueignore` file, which follows the exact same rules as `.gitignore`.
If you want to see exactly what files Continue has indexed, the metadata is stored in `~/.continue/index/index.sqlite`. You can use a tool like [DB Browser for SQLite](https://sqlitebrowser.org/) to view the `tags_catalog` table within this file.
If you want to see exactly what files Continue has indexed, the metadata is stored in `~/.continue/index/index.sqlite`. You can use a tool like [DB Browser for SQLite](https://sqlitebrowser.org/) to view the `tag_catalog` table within this file.
If you need to force a refresh of the index, reload the VS Code window with `cmd/ctrl + shift + p` + "Reload Window".

View file

@ -115,6 +115,14 @@
"title": "Extra Body Properties",
"description": "This object will be merged with the body when making the HTTP requests",
"type": "object"
},
"noProxy": {
"title": "No Proxy",
"description": "A list of hostnames for which Continue should not use the proxy specified in requestOptions.proxy",
"type": "array",
"items": {
"type": "string"
}
}
}
},
@ -376,6 +384,9 @@
"accountId": {
"type": "string"
},
"aiGatewaySlug": {
"type": "string"
},
"model": {
"anyOf": [
{
@ -1814,7 +1825,8 @@
"ollama",
"openai",
"cohere",
"free-trial"
"free-trial",
"gemini"
]
},
"model": {
@ -1838,20 +1850,20 @@
"if": {
"properties": {
"provider": {
"enum": ["ollama"]
"enum": ["cohere"]
}
},
"required": ["provider"]
},
"then": {
"required": ["model"]
"required": ["apiKey"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["cohere"]
"enum": ["gemini"]
}
},
"required": ["provider"]

View file

@ -4,7 +4,7 @@ pluginGroup = com.github.continuedev.continueintellijextension
pluginName = continue-intellij-extension
pluginRepositoryUrl = https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion = 0.0.48
pluginVersion = 0.0.50
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild = 223

View file

@ -31,23 +31,19 @@ const val DEFAULT_CONFIG = """
"slashCommands": [
{
"name": "edit",
"description": "Edit highlighted code",
"step": "EditHighlightedCodeStep"
"description": "Edit highlighted code"
},
{
"name": "comment",
"description": "Write comments for the highlighted code",
"step": "CommentCodeStep"
"description": "Write comments for the highlighted code"
},
{
"name": "share",
"description": "Export the current chat session to markdown",
"step": "ShareSessionStep"
"description": "Export the current chat session to markdown"
},
{
"name": "cmd",
"description": "Generate a shell command",
"step": "GenerateShellCommandStep"
"description": "Generate a shell command"
}
],
"customCommands": [

View file

@ -115,6 +115,14 @@
"title": "Extra Body Properties",
"description": "This object will be merged with the body when making the HTTP requests",
"type": "object"
},
"noProxy": {
"title": "No Proxy",
"description": "A list of hostnames for which Continue should not use the proxy specified in requestOptions.proxy",
"type": "array",
"items": {
"type": "string"
}
}
}
},
@ -376,6 +384,9 @@
"accountId": {
"type": "string"
},
"aiGatewaySlug": {
"type": "string"
},
"model": {
"anyOf": [
{
@ -1814,7 +1825,8 @@
"ollama",
"openai",
"cohere",
"free-trial"
"free-trial",
"gemini"
]
},
"model": {
@ -1838,20 +1850,20 @@
"if": {
"properties": {
"provider": {
"enum": ["ollama"]
"enum": ["cohere"]
}
},
"required": ["provider"]
},
"then": {
"required": ["model"]
"required": ["apiKey"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["cohere"]
"enum": ["gemini"]
}
},
"required": ["provider"]

View file

@ -115,6 +115,14 @@
"title": "Extra Body Properties",
"description": "This object will be merged with the body when making the HTTP requests",
"type": "object"
},
"noProxy": {
"title": "No Proxy",
"description": "A list of hostnames for which Continue should not use the proxy specified in requestOptions.proxy",
"type": "array",
"items": {
"type": "string"
}
}
}
},
@ -376,6 +384,9 @@
"accountId": {
"type": "string"
},
"aiGatewaySlug": {
"type": "string"
},
"model": {
"anyOf": [
{
@ -1814,7 +1825,8 @@
"ollama",
"openai",
"cohere",
"free-trial"
"free-trial",
"gemini"
]
},
"model": {
@ -1838,20 +1850,20 @@
"if": {
"properties": {
"provider": {
"enum": ["ollama"]
"enum": ["cohere"]
}
},
"required": ["provider"]
},
"then": {
"required": ["model"]
"required": ["apiKey"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["cohere"]
"enum": ["gemini"]
}
},
"required": ["provider"]

File diff suppressed because it is too large Load diff

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.141",
"version": "0.9.143",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.141",
"version": "0.9.143",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",
@ -136,6 +136,7 @@
},
"devDependencies": {
"@biomejs/biome": "1.6.4",
"@google/generative-ai": "^0.11.4",
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.11",
"@types/jquery": "^3.5.29",

View file

@ -1,7 +1,7 @@
{
"name": "continue",
"icon": "media/icon.png",
"version": "0.9.141",
"version": "0.9.143",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

File diff suppressed because it is too large Load diff

View file

@ -5,6 +5,7 @@ const { rimrafSync } = require("rimraf");
const {
validateFilesPresent,
execCmdSync,
autodetectPlatformAndArch,
} = require("../../../scripts/util/index");
// Clear folders that will be packaged to ensure clean slate
@ -28,29 +29,7 @@ if (args[2] === "--target") {
let os;
let arch;
if (!target) {
os = {
aix: "linux",
darwin: "darwin",
freebsd: "linux",
linux: "linux",
openbsd: "linux",
sunos: "linux",
win32: "win32",
}[process.platform];
arch = {
arm: "arm64",
arm64: "arm64",
ia32: "x64",
loong64: "arm64",
mips: "arm64",
mipsel: "arm64",
ppc: "x64",
ppc64: "x64",
riscv64: "arm64",
s390: "x64",
s390x: "x64",
x64: "x64",
}[process.arch];
[os, arch] = autodetectPlatformAndArch();
} else {
[os, arch] = target.split("-");
}
@ -269,17 +248,17 @@ const exe = os === "win32" ? ".exe" : "";
console.log("[info] Copied tree-sitter wasms");
// tree-sitter tag query files
ncp(
path.join(
__dirname,
"../../../core/node_modules/llm-code-highlighter/dist/tag-qry",
),
path.join(__dirname, "../out/tag-qry"),
(error) => {
if (error)
console.warn("Error copying code-highlighter tag-qry files", error);
},
);
// ncp(
// path.join(
// __dirname,
// "../../../core/node_modules/llm-code-highlighter/dist/tag-qry",
// ),
// path.join(__dirname, "../out/tag-qry"),
// (error) => {
// if (error)
// console.warn("Error copying code-highlighter tag-qry files", error);
// },
// );
// textmate-syntaxes
await new Promise((resolve, reject) => {
@ -320,7 +299,7 @@ const exe = os === "win32" ? ".exe" : "";
console.log(`Copying ${packageName} to ${toCopy}`);
// This is a way to install only one package without npm trying to install all the dependencies
// Create a temporary directory for installing the package
const adjustedName = toCopy.replace(/^@/, "").replace("/", "-");
const adjustedName = packageName.replace(/@/g, "").replace("/", "-");
const tempDir = `/tmp/continue-node_modules-${adjustedName}`;
const currentDir = process.cwd();

View file

@ -283,7 +283,9 @@ export async function getDefinitionsForNode(
ranges.push({
...classDef,
contents: `${
classNameNode?.text ? `${lang.comment} ${classNameNode.text}:\n` : ""
classNameNode?.text
? `${lang.singleLineComment} ${classNameNode.text}:\n`
: ""
}${contents.trim()}`,
});

View file

@ -6,11 +6,11 @@ import { threadStopped } from "../debug/debug";
import { VsCodeExtension } from "../extension/vscodeExtension";
import { GitExtension, Repository } from "../otherExtensions/git";
import {
SuggestionRanges,
acceptSuggestionCommand,
editorSuggestionsLocked,
rejectSuggestionCommand,
showSuggestion as showSuggestionInEditor,
type SuggestionRanges,
} from "../suggestions";
import { traverseDirectory } from "./traverseDirectory";
import {
@ -62,11 +62,15 @@ export class VsCodeIdeUtils {
);
}
private _workspaceDirectories: string[] | undefined = undefined;
getWorkspaceDirectories(): string[] {
return (
vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath) ||
[]
);
if (this._workspaceDirectories === undefined) {
this._workspaceDirectories =
vscode.workspace.workspaceFolders?.map((folder) => folder.uri.fsPath) ||
[];
}
return this._workspaceDirectories;
}
getUniqueId() {
@ -391,7 +395,7 @@ export class VsCodeIdeUtils {
if (lastLine) {
let i = lines.length - 1;
while (i >= 0 && !lines[i].trim().startsWith(lastLine)) i--;
terminalContents = lines.slice(i).join("\n");
terminalContents = lines.slice(Math.max(i, 0)).join("\n");
}
return terminalContents;
@ -545,7 +549,20 @@ export class VsCodeIdeUtils {
}
private _repoWasNone: boolean = false;
private repoCache: Map<string, Repository> = new Map();
async getRepo(forDirectory: vscode.Uri): Promise<Repository | undefined> {
const workspaceDirs = this.getWorkspaceDirectories();
const parentDir = workspaceDirs.find((dir) =>
forDirectory.fsPath.startsWith(dir),
);
if (parentDir) {
// Check if the repository is already cached
const cachedRepo = this.repoCache.get(parentDir);
if (cachedRepo) {
return cachedRepo;
}
}
let repo = await this._getRepo(forDirectory);
let i = 0;
@ -560,6 +577,12 @@ export class VsCodeIdeUtils {
}
repo = await this._getRepo(forDirectory);
}
if (parentDir) {
// Cache the repository for the parent directory
this.repoCache.set(parentDir, repo);
}
return repo;
}

10412
gui/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -62,6 +62,8 @@
"vscode-webview": "^1.0.1-beta.1"
},
"devDependencies": {
"@swc/cli": "^0.3.12",
"@swc/core": "^1.5.25",
"@types/node": "^20.5.6",
"@types/node-fetch": "^2.6.4",
"@types/react": "^18.0.27",

View file

@ -216,14 +216,13 @@ const Layout = () => {
const onboardingComplete = getLocalStorage("onboardingComplete");
if (
!onboardingComplete &&
!location.pathname.startsWith("/onboarding") &&
!location.pathname.startsWith("/existingUserOnboarding")
(location.pathname === "/" || location.pathname === "/index.html")
) {
navigate("/onboarding");
}
}, [location]);
const [indexingState, setIndexingState] = useState<IndexingProgressUpdate>({
const [indexingState, setIndexingState] = useState<IndexingProgressUpdate>({
desc: "Loading indexing config",
progress: 0.0,
status: "loading",

View file

@ -1,3 +1,4 @@
import { SiteIndexingConfig } from "core";
import { usePostHog } from "posthog-js/react";
import React, { useContext, useLayoutEffect } from "react";
import { useDispatch } from "react-redux";
@ -15,9 +16,12 @@ const GridDiv = styled.div`
`;
function AddDocsDialog() {
const defaultMaxDepth = 3;
const [docsUrl, setDocsUrl] = React.useState("");
const [docsTitle, setDocsTitle] = React.useState("");
const [urlValid, setUrlValid] = React.useState(false);
const [maxDepth, setMaxDepth] = React.useState<number | string>(""); // Change here
const dispatch = useDispatch();
const ideMessenger = useContext(IdeMessengerContext);
@ -61,17 +65,34 @@ function AddDocsDialog() {
value={docsTitle}
onChange={(e) => setDocsTitle(e.target.value)}
/>
<Input
type="text"
placeholder={`Optional: Max Depth (Default: ${defaultMaxDepth})`}
title="The maximum search tree depth - where your input url is the root node"
value={maxDepth}
onChange={(e) => {
const value = e.target.value;
if (value == "") {
setMaxDepth("");
} else if (!isNaN(+value) && Number(value) > 0) {
setMaxDepth(Number(value));
}
}}
/>
<Button
disabled={!docsUrl || !urlValid}
className="ml-auto"
onClick={() => {
ideMessenger.post("context/addDocs", {
url: docsUrl,
const siteIndexingConfig: SiteIndexingConfig = {
startUrl: docsUrl,
rootUrl: docsUrl,
title: docsTitle,
});
maxDepth: typeof maxDepth === "string" ? defaultMaxDepth : maxDepth, // Ensure maxDepth is a number
};
ideMessenger.post("context/addDocs", siteIndexingConfig);
setDocsTitle("");
setDocsUrl("");
setMaxDepth("");
dispatch(setShowDialog(false));
addItem("docs", {
id: docsUrl,

View file

@ -231,12 +231,30 @@ const MentionList = forwardRef((props: MentionListProps, ref) => {
}
};
const totalItems = allItems.length;
const itemRefs = useRef<Array<HTMLButtonElement | null>>([]);
const upHandler = () => {
setSelectedIndex((selectedIndex + allItems.length - 1) % allItems.length);
setSelectedIndex((prevIndex) => {
const newIndex = prevIndex - 1 >= 0 ? prevIndex - 1 : 0;
itemRefs.current[newIndex]?.scrollIntoView({
behavior: "instant" as ScrollBehavior,
block: "nearest",
});
return newIndex;
});
};
const downHandler = () => {
setSelectedIndex((selectedIndex + 1) % allItems.length);
setSelectedIndex((prevIndex) => {
const newIndex = prevIndex + 1 < totalItems ? prevIndex + 1 : prevIndex;
itemRefs.current[newIndex]?.scrollIntoView({
behavior: "instant" as ScrollBehavior,
block: "nearest",
});
return newIndex;
});
};
const enterHandler = () => {
@ -285,8 +303,12 @@ const MentionList = forwardRef((props: MentionListProps, ref) => {
return ["file", "code"].includes(item.type);
};
useEffect(() => {
itemRefs.current = itemRefs.current.slice(0, allItems.length);
}, [allItems]);
return (
<ItemsDiv>
<ItemsDiv className="items-container">
{querySubmenuItem ? (
<QueryInput
rows={1}
@ -318,6 +340,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => {
allItems.map((item, index) => (
<ItemDiv
as="button"
ref={(el) => (itemRefs.current[index] = el)}
className={`item ${
index === selectedIndex ? "is-selected" : ""
}`}
@ -339,7 +362,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => {
<DropdownIcon item={item} className="mr-2" />
</>
)}
{item.title}
<span title={item.id}>{item.title}</span>
{" "}
</div>
<span

View file

@ -82,6 +82,18 @@ function useHistory(dispatch: Dispatch) {
return await ideMessenger.request("history/save", sessionInfo);
}
async function getSession(id: string): Promise<PersistedSessionInfo> {
const json: PersistedSessionInfo = await ideMessenger.request(
"history/load",
{ id },
);
return json;
}
async function updateSession(sessionInfo: PersistedSessionInfo) {
return await ideMessenger.request("history/save", sessionInfo);
}
async function deleteSession(id: string) {
return await ideMessenger.request("history/delete", { id });
}
@ -114,6 +126,8 @@ function useHistory(dispatch: Dispatch) {
loadSession,
loadLastSession,
getLastSessionId,
updateSession,
getSession,
};
}

View file

@ -1,4 +1,5 @@
const fs = require("fs");
const os = require("os");
const { execSync } = require("child_process");
function execCmdSync(cmd) {
@ -10,11 +11,39 @@ function execCmdSync(cmd) {
}
}
function autodetectPlatformAndArch() {
platform = {
aix: "linux",
darwin: "darwin",
freebsd: "linux",
linux: "linux",
openbsd: "linux",
sunos: "linux",
win32: "win32",
}[process.platform];
arch = {
arm: "arm64",
arm64: "arm64",
ia32: "x64",
loong64: "arm64",
mips: "arm64",
mipsel: "arm64",
ppc: "x64",
ppc64: "x64",
riscv64: "arm64",
s390: "x64",
s390x: "x64",
x64: "x64",
}[process.arch];
return [platform, arch];
}
function validateFilesPresent(pathsToVerify) {
// This script verifies after pacakging that necessary files are in the correct locations
// In many cases just taking a sample file from the folder when they are all roughly the same thing
let missingFiles = [];
let emptyFiles = [];
for (const path of pathsToVerify) {
if (!fs.existsSync(path)) {
const parentFolder = path.split("/").slice(0, -1).join("/");
@ -51,11 +80,16 @@ function validateFilesPresent(pathsToVerify) {
missingFiles.push(path);
}
if (fs.existsSync(path) && fs.statSync(path).size === 0) {
console.error(`File ${path} is empty`);
emptyFiles.push(path);
}
}
if (missingFiles.length > 0) {
if (missingFiles.length > 0 || emptyFiles.length > 0) {
throw new Error(
`The following files were missing:\n- ${missingFiles.join("\n- ")}`,
`The following files were missing:\n- ${missingFiles.join("\n- ")}\n\nThe following files were empty:\n- ${emptyFiles.join("\n- ")}`,
);
} else {
console.log("All paths exist");
@ -65,4 +99,5 @@ function validateFilesPresent(pathsToVerify) {
module.exports = {
execCmdSync,
validateFilesPresent,
autodetectPlatformAndArch,
};