Merge remote-tracking branch 'upstream/preview' into debug-context-provider
This commit is contained in:
commit
20d4c19e3c
192 changed files with 14251 additions and 10422 deletions
4
.prettierrc
Normal file
4
.prettierrc
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"tabWidth": 2,
|
||||
"useTabs": false
|
||||
}
|
||||
12
.vscode/launch.json
vendored
12
.vscode/launch.json
vendored
|
|
@ -5,6 +5,18 @@
|
|||
"version": "0.2.0",
|
||||
"compounds": [],
|
||||
"configurations": [
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"name": "Core Binary",
|
||||
"skipFiles": ["<node_internals>/**"],
|
||||
"program": "${workspaceFolder}/pkg/out/index.js",
|
||||
"preLaunchTask": "pkg:esbuild",
|
||||
"outFiles": ["${workspaceFolder}/pkg/out/**/*.js"],
|
||||
"sourceMaps": true,
|
||||
"smartStep": true,
|
||||
"internalConsoleOptions": "openOnSessionStart"
|
||||
},
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
|
|
|
|||
3
.vscode/settings.json
vendored
3
.vscode/settings.json
vendored
|
|
@ -5,5 +5,6 @@
|
|||
"python.autoComplete.extraPaths": [],
|
||||
"python.testing.pytestArgs": ["server"],
|
||||
"python.testing.unittestEnabled": false,
|
||||
"python.testing.pytestEnabled": true
|
||||
"python.testing.pytestEnabled": true,
|
||||
"editor.tabSize": 2
|
||||
}
|
||||
|
|
|
|||
16
.vscode/tasks.json
vendored
16
.vscode/tasks.json
vendored
|
|
@ -56,8 +56,8 @@
|
|||
{
|
||||
"label": "vscode-extension:continue-ui:build",
|
||||
"type": "shell",
|
||||
"command": "node",
|
||||
"args": ["${workspaceFolder}/extensions/vscode/scripts/prepackage.js"],
|
||||
"command": "proxychains",
|
||||
"args": ["-q", "node", "${workspaceFolder}/extensions/vscode/scripts/prepackage.js"],
|
||||
"problemMatcher": ["$tsc"],
|
||||
"presentation": {
|
||||
"revealProblems": "onProblem",
|
||||
|
|
@ -136,6 +136,18 @@
|
|||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
//
|
||||
// esbuild for the core binary
|
||||
{
|
||||
"label": "pkg:esbuild",
|
||||
"type": "shell",
|
||||
"command": "npm",
|
||||
"args": ["run", "esbuild"],
|
||||
"problemMatcher": [],
|
||||
"options": {
|
||||
"cwd": "pkg"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
89
core/autocomplete/ast.ts
Normal file
89
core/autocomplete/ast.ts
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
import Parser from "web-tree-sitter";
|
||||
import { RangeInFileWithContents } from "../commands/util";
|
||||
import { getParserForFile } from "../util/treeSitter";
|
||||
|
||||
export async function getAst(
|
||||
filepath: string,
|
||||
fileContents: string
|
||||
): Promise<Parser.Tree | undefined> {
|
||||
const parser = await getParserForFile(filepath);
|
||||
|
||||
if (!parser) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const ast = parser.parse(fileContents);
|
||||
return ast;
|
||||
}
|
||||
|
||||
export async function getTreePathAtCursor(
|
||||
ast: Parser.Tree,
|
||||
cursorIndex: number
|
||||
): Promise<Parser.SyntaxNode[] | undefined> {
|
||||
const path = [ast.rootNode];
|
||||
while (path[path.length - 1].childCount > 0) {
|
||||
let foundChild = false;
|
||||
for (let child of path[path.length - 1].children) {
|
||||
if (child.startIndex <= cursorIndex && child.endIndex >= cursorIndex) {
|
||||
path.push(child);
|
||||
foundChild = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!foundChild) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
export async function getScopeAroundRange(
|
||||
range: RangeInFileWithContents
|
||||
): Promise<RangeInFileWithContents | undefined> {
|
||||
const ast = await getAst(range.filepath, range.contents);
|
||||
if (!ast) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const { start: s, end: e } = range.range;
|
||||
const lines = range.contents.split("\n");
|
||||
const startIndex =
|
||||
lines.slice(0, s.line).join("\n").length +
|
||||
(lines[s.line]?.slice(s.character).length ?? 0);
|
||||
const endIndex =
|
||||
lines.slice(0, e.line).join("\n").length +
|
||||
(lines[e.line]?.slice(0, e.character).length ?? 0);
|
||||
|
||||
let node = ast.rootNode;
|
||||
while (node.childCount > 0) {
|
||||
let foundChild = false;
|
||||
for (let child of node.children) {
|
||||
if (child.startIndex < startIndex && child.endIndex > endIndex) {
|
||||
node = child;
|
||||
foundChild = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!foundChild) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
contents: node.text,
|
||||
filepath: range.filepath,
|
||||
range: {
|
||||
start: {
|
||||
line: node.startPosition.row,
|
||||
character: node.startPosition.column,
|
||||
},
|
||||
end: {
|
||||
line: node.endPosition.row,
|
||||
character: node.endPosition.column,
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -7,7 +7,7 @@ export async function* onlyWhitespaceAfterEndOfLine(
|
|||
chunk = pending + chunk;
|
||||
pending = "";
|
||||
for (let i = 0; i < chunk.length - 1; i++) {
|
||||
if (endOfLine.includes(chunk[i]) && chunk[i + 1] === " ") {
|
||||
if (endOfLine.includes(chunk[i]) && chunk[i + 1] !== " ") {
|
||||
yield chunk.slice(0, i + 1);
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,17 @@
|
|||
import Parser from "web-tree-sitter";
|
||||
import { TabAutocompleteOptions } from "..";
|
||||
import { RangeInFileWithContents } from "../commands/util";
|
||||
import {
|
||||
countTokens,
|
||||
pruneLinesFromBottom,
|
||||
pruneLinesFromTop,
|
||||
} from "../llm/countTokens";
|
||||
import { getBasename } from "../util";
|
||||
import { getParserForFile } from "../util/treeSitter";
|
||||
|
||||
import { getAst, getTreePathAtCursor } from "./ast";
|
||||
import { AutocompleteLanguageInfo, LANGUAGES, Typescript } from "./languages";
|
||||
import { AutocompleteSnippet, fillPromptWithSnippets, rankSnippets, removeRangeFromSnippets } from "./ranking";
|
||||
import { slidingWindowMatcher } from "./slidingWindow";
|
||||
|
||||
export function languageForFilepath(
|
||||
filepath: string
|
||||
|
|
@ -23,57 +27,15 @@ function formatExternalSnippet(
|
|||
const comment = language.comment;
|
||||
const lines = [
|
||||
comment + " Path: " + getBasename(filepath),
|
||||
...snippet.split("\n").map((line) => comment + " " + line),
|
||||
...snippet.trim().split("\n").map((line) => comment + " " + line),
|
||||
comment,
|
||||
];
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
async function getAst(
|
||||
filepath: string,
|
||||
fileContents: string
|
||||
): Promise<Parser.Tree | undefined> {
|
||||
const parser = await getParserForFile(filepath);
|
||||
|
||||
if (!parser) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const ast = parser.parse(fileContents);
|
||||
return ast;
|
||||
}
|
||||
|
||||
async function getTreePathAtCursor(
|
||||
ast: Parser.Tree,
|
||||
cursorIndex: number
|
||||
): Promise<Parser.SyntaxNode[] | undefined> {
|
||||
const path = [ast.rootNode];
|
||||
while (path[path.length - 1].childCount > 0) {
|
||||
let foundChild = false;
|
||||
for (let child of path[path.length - 1].children) {
|
||||
if (child.startIndex <= cursorIndex && child.endIndex >= cursorIndex) {
|
||||
path.push(child);
|
||||
foundChild = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!foundChild) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
export interface AutocompleteSnippet {
|
||||
filepath: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
const BLOCK_TYPES = ["body", "statement_block"];
|
||||
|
||||
function shouldCompleteMultiline(
|
||||
function shouldCompleteMultilineAst(
|
||||
treePath: Parser.SyntaxNode[],
|
||||
cursorLine: number
|
||||
): boolean {
|
||||
|
|
@ -100,27 +62,12 @@ function shouldCompleteMultiline(
|
|||
return false;
|
||||
}
|
||||
|
||||
export async function constructAutocompletePrompt(
|
||||
async function shouldCompleteMultiline(
|
||||
filepath: string,
|
||||
fullPrefix: string,
|
||||
fullSuffix: string,
|
||||
clipboardText: string,
|
||||
language: AutocompleteLanguageInfo,
|
||||
getDefinition: (
|
||||
filepath: string,
|
||||
line: number,
|
||||
character: number
|
||||
) => Promise<AutocompleteSnippet | undefined>,
|
||||
options: TabAutocompleteOptions
|
||||
): Promise<{
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
useFim: boolean;
|
||||
completeMultiline: boolean;
|
||||
}> {
|
||||
// Find external snippets
|
||||
const snippets: AutocompleteSnippet[] = [];
|
||||
|
||||
fullSuffix: string
|
||||
): Promise<boolean> {
|
||||
// Use AST to determine whether to complete multiline
|
||||
let treePath: Parser.SyntaxNode[] | undefined;
|
||||
try {
|
||||
const ast = await getAst(filepath, fullPrefix + fullSuffix);
|
||||
|
|
@ -135,49 +82,115 @@ export async function constructAutocompletePrompt(
|
|||
|
||||
let completeMultiline = false;
|
||||
if (treePath) {
|
||||
// Get function def when inside call expression
|
||||
let callExpression = undefined;
|
||||
for (let node of treePath.reverse()) {
|
||||
if (node.type === "call_expression") {
|
||||
callExpression = node;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (callExpression) {
|
||||
const definition = await getDefinition(
|
||||
filepath,
|
||||
callExpression.startPosition.row,
|
||||
callExpression.startPosition.column
|
||||
);
|
||||
if (definition) {
|
||||
snippets.push(definition);
|
||||
}
|
||||
}
|
||||
|
||||
// Use AST to determine whether to complete multiline
|
||||
let cursorLine = fullPrefix.split("\n").length - 1;
|
||||
completeMultiline = shouldCompleteMultiline(treePath, cursorLine);
|
||||
completeMultiline = shouldCompleteMultilineAst(treePath, cursorLine);
|
||||
}
|
||||
return completeMultiline;
|
||||
}
|
||||
|
||||
// Construct basic prefix / suffix
|
||||
const formattedSnippets = snippets
|
||||
.map((snippet) =>
|
||||
formatExternalSnippet(snippet.filepath, snippet.content, language)
|
||||
)
|
||||
.join("\n");
|
||||
export async function constructAutocompletePrompt(
|
||||
filepath: string,
|
||||
cursorLine: number,
|
||||
fullPrefix: string,
|
||||
fullSuffix: string,
|
||||
clipboardText: string,
|
||||
language: AutocompleteLanguageInfo,
|
||||
options: TabAutocompleteOptions,
|
||||
recentlyEditedRanges: RangeInFileWithContents[],
|
||||
recentlyEditedDocuments: RangeInFileWithContents[],
|
||||
modelName: string,
|
||||
extraSnippets: AutocompleteSnippet[]
|
||||
): Promise<{
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
useFim: boolean;
|
||||
completeMultiline: boolean;
|
||||
}> {
|
||||
// Find external snippets
|
||||
let snippets: RangeInFileWithContents[] = extraSnippets;
|
||||
|
||||
const windowAroundCursor =
|
||||
fullPrefix.slice(
|
||||
-options.slidingWindowSize * options.slidingWindowPrefixPercentage
|
||||
) +
|
||||
fullSuffix.slice(
|
||||
options.slidingWindowSize * (1 - options.slidingWindowPrefixPercentage)
|
||||
);
|
||||
|
||||
const slidingWindowMatches = await slidingWindowMatcher(
|
||||
recentlyEditedDocuments,
|
||||
windowAroundCursor,
|
||||
3,
|
||||
options.slidingWindowSize
|
||||
);
|
||||
snippets.push(...slidingWindowMatches);
|
||||
|
||||
const recentlyEdited = (await Promise.all(
|
||||
recentlyEditedRanges
|
||||
.map(async (r) => {
|
||||
return r;
|
||||
// return await getScopeAroundRange(r);
|
||||
})
|
||||
)).filter((s) => !!s);
|
||||
snippets.push(...(recentlyEdited as any));
|
||||
|
||||
// Rank / order the snippets
|
||||
const scoredSnippets = rankSnippets(snippets, windowAroundCursor)
|
||||
|
||||
// Fill maxSnippetTokens with snippets
|
||||
const maxSnippetTokens = options.maxPromptTokens * options.maxSnippetPercentage;
|
||||
|
||||
// Construct basic prefix
|
||||
const maxPrefixTokens =
|
||||
options.maxPromptTokens * options.prefixPercentage -
|
||||
countTokens(formattedSnippets, "gpt-4");
|
||||
let prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens);
|
||||
if (formattedSnippets.length > 0) {
|
||||
prefix = formattedSnippets + "\n" + prefix;
|
||||
}
|
||||
|
||||
options.maxPromptTokens * options.prefixPercentage
|
||||
let prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens, modelName);
|
||||
|
||||
// Construct suffix
|
||||
const maxSuffixTokens = Math.min(
|
||||
options.maxPromptTokens - countTokens(prefix, "gpt-4"),
|
||||
options.maxPromptTokens - countTokens(prefix, modelName),
|
||||
options.maxSuffixPercentage * options.maxPromptTokens
|
||||
);
|
||||
let suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens);
|
||||
let suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName);
|
||||
|
||||
return { prefix, suffix, useFim: true, completeMultiline };
|
||||
// Remove prefix range from snippets
|
||||
const prefixLines = prefix.split('\n').length;
|
||||
const suffixLines = suffix.split('\n').length;
|
||||
const buffer = 8;
|
||||
const prefixSuffixRangeWithBuffer = {
|
||||
start: {
|
||||
line: cursorLine - prefixLines - buffer,
|
||||
character: 0
|
||||
},
|
||||
end: {
|
||||
line: cursorLine + suffixLines+ buffer,
|
||||
character: 0
|
||||
}
|
||||
}
|
||||
let finalSnippets = removeRangeFromSnippets(scoredSnippets, filepath.split("://").slice(-1)[0], prefixSuffixRangeWithBuffer);
|
||||
|
||||
// Filter snippets for those with best scores (must be above threshold)
|
||||
finalSnippets = finalSnippets.filter((snippet) => snippet.score >= options.recentlyEditedSimilarityThreshold)
|
||||
finalSnippets = fillPromptWithSnippets(scoredSnippets, maxSnippetTokens, modelName);
|
||||
|
||||
// Format snippets as comments and prepend to prefix
|
||||
const formattedSnippets = finalSnippets
|
||||
.map((snippet) =>
|
||||
formatExternalSnippet(snippet.filepath, snippet.contents, language)
|
||||
)
|
||||
.join("\n");
|
||||
if (formattedSnippets.length > 0) {
|
||||
prefix = formattedSnippets + "\n\n" + prefix;
|
||||
}
|
||||
|
||||
|
||||
return {
|
||||
prefix,
|
||||
suffix,
|
||||
useFim: true,
|
||||
completeMultiline: await shouldCompleteMultiline(
|
||||
filepath,
|
||||
fullPrefix,
|
||||
fullSuffix
|
||||
),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ export const Scala = {
|
|||
export const Go = {
|
||||
stopWords: ["func", "package", "import", "type"],
|
||||
comment: "//",
|
||||
endOfLine: [""],
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// Rust
|
||||
|
|
@ -69,9 +69,18 @@ export const Rust = {
|
|||
|
||||
// Haskell
|
||||
export const Haskell = {
|
||||
stopWords: ["data", "type", "newtype", "class", "instance", "let", "in", "where"],
|
||||
stopWords: [
|
||||
"data",
|
||||
"type",
|
||||
"newtype",
|
||||
"class",
|
||||
"instance",
|
||||
"let",
|
||||
"in",
|
||||
"where",
|
||||
],
|
||||
comment: "--",
|
||||
endOfLine: [""],
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// PHP
|
||||
|
|
@ -85,7 +94,7 @@ export const PHP = {
|
|||
export const RubyOnRails = {
|
||||
stopWords: ["def", "class", "module"],
|
||||
comment: "#",
|
||||
endOfLine: [""],
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// Swift
|
||||
|
|
@ -106,35 +115,66 @@ export const Kotlin = {
|
|||
export const Ruby = {
|
||||
stopWords: ["class", "module", "def"],
|
||||
comment: "#",
|
||||
endOfLine: [""],
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// Clojure
|
||||
export const Clojure = {
|
||||
stopWords: ["def", "fn", "let", "do", "if", "defn", "ns", "defmacro"],
|
||||
comment: ";",
|
||||
endOfLine: [""],
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// Julia
|
||||
export const Julia = {
|
||||
stopWords: ["function", "macro", "if", "else", "elseif", "while", "for", "begin", "end", "module"],
|
||||
stopWords: [
|
||||
"function",
|
||||
"macro",
|
||||
"if",
|
||||
"else",
|
||||
"elseif",
|
||||
"while",
|
||||
"for",
|
||||
"begin",
|
||||
"end",
|
||||
"module",
|
||||
],
|
||||
comment: "#",
|
||||
endOfLine: [";"],
|
||||
};
|
||||
|
||||
// F#
|
||||
export const FSharp = {
|
||||
stopWords: ["let", "type", "module", "namespace", "open", "if", "then", "else", "match", "with"],
|
||||
stopWords: [
|
||||
"let",
|
||||
"type",
|
||||
"module",
|
||||
"namespace",
|
||||
"open",
|
||||
"if",
|
||||
"then",
|
||||
"else",
|
||||
"match",
|
||||
"with",
|
||||
],
|
||||
comment: "//",
|
||||
endOfLine: [""],
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// R
|
||||
export const R = {
|
||||
stopWords: ["function", "if", "else", "for", "while", "repeat", "library", "require"],
|
||||
stopWords: [
|
||||
"function",
|
||||
"if",
|
||||
"else",
|
||||
"for",
|
||||
"while",
|
||||
"repeat",
|
||||
"library",
|
||||
"require",
|
||||
],
|
||||
comment: "#",
|
||||
endOfLine: [""],
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// Dart
|
||||
|
|
@ -154,7 +194,7 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
|
|||
java: Java,
|
||||
cpp: Cpp,
|
||||
cxx: Cpp,
|
||||
h: Cpp,
|
||||
h: Cpp,
|
||||
hpp: Cpp,
|
||||
cs: CSharp,
|
||||
c: C,
|
||||
|
|
@ -172,11 +212,11 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
|
|||
cljs: Clojure,
|
||||
cljc: Clojure,
|
||||
jl: Julia,
|
||||
fs: FSharp,
|
||||
fsi: FSharp,
|
||||
fsx: FSharp,
|
||||
fs: FSharp,
|
||||
fsi: FSharp,
|
||||
fsx: FSharp,
|
||||
fsscript: FSharp,
|
||||
r: R,
|
||||
R: R,
|
||||
dart: Dart,
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -2,6 +2,17 @@ import { distance } from "fastest-levenshtein";
|
|||
import { DiffLine } from "..";
|
||||
import { LineStream } from "../diff/util";
|
||||
|
||||
export async function* avoidPathLine(stream: LineStream, comment: string): LineStream {
|
||||
// Snippets are inserted as comments with a line at the start '// Path: <PATH>'.
|
||||
// Sometimes the model with copy this pattern, which is unwanted
|
||||
for await (const line of stream){
|
||||
if (line.startsWith(comment + " Path: ")) {
|
||||
continue;
|
||||
}
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
|
||||
export async function* streamWithNewLines(stream: LineStream): LineStream {
|
||||
let firstLine = true;
|
||||
for await (const nextLine of stream) {
|
||||
|
|
@ -39,6 +50,19 @@ export async function* stopAtSimilarLine(
|
|||
}
|
||||
}
|
||||
|
||||
const LINES_TO_STOP_AT = [
|
||||
"# End of file."
|
||||
]
|
||||
|
||||
export async function* stopAtLines(stream: LineStream): LineStream {
|
||||
for await (const line of stream) {
|
||||
if (LINES_TO_STOP_AT.includes(line)) {
|
||||
break;
|
||||
}
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
|
||||
function shouldRemoveLineBeforeStart(line: string): boolean {
|
||||
return (
|
||||
line.trimStart().startsWith("```") ||
|
||||
|
|
|
|||
|
|
@ -3,8 +3,15 @@ import { TabAutocompleteOptions } from "..";
|
|||
export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
|
||||
useCopyBuffer: true,
|
||||
useSuffix: true,
|
||||
maxPromptTokens: 650,
|
||||
maxPromptTokens: 500,
|
||||
prefixPercentage: 0.85,
|
||||
maxSuffixPercentage: 0.25,
|
||||
debounceDelay: 350,
|
||||
multilineCompletions: "auto",
|
||||
slidingWindowPrefixPercentage: 0.75,
|
||||
slidingWindowSize: 500,
|
||||
maxSnippetPercentage: 0.6,
|
||||
recentlyEditedSimilarityThreshold: 0.3,
|
||||
useCache: true,
|
||||
onlyMyCode: true
|
||||
};
|
||||
|
|
|
|||
207
core/autocomplete/ranking.ts
Normal file
207
core/autocomplete/ranking.ts
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
import { Range } from "..";
|
||||
import { RangeInFileWithContents } from "../commands/util";
|
||||
import { countTokens } from "../llm/countTokens";
|
||||
|
||||
export type AutocompleteSnippet = RangeInFileWithContents & {
|
||||
score: number;
|
||||
};
|
||||
|
||||
const rx = /[\s.,\/#!$%\^&\*;:{}=\-_`~()\[\]]/g;
|
||||
function getSymbolsForSnippet(snippet: string): Set<string> {
|
||||
const symbols = snippet
|
||||
.split(rx)
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s !== "");
|
||||
return new Set(symbols);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate similarity as number of shared symbols divided by total number of unique symbols between both.
|
||||
*/
|
||||
export function jaccardSimilarity(a: string, b: string): number {
|
||||
const aSet = getSymbolsForSnippet(a);
|
||||
const bSet = getSymbolsForSnippet(b);
|
||||
const union = new Set([...aSet, ...bSet]).size;
|
||||
|
||||
// Avoid division by zero
|
||||
if (union === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let intersection = 0;
|
||||
for (const symbol of aSet) {
|
||||
if (bSet.has(symbol)) {
|
||||
intersection++;
|
||||
}
|
||||
}
|
||||
|
||||
return intersection / union;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rank code snippets to be used in tab-autocomplete prompt. Returns a sorted version of the snippet array.
|
||||
*/
|
||||
export function rankSnippets(
|
||||
ranges: RangeInFileWithContents[],
|
||||
windowAroundCursor: string
|
||||
): AutocompleteSnippet[] {
|
||||
const snippets = ranges.map((snippet) => ({
|
||||
score: jaccardSimilarity(snippet.contents, windowAroundCursor),
|
||||
...snippet,
|
||||
}));
|
||||
const uniqueSnippets = deduplicateSnippets(snippets);
|
||||
return uniqueSnippets.sort((a, b) => a.score - b.score);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deduplicate code snippets by merging overlapping ranges into a single range.
|
||||
*/
|
||||
export function deduplicateSnippets(
|
||||
snippets: AutocompleteSnippet[]
|
||||
): AutocompleteSnippet[] {
|
||||
// Group by file
|
||||
const fileGroups: { [key: string]: AutocompleteSnippet[] } = {};
|
||||
for (const snippet of snippets) {
|
||||
if (!fileGroups[snippet.filepath]) {
|
||||
fileGroups[snippet.filepath] = [];
|
||||
}
|
||||
fileGroups[snippet.filepath].push(snippet);
|
||||
}
|
||||
|
||||
// Merge overlapping ranges
|
||||
const allRanges = [];
|
||||
for (const file of Object.keys(fileGroups)) {
|
||||
allRanges.push(...mergeSnippetsByRange(fileGroups[file]));
|
||||
}
|
||||
return allRanges;
|
||||
}
|
||||
|
||||
function mergeSnippetsByRange(
|
||||
snippets: AutocompleteSnippet[]
|
||||
): AutocompleteSnippet[] {
|
||||
if (snippets.length === 0) {
|
||||
return snippets;
|
||||
}
|
||||
|
||||
const sorted = snippets.sort(
|
||||
(a, b) => a.range.start.line - b.range.start.line
|
||||
);
|
||||
const merged: AutocompleteSnippet[] = [];
|
||||
|
||||
while (sorted.length > 0) {
|
||||
const next = sorted.shift()!;
|
||||
const last = merged[merged.length - 1];
|
||||
if (merged.length > 0 && last.range.end.line >= next.range.start.line) {
|
||||
// Merge with previous snippet
|
||||
last.score = Math.max(last.score, next.score);
|
||||
last.range.end = next.range.end;
|
||||
last.contents = mergeOverlappingRangeContents(last, next);
|
||||
} else {
|
||||
merged.push(next);
|
||||
}
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
function mergeOverlappingRangeContents(
|
||||
first: RangeInFileWithContents,
|
||||
second: RangeInFileWithContents
|
||||
): string {
|
||||
const firstLines = first.contents.split("\n");
|
||||
const numOverlapping = first.range.end.line - second.range.start.line;
|
||||
return firstLines.slice(-numOverlapping).join("\n") + "\n" + second.contents;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Fill the allowed space with snippets
|
||||
*/
|
||||
export function fillPromptWithSnippets(snippets: AutocompleteSnippet[], maxSnippetTokens: number, modelName: string): AutocompleteSnippet[] {
|
||||
let tokensRemaining = maxSnippetTokens;
|
||||
const keptSnippets: AutocompleteSnippet[] = []
|
||||
for (let i = 0; i < snippets.length; i++) {
|
||||
const snippet = snippets[i];
|
||||
const tokenCount = countTokens(snippet.contents, modelName)
|
||||
if (tokensRemaining - tokenCount >= 0) {
|
||||
tokensRemaining -= tokenCount;
|
||||
keptSnippets.push(snippet);
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return keptSnippets;
|
||||
};
|
||||
|
||||
function rangeIntersectionByLines(a: Range, b: Range): Range | null {
|
||||
const startLine = Math.max(a.start.line, b.start.line);
|
||||
const endLine = Math.min(a.end.line, b.end.line);
|
||||
if (startLine >= endLine) {
|
||||
return null;
|
||||
} else {
|
||||
return {
|
||||
start: {
|
||||
line: startLine,
|
||||
character: 0
|
||||
},
|
||||
end: {
|
||||
line: endLine,
|
||||
character: 0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove one range from another range, which may lead to returning two disjoint ranges
|
||||
*/
|
||||
function rangeDifferenceByLines(orig: Range, remove: Range): Range[] {
|
||||
if (orig.start.line >= remove.start.line && orig.end.line <= remove.end.line) {
|
||||
// / | | /
|
||||
return [];
|
||||
} else if (orig.start.line <= remove.start.line && orig.end.line >= remove.end.line) {
|
||||
// | / / |
|
||||
// Splits the range
|
||||
return [{
|
||||
start: orig.start,
|
||||
end: remove.start
|
||||
}, {
|
||||
start: remove.end,
|
||||
end: orig.end
|
||||
}]
|
||||
} else if (orig.start.line >= remove.start.line && orig.end.line >= remove.end.line) {
|
||||
// \ | / |
|
||||
return [{
|
||||
start: remove.end,
|
||||
end: orig.end
|
||||
}]
|
||||
} else if (orig.start.line <= remove.start.line && orig.end.line <= remove.end.line) {
|
||||
// | / | /
|
||||
return [{
|
||||
start: orig.start,
|
||||
end: remove.start
|
||||
}]
|
||||
} else {
|
||||
return [orig]
|
||||
}
|
||||
}
|
||||
|
||||
export function removeRangeFromSnippets(snippets: AutocompleteSnippet[], filepath: string, range: Range): AutocompleteSnippet[] {
|
||||
const finalSnippets: AutocompleteSnippet[] = [];
|
||||
for (let snippet of snippets) {
|
||||
if (snippet.filepath !== filepath) {
|
||||
finalSnippets.push(snippet);
|
||||
continue;
|
||||
}
|
||||
|
||||
const intersection = rangeIntersectionByLines(range, snippet.range);
|
||||
if (!intersection) {
|
||||
finalSnippets.push(snippet);
|
||||
} else {
|
||||
finalSnippets.push(...rangeDifferenceByLines(snippet.range, intersection).map(range => ({...snippet, range})));
|
||||
}
|
||||
}
|
||||
|
||||
return finalSnippets;
|
||||
}
|
||||
5
core/autocomplete/recentlyEdited.ts
Normal file
5
core/autocomplete/recentlyEdited.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import { RangeInFileWithContents } from "../commands/util";
|
||||
|
||||
export type RecentlyEditedRange = RangeInFileWithContents & {
|
||||
timestamp: number;
|
||||
};
|
||||
24
core/autocomplete/retrieval.ts
Normal file
24
core/autocomplete/retrieval.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { Chunk } from "..";
|
||||
import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch";
|
||||
import { IndexTag } from "../indexing/types";
|
||||
|
||||
export async function fullTextRetrieve(
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
indexTag: IndexTag
|
||||
): Promise<Chunk[]> {
|
||||
const index = new FullTextSearchCodebaseIndex();
|
||||
const searchStrings = prefix.split("\n").slice(-3);
|
||||
const results: Chunk[] = [];
|
||||
searchStrings.forEach(async (searchString) => {
|
||||
const chunks = await index.retrieve(
|
||||
[indexTag],
|
||||
searchString,
|
||||
3,
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
results.push(...chunks);
|
||||
});
|
||||
return results;
|
||||
}
|
||||
59
core/autocomplete/slidingWindow.ts
Normal file
59
core/autocomplete/slidingWindow.ts
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import { RangeInFileWithContents } from "../commands/util";
|
||||
import { AutocompleteSnippet, jaccardSimilarity } from "./ranking";
|
||||
|
||||
function* slidingWindow(
|
||||
content: string,
|
||||
windowSize: number
|
||||
): Generator<string> {
|
||||
const lines = content.split("\n");
|
||||
|
||||
let charCount = 0;
|
||||
let currWindowLines: string[] = [];
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (charCount + lines[i].length >= windowSize) {
|
||||
yield currWindowLines.join("\n");
|
||||
currWindowLines = [lines[i]];
|
||||
charCount = 0;
|
||||
} else {
|
||||
currWindowLines.push(lines[i]);
|
||||
}
|
||||
charCount += lines[i].length;
|
||||
}
|
||||
|
||||
if (currWindowLines.length > 0) {
|
||||
yield currWindowLines.join("\n");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Match by similarity over sliding windows of recent documents.
|
||||
* @param recentDocuments
|
||||
* @param prefix
|
||||
* @param suffix
|
||||
*/
|
||||
export async function slidingWindowMatcher(
|
||||
recentDocuments: RangeInFileWithContents[],
|
||||
windowAroundCursor: string,
|
||||
topN: number,
|
||||
windowSize: number
|
||||
): Promise<AutocompleteSnippet[]> {
|
||||
// Sorted lowest similarity to highest
|
||||
const topMatches: AutocompleteSnippet[] = [];
|
||||
|
||||
for (const { filepath, contents, range } of recentDocuments) {
|
||||
for (const window of slidingWindow(contents, windowSize)) {
|
||||
const score = jaccardSimilarity(window, windowAroundCursor);
|
||||
|
||||
// Insertion sort
|
||||
let i = -1;
|
||||
while (++i < topMatches.length && score > topMatches[i].score) {}
|
||||
topMatches.splice(i + 1, 0, { filepath, contents, score, range });
|
||||
if (topMatches.length > topN) {
|
||||
topMatches.shift();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: convert the arbitrary window frame to some whole AST node?
|
||||
return topMatches;
|
||||
}
|
||||
126
core/autocomplete/util.ts
Normal file
126
core/autocomplete/util.ts
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
export class ListenableGenerator<T> {
|
||||
private _source: AsyncGenerator<T>;
|
||||
private _buffer: T[] = [];
|
||||
private _listeners: Set<(value: T) => void> = new Set();
|
||||
private _isEnded: boolean = false;
|
||||
|
||||
constructor(source: AsyncGenerator<T>) {
|
||||
this._source = source;
|
||||
this._start();
|
||||
}
|
||||
|
||||
public cancel() {
|
||||
this._isEnded = true;
|
||||
}
|
||||
|
||||
private async _start() {
|
||||
try {
|
||||
for await (const value of this._source) {
|
||||
if (this._isEnded) {
|
||||
break;
|
||||
}
|
||||
this._buffer.push(value);
|
||||
for (const listener of this._listeners) {
|
||||
listener(value);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this._isEnded = true;
|
||||
for (const listener of this._listeners) {
|
||||
listener(null as any);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
listen(listener: (value: T) => void) {
|
||||
this._listeners.add(listener);
|
||||
for (const value of this._buffer) {
|
||||
listener(value);
|
||||
}
|
||||
if (this._isEnded) {
|
||||
listener(null as any);
|
||||
}
|
||||
}
|
||||
|
||||
async *tee(): AsyncGenerator<T> {
|
||||
try {
|
||||
for (const value of this._buffer) {
|
||||
yield value;
|
||||
}
|
||||
while (!this._isEnded) {
|
||||
let resolve: (value: any) => void;
|
||||
let promise = new Promise<T>((res) => {
|
||||
resolve = res;
|
||||
this._listeners.add(resolve!);
|
||||
});
|
||||
const value = await promise;
|
||||
this._listeners.delete(resolve!);
|
||||
|
||||
yield value;
|
||||
}
|
||||
} finally {
|
||||
// this._listeners.delete(resolve!);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class GeneratorReuseManager {
|
||||
static currentGenerator: ListenableGenerator<string> | undefined;
|
||||
static pendingGeneratorPrefix: string | undefined;
|
||||
static pendingCompletion: string = "";
|
||||
|
||||
private static _createListenableGenerator(
|
||||
gen: AsyncGenerator<string>,
|
||||
prefix: string
|
||||
) {
|
||||
GeneratorReuseManager.currentGenerator?.cancel();
|
||||
|
||||
const listenableGen = new ListenableGenerator(gen);
|
||||
listenableGen.listen(
|
||||
(chunk) => (GeneratorReuseManager.pendingCompletion += chunk ?? "")
|
||||
);
|
||||
|
||||
GeneratorReuseManager.pendingGeneratorPrefix = prefix;
|
||||
GeneratorReuseManager.pendingCompletion = "";
|
||||
GeneratorReuseManager.currentGenerator = listenableGen;
|
||||
}
|
||||
|
||||
static async *getGenerator(
|
||||
prefix: string,
|
||||
newGenerator: () => AsyncGenerator<string>
|
||||
): AsyncGenerator<string> {
|
||||
// Check if current can be reused
|
||||
if (
|
||||
!(
|
||||
GeneratorReuseManager.currentGenerator &&
|
||||
GeneratorReuseManager.pendingGeneratorPrefix &&
|
||||
(
|
||||
GeneratorReuseManager.pendingGeneratorPrefix +
|
||||
GeneratorReuseManager.pendingCompletion
|
||||
).startsWith(prefix) &&
|
||||
// for e.g. backspace
|
||||
GeneratorReuseManager.pendingGeneratorPrefix?.length <= prefix?.length
|
||||
)
|
||||
) {
|
||||
// Create a wrapper over the current generator to fix the prompt
|
||||
GeneratorReuseManager._createListenableGenerator(newGenerator(), prefix);
|
||||
}
|
||||
|
||||
let alreadyTyped =
|
||||
prefix.slice(GeneratorReuseManager.pendingGeneratorPrefix?.length) || "";
|
||||
for await (let chunk of GeneratorReuseManager.currentGenerator!.tee()) {
|
||||
if (!chunk) {
|
||||
continue;
|
||||
}
|
||||
while (chunk.length && alreadyTyped.length) {
|
||||
if (chunk[0] === alreadyTyped[0]) {
|
||||
alreadyTyped = alreadyTyped.slice(1);
|
||||
chunk = chunk.slice(1);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -230,13 +230,18 @@ const EditSlashCommand: SlashCommand = {
|
|||
}
|
||||
|
||||
// Strip unecessary parts of the input (the fact that you have to do this is suboptimal, should be refactored away)
|
||||
input = input.replace(
|
||||
let content = history[history.length - 1].content;
|
||||
if (typeof content !== "string") {
|
||||
content.forEach((part) => {
|
||||
if (part.text && part.text.startsWith("/edit")) {
|
||||
part.text = part.text.replace("/edit", "").trimStart();
|
||||
}
|
||||
})
|
||||
}
|
||||
let userInput = stripImages(content).replace(
|
||||
`\`\`\`${contextItemToEdit.name}\n${contextItemToEdit.content}\n\`\`\`\n`,
|
||||
""
|
||||
);
|
||||
if (input.startsWith("/edit")) {
|
||||
input = input.replace("/edit", "").trimStart();
|
||||
}
|
||||
|
||||
const rif: RangeInFileWithContents =
|
||||
contextItemToRangeInFileWithContents(contextItemToEdit);
|
||||
|
|
@ -248,14 +253,14 @@ const EditSlashCommand: SlashCommand = {
|
|||
rif,
|
||||
fullFileContents,
|
||||
llm,
|
||||
input,
|
||||
userInput,
|
||||
params?.tokenLimit
|
||||
);
|
||||
const [dedentedContents, commonWhitespace] =
|
||||
dedentAndGetCommonWhitespace(contents);
|
||||
contents = dedentedContents;
|
||||
|
||||
let prompt = compilePrompt(filePrefix, contents, fileSuffix, input);
|
||||
let prompt = compilePrompt(filePrefix, contents, fileSuffix, userInput);
|
||||
let fullFileContentsLines = fullFileContents.split("\n");
|
||||
let fullPrefixLines = fullFileContentsLines.slice(
|
||||
0,
|
||||
|
|
@ -428,7 +433,7 @@ const EditSlashCommand: SlashCommand = {
|
|||
}
|
||||
|
||||
let messages = history;
|
||||
messages.push({ role: "user", content: prompt });
|
||||
messages[messages.length - 1] = { role: "user", content: prompt };
|
||||
|
||||
let linesOfPrefixCopied = 0;
|
||||
let lines = [];
|
||||
|
|
@ -447,7 +452,7 @@ const EditSlashCommand: SlashCommand = {
|
|||
messages.slice(0, messages.length - 1),
|
||||
{
|
||||
codeToEdit: rif.contents,
|
||||
userInput: input,
|
||||
userInput,
|
||||
filePrefix: filePrefix,
|
||||
fileSuffix: fileSuffix,
|
||||
systemMessage: llm.systemMessage || "",
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import EditSlashCommand from "./edit";
|
|||
import HttpSlashCommand from "./http";
|
||||
import ShareSlashCommand from "./share";
|
||||
import StackOverflowSlashCommand from "./stackOverflow";
|
||||
import VerticalEditSlashCommand from "./verticalEdit";
|
||||
|
||||
export default [
|
||||
DraftIssueCommand,
|
||||
|
|
@ -17,5 +16,4 @@ export default [
|
|||
CommentSlashCommand,
|
||||
HttpSlashCommand,
|
||||
CommitMessageCommand,
|
||||
VerticalEditSlashCommand,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,12 +1,17 @@
|
|||
import { SerializedContinueConfig } from "..";
|
||||
|
||||
const defaultConfig: SerializedContinueConfig = {
|
||||
export const defaultConfig: SerializedContinueConfig = {
|
||||
models: [
|
||||
{
|
||||
title: "GPT-4 Vision (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "gpt-4-vision-preview",
|
||||
},
|
||||
{
|
||||
title: "GPT-3.5-Turbo (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "gpt-3.5-turbo",
|
||||
},
|
||||
{
|
||||
title: "Gemini Pro (Free Trial)",
|
||||
provider: "free-trial",
|
||||
|
|
@ -29,7 +34,7 @@ const defaultConfig: SerializedContinueConfig = {
|
|||
},
|
||||
{
|
||||
name: "share",
|
||||
description: "Download and share this session",
|
||||
description: "Export this session as markdown",
|
||||
},
|
||||
{
|
||||
name: "cmd",
|
||||
|
|
@ -55,6 +60,62 @@ const defaultConfig: SerializedContinueConfig = {
|
|||
{ name: "codebase", params: {} },
|
||||
{ name: "locals", params: {} },
|
||||
],
|
||||
tabAutocompleteModel: {
|
||||
title: "Starcoder 3b",
|
||||
provider: "ollama",
|
||||
model: "starcoder-3b",
|
||||
}
|
||||
};
|
||||
|
||||
export default defaultConfig;
|
||||
export const defaultConfigJetBrains: SerializedContinueConfig = {
|
||||
models: [
|
||||
{
|
||||
title: "GPT-4 Vision (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "gpt-4-vision-preview",
|
||||
},
|
||||
{
|
||||
title: "GPT-3.5-Turbo (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "gpt-3.5-turbo",
|
||||
},
|
||||
{
|
||||
title: "Gemini Pro (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "gemini-pro",
|
||||
},
|
||||
{
|
||||
title: "Codellama 70b (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "codellama-70b",
|
||||
},
|
||||
],
|
||||
slashCommands: [
|
||||
{
|
||||
name: "edit",
|
||||
description: "Edit selected code",
|
||||
},
|
||||
{
|
||||
name: "comment",
|
||||
description: "Write comments for the selected code",
|
||||
},
|
||||
{
|
||||
name: "share",
|
||||
description: "Export this session as markdown",
|
||||
},
|
||||
],
|
||||
customCommands: [
|
||||
{
|
||||
name: "test",
|
||||
prompt:
|
||||
"Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.",
|
||||
description: "Write unit tests for highlighted code",
|
||||
},
|
||||
],
|
||||
contextProviders: [
|
||||
{
|
||||
name: "open",
|
||||
params: {},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
|
|
|||
200
core/config/handler.ts
Normal file
200
core/config/handler.ts
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
import { http, https } from "follow-redirects";
|
||||
import * as fs from "fs";
|
||||
import { HttpProxyAgent } from "http-proxy-agent";
|
||||
import { HttpsProxyAgent } from "https-proxy-agent";
|
||||
import fetch from "node-fetch";
|
||||
import { ContinueConfig, ContinueRcJson, IDE, ILLM } from "..";
|
||||
import { Telemetry } from "../util/posthog";
|
||||
import {
|
||||
BrowserSerializedContinueConfig,
|
||||
finalToBrowserConfig,
|
||||
loadFullConfigNode,
|
||||
} from "./load";
|
||||
const tls = require("tls");
|
||||
export class ConfigHandler {
|
||||
private savedConfig: ContinueConfig | undefined;
|
||||
private savedBrowserConfig?: BrowserSerializedContinueConfig;
|
||||
|
||||
private readonly ide: IDE;
|
||||
private readonly remoteConfigServerUrl: URL | undefined;
|
||||
private readonly writeLog: (text: string) => void;
|
||||
private readonly onConfigUpdate: () => void;
|
||||
constructor(
|
||||
ide: IDE,
|
||||
remoteConfigServerUrl: URL | undefined,
|
||||
writeLog: (text: string) => void,
|
||||
onConfigUpdate: () => void
|
||||
) {
|
||||
this.ide = ide;
|
||||
this.remoteConfigServerUrl = remoteConfigServerUrl;
|
||||
this.writeLog = writeLog;
|
||||
this.onConfigUpdate = onConfigUpdate;
|
||||
try {
|
||||
this.loadConfig();
|
||||
} catch (e) {
|
||||
console.error("Failed to load config: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
reloadConfig() {
|
||||
this.savedConfig = undefined;
|
||||
this.savedBrowserConfig = undefined;
|
||||
this.loadConfig();
|
||||
this.onConfigUpdate()
|
||||
}
|
||||
|
||||
async getSerializedConfig(): Promise<BrowserSerializedContinueConfig> {
|
||||
if (!this.savedBrowserConfig) {
|
||||
this.savedConfig = await this.loadConfig();
|
||||
this.savedBrowserConfig = finalToBrowserConfig(this.savedConfig);
|
||||
}
|
||||
return this.savedBrowserConfig;
|
||||
}
|
||||
|
||||
async loadConfig(): Promise<ContinueConfig> {
|
||||
try {
|
||||
if (this.savedConfig) {
|
||||
return this.savedConfig;
|
||||
}
|
||||
|
||||
let workspaceConfigs: ContinueRcJson[] = [];
|
||||
try {
|
||||
workspaceConfigs = await this.ide.getWorkspaceConfigs();
|
||||
} catch (e) {
|
||||
console.warn("Failed to load workspace configs");
|
||||
}
|
||||
|
||||
const ideInfo = await this.ide.getIdeInfo();
|
||||
this.savedConfig = await loadFullConfigNode(
|
||||
this.ide.readFile,
|
||||
workspaceConfigs,
|
||||
this.remoteConfigServerUrl,
|
||||
ideInfo.ideType
|
||||
);
|
||||
this.savedConfig.allowAnonymousTelemetry =
|
||||
this.savedConfig.allowAnonymousTelemetry &&
|
||||
(await this.ide.isTelemetryEnabled());
|
||||
|
||||
// Setup telemetry only after (and if) we know it is enabled
|
||||
await Telemetry.setup(
|
||||
this.savedConfig.allowAnonymousTelemetry ?? true,
|
||||
await this.ide.getUniqueId()
|
||||
);
|
||||
|
||||
return this.savedConfig;
|
||||
} catch (e: any) {
|
||||
console.error("Failed to loadConfig: ", e.message);
|
||||
throw new Error("Failed to loadConfig: " + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
setupLlm(llm: ILLM): ILLM {
|
||||
const TIMEOUT = 7200; // 7200 seconds = 2 hours
|
||||
// Since we know this is happening in Node.js, we can add requestOptions through a custom agent
|
||||
const ca = [...tls.rootCertificates];
|
||||
const customCerts =
|
||||
typeof llm.requestOptions?.caBundlePath === "string"
|
||||
? [llm.requestOptions?.caBundlePath]
|
||||
: llm.requestOptions?.caBundlePath;
|
||||
if (customCerts) {
|
||||
ca.push(
|
||||
...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8"))
|
||||
);
|
||||
}
|
||||
|
||||
let timeout = (llm.requestOptions?.timeout || TIMEOUT) * 1000; // measured in ms
|
||||
|
||||
const agentOptions = {
|
||||
ca,
|
||||
rejectUnauthorized: llm.requestOptions?.verifySsl,
|
||||
timeout,
|
||||
sessionTimeout: timeout,
|
||||
keepAlive: true,
|
||||
keepAliveMsecs: timeout,
|
||||
};
|
||||
|
||||
const proxy = llm.requestOptions?.proxy;
|
||||
|
||||
llm._fetch = async (input, init) => {
|
||||
// Create agent
|
||||
const protocol = new URL(input).protocol === "https:" ? https : http;
|
||||
const agent = proxy
|
||||
? new URL(input).protocol === "https:"
|
||||
? new HttpsProxyAgent(proxy, agentOptions)
|
||||
: new HttpProxyAgent(proxy, agentOptions)
|
||||
: new protocol.Agent(agentOptions);
|
||||
|
||||
const headers: { [key: string]: string } =
|
||||
llm!.requestOptions?.headers || {};
|
||||
for (const [key, value] of Object.entries(init?.headers || {})) {
|
||||
headers[key] = value as string;
|
||||
}
|
||||
|
||||
// Replace localhost with 127.0.0.1
|
||||
input = new URL(input);
|
||||
if (input.hostname === "localhost") {
|
||||
input.hostname = "127.0.0.1";
|
||||
}
|
||||
|
||||
let updatedBody: string | undefined = undefined;
|
||||
try {
|
||||
if (
|
||||
llm.requestOptions?.extraBodyProperties &&
|
||||
typeof init.body === "string"
|
||||
) {
|
||||
const parsedBody = JSON.parse(init.body);
|
||||
updatedBody = JSON.stringify({
|
||||
...parsedBody,
|
||||
...llm.requestOptions.extraBodyProperties,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.log("Unable to parse HTTP request body: ", e);
|
||||
}
|
||||
|
||||
const resp = await fetch(input, {
|
||||
...init,
|
||||
body: updatedBody ?? init.body,
|
||||
headers,
|
||||
agent,
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
let text = await resp.text();
|
||||
if (resp.status === 404 && !resp.url.includes("/v1")) {
|
||||
if (text.includes("try pulling it first")) {
|
||||
const model = JSON.parse(text).error.split(" ")[1].slice(1, -1);
|
||||
text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`;
|
||||
} else if (text.includes("/api/chat")) {
|
||||
text =
|
||||
"The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue.";
|
||||
} else {
|
||||
text =
|
||||
"This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json.";
|
||||
}
|
||||
}
|
||||
throw new Error(
|
||||
`HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`
|
||||
);
|
||||
}
|
||||
|
||||
return resp;
|
||||
};
|
||||
|
||||
llm.writeLog = async (log: string) => {
|
||||
this.writeLog(log);
|
||||
};
|
||||
return llm;
|
||||
}
|
||||
|
||||
async llmFromTitle(title?: string): Promise<ILLM> {
|
||||
const config = await this.loadConfig();
|
||||
const model =
|
||||
config.models.find((m) => m.title === title) || config.models[0];
|
||||
if (!model) {
|
||||
throw new Error("No model found");
|
||||
}
|
||||
|
||||
return this.setupLlm(model);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import * as fs from "fs";
|
||||
import path from "path";
|
||||
import {
|
||||
BrowserSerializedContinueConfig,
|
||||
Config,
|
||||
|
|
@ -9,11 +10,11 @@ import {
|
|||
CustomLLM,
|
||||
EmbeddingsProviderDescription,
|
||||
IContextProvider,
|
||||
IdeType,
|
||||
ModelDescription,
|
||||
SerializedContinueConfig,
|
||||
SlashCommand,
|
||||
} from "..";
|
||||
|
||||
import {
|
||||
slashCommandFromDescription,
|
||||
slashFromCustomCommand,
|
||||
|
|
@ -33,31 +34,49 @@ import {
|
|||
getConfigJsonPath,
|
||||
getConfigJsonPathForRemote,
|
||||
getConfigTsPath,
|
||||
getContinueDotEnv,
|
||||
migrate,
|
||||
} from "../util/paths";
|
||||
const { execSync } = require("child_process");
|
||||
|
||||
function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
|
||||
let content = fs.readFileSync(filepath, "utf8");
|
||||
let config = JSON.parse(content) as SerializedContinueConfig;
|
||||
if (config.env && Array.isArray(config.env)) {
|
||||
const env = {
|
||||
...process.env,
|
||||
...getContinueDotEnv(),
|
||||
};
|
||||
|
||||
config.env.forEach((envVar) => {
|
||||
content = content.replaceAll(
|
||||
new RegExp(`"${envVar}"`, "g"),
|
||||
`"${env[envVar]}"`
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
return JSON.parse(content);
|
||||
}
|
||||
|
||||
const configMergeKeys = {
|
||||
"models": (a: any, b: any) => a.title === b.title,
|
||||
"contextProviders": (a: any, b: any) => a.name === b.name,
|
||||
"slashCommands": (a: any, b: any) => a.name === b.name,
|
||||
"customCommands": (a: any, b: any) => a.name === b.name,
|
||||
}
|
||||
|
||||
function loadSerializedConfig(
|
||||
workspaceConfigs: ContinueRcJson[],
|
||||
remoteConfigServerUrl: URL | undefined
|
||||
remoteConfigServerUrl: URL | undefined,
|
||||
ideType: IdeType
|
||||
): SerializedContinueConfig {
|
||||
const configPath = getConfigJsonPath();
|
||||
let contents = fs.readFileSync(configPath, "utf8");
|
||||
let config = JSON.parse(contents) as SerializedContinueConfig;
|
||||
const configPath = getConfigJsonPath(ideType);
|
||||
let config = resolveSerializedConfig(configPath);
|
||||
if (config.allowAnonymousTelemetry === undefined) {
|
||||
config.allowAnonymousTelemetry = true;
|
||||
}
|
||||
|
||||
// Migrate to camelCase - replace all instances of "snake_case" with "camelCase"
|
||||
migrate("camelCaseConfig", () => {
|
||||
contents = contents
|
||||
.replace(/(_\w)/g, function (m) {
|
||||
return m[1].toUpperCase();
|
||||
})
|
||||
.replace("openai-aiohttp", "openai");
|
||||
|
||||
fs.writeFileSync(configPath, contents, "utf8");
|
||||
});
|
||||
|
||||
migrate("codebaseContextProvider", () => {
|
||||
if (
|
||||
!config.contextProviders?.filter((cp) => cp.name === "codebase")?.length
|
||||
|
|
@ -112,21 +131,15 @@ function loadSerializedConfig(
|
|||
fs.writeFileSync(configPath, JSON.stringify(config, undefined, 2), "utf8");
|
||||
});
|
||||
|
||||
migrate("renameFreeTrialProvider", () => {
|
||||
contents = contents.replace(/openai-free-trial/g, "free-trial");
|
||||
fs.writeFileSync(configPath, contents, "utf8");
|
||||
});
|
||||
|
||||
if (remoteConfigServerUrl) {
|
||||
const remoteConfigJson = fs.readFileSync(
|
||||
getConfigJsonPathForRemote(remoteConfigServerUrl),
|
||||
"utf-8"
|
||||
const remoteConfigJson = resolveSerializedConfig(
|
||||
getConfigJsonPathForRemote(remoteConfigServerUrl)
|
||||
);
|
||||
config = mergeJson(config, JSON.parse(remoteConfigJson), "merge");
|
||||
config = mergeJson(config, remoteConfigJson, "merge", configMergeKeys);
|
||||
}
|
||||
|
||||
for (const workspaceConfig of workspaceConfigs) {
|
||||
config = mergeJson(config, workspaceConfig, workspaceConfig.mergeBehavior);
|
||||
config = mergeJson(config, workspaceConfig, workspaceConfig.mergeBehavior, configMergeKeys);
|
||||
}
|
||||
|
||||
return config;
|
||||
|
|
@ -317,53 +330,101 @@ function finalToBrowserConfig(
|
|||
};
|
||||
}
|
||||
|
||||
async function buildConfigTs(browser: boolean) {
|
||||
function getTarget() {
|
||||
const os =
|
||||
{
|
||||
aix: "linux",
|
||||
darwin: "darwin",
|
||||
freebsd: "linux",
|
||||
linux: "linux",
|
||||
openbsd: "linux",
|
||||
sunos: "linux",
|
||||
win32: "win32",
|
||||
}[process.platform as string] ?? "linux";
|
||||
const 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 `${os}-${arch}`;
|
||||
}
|
||||
|
||||
function escapeSpacesInPath(p: string): string {
|
||||
return p.replace(/ /g, "\\ ");
|
||||
}
|
||||
|
||||
async function buildConfigTs() {
|
||||
if (!fs.existsSync(getConfigTsPath())) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
// Dynamic import esbuild so potentially disastrous errors can be caught
|
||||
const esbuild = require("esbuild");
|
||||
if (process.env.IS_BINARY === "true") {
|
||||
execSync(
|
||||
escapeSpacesInPath(path.dirname(process.execPath)) +
|
||||
`/esbuild${
|
||||
getTarget().startsWith("win32") ? ".exe" : ""
|
||||
} ${escapeSpacesInPath(
|
||||
getConfigTsPath()
|
||||
)} --bundle --outfile=${escapeSpacesInPath(
|
||||
getConfigJsPath()
|
||||
)} --platform=node --format=cjs --sourcemap --external:fetch --external:fs --external:path --external:os --external:child_process`
|
||||
);
|
||||
} else {
|
||||
// Dynamic import esbuild so potentially disastrous errors can be caught
|
||||
const esbuild = require("esbuild");
|
||||
|
||||
await esbuild.build({
|
||||
entryPoints: [getConfigTsPath()],
|
||||
bundle: true,
|
||||
platform: browser ? "browser" : "node",
|
||||
format: browser ? "esm" : "cjs",
|
||||
outfile: getConfigJsPath(!browser),
|
||||
external: ["fetch", "fs", "path", "os", "child_process"],
|
||||
sourcemap: true,
|
||||
});
|
||||
await esbuild.build({
|
||||
entryPoints: [getConfigTsPath()],
|
||||
bundle: true,
|
||||
platform: "node",
|
||||
format: "cjs",
|
||||
outfile: getConfigJsPath(),
|
||||
external: ["fetch", "fs", "path", "os", "child_process"],
|
||||
sourcemap: true,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
console.log(
|
||||
"Build error. Please check your ~/.continue/config.ts file: " + e
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (!fs.existsSync(getConfigJsPath(!browser))) {
|
||||
if (!fs.existsSync(getConfigJsPath())) {
|
||||
return undefined;
|
||||
}
|
||||
return fs.readFileSync(getConfigJsPath(!browser), "utf8");
|
||||
return fs.readFileSync(getConfigJsPath(), "utf8");
|
||||
}
|
||||
|
||||
async function loadFullConfigNode(
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
workspaceConfigs: ContinueRcJson[],
|
||||
remoteConfigServerUrl: URL | undefined
|
||||
remoteConfigServerUrl: URL | undefined,
|
||||
ideType: IdeType
|
||||
): Promise<ContinueConfig> {
|
||||
let serialized = loadSerializedConfig(
|
||||
workspaceConfigs,
|
||||
remoteConfigServerUrl
|
||||
remoteConfigServerUrl,
|
||||
ideType
|
||||
);
|
||||
let intermediate = serializedToIntermediateConfig(serialized);
|
||||
|
||||
const configJsContents = await buildConfigTs(false);
|
||||
const configJsContents = await buildConfigTs();
|
||||
if (configJsContents) {
|
||||
try {
|
||||
// Try config.ts first
|
||||
const configJsPath = getConfigJsPath(true);
|
||||
const configJsPath = getConfigJsPath();
|
||||
const module = await require(configJsPath);
|
||||
delete require.cache[require.resolve(configJsPath)];
|
||||
if (!module.modifyConfig) {
|
||||
|
|
@ -401,5 +462,5 @@ export {
|
|||
intermediateToFinalConfig,
|
||||
loadFullConfigNode,
|
||||
serializedToIntermediateConfig,
|
||||
type BrowserSerializedContinueConfig,
|
||||
type BrowserSerializedContinueConfig
|
||||
};
|
||||
|
|
|
|||
|
|
@ -15,7 +15,11 @@ declare global {
|
|||
};
|
||||
colorThemeName?: string;
|
||||
workspacePaths?: string[];
|
||||
postIntellijMessage?: (type: string, data: any) => void;
|
||||
postIntellijMessage?: (
|
||||
messageType: string,
|
||||
data: any,
|
||||
messageIde: string
|
||||
) => void;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -313,13 +317,24 @@ declare global {
|
|||
message: string;
|
||||
}
|
||||
|
||||
export type IdeType = "vscode" | "jetbrains";
|
||||
export interface IdeInfo {
|
||||
ideType: IdeType;
|
||||
name: string;
|
||||
version: string;
|
||||
remoteName: string;
|
||||
}
|
||||
|
||||
export interface IDE {
|
||||
getSerializedConfig(): Promise<BrowserSerializedContinueConfig>;
|
||||
getIdeInfo(): Promise<IdeInfo>;
|
||||
getDiff(): Promise<string>;
|
||||
isTelemetryEnabled(): Promise<boolean>;
|
||||
getUniqueId(): Promise<string>;
|
||||
getTerminalContents(): Promise<string>;
|
||||
listWorkspaceContents(directory?: string): Promise<string[]>;
|
||||
listFolders(): Promise<string[]>;
|
||||
getWorkspaceDirs(): Promise<string[]>;
|
||||
getWorkspaceConfigs(): Promise<ContinueRcJson[]>;
|
||||
writeFile(path: string, contents: string): Promise<void>;
|
||||
showVirtualFile(title: string, contents: string): Promise<void>;
|
||||
getContinueDir(): Promise<string>;
|
||||
|
|
@ -327,6 +342,7 @@ declare global {
|
|||
runCommand(command: string): Promise<void>;
|
||||
saveFile(filepath: string): Promise<void>;
|
||||
readFile(filepath: string): Promise<string>;
|
||||
readRangeInFile(filepath: string, range: Range): Promise<string>;
|
||||
showLines(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
|
|
@ -337,34 +353,13 @@ declare global {
|
|||
newContents: string,
|
||||
stepIndex: number
|
||||
): Promise<void>;
|
||||
verticalDiffUpdate(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
diffLine: DiffLine
|
||||
): Promise<void>;
|
||||
getOpenFiles(): Promise<string[]>;
|
||||
getPinnedFiles(): Promise<string[]>;
|
||||
getSearchResults(query: string): Promise<string>;
|
||||
subprocess(command: string): Promise<[string, string]>;
|
||||
getProblems(filepath?: string | undefined): Promise<Problem[]>;
|
||||
getBranch(dir: string): Promise<string>;
|
||||
|
||||
// Embeddings
|
||||
/**
|
||||
* Returns list of [tag, filepath, hash of contents] that need to be embedded
|
||||
*/
|
||||
getFilesToEmbed(providerId: string): Promise<[string, string, string][]>;
|
||||
sendEmbeddingForChunk(
|
||||
chunk: Chunk,
|
||||
embedding: number[],
|
||||
tags: string[]
|
||||
): void;
|
||||
retrieveChunks(
|
||||
text: string,
|
||||
n: number,
|
||||
directory: string | undefined
|
||||
): Promise<Chunk[]>;
|
||||
getStats(directory: string): Promise<{ [path: string]: number }>;
|
||||
}
|
||||
|
||||
// Slash Commands
|
||||
|
|
@ -377,6 +372,8 @@ declare global {
|
|||
input: string;
|
||||
params?: { [key: string]: any } | undefined;
|
||||
contextItems: ContextItemWithId[];
|
||||
selectedCode: RangeInFile[];
|
||||
config: ContinueConfig;
|
||||
}
|
||||
|
||||
export interface SlashCommand {
|
||||
|
|
|
|||
38
core/config/util.ts
Normal file
38
core/config/util.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import { readFileSync, writeFileSync } from "fs";
|
||||
import { ModelDescription } from "..";
|
||||
import { editConfigJson, getConfigJsonPath } from "../util/paths";
|
||||
|
||||
export function addModel(model: ModelDescription) {
|
||||
const config = readFileSync(getConfigJsonPath(), "utf8");
|
||||
const configJson = JSON.parse(config);
|
||||
configJson.models.push(model);
|
||||
const newConfigString = JSON.stringify(
|
||||
configJson,
|
||||
(key, value) => {
|
||||
return value === null ? undefined : value;
|
||||
},
|
||||
2
|
||||
);
|
||||
writeFileSync(getConfigJsonPath(), newConfigString);
|
||||
return newConfigString;
|
||||
}
|
||||
|
||||
export function addOpenAIKey(key: string) {
|
||||
editConfigJson((config) => {
|
||||
config.models = config.models.map((m: ModelDescription) => {
|
||||
if (m.provider === "free-trial") {
|
||||
m.apiKey = key;
|
||||
m.provider = "openai";
|
||||
}
|
||||
return m;
|
||||
});
|
||||
return config;
|
||||
});
|
||||
}
|
||||
|
||||
export function deleteModel(title: string) {
|
||||
editConfigJson((config) => {
|
||||
config.models = config.models.filter((m: any) => m.title !== title);
|
||||
return config;
|
||||
});
|
||||
}
|
||||
|
|
@ -6,8 +6,7 @@ import {
|
|||
} from "../..";
|
||||
import { getBasename } from "../../util";
|
||||
|
||||
import { getHighlightsThatFit, ILLMContextSizer } from "llm-code-highlighter/dist/index.continue";
|
||||
import { countTokens } from "../../llm/countTokens";
|
||||
// import { getHighlightsThatFit, ILLMContextSizer } from "llm-code-highlighter/dist/index.continue";
|
||||
|
||||
const HIGHLIGHTS_TOKEN_BUDGET = 2000;
|
||||
|
||||
|
|
@ -35,30 +34,31 @@ class CodeHighlightsContextProvider extends BaseContextProvider {
|
|||
};
|
||||
})
|
||||
);
|
||||
const contextSizer = {
|
||||
fits(content: string): boolean {
|
||||
return countTokens(content, "") < HIGHLIGHTS_TOKEN_BUDGET;
|
||||
}
|
||||
} as ILLMContextSizer
|
||||
const repoMap = await getHighlightsThatFit(
|
||||
contextSizer,
|
||||
[],
|
||||
allFiles
|
||||
.filter((file) => file.content.length > 0)
|
||||
.map((file) => {
|
||||
return {
|
||||
relPath: file.name,
|
||||
code: file.content,
|
||||
};
|
||||
})
|
||||
);
|
||||
return [
|
||||
{
|
||||
content: repoMap ? repoMap : "",
|
||||
name: "Code Highlights",
|
||||
description: "Code highlights from open files",
|
||||
},
|
||||
];
|
||||
// const contextSizer = {
|
||||
// fits(content: string): boolean {
|
||||
// return countTokens(content, "") < HIGHLIGHTS_TOKEN_BUDGET;
|
||||
// }
|
||||
// } as ILLMContextSizer
|
||||
// const repoMap = await getHighlightsThatFit(
|
||||
// contextSizer,
|
||||
// [],
|
||||
// allFiles
|
||||
// .filter((file) => file.content.length > 0)
|
||||
// .map((file) => {
|
||||
// return {
|
||||
// relPath: file.name,
|
||||
// code: file.content,
|
||||
// };
|
||||
// })
|
||||
// );
|
||||
// return [
|
||||
// {
|
||||
// content: repoMap ? repoMap : "",
|
||||
// name: "Code Highlights",
|
||||
// description: "Code highlights from open files",
|
||||
// },
|
||||
// ];
|
||||
return []
|
||||
}
|
||||
|
||||
async load(): Promise<void> {}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import {
|
|||
} from "../..";
|
||||
import { getBasename } from "../../util";
|
||||
|
||||
import { getOutlines } from "llm-code-highlighter/dist/index.continue";
|
||||
// import { getOutlines } from "llm-code-highlighter/dist/index.continue";
|
||||
|
||||
class CodeOutlineContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
|
|
@ -32,23 +32,24 @@ class CodeOutlineContextProvider extends BaseContextProvider {
|
|||
};
|
||||
})
|
||||
);
|
||||
const outlines = await getOutlines(
|
||||
allFiles
|
||||
.filter((file) => file.content.length > 0)
|
||||
.map((file) => {
|
||||
return {
|
||||
relPath: file.name,
|
||||
code: file.content,
|
||||
};
|
||||
})
|
||||
);
|
||||
return [
|
||||
{
|
||||
content: outlines ? outlines : "",
|
||||
name: "Code Outline",
|
||||
description: "Definition lines only (from open files)",
|
||||
},
|
||||
];
|
||||
// const outlines = await getOutlines(
|
||||
// allFiles
|
||||
// .filter((file) => file.content.length > 0)
|
||||
// .map((file) => {
|
||||
// return {
|
||||
// relPath: file.name,
|
||||
// code: file.content,
|
||||
// };
|
||||
// })
|
||||
// );
|
||||
// return [
|
||||
// {
|
||||
// content: outlines ? outlines : "",
|
||||
// name: "Code Outline",
|
||||
// description: "Definition lines only (from open files)",
|
||||
// },
|
||||
// ];
|
||||
return []
|
||||
}
|
||||
|
||||
async load(): Promise<void> {}
|
||||
|
|
|
|||
112
core/context/providers/DatabaseContextProvider.ts
Normal file
112
core/context/providers/DatabaseContextProvider.ts
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
import { BaseContextProvider } from "..";
|
||||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
LoadSubmenuItemsArgs,
|
||||
ContextSubmenuItem,
|
||||
} from "../..";
|
||||
|
||||
class DatabaseContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "database",
|
||||
displayTitle: "Database",
|
||||
description: "Table schemas",
|
||||
type: "submenu",
|
||||
};
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
): Promise<ContextItem[]> {
|
||||
const contextItems: ContextItem[] = [];
|
||||
|
||||
const connections = this.options?.connections;
|
||||
|
||||
if (connections === null) { return contextItems; }
|
||||
|
||||
let [connectionName, table] = query.split('.');
|
||||
|
||||
const getDatabaseAdapter = await require("dbinfoz");
|
||||
|
||||
for (const connection of connections) {
|
||||
if(connection.name == connectionName) {
|
||||
const adapter = getDatabaseAdapter(connection.connection_type, connection.connection);
|
||||
const tablesAndSchemas = await adapter.getAllTablesAndSchemas(connection.connection.database);
|
||||
|
||||
if(table === 'all') {
|
||||
let prompt = `Schema for all tables on ${connection.connection_type} is `;
|
||||
prompt += JSON.stringify(tablesAndSchemas);
|
||||
|
||||
let contextItem = {
|
||||
name: `${connectionName}-all-tables-schemas`,
|
||||
description: `Schema for all tables.`,
|
||||
content: prompt
|
||||
}
|
||||
|
||||
contextItems.push(contextItem);
|
||||
} else {
|
||||
const tables = Object.keys(tablesAndSchemas);
|
||||
|
||||
tables.forEach(tableName => {
|
||||
if(table === tableName) {
|
||||
let prompt = `Schema for ${tableName} on ${connection.connection_type} is `;
|
||||
prompt += JSON.stringify(tablesAndSchemas[tableName]);
|
||||
|
||||
let contextItem = {
|
||||
name: `${connectionName}-${tableName}-schema`,
|
||||
description: `${tableName} Schema`,
|
||||
content: prompt
|
||||
}
|
||||
|
||||
contextItems.push(contextItem);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return contextItems;
|
||||
}
|
||||
|
||||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const contextItems: ContextSubmenuItem[] = [];
|
||||
const connections = this.options?.connections;
|
||||
|
||||
if (connections === null) { return contextItems; }
|
||||
|
||||
const getDatabaseAdapter = await require("dbinfoz");
|
||||
|
||||
for (const connection of connections) {
|
||||
let adapter = getDatabaseAdapter(connection.connection_type, connection.connection);
|
||||
const tablesAndSchemas = await adapter.getAllTablesAndSchemas(connection.connection.database);
|
||||
const tables = Object.keys(tablesAndSchemas);
|
||||
|
||||
let contextItem = {
|
||||
id: `${connection.name}.all`,
|
||||
title: `${connection.name} all table schemas`,
|
||||
description: ``
|
||||
}
|
||||
|
||||
contextItems.push(contextItem);
|
||||
|
||||
tables.forEach(tableName => {
|
||||
let contextItem = {
|
||||
id: `${connection.name}.${tableName}`,
|
||||
title: `${connection.name}.${tableName} schema`,
|
||||
description: ``
|
||||
}
|
||||
|
||||
contextItems.push(contextItem);
|
||||
});
|
||||
}
|
||||
|
||||
return contextItems;
|
||||
}
|
||||
}
|
||||
|
||||
export default DatabaseContextProvider;
|
||||
|
||||
146
core/context/providers/PostgresContextProvider.ts
Normal file
146
core/context/providers/PostgresContextProvider.ts
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
import { BaseContextProvider } from "..";
|
||||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
LoadSubmenuItemsArgs,
|
||||
ContextSubmenuItem,
|
||||
} from "../..";
|
||||
|
||||
class PostgresContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "postgres",
|
||||
displayTitle: "PostgreSQL",
|
||||
description: "Retrieve PostgreSQL table schema and sample rows",
|
||||
type: "submenu",
|
||||
};
|
||||
|
||||
static ALL_TABLES = "__all_tables";
|
||||
static DEFAULT_SAMPLE_ROWS = 3;
|
||||
|
||||
constructor(options: {
|
||||
host: string;
|
||||
port: number;
|
||||
user: string;
|
||||
password: string;
|
||||
database: string;
|
||||
schema?: string;
|
||||
sampleRows?: number;
|
||||
}) {
|
||||
super(options);
|
||||
}
|
||||
|
||||
private async getPool() {
|
||||
const pg = await require("pg");
|
||||
return new pg.Pool({
|
||||
host: this.options.host,
|
||||
port: this.options.port,
|
||||
user: this.options.user,
|
||||
password: this.options.password,
|
||||
database: this.options.database,
|
||||
});
|
||||
}
|
||||
|
||||
private async getTableNames(pool: any): Promise<string[]> {
|
||||
const schema = this.options.schema ?? "public";
|
||||
var tablesInfoQuery = `
|
||||
SELECT table_schema, table_name
|
||||
FROM information_schema.tables`;
|
||||
if (schema != null) {
|
||||
tablesInfoQuery += ` WHERE table_schema = '${schema}'`;
|
||||
}
|
||||
const { rows: tablesInfo } = await pool.query(tablesInfoQuery);
|
||||
return tablesInfo.map(
|
||||
(tableInfo: any) => `${tableInfo.table_schema}.${tableInfo.table_name}`
|
||||
);
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string = "",
|
||||
_: ContextProviderExtras = {} as ContextProviderExtras
|
||||
): Promise<ContextItem[]> {
|
||||
const pool = await this.getPool();
|
||||
|
||||
try {
|
||||
const contextItems: ContextItem[] = [];
|
||||
|
||||
const tableNames = [];
|
||||
if (query === PostgresContextProvider.ALL_TABLES) {
|
||||
tableNames.push(...(await this.getTableNames(pool)));
|
||||
} else {
|
||||
tableNames.push(query);
|
||||
}
|
||||
|
||||
for (const tableName of tableNames) {
|
||||
// Get the table schema
|
||||
if (!tableName.includes(".")) {
|
||||
throw new Error(
|
||||
`Table name must be in format schema.table_name, got ${tableName}`
|
||||
);
|
||||
}
|
||||
var schemaQuery = `
|
||||
SELECT column_name, data_type, character_maximum_length
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE table_schema = '${tableName.split(".")[0]}'
|
||||
AND table_name = '${tableName.split(".")[1]}'`;
|
||||
console.log("schemaQuery", schemaQuery);
|
||||
const { rows: tableSchema } = await pool.query(schemaQuery);
|
||||
|
||||
// Get the sample rows
|
||||
const sampleRows =
|
||||
this.options.sampleRows ??
|
||||
PostgresContextProvider.DEFAULT_SAMPLE_ROWS;
|
||||
const { rows: sampleRowResults } = await pool.query(`
|
||||
SELECT *
|
||||
FROM ${tableName}
|
||||
LIMIT ${sampleRows}`);
|
||||
|
||||
// Create prompt from the table schema and sample rows
|
||||
var prompt = `Postgres schema for database ${this.options.database} table ${tableName}:\n`;
|
||||
prompt += `${JSON.stringify(tableSchema, null, 2)}\n\n`;
|
||||
prompt += `Sample rows: ${JSON.stringify(sampleRowResults, null, 2)}`;
|
||||
|
||||
contextItems.push({
|
||||
name: `${this.options.database}-${tableName}-schema-and-sample-rows`,
|
||||
description: `Schema and sample rows for table ${tableName}`,
|
||||
content: prompt,
|
||||
});
|
||||
}
|
||||
|
||||
return contextItems;
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to query PostgreSQL database: ${error}`);
|
||||
} finally {
|
||||
}
|
||||
}
|
||||
|
||||
async loadSubmenuItems(
|
||||
_: LoadSubmenuItemsArgs
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const pool = await this.getPool();
|
||||
|
||||
try {
|
||||
const contextItems: ContextSubmenuItem[] = [];
|
||||
const tableNames = await this.getTableNames(pool);
|
||||
|
||||
for (const tableName of tableNames) {
|
||||
contextItems.push({
|
||||
id: tableName,
|
||||
title: tableName,
|
||||
description: `Schema from ${tableName} and ${this.options.sampleRows} sample rows.`,
|
||||
});
|
||||
}
|
||||
contextItems.push({
|
||||
id: PostgresContextProvider.ALL_TABLES,
|
||||
title: "All tables",
|
||||
description: `Schema from all tables and ${this.options.sampleRows} sample rows each.`,
|
||||
});
|
||||
|
||||
return contextItems;
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to query PostgreSQL database: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default PostgresContextProvider;
|
||||
|
|
@ -1,8 +1,7 @@
|
|||
import { BaseContextProvider } from "..";
|
||||
import { ContextProviderName } from "../..";
|
||||
import CodebaseContextProvider from "./CodebaseContextProvider";
|
||||
import CodeHighlightsContextProvider from "./CodeHighlightsContextProvider";
|
||||
import CodeOutlineContextProvider from "./CodeOutlineContextProvider";
|
||||
import DatabaseContextProvider from "./DatabaseContextProvider";
|
||||
import DiffContextProvider from "./DiffContextProvider";
|
||||
import DocsContextProvider from "./DocsContextProvider";
|
||||
import FileTreeContextProvider from "./FileTreeContextProvider";
|
||||
|
|
@ -10,13 +9,14 @@ import FolderContextProvider from "./FolderContextProvider";
|
|||
import GitHubIssuesContextProvider from "./GitHubIssuesContextProvider";
|
||||
import GoogleContextProvider from "./GoogleContextProvider";
|
||||
import HttpContextProvider from "./HttpContextProvider";
|
||||
import JiraIssuesContextProvider from "./JiraIssuesContextProvider";
|
||||
import OpenFilesContextProvider from "./OpenFilesContextProvider";
|
||||
import PostgresContextProvider from "./PostgresContextProvider";
|
||||
import ProblemsContextProvider from "./ProblemsContextProvider";
|
||||
import SearchContextProvider from "./SearchContextProvider";
|
||||
import TerminalContextProvider from "./TerminalContextProvider";
|
||||
import LocalsProvider from "./LocalsProvider";
|
||||
import URLContextProvider from "./URLContextProvider";
|
||||
import JiraIssuesContextProvider from "./JiraIssuesContextProvider";
|
||||
|
||||
const Providers: (typeof BaseContextProvider)[] = [
|
||||
DiffContextProvider,
|
||||
|
|
@ -33,9 +33,11 @@ const Providers: (typeof BaseContextProvider)[] = [
|
|||
ProblemsContextProvider,
|
||||
FolderContextProvider,
|
||||
DocsContextProvider,
|
||||
CodeHighlightsContextProvider,
|
||||
CodeOutlineContextProvider,
|
||||
// CodeHighlightsContextProvider,
|
||||
// CodeOutlineContextProvider,
|
||||
JiraIssuesContextProvider,
|
||||
PostgresContextProvider,
|
||||
DatabaseContextProvider,
|
||||
];
|
||||
|
||||
export function contextProviderClassFromName(
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { Chunk, ContextItem, ContextProviderExtras, ILLM } from "..";
|
||||
import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch";
|
||||
import { ChunkCodebaseIndex } from "../indexing/chunk/ChunkCodebaseIndex";
|
||||
import { LanceDbIndex } from "../indexing/LanceDbIndex";
|
||||
import { IndexTag } from "../indexing/types";
|
||||
import { llmCanGenerateInParallel } from "../llm/autodetect";
|
||||
import { getBasename } from "../util";
|
||||
|
|
@ -8,7 +8,7 @@ import { getBasename } from "../util";
|
|||
const RERANK_PROMPT = (
|
||||
query: string,
|
||||
documentId: string,
|
||||
document: string
|
||||
document: string,
|
||||
) => `You are an expert software developer responsible for helping detect whether the retrieved snippet of code is relevant to the query. For a given input, you need to output a single word: "Yes" or "No" indicating the retrieved snippet is relevant to the query.
|
||||
|
||||
Query: Where is the FastAPI server?
|
||||
|
|
@ -48,7 +48,7 @@ Relevant:
|
|||
async function scoreChunk(
|
||||
chunk: Chunk,
|
||||
llm: ILLM,
|
||||
query: string
|
||||
query: string,
|
||||
): Promise<number> {
|
||||
const completion = await llm.complete(
|
||||
RERANK_PROMPT(query, getBasename(chunk.filepath), chunk.content),
|
||||
|
|
@ -58,7 +58,7 @@ async function scoreChunk(
|
|||
llm.providerName.startsWith("openai") && llm.model.startsWith("gpt-4")
|
||||
? "gpt-3.5-turbo"
|
||||
: llm.model,
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
if (!completion) {
|
||||
|
|
@ -78,7 +78,7 @@ async function scoreChunk(
|
|||
return 0.0;
|
||||
} else {
|
||||
console.warn(
|
||||
`Unexpected response from single token reranker: "${answer}". Expected "yes" or "no".`
|
||||
`Unexpected response from single token reranker: "${answer}". Expected "yes" or "no".`,
|
||||
);
|
||||
return 0.0;
|
||||
}
|
||||
|
|
@ -88,10 +88,10 @@ async function rerank(
|
|||
chunks: Chunk[],
|
||||
llm: ILLM,
|
||||
query: string,
|
||||
nFinal: number
|
||||
nFinal: number,
|
||||
): Promise<Chunk[]> {
|
||||
const scores = await Promise.all(
|
||||
chunks.map((chunk) => scoreChunk(chunk, llm, query))
|
||||
chunks.map((chunk) => scoreChunk(chunk, llm, query)),
|
||||
);
|
||||
const sorted = chunks
|
||||
.map((chunk, i) => ({ chunk, score: scores[i] }))
|
||||
|
|
@ -103,7 +103,7 @@ async function rerank(
|
|||
export async function retrieveContextItemsFromEmbeddings(
|
||||
extras: ContextProviderExtras,
|
||||
options: any | undefined,
|
||||
filterDirectory: string | undefined
|
||||
filterDirectory: string | undefined,
|
||||
): Promise<ContextItem[]> {
|
||||
if (!extras.embeddingsProvider) {
|
||||
return [];
|
||||
|
|
@ -122,35 +122,49 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
throw new Error("No workspace directories found");
|
||||
}
|
||||
|
||||
const branches = await Promise.all(
|
||||
workspaceDirs.map((dir) => extras.ide.getBranch(dir))
|
||||
);
|
||||
const tags: IndexTag[] = workspaceDirs.map((directory, i) => ({
|
||||
directory,
|
||||
branch: branches[i],
|
||||
artifactId: ChunkCodebaseIndex.artifactId,
|
||||
}));
|
||||
const branches = (await Promise.race([
|
||||
Promise.all(workspaceDirs.map((dir) => extras.ide.getBranch(dir))),
|
||||
new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve(["NONE"]);
|
||||
}, 500);
|
||||
}),
|
||||
])) as string[];
|
||||
const tags: (artifactId: string) => IndexTag[] = (artifactId: string) =>
|
||||
workspaceDirs.map((directory, i) => ({
|
||||
directory,
|
||||
branch: branches[i],
|
||||
artifactId,
|
||||
}));
|
||||
|
||||
let ftsResults: Chunk[] = [];
|
||||
|
||||
try {
|
||||
if (extras.fullInput.trim() !== "") {
|
||||
ftsResults = await ftsIndex.retrieve(
|
||||
tags,
|
||||
extras.fullInput.trim().split(" ").map(element => `"${element}"`).join(" OR "),
|
||||
tags(ftsIndex.artifactId),
|
||||
extras.fullInput
|
||||
.trim()
|
||||
.split(" ")
|
||||
.map((element) => `"${element}"`)
|
||||
.join(" OR "),
|
||||
nRetrieve / 2,
|
||||
filterDirectory,
|
||||
undefined
|
||||
undefined,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("Error retrieving from FTS:", e);
|
||||
}
|
||||
|
||||
let vecResults = await extras.ide.retrieveChunks(
|
||||
const lanceDbIndex = new LanceDbIndex(extras.embeddingsProvider, (path) =>
|
||||
extras.ide.readFile(path),
|
||||
);
|
||||
let vecResults = await lanceDbIndex.retrieve(
|
||||
tags(lanceDbIndex.artifactId),
|
||||
extras.fullInput,
|
||||
nRetrieve,
|
||||
filterDirectory
|
||||
filterDirectory,
|
||||
);
|
||||
|
||||
// Now combine these (de-duplicate) and re-rank
|
||||
|
|
@ -164,7 +178,7 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
(r) =>
|
||||
r.filepath === vecResult.filepath &&
|
||||
r.startLine === vecResult.startLine &&
|
||||
r.endLine === vecResult.endLine
|
||||
r.endLine === vecResult.endLine,
|
||||
)
|
||||
) {
|
||||
results.push(vecResult);
|
||||
|
|
@ -178,7 +192,7 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
|
||||
if (results.length === 0) {
|
||||
throw new Error(
|
||||
"Warning: No results found for @codebase context provider."
|
||||
"Warning: No results found for @codebase context provider.",
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ export async function* streamDiff(
|
|||
oldLines: string[],
|
||||
newLines: LineStream
|
||||
): AsyncGenerator<DiffLine> {
|
||||
oldLines = [...oldLines]; // be careful
|
||||
const mutatedOldLines = [...oldLines]; // be careful
|
||||
let seenIndentationMistake = false;
|
||||
|
||||
let newLineResult = await newLines.next();
|
||||
|
|
|
|||
|
|
@ -1,144 +0,0 @@
|
|||
import { Chunk, DiffLine, Problem } from "..";
|
||||
import { BrowserSerializedContinueConfig } from "../config/load";
|
||||
import { IDE } from "../index";
|
||||
|
||||
import { ideRequest } from "./messaging";
|
||||
async function r(messageType: string, options: any = {}) {
|
||||
return await ideRequest(messageType, options);
|
||||
}
|
||||
export class ExtensionIde implements IDE {
|
||||
async getTopLevelCallStackSources(
|
||||
threadIndex: number,
|
||||
stackDepth: number
|
||||
): Promise<string[]> {
|
||||
return await r("getTopLevelCallStackSources");
|
||||
}
|
||||
async getAvailableThreads(): Promise<string[]> {
|
||||
return await r("getAvailableThreads");
|
||||
}
|
||||
async getSerializedConfig(): Promise<BrowserSerializedContinueConfig> {
|
||||
return await r("getSerializedConfig");
|
||||
}
|
||||
|
||||
async getDiff() {
|
||||
return await r("getDiff");
|
||||
}
|
||||
|
||||
async getTerminalContents() {
|
||||
return await r("getTerminalContents");
|
||||
}
|
||||
|
||||
async getDebugLocals(threadIndex: number) {
|
||||
return await r("getTerminalContents");
|
||||
}
|
||||
|
||||
async listWorkspaceContents(directory?: string): Promise<string[]> {
|
||||
return await r("listWorkspaceContents");
|
||||
}
|
||||
|
||||
async getWorkspaceDirs(): Promise<string[]> {
|
||||
return await r("getWorkspaceDirs");
|
||||
}
|
||||
|
||||
async showLines(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number
|
||||
): Promise<void> {
|
||||
return await r("showLines", { filepath, startLine, endLine });
|
||||
}
|
||||
|
||||
async listFolders(): Promise<string[]> {
|
||||
return await r("listFolders");
|
||||
}
|
||||
|
||||
_continueDir: string | null = null;
|
||||
|
||||
async getContinueDir(): Promise<string> {
|
||||
if (this._continueDir) {
|
||||
return this._continueDir;
|
||||
}
|
||||
const dir = await r("getContinueDir");
|
||||
this._continueDir = dir;
|
||||
return dir;
|
||||
}
|
||||
|
||||
async writeFile(path: string, contents: string): Promise<void> {
|
||||
await r("writeFile", { path, contents });
|
||||
}
|
||||
|
||||
async showVirtualFile(title: string, contents: string): Promise<void> {
|
||||
await r("showVirtualFile", { name: title, content: contents });
|
||||
}
|
||||
|
||||
async openFile(path: string): Promise<void> {
|
||||
await r("openFile", { path });
|
||||
}
|
||||
|
||||
async runCommand(command: string): Promise<void> {
|
||||
await r("runCommand", { command });
|
||||
}
|
||||
|
||||
async saveFile(filepath: string): Promise<void> {
|
||||
await r("saveFile", { filepath });
|
||||
}
|
||||
async readFile(filepath: string): Promise<string> {
|
||||
return await r("readFile", { filepath });
|
||||
}
|
||||
async showDiff(
|
||||
filepath: string,
|
||||
newContents: string,
|
||||
stepIndex: number
|
||||
): Promise<void> {
|
||||
await r("showDiff", { filepath, newContents, stepIndex });
|
||||
}
|
||||
|
||||
async verticalDiffUpdate(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
diffLine: DiffLine
|
||||
) {
|
||||
await r("diffLine", { filepath, startLine, endLine, diffLine });
|
||||
}
|
||||
|
||||
getOpenFiles(): Promise<string[]> {
|
||||
return r("getOpenFiles");
|
||||
}
|
||||
|
||||
getPinnedFiles(): Promise<string[]> {
|
||||
return r("getPinnedFiles");
|
||||
}
|
||||
|
||||
getSearchResults(query: string): Promise<string> {
|
||||
return r("getSearchResults", { query });
|
||||
}
|
||||
|
||||
getProblems(filepath?: string | undefined): Promise<Problem[]> {
|
||||
return r("getProblems", { filepath });
|
||||
}
|
||||
|
||||
subprocess(command: string): Promise<[string, string]> {
|
||||
return r("subprocess", { command });
|
||||
}
|
||||
|
||||
getFilesToEmbed(providerId: string): Promise<[string, string, string][]> {
|
||||
return r("getFilesToEmbed", { providerId });
|
||||
}
|
||||
|
||||
sendEmbeddingForChunk(chunk: Chunk, embedding: number[], tags: string[]) {
|
||||
return r("sendChunkForFile", { chunk, embedding, tags });
|
||||
}
|
||||
|
||||
async getBranch(dir: string): Promise<string> {
|
||||
return r("getBranch", { dir });
|
||||
}
|
||||
|
||||
retrieveChunks(
|
||||
text: string,
|
||||
n: number,
|
||||
directory: string | undefined
|
||||
): Promise<Chunk[]> {
|
||||
return r("retrieveChunks", { text, n, directory });
|
||||
}
|
||||
}
|
||||
|
|
@ -1,142 +0,0 @@
|
|||
// import "vscode-webview";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { ChatMessage, LLMFullCompletionOptions, LLMReturnValue } from "..";
|
||||
interface vscode {
|
||||
postMessage(message: any): vscode;
|
||||
}
|
||||
|
||||
declare const vscode: any;
|
||||
|
||||
function _postToIde(type: string, data: any) {
|
||||
if (typeof vscode === "undefined") {
|
||||
if (localStorage.getItem("ide") === "jetbrains") {
|
||||
if (window.postIntellijMessage === undefined) {
|
||||
console.log(
|
||||
"Unable to send message: postIntellijMessage is undefined. ",
|
||||
type,
|
||||
data
|
||||
);
|
||||
throw new Error("postIntellijMessage is undefined");
|
||||
}
|
||||
window.postIntellijMessage?.(type, data);
|
||||
return;
|
||||
} else {
|
||||
console.log("Unable to send message: vscode is undefined. ", type, data);
|
||||
return;
|
||||
}
|
||||
}
|
||||
vscode.postMessage({
|
||||
type,
|
||||
...data,
|
||||
});
|
||||
}
|
||||
|
||||
export function postToIde(type: string, data: any, attempt: number = 0) {
|
||||
try {
|
||||
_postToIde(type, data);
|
||||
} catch (error) {
|
||||
if (attempt < 5) {
|
||||
console.log(`Attempt ${attempt} failed. Retrying...`);
|
||||
setTimeout(
|
||||
() => postToIde(type, data, attempt + 1),
|
||||
Math.pow(2, attempt) * 1000
|
||||
);
|
||||
} else {
|
||||
console.error("Max attempts reached. Message could not be sent.", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function ideRequest(type: string, message: any): Promise<any> {
|
||||
// message, messageId, and type are passed back and forth
|
||||
const messageId = uuidv4();
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const handler = (event: any) => {
|
||||
if (event.data.messageId === messageId) {
|
||||
window.removeEventListener("message", handler);
|
||||
resolve(event.data.message);
|
||||
}
|
||||
};
|
||||
window.addEventListener("message", handler);
|
||||
|
||||
postToIde(type, { message, messageId });
|
||||
});
|
||||
}
|
||||
|
||||
export async function* ideStreamRequest(
|
||||
type: string,
|
||||
message: any,
|
||||
cancelToken?: AbortSignal
|
||||
): AsyncGenerator<any, any> {
|
||||
const messageId = uuidv4();
|
||||
|
||||
postToIde(type, { message, messageId });
|
||||
|
||||
let buffer = "";
|
||||
let index = 0;
|
||||
let done = false;
|
||||
let returnVal = undefined;
|
||||
|
||||
const handler = (event: any) => {
|
||||
if (event.data.messageId === messageId) {
|
||||
if (event.data.message.done) {
|
||||
window.removeEventListener("message", handler);
|
||||
done = true;
|
||||
returnVal = event.data.message.data;
|
||||
} else {
|
||||
buffer += event.data.message.content || "";
|
||||
}
|
||||
}
|
||||
};
|
||||
window.addEventListener("message", handler);
|
||||
|
||||
cancelToken?.addEventListener("abort", () => {
|
||||
postToIde("abort", { messageId });
|
||||
});
|
||||
|
||||
while (!done) {
|
||||
if (buffer.length > index) {
|
||||
const chunk = buffer.slice(index);
|
||||
index = buffer.length;
|
||||
yield chunk;
|
||||
} else {
|
||||
yield undefined;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
}
|
||||
|
||||
if (buffer.length > index) {
|
||||
const chunk = buffer.slice(index);
|
||||
index = buffer.length;
|
||||
yield chunk;
|
||||
}
|
||||
|
||||
return returnVal;
|
||||
}
|
||||
|
||||
export async function* llmStreamChat(
|
||||
modelTitle: string,
|
||||
cancelToken: AbortSignal | undefined,
|
||||
messages: ChatMessage[],
|
||||
options: LLMFullCompletionOptions = {}
|
||||
): AsyncGenerator<ChatMessage, LLMReturnValue> {
|
||||
const gen = ideStreamRequest(
|
||||
"llmStreamChat",
|
||||
{
|
||||
messages,
|
||||
title: modelTitle,
|
||||
completionOptions: options,
|
||||
},
|
||||
cancelToken
|
||||
);
|
||||
|
||||
let next = await gen.next();
|
||||
while (!next.done) {
|
||||
if (next.value) {
|
||||
yield { role: "user", content: next.value };
|
||||
}
|
||||
next = await gen.next();
|
||||
}
|
||||
return { prompt: next.value?.prompt, completion: next.value?.completion };
|
||||
}
|
||||
63
core/index.d.ts
vendored
63
core/index.d.ts
vendored
|
|
@ -13,7 +13,11 @@ declare global {
|
|||
};
|
||||
colorThemeName?: string;
|
||||
workspacePaths?: string[];
|
||||
postIntellijMessage?: (type: string, data: any) => void;
|
||||
postIntellijMessage?: (
|
||||
messageType: string,
|
||||
data: any,
|
||||
messageIde: string
|
||||
) => void;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -162,6 +166,11 @@ export interface RangeInFile {
|
|||
range: Range;
|
||||
}
|
||||
|
||||
export interface FileWithContents {
|
||||
filepath: string;
|
||||
contents: string;
|
||||
}
|
||||
|
||||
export interface Range {
|
||||
start: Position;
|
||||
end: Position;
|
||||
|
|
@ -311,9 +320,19 @@ export class Problem {
|
|||
message: string;
|
||||
}
|
||||
|
||||
export type IdeType = "vscode" | "jetbrains";
|
||||
export interface IdeInfo {
|
||||
ideType: IdeType;
|
||||
name: string;
|
||||
version: string;
|
||||
remoteName: string;
|
||||
}
|
||||
|
||||
export interface IDE {
|
||||
getSerializedConfig(): Promise<BrowserSerializedContinueConfig>;
|
||||
getIdeInfo(): Promise<IdeInfo>;
|
||||
getDiff(): Promise<string>;
|
||||
isTelemetryEnabled(): Promise<boolean>;
|
||||
getUniqueId(): Promise<string>;
|
||||
getTerminalContents(): Promise<string>;
|
||||
getDebugLocals(threadIndex: number): Promise<string>;
|
||||
getTopLevelCallStackSources(
|
||||
|
|
@ -324,6 +343,7 @@ export interface IDE {
|
|||
listWorkspaceContents(directory?: string): Promise<string[]>;
|
||||
listFolders(): Promise<string[]>;
|
||||
getWorkspaceDirs(): Promise<string[]>;
|
||||
getWorkspaceConfigs(): Promise<ContinueRcJson[]>;
|
||||
writeFile(path: string, contents: string): Promise<void>;
|
||||
showVirtualFile(title: string, contents: string): Promise<void>;
|
||||
getContinueDir(): Promise<string>;
|
||||
|
|
@ -331,6 +351,7 @@ export interface IDE {
|
|||
runCommand(command: string): Promise<void>;
|
||||
saveFile(filepath: string): Promise<void>;
|
||||
readFile(filepath: string): Promise<string>;
|
||||
readRangeInFile(filepath: string, range: Range): Promise<string>;
|
||||
showLines(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
|
|
@ -341,34 +362,13 @@ export interface IDE {
|
|||
newContents: string,
|
||||
stepIndex: number
|
||||
): Promise<void>;
|
||||
verticalDiffUpdate(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
diffLine: DiffLine
|
||||
): Promise<void>;
|
||||
getOpenFiles(): Promise<string[]>;
|
||||
getPinnedFiles(): Promise<string[]>;
|
||||
getSearchResults(query: string): Promise<string>;
|
||||
subprocess(command: string): Promise<[string, string]>;
|
||||
getProblems(filepath?: string | undefined): Promise<Problem[]>;
|
||||
getBranch(dir: string): Promise<string>;
|
||||
|
||||
// Embeddings
|
||||
/**
|
||||
* Returns list of [tag, filepath, hash of contents] that need to be embedded
|
||||
*/
|
||||
getFilesToEmbed(providerId: string): Promise<[string, string, string][]>;
|
||||
sendEmbeddingForChunk(
|
||||
chunk: Chunk,
|
||||
embedding: number[],
|
||||
tags: string[]
|
||||
): void;
|
||||
retrieveChunks(
|
||||
text: string,
|
||||
n: number,
|
||||
directory: string | undefined
|
||||
): Promise<Chunk[]>;
|
||||
getStats(directory: string): Promise<{ [path: string]: number }>;
|
||||
}
|
||||
|
||||
// Slash Commands
|
||||
|
|
@ -381,6 +381,8 @@ export interface ContinueSDK {
|
|||
input: string;
|
||||
params?: { [key: string]: any } | undefined;
|
||||
contextItems: ContextItemWithId[];
|
||||
selectedCode: RangeInFile[];
|
||||
config: ContinueConfig;
|
||||
}
|
||||
|
||||
export interface SlashCommand {
|
||||
|
|
@ -422,7 +424,9 @@ type ContextProviderName =
|
|||
| "codebase"
|
||||
| "problems"
|
||||
| "folder"
|
||||
| "jira";
|
||||
| "jira"
|
||||
| "postgres"
|
||||
| "database";
|
||||
|
||||
type TemplateType =
|
||||
| "llama2"
|
||||
|
|
@ -588,10 +592,17 @@ export interface TabAutocompleteOptions {
|
|||
maxSuffixPercentage: number;
|
||||
prefixPercentage: number;
|
||||
template?: string;
|
||||
disableMultiLineCompletions?: boolean;
|
||||
multilineCompletions: "always" | "never" | "auto";
|
||||
slidingWindowPrefixPercentage: number;
|
||||
slidingWindowSize: number;
|
||||
maxSnippetPercentage: number;
|
||||
recentlyEditedSimilarityThreshold: number;
|
||||
useCache: boolean;
|
||||
onlyMyCode: boolean;
|
||||
}
|
||||
|
||||
export interface SerializedContinueConfig {
|
||||
env?: string[];
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ModelDescription[];
|
||||
systemMessage?: string;
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ export function* basicChunker(
|
|||
let currLine = 0;
|
||||
|
||||
for (const line of contents.split("\n")) {
|
||||
const lineTokens = countTokens(line, "gpt-4");
|
||||
const lineTokens = countTokens(line);
|
||||
if (chunkTokens + lineTokens > maxChunkSize - 5) {
|
||||
yield { content: chunkContent, startLine, endLine: currLine - 1 };
|
||||
chunkContent = "";
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ async function* chunkDocumentWithoutId(
|
|||
}
|
||||
return;
|
||||
} catch (e) {
|
||||
console.error(`Failed to parse ${filepath}: `, e);
|
||||
// console.error(`Failed to parse ${filepath}: `, e);
|
||||
// falls back to basicChunker
|
||||
}
|
||||
}
|
||||
|
|
@ -43,11 +43,11 @@ export async function* chunkDocument(
|
|||
contents,
|
||||
maxChunkSize
|
||||
)) {
|
||||
if (countTokens(chunkWithoutId.content, "gpt-4") > MAX_CHUNK_SIZE) {
|
||||
if (countTokens(chunkWithoutId.content) > MAX_CHUNK_SIZE) {
|
||||
console.warn(
|
||||
`Chunk with more than ${maxChunkSize} tokens constructed: `,
|
||||
filepath,
|
||||
countTokens(chunkWithoutId.content, "gpt-4")
|
||||
countTokens(chunkWithoutId.content)
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -59,10 +59,7 @@ function collapseChildren(
|
|||
}
|
||||
code = code.slice(node.startIndex);
|
||||
let removedChild = false;
|
||||
while (
|
||||
countTokens(code, "gpt-4") > maxChunkSize &&
|
||||
collapsedChildren.length > 0
|
||||
) {
|
||||
while (countTokens(code) > maxChunkSize && collapsedChildren.length > 0) {
|
||||
removedChild = true;
|
||||
// Remove children starting at the end - TODO: Add multiple chunks so no children are missing
|
||||
const childCode = collapsedChildren.pop()!;
|
||||
|
|
@ -169,7 +166,7 @@ function* getSmartCollapsedChunks(
|
|||
// Keep entire text if not over size
|
||||
if (
|
||||
(root || node.type in collapsedNodeConstructors) &&
|
||||
countTokens(node.text, "gpt-4") < maxChunkSize
|
||||
countTokens(node.text) < maxChunkSize
|
||||
) {
|
||||
yield {
|
||||
content: node.text,
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ export async function* markdownChunker(
|
|||
maxChunkSize: number,
|
||||
hLevel: number
|
||||
): AsyncGenerator<ChunkWithoutID> {
|
||||
if (countTokens(content, "gpt-4") <= maxChunkSize) {
|
||||
if (countTokens(content) <= maxChunkSize) {
|
||||
const header = findHeader(content.split("\n"));
|
||||
yield {
|
||||
content,
|
||||
|
|
@ -122,8 +122,7 @@ export async function* markdownChunker(
|
|||
for (const section of sections) {
|
||||
for await (const chunk of markdownChunker(
|
||||
section.content,
|
||||
maxChunkSize -
|
||||
(section.header ? countTokens(section.header, "gpt-4") : 0),
|
||||
maxChunkSize - (section.header ? countTokens(section.header) : 0),
|
||||
hLevel + 1
|
||||
)) {
|
||||
yield {
|
||||
|
|
|
|||
|
|
@ -26,10 +26,10 @@ class OllamaEmbeddingsProvider extends BaseEmbeddingsProvider {
|
|||
return "ollama::" + this.options.model;
|
||||
}
|
||||
|
||||
embed(chunks: string[]) {
|
||||
async embed(chunks: string[]) {
|
||||
const results: any = [];
|
||||
for (const chunk of chunks) {
|
||||
results.push(embedOne(chunk, this.options));
|
||||
results.push(await embedOne(chunk, this.options));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,13 +4,14 @@ import {
|
|||
pipeline,
|
||||
} from "../../vendor/node_modules/@xenova/transformers";
|
||||
|
||||
import path from "path";
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider";
|
||||
|
||||
env.allowLocalModels = true;
|
||||
env.allowRemoteModels = false;
|
||||
if (typeof window === "undefined") {
|
||||
// The embeddings provider should just never be called in the browser
|
||||
env.localModelPath = `${__dirname}/../models`;
|
||||
env.localModelPath = path.join(__dirname, "..", "models");
|
||||
}
|
||||
|
||||
class EmbeddingsPipeline {
|
||||
|
|
|
|||
59
core/indexing/embeddings/TransformersJsWorkerThread.js
Normal file
59
core/indexing/embeddings/TransformersJsWorkerThread.js
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import path from "path";
|
||||
import {
|
||||
env,
|
||||
pipeline,
|
||||
} from "../../vendor/node_modules/@xenova/transformers/types/transformers";
|
||||
import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider";
|
||||
const { parentPort } = require("worker_threads");
|
||||
|
||||
env.allowLocalModels = true;
|
||||
env.allowRemoteModels = false;
|
||||
if (typeof window === "undefined") {
|
||||
// The embeddings provider should just never be called in the browser
|
||||
env.localModelPath = path.join(__dirname, "..", "models");
|
||||
}
|
||||
|
||||
class EmbeddingsPipeline {
|
||||
static task = "feature-extraction";
|
||||
static model = TransformersJsEmbeddingsProvider.ModelName;
|
||||
static instance = null;
|
||||
|
||||
static async getInstance() {
|
||||
if (this.instance === null) {
|
||||
this.instance = await pipeline(this.task, this.model);
|
||||
}
|
||||
|
||||
return this.instance;
|
||||
}
|
||||
}
|
||||
|
||||
parentPort.on("message", async (chunks) => {
|
||||
try {
|
||||
const extractor = await EmbeddingsPipeline.getInstance();
|
||||
|
||||
if (!extractor) {
|
||||
throw new Error("TransformerJS embeddings pipeline is not initialized");
|
||||
}
|
||||
|
||||
let outputs = [];
|
||||
for (
|
||||
let i = 0;
|
||||
i < chunks.length;
|
||||
i += TransformersJsEmbeddingsProvider.MaxGroupSize
|
||||
) {
|
||||
let chunkGroup = chunks.slice(
|
||||
i,
|
||||
i + TransformersJsEmbeddingsProvider.MaxGroupSize
|
||||
);
|
||||
let output = await extractor(chunkGroup, {
|
||||
pooling: "mean",
|
||||
normalize: true,
|
||||
});
|
||||
outputs.push(...output.tolist());
|
||||
}
|
||||
|
||||
parentPort.postMessage(outputs);
|
||||
} catch (error) {
|
||||
parentPort.postMessage({ error: error.message });
|
||||
}
|
||||
});
|
||||
120
core/indexing/indexCodebase.ts
Normal file
120
core/indexing/indexCodebase.ts
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
import { IDE, IndexingProgressUpdate } from "..";
|
||||
import { ConfigHandler } from "../config/handler";
|
||||
import { FullTextSearchCodebaseIndex } from "./FullTextSearch";
|
||||
import { LanceDbIndex } from "./LanceDbIndex";
|
||||
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex";
|
||||
import { getComputeDeleteAddRemove } from "./refreshIndex";
|
||||
import { CodebaseIndex, IndexTag } from "./types";
|
||||
|
||||
export class PauseToken {
|
||||
constructor(private _paused: boolean) {}
|
||||
|
||||
set paused(value: boolean) {
|
||||
this._paused = value;
|
||||
}
|
||||
|
||||
get paused(): boolean {
|
||||
return this._paused;
|
||||
}
|
||||
}
|
||||
|
||||
export class CodebaseIndexer {
|
||||
configHandler: ConfigHandler;
|
||||
ide: IDE;
|
||||
pauseToken: PauseToken;
|
||||
|
||||
constructor(configHandler: ConfigHandler, ide: IDE, pauseToken: PauseToken) {
|
||||
this.configHandler = configHandler;
|
||||
this.ide = ide;
|
||||
this.pauseToken = pauseToken;
|
||||
}
|
||||
|
||||
private async getIndexesToBuild(): Promise<CodebaseIndex[]> {
|
||||
const config = await this.configHandler.loadConfig();
|
||||
|
||||
const indexes = [
|
||||
new ChunkCodebaseIndex(this.ide.readFile.bind(this.ide)), // Chunking must come first
|
||||
new LanceDbIndex(
|
||||
config.embeddingsProvider,
|
||||
this.ide.readFile.bind(this.ide)
|
||||
),
|
||||
new FullTextSearchCodebaseIndex(),
|
||||
];
|
||||
|
||||
return indexes;
|
||||
}
|
||||
|
||||
async *refresh(
|
||||
workspaceDirs: string[]
|
||||
): AsyncGenerator<IndexingProgressUpdate> {
|
||||
const config = await this.configHandler.loadConfig();
|
||||
if (config.disableIndexing) {
|
||||
return;
|
||||
}
|
||||
|
||||
const indexesToBuild = await this.getIndexesToBuild();
|
||||
|
||||
let completedDirs = 0;
|
||||
|
||||
yield {
|
||||
progress:
|
||||
0,
|
||||
desc: "Starting indexing...",
|
||||
};
|
||||
|
||||
for (let directory of workspaceDirs) {
|
||||
const stats = await this.ide.getStats(directory);
|
||||
const branch = await this.ide.getBranch(directory);
|
||||
let completedIndexes = 0;
|
||||
|
||||
try {
|
||||
for (let codebaseIndex of indexesToBuild) {
|
||||
const tag: IndexTag = {
|
||||
directory,
|
||||
branch,
|
||||
artifactId: codebaseIndex.artifactId,
|
||||
};
|
||||
const [results, markComplete] = await getComputeDeleteAddRemove(
|
||||
tag,
|
||||
{ ...stats },
|
||||
(filepath) => this.ide.readFile(filepath)
|
||||
);
|
||||
|
||||
for await (let { progress, desc } of codebaseIndex.update(
|
||||
tag,
|
||||
results,
|
||||
markComplete
|
||||
)) {
|
||||
// Handle pausing in this loop because it's the only one really taking time
|
||||
while (this.pauseToken.paused) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
|
||||
yield {
|
||||
progress:
|
||||
(completedDirs +
|
||||
(completedIndexes + progress) / indexesToBuild.length) /
|
||||
workspaceDirs.length,
|
||||
desc,
|
||||
};
|
||||
}
|
||||
completedIndexes++;
|
||||
yield {
|
||||
progress:
|
||||
(completedDirs + completedIndexes / indexesToBuild.length) /
|
||||
workspaceDirs.length,
|
||||
desc: "Completed indexing " + codebaseIndex.artifactId,
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("Error refreshing index: ", e);
|
||||
}
|
||||
|
||||
completedDirs++;
|
||||
yield {
|
||||
progress: completedDirs / workspaceDirs.length,
|
||||
desc: "Indexing Complete",
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,16 +1,29 @@
|
|||
import { encodingForModel as _encodingForModel, Tiktoken } from "js-tiktoken";
|
||||
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
|
||||
// @ts-ignore
|
||||
import llamaTokenizer from "llama-tokenizer-js";
|
||||
import { ChatMessage, MessageContent, MessagePart } from "..";
|
||||
import { autodetectTemplateType } from "./autodetect";
|
||||
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants";
|
||||
|
||||
let encoding: Tiktoken | null = null;
|
||||
interface Encoding {
|
||||
encode: Tiktoken["encode"];
|
||||
decode: Tiktoken["decode"];
|
||||
}
|
||||
|
||||
function encodingForModel(modelName: string): Tiktoken {
|
||||
if (encoding) {
|
||||
return encoding;
|
||||
let gptEncoding: Encoding | null = null;
|
||||
|
||||
function encodingForModel(modelName: string): Encoding {
|
||||
const modelType = autodetectTemplateType(modelName);
|
||||
|
||||
if (!modelType || modelType === "none") {
|
||||
if (!gptEncoding) {
|
||||
gptEncoding = _encodingForModel("gpt-4");
|
||||
}
|
||||
|
||||
return gptEncoding;
|
||||
}
|
||||
|
||||
encoding = _encodingForModel("gpt-4");
|
||||
return encoding;
|
||||
return llamaTokenizer;
|
||||
}
|
||||
|
||||
function countImageTokens(content: MessagePart): number {
|
||||
|
|
@ -21,7 +34,11 @@ function countImageTokens(content: MessagePart): number {
|
|||
}
|
||||
}
|
||||
|
||||
function countTokens(content: MessageContent, modelName: string): number {
|
||||
function countTokens(
|
||||
content: MessageContent,
|
||||
// defaults to llama2 because the tokenizer tends to produce more tokens
|
||||
modelName: string = "llama2"
|
||||
): number {
|
||||
const encoding = encodingForModel(modelName);
|
||||
if (Array.isArray(content)) {
|
||||
return content.reduce((acc, part) => {
|
||||
|
|
@ -72,21 +89,29 @@ function countChatMessageTokens(
|
|||
return countTokens(chatMessage.content, modelName) + TOKENS_PER_MESSAGE;
|
||||
}
|
||||
|
||||
function pruneLinesFromTop(prompt: string, maxTokens: number): string {
|
||||
let totalTokens = countTokens(prompt, "gpt-4");
|
||||
function pruneLinesFromTop(
|
||||
prompt: string,
|
||||
maxTokens: number,
|
||||
modelName: string
|
||||
): string {
|
||||
let totalTokens = countTokens(prompt, modelName);
|
||||
const lines = prompt.split("\n");
|
||||
while (totalTokens > maxTokens && lines.length > 0) {
|
||||
totalTokens -= countTokens(lines.shift()!, "gpt-4");
|
||||
totalTokens -= countTokens(lines.shift()!, modelName);
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function pruneLinesFromBottom(prompt: string, maxTokens: number): string {
|
||||
let totalTokens = countTokens(prompt, "gpt-4");
|
||||
function pruneLinesFromBottom(
|
||||
prompt: string,
|
||||
maxTokens: number,
|
||||
modelName: string
|
||||
): string {
|
||||
let totalTokens = countTokens(prompt, modelName);
|
||||
const lines = prompt.split("\n");
|
||||
while (totalTokens > maxTokens && lines.length > 0) {
|
||||
totalTokens -= countTokens(lines.pop()!, "gpt-4");
|
||||
totalTokens -= countTokens(lines.pop()!, modelName);
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { ChatMessage, CompletionOptions, ModelProvider } from "../..";
|
|||
import { streamResponse } from "../stream";
|
||||
|
||||
// const SERVER_URL = "http://localhost:3000";
|
||||
const SERVER_URL = "https://node-proxy-server-blue-l6vsfbzhba-uw.a.run.app";
|
||||
const SERVER_URL = "https://node-proxy-server-green-l6vsfbzhba-uw.a.run.app";
|
||||
|
||||
class FreeTrial extends BaseLLM {
|
||||
static providerName: ModelProvider = "free-trial";
|
||||
|
|
|
|||
|
|
@ -25,40 +25,44 @@ class Ollama extends BaseLLM {
|
|||
method: "POST",
|
||||
headers: {},
|
||||
body: JSON.stringify({ name: this._getModel() }),
|
||||
}).then(async (response) => {
|
||||
if (response.status !== 200) {
|
||||
console.warn(
|
||||
"Error calling Ollama /api/show endpoint: ",
|
||||
await response.text()
|
||||
);
|
||||
return;
|
||||
}
|
||||
const body = await response.json();
|
||||
if (body.parameters) {
|
||||
const params = [];
|
||||
for (let line of body.parameters.split("\n")) {
|
||||
let parts = line.split(" ");
|
||||
if (parts.length < 2) {
|
||||
continue;
|
||||
}
|
||||
let key = parts[0];
|
||||
let value = parts[parts.length - 1];
|
||||
switch (key) {
|
||||
case "num_ctx":
|
||||
this.contextLength = parseInt(value);
|
||||
break;
|
||||
case "stop":
|
||||
if (!this.completionOptions.stop) {
|
||||
this.completionOptions.stop = [];
|
||||
}
|
||||
this.completionOptions.stop.push(value);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
})
|
||||
.then(async (response) => {
|
||||
if (response.status !== 200) {
|
||||
console.warn(
|
||||
"Error calling Ollama /api/show endpoint: ",
|
||||
await response.text()
|
||||
);
|
||||
return;
|
||||
}
|
||||
const body = await response.json();
|
||||
if (body.parameters) {
|
||||
const params = [];
|
||||
for (let line of body.parameters.split("\n")) {
|
||||
let parts = line.split(" ");
|
||||
if (parts.length < 2) {
|
||||
continue;
|
||||
}
|
||||
let key = parts[0];
|
||||
let value = parts[parts.length - 1];
|
||||
switch (key) {
|
||||
case "num_ctx":
|
||||
this.contextLength = parseInt(value);
|
||||
break;
|
||||
case "stop":
|
||||
if (!this.completionOptions.stop) {
|
||||
this.completionOptions.stop = [];
|
||||
}
|
||||
this.completionOptions.stop.push(value);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
})
|
||||
.catch((e) => {
|
||||
console.warn(`Error calling Ollama /api/show endpoint: ${e}`);
|
||||
});
|
||||
}
|
||||
|
||||
private _getModel() {
|
||||
|
|
|
|||
|
|
@ -71,7 +71,9 @@ class OpenAI extends BaseLLM {
|
|||
top_p: options.topP,
|
||||
frequency_penalty: options.frequencyPenalty,
|
||||
presence_penalty: options.presencePenalty,
|
||||
stop: options.stop?.slice(0, 4),
|
||||
stop: this.apiBase?.includes(":1337")
|
||||
? options.stop?.slice(0, 4)
|
||||
: options.stop,
|
||||
};
|
||||
|
||||
return finalOptions;
|
||||
|
|
@ -79,12 +81,12 @@ class OpenAI extends BaseLLM {
|
|||
|
||||
protected async _complete(
|
||||
prompt: string,
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): Promise<string> {
|
||||
let completion = "";
|
||||
for await (const chunk of this._streamChat(
|
||||
[{ role: "user", content: prompt }],
|
||||
options
|
||||
options,
|
||||
)) {
|
||||
completion += chunk.content;
|
||||
}
|
||||
|
|
@ -93,7 +95,7 @@ class OpenAI extends BaseLLM {
|
|||
}
|
||||
|
||||
private _getEndpoint(
|
||||
endpoint: "/chat/completions" | "/completions" | "/models"
|
||||
endpoint: "/chat/completions" | "/completions" | "/models",
|
||||
) {
|
||||
if (this.apiType === "azure") {
|
||||
return `${this.apiBase}/openai/deployments/${this.engine}${endpoint}?api-version=${this.apiVersion}`;
|
||||
|
|
@ -101,7 +103,7 @@ class OpenAI extends BaseLLM {
|
|||
let url = this.apiBase;
|
||||
if (!url) {
|
||||
throw new Error(
|
||||
"No API base URL provided. Please set the 'apiBase' option in config.json"
|
||||
"No API base URL provided. Please set the 'apiBase' option in config.json",
|
||||
);
|
||||
}
|
||||
if (url.endsWith("/")) {
|
||||
|
|
@ -114,11 +116,11 @@ class OpenAI extends BaseLLM {
|
|||
|
||||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
for await (const chunk of this._streamChat(
|
||||
[{ role: "user", content: prompt }],
|
||||
options
|
||||
options,
|
||||
)) {
|
||||
yield stripImages(chunk.content);
|
||||
}
|
||||
|
|
@ -126,7 +128,7 @@ class OpenAI extends BaseLLM {
|
|||
|
||||
protected async *_legacystreamComplete(
|
||||
prompt: string,
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
const args: any = this._convertArgs(options, []);
|
||||
args.prompt = prompt;
|
||||
|
|
@ -154,7 +156,7 @@ class OpenAI extends BaseLLM {
|
|||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
if (
|
||||
!CHAT_ONLY_MODELS.includes(options.model) &&
|
||||
|
|
@ -163,7 +165,7 @@ class OpenAI extends BaseLLM {
|
|||
) {
|
||||
for await (const content of this._legacystreamComplete(
|
||||
stripImages(messages[messages.length - 1]?.content || ""),
|
||||
options
|
||||
options,
|
||||
)) {
|
||||
yield {
|
||||
role: "assistant",
|
||||
|
|
|
|||
1760
core/package-lock.json
generated
1760
core/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -8,6 +8,7 @@
|
|||
"author": "Nate Sesti and Ty Dunn",
|
||||
"license": "Apache-2.0",
|
||||
"devDependencies": {
|
||||
"@types/follow-redirects": "^1.14.4",
|
||||
"@types/handlebars": "^4.1.0",
|
||||
"@types/jest": "^29.5.11",
|
||||
"@types/jquery": "^3.5.29",
|
||||
|
|
@ -24,15 +25,21 @@
|
|||
"adf-to-md": "^1.1.0",
|
||||
"axios": "^1.6.7",
|
||||
"cheerio": "^1.0.0-rc.12",
|
||||
"commander": "^12.0.0",
|
||||
"dbinfoz": "^0.1.4",
|
||||
"dotenv": "^16.3.1",
|
||||
"fastest-levenshtein": "^1.0.16",
|
||||
"follow-redirects": "^1.15.5",
|
||||
"handlebars": "^4.7.8",
|
||||
"http-proxy-agent": "^7.0.1",
|
||||
"https-proxy-agent": "^7.0.3",
|
||||
"js-tiktoken": "^1.0.8",
|
||||
"llm-code-highlighter": "^0.0.13",
|
||||
"llama-tokenizer-js": "^1.1.3",
|
||||
"node-fetch": "^3.3.2",
|
||||
"node-html-markdown": "^1.3.0",
|
||||
"ollama": "^0.4.6",
|
||||
"openai": "^4.20.1",
|
||||
"pg": "^8.11.3",
|
||||
"posthog-node": "^3.6.2",
|
||||
"replicate": "^0.26.0",
|
||||
"socket.io-client": "^4.7.3",
|
||||
|
|
@ -41,7 +48,7 @@
|
|||
"tree-sitter-wasms": "^0.1.6",
|
||||
"uuid": "^9.0.1",
|
||||
"vectordb": "^0.4.3",
|
||||
"web-tree-sitter": "^0.20.8"
|
||||
"web-tree-sitter": "^0.21.0"
|
||||
},
|
||||
"puppeteer": {
|
||||
"chromium_revision": "119.0.6045.105"
|
||||
|
|
|
|||
98
core/protocol.ts
Normal file
98
core/protocol.ts
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
import {
|
||||
BrowserSerializedContinueConfig,
|
||||
ChatMessage,
|
||||
ContextItemWithId,
|
||||
ContextSubmenuItem,
|
||||
LLMFullCompletionOptions,
|
||||
MessageContent,
|
||||
PersistedSessionInfo,
|
||||
RangeInFile,
|
||||
SerializedContinueConfig,
|
||||
SessionInfo,
|
||||
} from ".";
|
||||
|
||||
export type ProtocolGeneratorType<T> = AsyncGenerator<{
|
||||
done?: boolean;
|
||||
content: T;
|
||||
}>;
|
||||
|
||||
export type Protocol = {
|
||||
// New
|
||||
"update/modelChange": [string, void];
|
||||
// Special
|
||||
ping: [string, string];
|
||||
abort: [undefined, void];
|
||||
|
||||
// History
|
||||
"history/list": [undefined, SessionInfo[]];
|
||||
"history/delete": [{ id: string }, void];
|
||||
"history/load": [{ id: string }, PersistedSessionInfo];
|
||||
"history/save": [PersistedSessionInfo, void];
|
||||
"devdata/log": [{ tableName: string; data: any }, void];
|
||||
"config/addOpenAiKey": [string, void];
|
||||
"config/addModel": [
|
||||
{ model: SerializedContinueConfig["models"][number] },
|
||||
void,
|
||||
];
|
||||
"config/getBrowserSerialized": [
|
||||
undefined,
|
||||
Promise<BrowserSerializedContinueConfig>,
|
||||
];
|
||||
"config/deleteModel": [{ title: string }, void];
|
||||
"config/reload": [undefined, Promise<BrowserSerializedContinueConfig>];
|
||||
"context/getContextItems": [
|
||||
{
|
||||
name: string;
|
||||
query: string;
|
||||
fullInput: string;
|
||||
selectedCode: RangeInFile[];
|
||||
},
|
||||
Promise<ContextItemWithId[]>,
|
||||
];
|
||||
"context/loadSubmenuItems": [
|
||||
{ title: string },
|
||||
Promise<ContextSubmenuItem[]>,
|
||||
];
|
||||
"context/addDocs": [{ title: string; url: string }, void];
|
||||
"autocomplete/complete": [
|
||||
{ filepath: string; line: number; column: number },
|
||||
string[],
|
||||
];
|
||||
"command/run": [
|
||||
{
|
||||
input: string;
|
||||
history: ChatMessage[];
|
||||
modelTitle: string;
|
||||
slashCommandName: string;
|
||||
contextItems: ContextItemWithId[];
|
||||
params: any;
|
||||
historyIndex: number;
|
||||
selectedCode: RangeInFile[];
|
||||
},
|
||||
ProtocolGeneratorType<string>,
|
||||
];
|
||||
"llm/complete": [
|
||||
{
|
||||
prompt: string;
|
||||
completionOptions: LLMFullCompletionOptions;
|
||||
title: string;
|
||||
},
|
||||
string,
|
||||
];
|
||||
"llm/streamComplete": [
|
||||
{
|
||||
prompt: string;
|
||||
completionOptions: LLMFullCompletionOptions;
|
||||
title: string;
|
||||
},
|
||||
ProtocolGeneratorType<string>,
|
||||
];
|
||||
"llm/streamChat": [
|
||||
{
|
||||
messages: ChatMessage[];
|
||||
completionOptions: LLMFullCompletionOptions;
|
||||
title: string;
|
||||
},
|
||||
ProtocolGeneratorType<MessageContent>,
|
||||
];
|
||||
};
|
||||
|
|
@ -1,6 +1,18 @@
|
|||
import { streamDiff } from "../diff/streamDiff";
|
||||
|
||||
const oldCode = [
|
||||
`A
|
||||
B`,
|
||||
`A
|
||||
B
|
||||
C`,
|
||||
`A
|
||||
B
|
||||
C
|
||||
A
|
||||
B
|
||||
B
|
||||
A`,
|
||||
`function mergeSortAlgorithm() {
|
||||
// TODO: implement
|
||||
}`,
|
||||
|
|
@ -10,6 +22,19 @@ const oldCode = [
|
|||
];
|
||||
|
||||
const newCode = [
|
||||
`C
|
||||
D`,
|
||||
`D
|
||||
E
|
||||
C
|
||||
F
|
||||
C`,
|
||||
`C
|
||||
B
|
||||
A
|
||||
B
|
||||
A
|
||||
C`,
|
||||
`function mergeSortAlgorithm(arr: number[]): number[] {
|
||||
if (arr.length <= 1) {
|
||||
return arr;
|
||||
|
|
@ -113,7 +138,11 @@ describe("streamDiff", () => {
|
|||
// Check that there are no red lines immediately following green (they should always be above)
|
||||
for (let i = 1; i < diff.length; i++) {
|
||||
if (diff[i].type === "old" && diff[i - 1].type === "new") {
|
||||
throw new Error("Found red immediately after green line");
|
||||
throw new Error(
|
||||
`Found red '${diff[i].line}' immediately after green line '${
|
||||
diff[i - 1].line
|
||||
}`
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -2,10 +2,10 @@ import * as dotenv from "dotenv";
|
|||
import { ContinueSDK } from "..";
|
||||
import EditSlashCommand, { getPromptParts } from "../commands/slash/edit";
|
||||
import { contextItemToRangeInFileWithContents } from "../commands/util";
|
||||
import FileSystemIde from "../ide/filesystem";
|
||||
import FreeTrial from "../llm/llms/FreeTrial";
|
||||
import Ollama from "../llm/llms/Ollama";
|
||||
import { dedentAndGetCommonWhitespace } from "../util";
|
||||
import FileSystemIde from "../util/filesystem";
|
||||
|
||||
jest.setTimeout(100_000);
|
||||
|
||||
|
|
@ -62,6 +62,8 @@ describe("/edit slash command", () => {
|
|||
history: [],
|
||||
input: "implement this function",
|
||||
contextItems: [TEST_CONTEXT_ITEM],
|
||||
selectedCode: [],
|
||||
config: {} as any,
|
||||
};
|
||||
|
||||
let total = "";
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"compilerOptions": {
|
||||
"target": "ESNext",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["DOM", "DOM.Iterable", "ESNext"],
|
||||
"lib": ["DOM", "DOM.Iterable", "ESNext", "ES2021"],
|
||||
"allowJs": false,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": false,
|
||||
|
|
@ -18,5 +18,5 @@
|
|||
"noEmitOnError": false,
|
||||
"types": ["jest", "node"]
|
||||
},
|
||||
"include": ["./**/*.ts"]
|
||||
"include": ["./**/*.ts", "indexing/embeddings/TransformersJsWorkerThread.js"]
|
||||
}
|
||||
|
|
|
|||
8
core/util/devdata.ts
Normal file
8
core/util/devdata.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
import { writeFileSync } from "fs";
|
||||
import { getDevDataFilePath } from "./paths";
|
||||
|
||||
export function logDevData(tableName: string, data: any) {
|
||||
const filepath: string = getDevDataFilePath(tableName);
|
||||
const jsonLine = JSON.stringify(data);
|
||||
writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" });
|
||||
}
|
||||
|
|
@ -1,21 +1,30 @@
|
|||
import * as fs from "fs";
|
||||
import { DiffLine, IDE, Problem } from "..";
|
||||
import { BrowserSerializedContinueConfig } from "../config/load";
|
||||
import { Chunk } from "../index";
|
||||
import { getContinueGlobalPath } from "../util/paths";
|
||||
import { ContinueRcJson, IDE, IdeInfo, Problem, Range } from "..";
|
||||
import { getContinueGlobalPath } from "./paths";
|
||||
|
||||
class FileSystemIde implements IDE {
|
||||
getTopLevelCallStackSources(threadIndex: number, stackDepth: number): Promise<string[]> {
|
||||
throw new Error("Method not implemented.");
|
||||
getIdeInfo(): Promise<IdeInfo> {
|
||||
return Promise.resolve({
|
||||
ideType: "vscode",
|
||||
name: "na",
|
||||
version: "0.1",
|
||||
remoteName: "na",
|
||||
});
|
||||
}
|
||||
getAvailableThreads(): Promise<string[]> {
|
||||
throw new Error("Method not implemented.");
|
||||
readRangeInFile(filepath: string, range: Range): Promise<string> {
|
||||
return Promise.resolve("");
|
||||
}
|
||||
async getDebugLocals(threadIndex: number): Promise<string> {
|
||||
throw new Error("Method not implemented.");
|
||||
getStats(directory: string): Promise<{ [path: string]: number }> {
|
||||
return Promise.resolve({});
|
||||
}
|
||||
async getSerializedConfig(): Promise<BrowserSerializedContinueConfig> {
|
||||
throw new Error("Not implemented");
|
||||
isTelemetryEnabled(): Promise<boolean> {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
getUniqueId(): Promise<string> {
|
||||
return Promise.resolve("NOT_UNIQUE");
|
||||
}
|
||||
getWorkspaceConfigs(): Promise<ContinueRcJson[]> {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
getDiff(): Promise<string> {
|
||||
|
|
@ -24,6 +33,15 @@ class FileSystemIde implements IDE {
|
|||
getTerminalContents(): Promise<string> {
|
||||
return Promise.resolve("");
|
||||
}
|
||||
async getDebugLocals(threadIndex: number): Promise<string> {
|
||||
return Promise.resolve("");
|
||||
}
|
||||
async getTopLevelCallStackSources(threadIndex: number, stackDepth: number): Promise<string[]> {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
async getAvailableThreads(): Promise<string[]> {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
showLines(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
|
|
@ -101,15 +119,6 @@ class FileSystemIde implements IDE {
|
|||
return Promise.resolve("");
|
||||
}
|
||||
|
||||
async verticalDiffUpdate(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
diffLine: DiffLine
|
||||
) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
getOpenFiles(): Promise<string[]> {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
|
@ -129,20 +138,6 @@ class FileSystemIde implements IDE {
|
|||
async subprocess(command: string): Promise<[string, string]> {
|
||||
return ["", ""];
|
||||
}
|
||||
|
||||
getFilesToEmbed(providerId: string): Promise<[string, string, string][]> {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
sendEmbeddingForChunk(chunk: Chunk, embedding: number[], tags: string[]) {}
|
||||
|
||||
retrieveChunks(
|
||||
text: string,
|
||||
n: number,
|
||||
directory: string | undefined
|
||||
): Promise<Chunk[]> {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
}
|
||||
|
||||
export default FileSystemIde;
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
import { PersistedSessionInfo, SessionInfo } from "core";
|
||||
import { getSessionFilePath, getSessionsListPath } from "core/util/paths";
|
||||
import * as fs from "fs";
|
||||
import { PersistedSessionInfo, SessionInfo } from "..";
|
||||
import { getSessionFilePath, getSessionsListPath } from "./paths";
|
||||
|
||||
class HistoryManager {
|
||||
list(): PersistedSessionInfo[] {
|
||||
list(): SessionInfo[] {
|
||||
const filepath = getSessionsListPath();
|
||||
if (!fs.existsSync(filepath)) {
|
||||
return [];
|
||||
|
|
@ -5,7 +5,8 @@ type JsonObject = { [key: string]: any };
|
|||
export function mergeJson(
|
||||
first: JsonObject,
|
||||
second: JsonObject,
|
||||
mergeBehavior?: ConfigMergeType
|
||||
mergeBehavior?: ConfigMergeType,
|
||||
mergeKeys?: {[key: string]: (a: any, b: any) => boolean}
|
||||
): any {
|
||||
first = { ...first };
|
||||
|
||||
|
|
@ -20,10 +21,21 @@ export function mergeJson(
|
|||
}
|
||||
|
||||
const firstValue = first[key];
|
||||
if (Array.isArray(secondValue)) {
|
||||
if (Array.isArray(secondValue) && Array.isArray(firstValue)) {
|
||||
// Array
|
||||
first[key] = [...firstValue, ...secondValue];
|
||||
} else if (typeof secondValue === "object") {
|
||||
if (mergeKeys?.[key]) {
|
||||
// Merge keys are used to determine whether an item form the second object should override one from the first
|
||||
let keptFromFirst: any[] = [];
|
||||
firstValue.forEach((item: any) => {
|
||||
if (!secondValue.some((item2: any) => mergeKeys[key](item, item2))) {
|
||||
keptFromFirst.push(item);
|
||||
}
|
||||
})
|
||||
first[key] = [...keptFromFirst, ...secondValue];
|
||||
} else {
|
||||
first[key] = [...firstValue, ...secondValue];
|
||||
}
|
||||
} else if (typeof secondValue === "object" && typeof firstValue === "object") {
|
||||
// Object
|
||||
first[key] = mergeJson(firstValue, secondValue, mergeBehavior);
|
||||
} else {
|
||||
|
|
|
|||
136
core/util/messageIde.ts
Normal file
136
core/util/messageIde.ts
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
import { ContinueRcJson, IDE, IdeInfo, Problem, Range } from "..";
|
||||
|
||||
export class MessageIde implements IDE {
|
||||
constructor(
|
||||
private readonly request: (messageType: string, data: any) => Promise<any>
|
||||
) {}
|
||||
getDebugLocals(threadIndex: number): Promise<string> {
|
||||
return this.request("getDebugLocals", { threadIndex });
|
||||
}
|
||||
getTopLevelCallStackSources(
|
||||
threadIndex: number,
|
||||
stackDepth: number
|
||||
): Promise<string[]> {
|
||||
return this.request("getTopLevelCallStackSources", {
|
||||
threadIndex,
|
||||
stackDepth,
|
||||
});
|
||||
}
|
||||
getAvailableThreads(): Promise<string[]> {
|
||||
return this.request("getTopLevelCallStackSources", undefined);
|
||||
}
|
||||
getIdeInfo(): Promise<IdeInfo> {
|
||||
return this.request("getIdeInfo", undefined);
|
||||
}
|
||||
|
||||
readRangeInFile(filepath: string, range: Range): Promise<string> {
|
||||
return this.request("readRangeInFile", { filepath, range });
|
||||
}
|
||||
getStats(directory: string): Promise<{ [path: string]: number }> {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
isTelemetryEnabled(): Promise<boolean> {
|
||||
return this.request("isTelemetryEnabled", undefined);
|
||||
}
|
||||
|
||||
getUniqueId(): Promise<string> {
|
||||
return this.request("getUniqueId", undefined);
|
||||
}
|
||||
|
||||
getWorkspaceConfigs(): Promise<ContinueRcJson[]> {
|
||||
return this.request("getWorkspaceConfigs", undefined);
|
||||
}
|
||||
|
||||
async getDiff() {
|
||||
return await this.request("getDiff", undefined);
|
||||
}
|
||||
|
||||
async getTerminalContents() {
|
||||
return await this.request("getTerminalContents", undefined);
|
||||
}
|
||||
|
||||
async listWorkspaceContents(directory?: string): Promise<string[]> {
|
||||
return await this.request("listWorkspaceContents", undefined);
|
||||
}
|
||||
|
||||
async getWorkspaceDirs(): Promise<string[]> {
|
||||
return await this.request("getWorkspaceDirs", undefined);
|
||||
}
|
||||
|
||||
async showLines(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number
|
||||
): Promise<void> {
|
||||
return await this.request("showLines", { filepath, startLine, endLine });
|
||||
}
|
||||
|
||||
async listFolders(): Promise<string[]> {
|
||||
return await this.request("listFolders", undefined);
|
||||
}
|
||||
|
||||
_continueDir: string | null = null;
|
||||
|
||||
async getContinueDir(): Promise<string> {
|
||||
if (this._continueDir) {
|
||||
return this._continueDir;
|
||||
}
|
||||
const dir = await this.request("getContinueDir", undefined);
|
||||
this._continueDir = dir;
|
||||
return dir;
|
||||
}
|
||||
|
||||
async writeFile(path: string, contents: string): Promise<void> {
|
||||
await this.request("writeFile", { path, contents });
|
||||
}
|
||||
|
||||
async showVirtualFile(title: string, contents: string): Promise<void> {
|
||||
await this.request("showVirtualFile", { name: title, content: contents });
|
||||
}
|
||||
|
||||
async openFile(path: string): Promise<void> {
|
||||
await this.request("openFile", { path });
|
||||
}
|
||||
|
||||
async runCommand(command: string): Promise<void> {
|
||||
await this.request("runCommand", { command });
|
||||
}
|
||||
|
||||
async saveFile(filepath: string): Promise<void> {
|
||||
await this.request("saveFile", { filepath });
|
||||
}
|
||||
async readFile(filepath: string): Promise<string> {
|
||||
return await this.request("readFile", { filepath });
|
||||
}
|
||||
async showDiff(
|
||||
filepath: string,
|
||||
newContents: string,
|
||||
stepIndex: number
|
||||
): Promise<void> {
|
||||
await this.request("showDiff", { filepath, newContents, stepIndex });
|
||||
}
|
||||
|
||||
getOpenFiles(): Promise<string[]> {
|
||||
return this.request("getOpenFiles", undefined);
|
||||
}
|
||||
|
||||
getPinnedFiles(): Promise<string[]> {
|
||||
return this.request("getPinnedFiles", undefined);
|
||||
}
|
||||
|
||||
getSearchResults(query: string): Promise<string> {
|
||||
return this.request("getSearchResults", { query });
|
||||
}
|
||||
|
||||
getProblems(filepath?: string | undefined): Promise<Problem[]> {
|
||||
return this.request("getProblems", { filepath });
|
||||
}
|
||||
|
||||
subprocess(command: string): Promise<[string, string]> {
|
||||
return this.request("subprocess", { command });
|
||||
}
|
||||
|
||||
async getBranch(dir: string): Promise<string> {
|
||||
return this.request("getBranch", { dir });
|
||||
}
|
||||
}
|
||||
5
core/util/messenger.ts
Normal file
5
core/util/messenger.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
export interface Message<T = any> {
|
||||
messageType: string;
|
||||
messageId: string;
|
||||
data: T;
|
||||
}
|
||||
|
|
@ -1,8 +1,9 @@
|
|||
import dotenv from "dotenv";
|
||||
import * as fs from "fs";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
import { SerializedContinueConfig } from "..";
|
||||
import defaultConfig from "../config/default";
|
||||
import { IdeType, SerializedContinueConfig } from "..";
|
||||
import { defaultConfig, defaultConfigJetBrains } from "../config/default";
|
||||
import Types from "../config/types";
|
||||
|
||||
export function getContinueGlobalPath(): string {
|
||||
|
|
@ -42,10 +43,14 @@ export function getSessionsListPath(): string {
|
|||
return filepath;
|
||||
}
|
||||
|
||||
export function getConfigJsonPath(): string {
|
||||
export function getConfigJsonPath(ideType: IdeType = "vscode"): string {
|
||||
const p = path.join(getContinueGlobalPath(), "config.json");
|
||||
if (!fs.existsSync(p)) {
|
||||
fs.writeFileSync(p, JSON.stringify(defaultConfig, null, 2));
|
||||
if (ideType === "jetbrains") {
|
||||
fs.writeFileSync(p, JSON.stringify(defaultConfigJetBrains, null, 2));
|
||||
} else {
|
||||
fs.writeFileSync(p, JSON.stringify(defaultConfig, null, 2));
|
||||
}
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
|
@ -86,13 +91,9 @@ export function getConfigTsPath(): string {
|
|||
return p;
|
||||
}
|
||||
|
||||
export function getConfigJsPath(node: boolean): string {
|
||||
export function getConfigJsPath(): string {
|
||||
// Do not create automatically
|
||||
return path.join(
|
||||
getContinueGlobalPath(),
|
||||
"out",
|
||||
`config${node ? ".node" : ""}.js`
|
||||
);
|
||||
return path.join(getContinueGlobalPath(), "out", "config.js");
|
||||
}
|
||||
|
||||
export function getTsConfigPath(): string {
|
||||
|
|
@ -210,3 +211,16 @@ export function getConfigJsonPathForRemote(remoteConfigServerUrl: URL): string {
|
|||
export function getConfigJsPathForRemote(remoteConfigServerUrl: URL): string {
|
||||
return path.join(getPathToRemoteConfig(remoteConfigServerUrl), "config.js");
|
||||
}
|
||||
|
||||
export function getContinueDotEnv(): { [key: string]: string } {
|
||||
const filepath = path.join(getContinueGlobalPath(), ".env");
|
||||
if (fs.existsSync(filepath)) {
|
||||
return dotenv.parse(fs.readFileSync(filepath));
|
||||
} else {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function getCoreLogsPath(): string {
|
||||
return path.join(getContinueGlobalPath(), "core.log");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,14 +19,18 @@ export class Telemetry {
|
|||
if (!allow) {
|
||||
Telemetry.client = undefined;
|
||||
} else {
|
||||
if (!Telemetry.client) {
|
||||
const { PostHog } = await import("posthog-node");
|
||||
Telemetry.client = new PostHog(
|
||||
"phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs",
|
||||
{
|
||||
host: "https://app.posthog.com",
|
||||
}
|
||||
);
|
||||
try {
|
||||
if (!Telemetry.client) {
|
||||
const { PostHog } = await import("posthog-node");
|
||||
Telemetry.client = new PostHog(
|
||||
"phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs",
|
||||
{
|
||||
host: "https://app.posthog.com",
|
||||
}
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`Failed to setup telemetry: ${e}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import * as path from "path";
|
||||
import Parser from "web-tree-sitter";
|
||||
const Parser = require("web-tree-sitter")
|
||||
|
||||
export const supportedLanguages: { [key: string]: string } = {
|
||||
cpp: "cpp",
|
||||
|
|
@ -68,26 +68,31 @@ export const supportedLanguages: { [key: string]: string } = {
|
|||
};
|
||||
|
||||
export async function getParserForFile(filepath: string) {
|
||||
await Parser.init();
|
||||
const parser = new Parser();
|
||||
const extension = path.extname(filepath).slice(1);
|
||||
|
||||
if (!supportedLanguages[extension]) {
|
||||
console.warn(
|
||||
"Unable to load language for file",
|
||||
extension,
|
||||
"from path: ",
|
||||
filepath
|
||||
try {
|
||||
await Parser.init();
|
||||
const parser = new Parser();
|
||||
const extension = path.extname(filepath).slice(1);
|
||||
|
||||
if (!supportedLanguages[extension]) {
|
||||
console.warn(
|
||||
"Unable to load language for file",
|
||||
extension,
|
||||
"from path: ",
|
||||
filepath
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const wasmPath = path.join(
|
||||
__dirname,
|
||||
"tree-sitter-wasms",
|
||||
`tree-sitter-${supportedLanguages[extension]}.wasm`
|
||||
);
|
||||
const language = await Parser.Language.load(wasmPath);
|
||||
parser.setLanguage(language);
|
||||
return parser;
|
||||
} catch (e) {
|
||||
console.error("Unable to load language for file", filepath, e);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const wasmPath = path.join(
|
||||
__dirname,
|
||||
"tree-sitter-wasms",
|
||||
`tree-sitter-${supportedLanguages[extension]}.wasm`
|
||||
);
|
||||
const Language = await Parser.Language.load(wasmPath);
|
||||
parser.setLanguage(Language);
|
||||
return parser;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,24 +1,16 @@
|
|||
import { ContextItemWithId, DiffLine, ILLM, SlashCommand } from "../..";
|
||||
import { DiffLine, ILLM } from "..";
|
||||
import {
|
||||
filterCodeBlockLines,
|
||||
filterEnglishLinesAtEnd,
|
||||
filterEnglishLinesAtStart,
|
||||
filterLeadingAndTrailingNewLineInsertion,
|
||||
fixCodeLlamaFirstLineIndentation,
|
||||
} from "../../autocomplete/lineStream";
|
||||
import { streamDiff } from "../../diff/streamDiff";
|
||||
import { streamLines } from "../../diff/util";
|
||||
import { stripImages } from "../../llm/countTokens";
|
||||
import { gptEditPrompt } from "../../llm/templates/edit";
|
||||
import {
|
||||
dedentAndGetCommonWhitespace,
|
||||
getMarkdownLanguageTagForFile,
|
||||
renderPromptTemplate,
|
||||
} from "../../util";
|
||||
import {
|
||||
RangeInFileWithContents,
|
||||
contextItemToRangeInFileWithContents,
|
||||
} from "../util";
|
||||
} from "../autocomplete/lineStream";
|
||||
import { streamDiff } from "../diff/streamDiff";
|
||||
import { streamLines } from "../diff/util";
|
||||
import { stripImages } from "../llm/countTokens";
|
||||
import { gptEditPrompt } from "../llm/templates/edit";
|
||||
import { dedentAndGetCommonWhitespace, renderPromptTemplate } from "../util";
|
||||
|
||||
function constructPrompt(
|
||||
codeToEdit: string,
|
||||
|
|
@ -87,38 +79,3 @@ export async function* streamDiffLines(
|
|||
yield diffLine;
|
||||
}
|
||||
}
|
||||
|
||||
const VerticalEditSlashCommand: SlashCommand = {
|
||||
name: "verticalEdit",
|
||||
description: "Edit selected code with vertical diff",
|
||||
run: async function* ({ ide, llm, input, contextItems }) {
|
||||
const contextItemToEdit = contextItems.find(
|
||||
(item: ContextItemWithId) =>
|
||||
item.editing && item.id.providerTitle === "code"
|
||||
);
|
||||
|
||||
if (!contextItemToEdit) {
|
||||
yield "Highlight the code that you want to edit first";
|
||||
return;
|
||||
}
|
||||
|
||||
const rif: RangeInFileWithContents =
|
||||
contextItemToRangeInFileWithContents(contextItemToEdit);
|
||||
const startLine = rif.range.start.line;
|
||||
const endLine = rif.range.end.line;
|
||||
const filepath = rif.filepath;
|
||||
|
||||
const diffLineGenerator = streamDiffLines(
|
||||
rif.contents,
|
||||
llm,
|
||||
input,
|
||||
getMarkdownLanguageTagForFile(rif.filepath)
|
||||
);
|
||||
|
||||
for await (const diffLine of diffLineGenerator) {
|
||||
await ide.verticalDiffUpdate(filepath, startLine, endLine, diffLine);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export default VerticalEditSlashCommand;
|
||||
2
core/vendor/package-lock.json
generated
vendored
2
core/vendor/package-lock.json
generated
vendored
|
|
@ -7,7 +7,7 @@
|
|||
"": {
|
||||
"name": "vendor",
|
||||
"version": "1.0.0",
|
||||
"license": "ISC",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@xenova/transformers": "^2.14.0"
|
||||
}
|
||||
|
|
|
|||
2
core/vendor/package.json
vendored
2
core/vendor/package.json
vendored
|
|
@ -7,7 +7,7 @@
|
|||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@xenova/transformers": "^2.14.0"
|
||||
}
|
||||
|
|
|
|||
BIN
core/vendor/tree-sitter.wasm
vendored
BIN
core/vendor/tree-sitter.wasm
vendored
Binary file not shown.
106
core/web/webviewProtocol.ts
Normal file
106
core/web/webviewProtocol.ts
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
import {
|
||||
ContextItemWithId,
|
||||
ContinueRcJson,
|
||||
DiffLine,
|
||||
Problem,
|
||||
Range,
|
||||
} from "..";
|
||||
import { RangeInFileWithContents } from "../commands/util";
|
||||
import { Protocol } from "../protocol";
|
||||
|
||||
export type IdeProtocol = {
|
||||
listWorkspaceContents: [undefined, string[]];
|
||||
getWorkspaceDirs: [undefined, string[]];
|
||||
listFolders: [undefined, string[]];
|
||||
writeFile: [{ path: string; contents: string }, void];
|
||||
showVirtualFile: [{ name: string; content: string }, void];
|
||||
getContinueDir: [undefined, string];
|
||||
openFile: [{ path: string }, void];
|
||||
runCommand: [{ command: string }, void];
|
||||
getSearchResults: [{ query: string }, string];
|
||||
subprocess: [{ command: string }, [string, string]];
|
||||
saveFile: [{ filepath: string }, void];
|
||||
readFile: [{ filepath: string }, string];
|
||||
showDiff: [
|
||||
{ filepath: string; newContents: string; stepIndex: number },
|
||||
void,
|
||||
];
|
||||
diffLine: [
|
||||
{
|
||||
diffLine: DiffLine;
|
||||
filepath: string;
|
||||
startLine: number;
|
||||
endLine: number;
|
||||
},
|
||||
void,
|
||||
];
|
||||
getProblems: [{ filepath: string }, Problem[]];
|
||||
getBranch: [{ dir: string }, string];
|
||||
getOpenFiles: [undefined, string[]];
|
||||
getPinnedFiles: [undefined, string[]];
|
||||
showLines: [{ filepath: string; startLine: number; endLine: number }, void];
|
||||
readRangeInFile: [{ filepath: string; range: Range }, string];
|
||||
getDiff: [undefined, string];
|
||||
getWorkspaceConfigs: [undefined, ContinueRcJson[]];
|
||||
getTerminalContents: [undefined, string];
|
||||
getDebugLocals: [{threadIndex: Number}, string];
|
||||
getTopLevelCallStackSources: [{threadIndex: number, stackDepth: number}, string[]];
|
||||
getAvailableThreads: [undefined, string[]];
|
||||
isTelemetryEnabled: [undefined, boolean];
|
||||
getUniqueId: [undefined, string];
|
||||
};
|
||||
|
||||
export type WebviewProtocol = Protocol &
|
||||
IdeProtocol & {
|
||||
onLoad: [
|
||||
undefined,
|
||||
{
|
||||
windowId: string;
|
||||
serverUrl: string;
|
||||
workspacePaths: string[];
|
||||
vscMachineId: string;
|
||||
vscMediaUrl: string;
|
||||
},
|
||||
];
|
||||
|
||||
errorPopup: [{ message: string }, void];
|
||||
"index/setPaused": [boolean, void];
|
||||
openUrl: [string, void];
|
||||
applyToCurrentFile: [{ text: string }, void];
|
||||
showTutorial: [undefined, void];
|
||||
showFile: [{ filepath: string }, void];
|
||||
openConfigJson: [undefined, void];
|
||||
|
||||
toggleDevTools: [undefined, void];
|
||||
reloadWindow: [undefined, void];
|
||||
focusEditor: [undefined, void];
|
||||
toggleFullScreen: [undefined, void];
|
||||
};
|
||||
|
||||
export type ReverseWebviewProtocol = {
|
||||
setInactive: [undefined, void];
|
||||
configUpdate: [undefined, void];
|
||||
submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap
|
||||
addContextItem: [
|
||||
{
|
||||
historyIndex: number;
|
||||
item: ContextItemWithId;
|
||||
},
|
||||
void,
|
||||
];
|
||||
getDefaultModelTitle: [undefined, string];
|
||||
newSessionWithPrompt: [{ prompt: string }, void];
|
||||
userInput: [{ input: string }, void];
|
||||
focusContinueInput: [undefined, void];
|
||||
focusContinueInputWithoutClear: [undefined, void];
|
||||
focusContinueInputWithNewSession: [undefined, void];
|
||||
highlightedCode: [{ rangeInFileWithContents: RangeInFileWithContents }, void];
|
||||
addModel: [undefined, void];
|
||||
openSettings: [undefined, void];
|
||||
viewHistory: [undefined, void];
|
||||
indexProgress: [{ progress: number; desc: string }, void];
|
||||
newSession: [undefined, void];
|
||||
refreshSubmenuItems: [undefined, void];
|
||||
setTheme: [{ theme: any }, void];
|
||||
setColors: [{ [key: string]: string }, void];
|
||||
};
|
||||
5260
core/yarn.lock
5260
core/yarn.lock
File diff suppressed because it is too large
Load diff
|
|
@ -137,7 +137,6 @@ assignee = currentUser() AND resolution = Unresolved order by updated DESC
|
|||
|
||||
You can override this query by setting the `issueQuery` parameter.
|
||||
|
||||
|
||||
### Code Outline
|
||||
|
||||
Type '@outline' to reference the outline of all currently open files. The outline of a files consists of only the function and class definitions in the file. Supported file extensions are '.js', '.mjs', '.go', '.c', '.cc', '.cs', '.cpp', '.el', '.ex', '.elm', '.java', '.ml', '.php', '.ql', '.rb', '.rs', '.ts'
|
||||
|
|
@ -154,6 +153,63 @@ Type '@highlights' to reference the 'highlights' from all currently open files.
|
|||
{ "name": "highlights" }
|
||||
```
|
||||
|
||||
### PostgreSQL
|
||||
|
||||
Type `@postgres` to reference the schema of a table, and some sample rows. A dropdown will appear, allowing you to select a specific table, or all tables.
|
||||
|
||||
The only required settings are those for creating the database connection: `host`, `port`, `user`, `password`, and `database`.
|
||||
|
||||
By default, the `schema` filter is set to `public`, and the `sampleRows` is set to 3. You may unset the schema if you want to include tables from all schemas.
|
||||
|
||||
[Here is a short demo.](https://github.com/continuedev/continue/pull/859)
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "postgres",
|
||||
"params": {
|
||||
"host": "localhost",
|
||||
"port": 5436,
|
||||
"user": "myuser",
|
||||
"password": "catsarecool",
|
||||
"database": "animals",
|
||||
"schema": "public",
|
||||
"sampleRows": 3
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Database Tables
|
||||
|
||||
Type `@database` to reference table schemas you can use the drop-down or start typeing table names based off of your configuration. Configuration supports multiple databases, allowing you to specify various connection details for PostgreSQL, MySQL, SQLite. Each connection should include a unique name, the connection_type (e.g., postgres, sqlite), and the necessary connection parameters specific to each database type.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "database",
|
||||
"params": {
|
||||
"connections": [
|
||||
{
|
||||
"name": "examplePostgres",
|
||||
"connection_type": "postgres",
|
||||
"connection": {
|
||||
"user": "username",
|
||||
"host": "localhost",
|
||||
"database": "exampleDB",
|
||||
"password": "yourPassword",
|
||||
"port": 5432
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "exampleSqlite",
|
||||
"connection_type": "sqlite",
|
||||
"connection": {
|
||||
"filename": "/path/to/your/sqlite/database.db"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Requesting Context Providers
|
||||
|
||||
Not seeing what you want? Create an issue [here](https://github.com/continuedev/continue/issues/new?assignees=TyDunn&labels=enhancement&projects=&template=feature-request-%F0%9F%92%AA.md&title=) to request a new ContextProvider.
|
||||
|
|
|
|||
|
|
@ -52,6 +52,27 @@ For many cases, either Continue will have a built-in provider or the API you use
|
|||
|
||||
However, if neither of these are the case, you will need to wire up a new LLM object. Learn how to do this [here](#defining-a-custom-llm-provider).
|
||||
|
||||
## Authentication
|
||||
|
||||
If you need to send custom headers for authentication, you may use the `requestOptions.headers` property like in this example with Ollama:
|
||||
|
||||
```json title="~/.continue/config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Ollama",
|
||||
"provider": "ollama",
|
||||
"model": "llama2-7b",
|
||||
"requestOptions": {
|
||||
"headers": {
|
||||
"Authorization": "Bearer xxx"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Customizing the Chat Template
|
||||
|
||||
Most open-source models expect a specific chat format, for example llama2 and codellama expect the input to look like `"[INST] How do I write bubble sort in Rust? [/INST]"`. Continue will automatically attempt to detect the correct prompt format based on the `model`value that you provide, but if you are receiving nonsense responses, you can use the`template`property to explicitly set the format that you expect. The options are:`["llama2", "alpaca", "zephyr", "phind", "anthropic", "chatml", "openchat", "neural-chat", "none"]`.
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ You can run a model on your local computer using:
|
|||
- [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)
|
||||
|
||||
Once you have it running, you will need to configure it in the GUI or manually add it to your `config.json`.
|
||||
|
||||
|
|
|
|||
|
|
@ -25,4 +25,25 @@ In addition to the model type, you can also configure some of the parameters tha
|
|||
- num_predict: options.maxTokens - This determines the maximum number of tokens (words or characters) to generate for the given input prompt.
|
||||
- num_thread: options.numThreads - This is the multi-threading configuration option that controls how many threads the model uses for parallel processing. Higher values may lead to faster generation times but could also increase memory usage and complexity. Set this to one or two lower than the number of threads your CPU can handle to leave some for your GUI when running the model locally.
|
||||
|
||||
## Authentication
|
||||
|
||||
If you need to send custom headers for authentication, you may use the `requestOptions.headers` property like this:
|
||||
|
||||
```json title="~/.continue/config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Ollama",
|
||||
"provider": "ollama",
|
||||
"model": "llama2-7b",
|
||||
"requestOptions": {
|
||||
"headers": {
|
||||
"Authorization": "Bearer xxx"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Ollama.ts)
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ OpenAI compatible servers
|
|||
- [FastChat](https://github.com/lm-sys/FastChat/blob/main/docs/openai_api.md)
|
||||
- [LocalAI](https://localai.io/basics/getting_started/)
|
||||
- [llama-cpp-python](https://github.com/abetlen/llama-cpp-python#web-server)
|
||||
- [TensorRT-LLM](https://github.com/NVIDIA/trt-llm-as-openai-windows?tab=readme-ov-file#examples)
|
||||
|
||||
OpenAI compatible APIs
|
||||
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
# Tab Autocomplete (Experimental)
|
||||
# Tab Autocomplete (beta)
|
||||
|
||||
Continue now provides experimental support for tab autocomplete in VS Code. You can enable it by downloading the pre-release version of the extension, opening VS Code settings, and then checking the box that says "Enable Tab Autocomplete". There is also a button on the bottom/status bar for fast access. We will be greatly improving the experience over the next few releases, and it is always helpful to hear feedback. If you have any problems or suggestions, please let us know in our [Discord](https://discord.gg/vapESyrFmJ).
|
||||
Continue now provides support for tab autocomplete in [the VS Code extension](https://marketplace.visualstudio.com/items?itemName=Continue.continue) (make sure to download the pre-release). We will be greatly improving the experience over the next few releases, and it is always helpful to hear feedback. If you have any problems or suggestions, please let us know in our [Discord](https://discord.gg/vapESyrFmJ).
|
||||
|
||||
## Setting up with Ollama (default)
|
||||
|
||||
We recommend setting up tab-autocomplete with a local Ollama instance. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model:
|
||||
|
||||
```bash
|
||||
ollama run deepseek-coder:1.3b-base
|
||||
ollama run starcoder:3b
|
||||
```
|
||||
|
||||
Once it has been downloaded, you should begin to see completions in VS Code.
|
||||
|
|
@ -21,7 +21,7 @@ All of the configuration options available for chat models are available to use
|
|||
"tabAutocompleteModel": {
|
||||
"title": "Tab Autocomplete Model",
|
||||
"provider": "ollama",
|
||||
"model": "deepseek-coder:1.3b-base",
|
||||
"model": "starcoder:3b",
|
||||
"apiBase": "https://<my endpoint>"
|
||||
},
|
||||
...
|
||||
|
|
@ -49,6 +49,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa
|
|||
- `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number)
|
||||
- `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number)
|
||||
- `template`: An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables. (String)
|
||||
- `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "auto".
|
||||
|
||||
### Full example
|
||||
|
||||
|
|
@ -57,7 +58,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa
|
|||
"tabAutocompleteModel": {
|
||||
"title": "Tab Autocomplete Model",
|
||||
"provider": "ollama",
|
||||
"model": "deepseek-coder:1.3b-base",
|
||||
"model": "starcoder:3b",
|
||||
"apiBase": "https://<my endpoint>"
|
||||
},
|
||||
"tabAutocompleteOptions": {
|
||||
|
|
@ -75,9 +76,9 @@ This object allows you to customize the behavior of tab-autocomplete. The availa
|
|||
Follow these steps to ensure that everything is set up correctly:
|
||||
|
||||
1. Make sure you have the pre-release version of the extension installed.
|
||||
2. Make sure you have the "Enable Tab Autocomplete" setting checked.
|
||||
2. Make sure you have the "Enable Tab Autocomplete" setting checked (can toggle by clicking the "Continue" button in the status bar).
|
||||
3. Make sure you have downloaded Ollama.
|
||||
4. Run `ollama run deepseek-coder:1.3b-base` to verify that the model is downloaded.
|
||||
4. Run `ollama run starcoder:3b` to verify that the model is downloaded.
|
||||
5. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere.
|
||||
6. Make sure that you aren't also using another Ollama model for chat. This will cause Ollama to constantly load and unload the models from memory, resulting in slow responses (or none at all) for both.
|
||||
7. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab).
|
||||
|
|
@ -85,11 +86,11 @@ Follow these steps to ensure that everything is set up correctly:
|
|||
|
||||
### Completions are slow
|
||||
|
||||
We are working on this! You can expect improvements in the time frame of the next few days. For now, you will probably see faster completions in smaller files where there isn't as much context above the cursor.
|
||||
Depending on your hardware, you may want to try a smaller, faster model. If 3b isn't working for you we recommend trying `deepseek-coder:1.3b-base`.
|
||||
|
||||
### Completions don't know about my code
|
||||
|
||||
We are working on this as well! Right now Continue only sees your current file surrounding the cursor. We're already partway through building a full-text search feature that will help Continue know about other files. You can expect to see improvements in the time frame of roughly a week.
|
||||
We are working on this! Right now Continue uses the Language Server Protocol to add definitions to the prompt, as well as using similarity search over recently edited files. We will be improving the accuracy of this system greatly over the next few weeks.
|
||||
|
||||
### Completions contain formatting errors
|
||||
|
||||
|
|
|
|||
138
docs/static/schemas/config.json
vendored
138
docs/static/schemas/config.json
vendored
|
|
@ -1029,7 +1029,8 @@
|
|||
"docs",
|
||||
"tree",
|
||||
"highlights",
|
||||
"outline"
|
||||
"outline",
|
||||
"postgres"
|
||||
],
|
||||
"markdownEnumDescriptions": [
|
||||
"Reference the contents of the current changes as given by `git diff`",
|
||||
|
|
@ -1047,7 +1048,8 @@
|
|||
"Display a file tree of the current workspace",
|
||||
"Include a repo map showing important code objects",
|
||||
"Displays important snippets of code from the currently open files",
|
||||
"Displays definition lines from the currently open files"
|
||||
"Displays definition lines from the currently open files",
|
||||
"References Postgres table schema and sample rows"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -1154,6 +1156,67 @@
|
|||
"required": ["params"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["database"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"connections": {
|
||||
"type": "array",
|
||||
"description": "A list of database connections",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "A unique name for this database connection"
|
||||
},
|
||||
"connection_type": {
|
||||
"type": "string",
|
||||
"description": "The type of database (e.g., 'postgres', 'mysql')",
|
||||
"enum": ["postgres", "mysql", "sqlite"]
|
||||
},
|
||||
"connection": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"user": {
|
||||
"type": "string",
|
||||
"description": "The database user name"
|
||||
},
|
||||
"host": {
|
||||
"type": "string",
|
||||
"description": "The host address of the database server"
|
||||
},
|
||||
"database": {
|
||||
"type": "string",
|
||||
"description": "The name of the database to connect to"
|
||||
},
|
||||
"password": {
|
||||
"type": "string",
|
||||
"description": "The password for the database user"
|
||||
},
|
||||
"port": {
|
||||
"type": "integer",
|
||||
"description": "The port number to connect to at the host"
|
||||
},
|
||||
"filename": {
|
||||
"type": "string",
|
||||
"description": "File location for simple file DB's"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
},
|
||||
"required": ["name", "type", "connection"]
|
||||
}
|
||||
},
|
||||
"required": ["connections"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
|
|
@ -1246,6 +1309,65 @@
|
|||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["postgres"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"params": {
|
||||
"properties": {
|
||||
"host": {
|
||||
"title": "Host",
|
||||
"description": "Database host",
|
||||
"default": "localhost",
|
||||
"type": "string"
|
||||
},
|
||||
"port": {
|
||||
"title": "Port",
|
||||
"description": "Database port",
|
||||
"default": 5432,
|
||||
"type": "integer"
|
||||
},
|
||||
"user": {
|
||||
"title": "User",
|
||||
"description": "Database user",
|
||||
"default": "postgres",
|
||||
"type": "string"
|
||||
},
|
||||
"password": {
|
||||
"title": "Password",
|
||||
"description": "Database password",
|
||||
"type": "string"
|
||||
},
|
||||
"database": {
|
||||
"title": "Database",
|
||||
"description": "Database name",
|
||||
"default": "postgres",
|
||||
"type": "string"
|
||||
},
|
||||
"schema": {
|
||||
"title": "Schema",
|
||||
"description": "Database schema",
|
||||
"default": "public",
|
||||
"type": "string"
|
||||
},
|
||||
"sampleRows": {
|
||||
"title": "Sample Rows",
|
||||
"description": "Number of rows to sample from the database",
|
||||
"default": 3,
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["host", "port", "user", "password", "database"]
|
||||
}
|
||||
}
|
||||
],
|
||||
"required": ["name"]
|
||||
|
|
@ -1437,9 +1559,17 @@
|
|||
"type": "string",
|
||||
"description": "An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables."
|
||||
},
|
||||
"disableMultiLineCompletions": {
|
||||
"type": "boolean",
|
||||
"multilineCompletions": {
|
||||
"enum": ["always", "never", "auto"],
|
||||
"description": "If set to true, Continue will only complete a single line at a time."
|
||||
},
|
||||
"useCache": {
|
||||
"type": "boolean",
|
||||
"description": "Whether to cache completions"
|
||||
},
|
||||
"onlyMyCode": {
|
||||
"type": "boolean",
|
||||
"description": "If set to true, Continue will not include any snippets from go to definition unless they are within your repository"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
|
|
|
|||
3
extensions/intellij/.gitignore
vendored
3
extensions/intellij/.gitignore
vendored
|
|
@ -1 +1,2 @@
|
|||
src/main/resources/webview
|
||||
src/main/resources/webview
|
||||
src/main/resources/bin
|
||||
|
|
@ -79,6 +79,12 @@ koverReport {
|
|||
}
|
||||
|
||||
tasks {
|
||||
prepareSandbox {
|
||||
from("../../pkg/bin") {
|
||||
into("${intellij.pluginName.get()}/core/")
|
||||
}
|
||||
}
|
||||
|
||||
wrapper {
|
||||
gradleVersion = properties("gradleVersion").get()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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.27
|
||||
pluginVersion = 0.0.33
|
||||
|
||||
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
|
||||
pluginSinceBuild = 223
|
||||
|
|
|
|||
|
|
@ -4,13 +4,11 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS
|
|||
import com.google.gson.Gson
|
||||
import com.intellij.openapi.actionSystem.AnAction
|
||||
import com.intellij.openapi.actionSystem.AnActionEvent
|
||||
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
|
||||
import com.intellij.openapi.components.ServiceManager
|
||||
import com.intellij.openapi.ui.DialogWrapper
|
||||
import com.intellij.openapi.ui.Messages
|
||||
import com.intellij.openapi.wm.ToolWindowManager
|
||||
import java.awt.Dimension
|
||||
import java.awt.GridLayout
|
||||
import javax.swing.*
|
||||
import javax.swing.event.DocumentEvent
|
||||
import javax.swing.event.DocumentListener
|
||||
|
|
@ -130,7 +128,7 @@ class QuickTextEntryAction : AnAction() {
|
|||
}
|
||||
|
||||
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
|
||||
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInput")))
|
||||
continuePluginService.sendToWebview("focusContinueInput", null)
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -179,7 +177,7 @@ class FocusContinueInputWithoutClearAction : AnAction() {
|
|||
|
||||
val continuePluginService = pluginServiceFromActionEvent(e) ?: return
|
||||
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
|
||||
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInputWithoutClear")))
|
||||
continuePluginService.sendToWebview("focusContinueInputWithoutClear", null)
|
||||
|
||||
continuePluginService.ideProtocolClient?.sendHighlightedCode()
|
||||
}
|
||||
|
|
@ -202,7 +200,7 @@ class FocusContinueInputAction : AnAction() {
|
|||
val continuePluginService = pluginServiceFromActionEvent(e) ?: return
|
||||
|
||||
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
|
||||
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInput")))
|
||||
continuePluginService.sendToWebview("focusContinueInput", null)
|
||||
|
||||
continuePluginService.ideProtocolClient?.sendHighlightedCode()
|
||||
}
|
||||
|
|
@ -225,7 +223,7 @@ class NewContinueSessionAction : AnAction() {
|
|||
val continuePluginService = pluginServiceFromActionEvent(e) ?: return
|
||||
|
||||
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
|
||||
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInputWithNewSession")))
|
||||
continuePluginService.sendToWebview("focusContinueInputWithNewSession", null)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -239,6 +237,6 @@ class ViewHistoryAction : AnAction() {
|
|||
|
||||
val continuePluginService = pluginServiceFromActionEvent(e) ?: return
|
||||
|
||||
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "viewHistory")))
|
||||
continuePluginService.sendToWebview("viewHistory", null)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,9 +1,7 @@
|
|||
package com.github.continuedev.continueintellijextension.activities
|
||||
|
||||
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
|
||||
import com.github.continuedev.continueintellijextension.`continue`.startProxyServer
|
||||
import com.github.continuedev.continueintellijextension.`continue`.DefaultTextSelectionStrategy
|
||||
import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient
|
||||
import com.github.continuedev.continueintellijextension.`continue`.*
|
||||
import com.github.continuedev.continueintellijextension.listeners.ContinuePluginSelectionListener
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
|
|
@ -30,7 +28,9 @@ import java.nio.charset.StandardCharsets
|
|||
import java.nio.file.Files
|
||||
import java.nio.file.Paths
|
||||
import javax.swing.*
|
||||
|
||||
import com.intellij.openapi.application.PathManager;
|
||||
import com.intellij.ide.plugins.PluginManager
|
||||
import com.intellij.openapi.extensions.PluginId
|
||||
|
||||
class WelcomeDialogWrapper(val project: Project) : DialogWrapper(true) {
|
||||
private var panel: JPanel? = null
|
||||
|
|
@ -78,6 +78,28 @@ class WelcomeDialogWrapper(val project: Project) : DialogWrapper(true) {
|
|||
}
|
||||
}
|
||||
|
||||
fun showTutorial(project: Project) {
|
||||
ContinuePluginStartupActivity::class.java.getClassLoader().getResourceAsStream("continue_tutorial.py").use { `is` ->
|
||||
if (`is` == null) {
|
||||
throw IOException("Resource not found: continue_tutorial.py")
|
||||
}
|
||||
var content = StreamUtil.readText(`is`, StandardCharsets.UTF_8)
|
||||
if (!System.getProperty("os.name").toLowerCase().contains("mac")) {
|
||||
content = content.replace("⌘", "⌃")
|
||||
}
|
||||
val filepath = Paths.get(getContinueGlobalPath(), "continue_tutorial.py").toString()
|
||||
File(filepath).writeText(content)
|
||||
val virtualFile = LocalFileSystem.getInstance().findFileByPath(filepath)
|
||||
|
||||
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
if (virtualFile != null) {
|
||||
FileEditorManager.getInstance(project).openFile(virtualFile, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
|
||||
private val coroutineScope = CoroutineScope(Dispatchers.IO)
|
||||
|
||||
|
|
@ -121,6 +143,8 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
|
|||
ContinuePluginService::class.java
|
||||
)
|
||||
|
||||
val theme = GetTheme().getTheme()
|
||||
|
||||
val defaultStrategy = DefaultTextSelectionStrategy()
|
||||
|
||||
coroutineScope.launch {
|
||||
|
|
@ -129,24 +153,7 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
|
|||
if (!settings.continueState.shownWelcomeDialog) {
|
||||
settings.continueState.shownWelcomeDialog = true
|
||||
// Open continue_tutorial.py
|
||||
ContinuePluginStartupActivity::class.java.getClassLoader().getResourceAsStream("continue_tutorial.py").use { `is` ->
|
||||
if (`is` == null) {
|
||||
throw IOException("Resource not found: continue_tutorial.py")
|
||||
}
|
||||
var content = StreamUtil.readText(`is`, StandardCharsets.UTF_8)
|
||||
if (!System.getProperty("os.name").toLowerCase().contains("mac")) {
|
||||
content = content.replace("⌘", "⌃")
|
||||
}
|
||||
val filepath = Paths.get(getContinueGlobalPath(), "continue_tutorial.py").toString()
|
||||
File(filepath).writeText(content)
|
||||
val virtualFile = LocalFileSystem.getInstance().findFileByPath(filepath)
|
||||
|
||||
if (virtualFile != null) {
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
FileEditorManager.getInstance(project).openFile(virtualFile, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
showTutorial(project)
|
||||
|
||||
// Show the welcome dialog
|
||||
// withContext(Dispatchers.Main) {
|
||||
|
|
@ -156,17 +163,17 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
|
|||
// settings.continueState.shownWelcomeDialog = true
|
||||
}
|
||||
|
||||
GlobalScope.async(Dispatchers.IO) {
|
||||
val ideProtocolClient = IdeProtocolClient(
|
||||
val ideProtocolClient = IdeProtocolClient(
|
||||
continuePluginService,
|
||||
defaultStrategy,
|
||||
coroutineScope,
|
||||
project.basePath,
|
||||
project
|
||||
)
|
||||
)
|
||||
|
||||
continuePluginService.ideProtocolClient = ideProtocolClient
|
||||
continuePluginService.ideProtocolClient = ideProtocolClient
|
||||
|
||||
GlobalScope.async(Dispatchers.IO) {
|
||||
val listener =
|
||||
ContinuePluginSelectionListener(
|
||||
ideProtocolClient,
|
||||
|
|
@ -193,6 +200,34 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
|
|||
}
|
||||
}
|
||||
|
||||
GlobalScope.async(Dispatchers.IO) {
|
||||
val myPluginId = "com.github.continuedev.continueintellijextension"
|
||||
val pluginDescriptor = PluginManager.getPlugin(PluginId.getId(myPluginId))
|
||||
|
||||
if (pluginDescriptor == null) {
|
||||
throw Exception("Plugin not found")
|
||||
}
|
||||
val pluginPath = pluginDescriptor.pluginPath
|
||||
val osName = System.getProperty("os.name").toLowerCase()
|
||||
val os = when {
|
||||
osName.contains("mac") || osName.contains("darwin") -> "darwin"
|
||||
osName.contains("win") -> "win32"
|
||||
osName.contains("nix") || osName.contains("nux") || osName.contains("aix") -> "linux"
|
||||
else -> "linux"
|
||||
}
|
||||
val osArch = System.getProperty("os.arch").toLowerCase()
|
||||
val arch = when {
|
||||
osArch.contains("aarch64") || (osArch.contains("arm") && osArch.contains("64")) -> "arm64"
|
||||
osArch.contains("amd64") || osArch.contains("x86_64") -> "x64"
|
||||
else -> "x64"
|
||||
}
|
||||
val target = "$os-$arch"
|
||||
|
||||
val continueCorePath = Paths.get(pluginPath.toString(), "core", target, "pkg").toString()
|
||||
|
||||
val coreMessenger = CoreMessenger(continueCorePath, ideProtocolClient);
|
||||
continuePluginService.coreMessenger = coreMessenger
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,48 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`
|
||||
|
||||
import com.github.continuedev.continueintellijextension.activities.ContinuePluginStartupActivity
|
||||
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.util.io.StreamUtil
|
||||
import com.intellij.openapi.vfs.LocalFileSystem
|
||||
import com.intellij.openapi.vfs.VirtualFile
|
||||
import com.jetbrains.jsonSchema.extension.JsonSchemaFileProvider
|
||||
import com.jetbrains.jsonSchema.extension.JsonSchemaProviderFactory
|
||||
import com.jetbrains.jsonSchema.extension.SchemaType
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.nio.file.Paths
|
||||
|
||||
class ConfigJsonSchemaProviderFactory : JsonSchemaProviderFactory {
|
||||
override fun getProviders(project: Project): MutableList<JsonSchemaFileProvider> {
|
||||
return mutableListOf(ConfigJsonSchemaFileProvider())
|
||||
}
|
||||
}
|
||||
|
||||
class ConfigJsonSchemaFileProvider : JsonSchemaFileProvider {
|
||||
override fun isAvailable(file: VirtualFile): Boolean {
|
||||
return file.name == "config.json"
|
||||
}
|
||||
|
||||
override fun getName(): String {
|
||||
return "config.json"
|
||||
}
|
||||
|
||||
override fun getSchemaFile(): VirtualFile? {
|
||||
ContinuePluginStartupActivity::class.java.getClassLoader().getResourceAsStream("config_schema.json").use { `is` ->
|
||||
if (`is` == null) {
|
||||
throw IOException("Resource not found: config_schema.json")
|
||||
}
|
||||
val content = StreamUtil.readText(`is`, StandardCharsets.UTF_8)
|
||||
val filepath = Paths.get(getContinueGlobalPath(), "config_schema.json").toString()
|
||||
File(filepath).writeText(content)
|
||||
return LocalFileSystem.getInstance().findFileByPath(filepath)
|
||||
}
|
||||
}
|
||||
|
||||
override fun getSchemaType(): SchemaType {
|
||||
return SchemaType.embeddedSchema
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,179 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`
|
||||
import java.io.BufferedReader
|
||||
import java.io.InputStreamReader
|
||||
import java.io.OutputStreamWriter
|
||||
|
||||
import java.io.*
|
||||
|
||||
import com.google.gson.Gson
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Paths
|
||||
import java.nio.file.attribute.PosixFilePermission
|
||||
|
||||
class CoreMessenger(continueCorePath: String, ideProtocolClient: IdeProtocolClient) {
|
||||
private val writer: OutputStreamWriter
|
||||
private val reader: BufferedReader
|
||||
private val process: Process
|
||||
private val gson = Gson()
|
||||
private val responseListeners = mutableMapOf<String, (String) -> Unit>()
|
||||
private val ideProtocolClient = ideProtocolClient
|
||||
|
||||
private fun write(message: String) {
|
||||
writer.write(message + "\r\n")
|
||||
writer.flush()
|
||||
}
|
||||
|
||||
private fun close() {
|
||||
writer.close()
|
||||
reader.close()
|
||||
val exitCode = process.waitFor()
|
||||
println("Subprocess exited with code: $exitCode")
|
||||
}
|
||||
|
||||
fun request(messageType: String, data: Any?, messageId: String?, onResponse: (String) -> Unit) {
|
||||
val id = messageId ?: uuid()
|
||||
val message = gson.toJson(mapOf(
|
||||
"messageId" to id,
|
||||
"messageType" to messageType,
|
||||
"data" to data
|
||||
))
|
||||
responseListeners[id] = onResponse
|
||||
write(message)
|
||||
}
|
||||
|
||||
private fun handleMessage(json: String) {
|
||||
val responseMap = gson.fromJson(json, Map::class.java)
|
||||
val messageId = responseMap["messageId"].toString()
|
||||
val messageType = responseMap["messageType"].toString()
|
||||
val data = gson.toJson(responseMap["data"])
|
||||
|
||||
// IDE listeners
|
||||
if (ideMessageTypes.contains(messageType)) {
|
||||
ideProtocolClient.handleMessage(json) { data ->
|
||||
val message = gson.toJson(mapOf(
|
||||
"messageId" to messageId,
|
||||
"messageType" to messageType,
|
||||
"data" to data
|
||||
))
|
||||
write(message)
|
||||
};
|
||||
}
|
||||
|
||||
// Responses for messageId
|
||||
responseListeners[messageId]?.let { listener ->
|
||||
listener(data)
|
||||
if (generatorTypes.contains(messageType)) {
|
||||
val parsedData = gson.fromJson(data, Map::class.java)
|
||||
val done = parsedData["done"] as Boolean?
|
||||
if (done == true) {
|
||||
responseListeners.remove(messageId)
|
||||
} else {}
|
||||
} else {
|
||||
responseListeners.remove(messageId)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private val generatorTypes = listOf(
|
||||
"llm/streamComplete",
|
||||
"llm/streamChat",
|
||||
"command/run"
|
||||
)
|
||||
|
||||
private val ideMessageTypes = listOf(
|
||||
"readRangeInFile",
|
||||
"isTelemetryEnabled",
|
||||
"getUniqueId",
|
||||
"getWorkspaceConfigs",
|
||||
"getDiff",
|
||||
"getTerminalContents",
|
||||
"listWorkspaceContents",
|
||||
"getWorkspaceDirs",
|
||||
"showLines",
|
||||
"listFolders",
|
||||
"getContinueDir",
|
||||
"writeFile",
|
||||
"showVirtualFile",
|
||||
"openFile",
|
||||
"runCommand",
|
||||
"saveFile",
|
||||
"readFile",
|
||||
"showDiff",
|
||||
"getOpenFiles",
|
||||
"getPinnedFiles",
|
||||
"getSearchResults",
|
||||
"getProblems",
|
||||
"subprocess",
|
||||
"getBranch",
|
||||
"getIdeInfo"
|
||||
)
|
||||
|
||||
private fun setPermissions(destination: String) {
|
||||
val osName = System.getProperty("os.name").toLowerCase()
|
||||
if (osName.contains("mac") || osName.contains("darwin")) {
|
||||
ProcessBuilder(
|
||||
"xattr",
|
||||
"-dr",
|
||||
"com.apple.quarantine",
|
||||
destination
|
||||
).start()
|
||||
setFilePermissions(destination, "rwxr-xr-x")
|
||||
} else if (osName.contains("nix") || osName.contains("nux") || osName.contains("mac")) {
|
||||
setFilePermissions(destination, "rwxr-xr-x")
|
||||
}
|
||||
}
|
||||
|
||||
private fun setFilePermissions(path: String, posixPermissions: String) {
|
||||
val perms = HashSet<PosixFilePermission>()
|
||||
if (posixPermissions.contains("r")) perms.add(PosixFilePermission.OWNER_READ)
|
||||
if (posixPermissions.contains("w")) perms.add(PosixFilePermission.OWNER_WRITE)
|
||||
if (posixPermissions.contains("x")) perms.add(PosixFilePermission.OWNER_EXECUTE)
|
||||
Files.setPosixFilePermissions(Paths.get(path), perms)
|
||||
}
|
||||
|
||||
init {
|
||||
// Set proper permissions
|
||||
setPermissions(continueCorePath)
|
||||
|
||||
// Start the subprocess
|
||||
val processBuilder = ProcessBuilder(continueCorePath)
|
||||
process = processBuilder.start()
|
||||
|
||||
val outputStream = process.outputStream
|
||||
val inputStream = process.inputStream
|
||||
|
||||
writer = OutputStreamWriter(outputStream)
|
||||
reader = BufferedReader(InputStreamReader(inputStream))
|
||||
|
||||
process.onExit().thenRun {
|
||||
val err = process.errorStream.bufferedReader().readText()
|
||||
ideProtocolClient.showMessage("Core process exited with output: $err")
|
||||
}
|
||||
|
||||
Thread {
|
||||
try {
|
||||
while (true) {
|
||||
val line = reader.readLine()
|
||||
if (line != null && line.isNotEmpty()) {
|
||||
handleMessage(line)
|
||||
} else {
|
||||
Thread.sleep(100)
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
e.printStackTrace()
|
||||
} finally {
|
||||
try {
|
||||
reader.close()
|
||||
writer.close()
|
||||
outputStream.close()
|
||||
inputStream.close()
|
||||
process.destroy()
|
||||
} catch (e: IOException) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
}.start()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`
|
||||
import com.intellij.codeInsight.template.impl.TemplateColors
|
||||
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
|
||||
import com.intellij.openapi.editor.colors.EditorColors
|
||||
import com.intellij.openapi.editor.colors.EditorColorsManager
|
||||
import com.intellij.openapi.editor.colors.EditorColorsScheme
|
||||
import com.intellij.openapi.editor.colors.TextAttributesKey
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
|
||||
class GetTheme {
|
||||
fun getTheme(): Map<String, String> {
|
||||
val globalScheme = EditorColorsManager.getInstance().globalScheme
|
||||
val defaultBackground = globalScheme.defaultBackground
|
||||
val defaultForeground = globalScheme.defaultForeground
|
||||
val highlight = globalScheme.getColor(EditorColors.MODIFIED_TAB_ICON_COLOR) ?: defaultForeground
|
||||
val defaultBackgroundHex = String.format("#%02x%02x%02x", defaultBackground.red, defaultBackground.green, defaultBackground.blue)
|
||||
val defaultForegroundHex = String.format("#%02x%02x%02x", defaultForeground.red, defaultForeground.green, defaultForeground.blue)
|
||||
val highlightHex = String.format("#%02x%02x%02x", highlight.red, highlight.green, highlight.blue)
|
||||
|
||||
val grayscale = (defaultBackground.red * 0.3 + defaultBackground.green * 0.59 + defaultBackground.blue * 0.11).toInt()
|
||||
|
||||
val adjustedRed: Int
|
||||
val adjustedGreen: Int
|
||||
val adjustedBlue: Int
|
||||
|
||||
val tint: Int = 20
|
||||
if (grayscale > 128) { // if closer to white
|
||||
adjustedRed = max(0, defaultBackground.red - tint)
|
||||
adjustedGreen = max(0, defaultBackground.green - tint)
|
||||
adjustedBlue = max(0, defaultBackground.blue - tint)
|
||||
} else { // if closer to black
|
||||
adjustedRed = min(255, defaultBackground.red + tint)
|
||||
adjustedGreen = min(255, defaultBackground.green + tint)
|
||||
adjustedBlue = min(255, defaultBackground.blue + tint)
|
||||
}
|
||||
|
||||
val secondaryDarkHex = String.format("#%02x%02x%02x", adjustedRed, adjustedGreen, adjustedBlue)
|
||||
|
||||
return mapOf(
|
||||
"--vscode-editor-foreground" to defaultForegroundHex,
|
||||
"--vscode-sideBar-background" to defaultBackgroundHex,
|
||||
"--vscode-input-background" to secondaryDarkHex,
|
||||
"--vscode-editor-background" to defaultBackgroundHex,
|
||||
"--vscode-button-background" to defaultBackgroundHex,
|
||||
"--vscode-list-activeSelectionBackground" to defaultBackgroundHex,
|
||||
"--vscode-focusBorder" to highlightHex,
|
||||
"--vscode-quickInputList-focusForeground" to defaultForegroundHex,
|
||||
"--vscode-quickInput-background" to secondaryDarkHex,
|
||||
"--vscode-input-border" to "#80808080",
|
||||
"--vscode-badge-background" to highlightHex,
|
||||
"--vscode-badge-foreground" to defaultForegroundHex,
|
||||
"--vscode-sideBar-border" to "#80808080"
|
||||
)
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -1,28 +1,19 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`
|
||||
|
||||
import com.github.continuedev.continueintellijextension.*
|
||||
import com.github.continuedev.continueintellijextension.constants.*
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.GsonBuilder
|
||||
import com.google.gson.JsonObject
|
||||
import com.google.gson.reflect.TypeToken
|
||||
import com.intellij.execution.ExecutionManager
|
||||
import com.intellij.execution.process.ProcessAdapter
|
||||
import com.intellij.execution.process.ProcessEvent
|
||||
import com.intellij.execution.ui.RunContentDescriptor
|
||||
import com.intellij.openapi.Disposable
|
||||
import com.intellij.openapi.actionSystem.AnActionEvent
|
||||
import com.intellij.openapi.application.ApplicationInfo
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.components.ServiceManager
|
||||
import com.intellij.openapi.editor.SelectionModel
|
||||
import com.intellij.openapi.fileEditor.FileDocumentManager
|
||||
import com.intellij.openapi.fileEditor.FileEditorManager
|
||||
import com.intellij.openapi.fileEditor.TextEditor
|
||||
import com.intellij.openapi.project.DumbAware
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.project.ProjectManagerListener
|
||||
import com.intellij.openapi.ui.MessageType
|
||||
import com.intellij.openapi.ui.popup.Balloon
|
||||
import com.intellij.openapi.ui.popup.JBPopupFactory
|
||||
|
|
@ -32,15 +23,10 @@ import com.intellij.openapi.wm.WindowManager
|
|||
import com.intellij.testFramework.LightVirtualFile
|
||||
import com.intellij.ui.awt.RelativePoint
|
||||
import kotlinx.coroutines.*
|
||||
import net.minidev.json.JSONObject
|
||||
import org.jetbrains.annotations.NotNull
|
||||
import java.io.*
|
||||
import java.net.NetworkInterface
|
||||
import java.nio.charset.Charset
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Paths
|
||||
import java.util.*
|
||||
import kotlin.coroutines.ContinuationInterceptor
|
||||
|
||||
|
||||
fun uuid(): String {
|
||||
|
|
@ -103,7 +89,7 @@ class AsyncFileSaveListener : AsyncFileListener {
|
|||
}
|
||||
override fun prepareChange(events: MutableList<out VFileEvent>): AsyncFileListener.ChangeApplier? {
|
||||
for (event in events) {
|
||||
if (event.path.endsWith(".continue/config.json") || event.path.endsWith(".continue/config.ts") || event.path.endsWith(".continue\\config.json") || event.path.endsWith(".continue\\config.ts")) {
|
||||
if (event.path.endsWith(".continue/config.json") || event.path.endsWith(".continue/config.ts") || event.path.endsWith(".continue\\config.json") || event.path.endsWith(".continue\\config.ts") || event.path.endsWith(".continuerc.json")) {
|
||||
return object : AsyncFileListener.ChangeApplier {
|
||||
override fun afterVfsChange() {
|
||||
val config = readConfigJson()
|
||||
|
|
@ -137,35 +123,21 @@ class IdeProtocolClient (
|
|||
|
||||
private fun send(messageType: String, data: Any?, messageId: String? = null) {
|
||||
val id = messageId ?: uuid()
|
||||
val message = IdeMessage(
|
||||
messageType,
|
||||
id,
|
||||
data
|
||||
)
|
||||
val json = Gson().toJson(message)
|
||||
continuePluginService.dispatchCustomEvent(json)
|
||||
continuePluginService.sendToWebview(messageType, data, id)
|
||||
}
|
||||
|
||||
fun handleWebsocketMessage(text: String) {
|
||||
fun handleMessage(text: String, respond: (Any?) -> Unit) {
|
||||
coroutineScope.launch(Dispatchers.IO) {
|
||||
val parsedMessage: Map<String, Any> = Gson().fromJson(
|
||||
text,
|
||||
object : TypeToken<Map<String, Any>>() {}.type
|
||||
)
|
||||
val messageType = parsedMessage["type"] as? String
|
||||
val messageType = parsedMessage["messageType"] as? String
|
||||
if (messageType == null) {
|
||||
println("Recieved message without type: $text")
|
||||
return@launch
|
||||
}
|
||||
val data = parsedMessage["data"] as Map<*, *>
|
||||
|
||||
fun respond(responseData: Any?) {
|
||||
if (data["messageId"] == null) {
|
||||
println("Recieved message without messageId: $text")
|
||||
return
|
||||
}
|
||||
send(messageType, responseData ?: emptyMap<String, String>(), data["messageId"] as String);
|
||||
}
|
||||
val data = parsedMessage["data"]
|
||||
|
||||
val historyManager = HistoryManager()
|
||||
|
||||
|
|
@ -175,7 +147,7 @@ class IdeProtocolClient (
|
|||
mapOf("uniqueId" to uniqueId())
|
||||
)
|
||||
|
||||
"ide" -> {
|
||||
"getIdeInfo" -> {
|
||||
val applicationInfo = ApplicationInfo.getInstance()
|
||||
val ideName: String = applicationInfo.fullApplicationName
|
||||
val ideVersion = applicationInfo.fullVersion
|
||||
|
|
@ -187,14 +159,19 @@ class IdeProtocolClient (
|
|||
remoteName = "ssh"
|
||||
}
|
||||
respond(mapOf(
|
||||
"ideType" to "jetbrains",
|
||||
"name" to ideName,
|
||||
"version" to ideVersion,
|
||||
"remoteName" to remoteName
|
||||
))
|
||||
}
|
||||
|
||||
"getUniqueId" -> {
|
||||
respond(uniqueId())
|
||||
}
|
||||
|
||||
"showDiff" -> {
|
||||
val data = data["message"] as Map<String, Any>
|
||||
val data = data as Map<String, Any>
|
||||
diffManager.showDiff(
|
||||
data["filepath"] as String,
|
||||
data["newContents"] as String,
|
||||
|
|
@ -204,10 +181,31 @@ class IdeProtocolClient (
|
|||
}
|
||||
|
||||
"readFile" -> {
|
||||
val msg = readFile((data["message"] as Map<String, String>)["filepath"] as String)
|
||||
val msg = readFile((data as Map<String, String>)["filepath"] as String)
|
||||
respond(msg)
|
||||
}
|
||||
|
||||
"isTelemetryEnabled" -> {
|
||||
respond(true)
|
||||
}
|
||||
|
||||
"readRangeInFile" -> {
|
||||
val fullContents = readFile((data as Map<String, String>)["filepath"] as String)
|
||||
val range = data["range"] as Map<String, Any>
|
||||
val start = range["start"] as Map<String, Any>
|
||||
val end = range["end"] as Map<String, Any>
|
||||
val startLine = start["line"] as Int
|
||||
val startCharacter = start["character"] as Int
|
||||
val endLine = end["line"] as Int
|
||||
val endCharacter = end["character"] as Int
|
||||
|
||||
val firstLine = fullContents.split("\n")[startLine].slice(startCharacter until fullContents.split("\n")[startLine].length)
|
||||
val lastLine = fullContents.split("\n")[endLine].slice(0 until endCharacter)
|
||||
val between = fullContents.split("\n").slice(startLine + 1 until endLine).joinToString("\n")
|
||||
|
||||
respond(firstLine + "\n" + between + "\n" + lastLine)
|
||||
}
|
||||
|
||||
"listWorkspaceContents" -> {
|
||||
respond(listDirectoryContents(null))
|
||||
}
|
||||
|
|
@ -216,6 +214,10 @@ class IdeProtocolClient (
|
|||
respond(workspaceDirectories())
|
||||
}
|
||||
|
||||
"getWorkspaceConfigs" -> {
|
||||
respond(emptyList<String>())
|
||||
}
|
||||
|
||||
"getTerminalContents" -> {
|
||||
respond(
|
||||
mapOf("contents" to "Terminal cannot be accessed in JetBrains IDE")
|
||||
|
|
@ -229,10 +231,11 @@ class IdeProtocolClient (
|
|||
}
|
||||
|
||||
"saveFile" -> {
|
||||
saveFile((data["message"] as Map<String, String>)["filepath"] ?: throw Exception("No filepath provided"))
|
||||
saveFile((data as Map<String, String>)["filepath"] ?: throw Exception("No filepath provided"))
|
||||
respond(null)
|
||||
}
|
||||
"showVirtualFile" -> {
|
||||
val data = data as Map<String, Any>
|
||||
showVirtualFile(
|
||||
data["name"] as String,
|
||||
data["contents"] as String
|
||||
|
|
@ -242,10 +245,11 @@ class IdeProtocolClient (
|
|||
|
||||
"connected" -> {}
|
||||
"showMessage" -> {
|
||||
showMessage(data["message"] as String)
|
||||
showMessage(data as String)
|
||||
respond(null)
|
||||
}
|
||||
"setFileOpen" -> {
|
||||
val data = data as Map<String, Any>
|
||||
setFileOpen(
|
||||
data["filepath"] as String,
|
||||
data["open"] as Boolean
|
||||
|
|
@ -253,8 +257,27 @@ class IdeProtocolClient (
|
|||
respond(null)
|
||||
}
|
||||
|
||||
"showLines" -> {
|
||||
val data = data as Map<String, Any>
|
||||
val filepath = data["filepath"] as String
|
||||
val startLine = data["startLine"] as Int
|
||||
val endLine = data["endLine"] as Int
|
||||
highlightCode(
|
||||
RangeInFile(
|
||||
filepath,
|
||||
Range(
|
||||
Position(startLine, 0),
|
||||
Position(endLine, 0)
|
||||
)
|
||||
),
|
||||
data["color"] as String
|
||||
)
|
||||
respond(null)
|
||||
}
|
||||
|
||||
"highlightCode" -> {
|
||||
val gson = Gson()
|
||||
val data = data as Map<String, Any>
|
||||
val json = gson.toJson(data["rangeInFile"])
|
||||
val type = object : TypeToken<RangeInFile>() {}.type
|
||||
val rangeInFile =
|
||||
|
|
@ -265,16 +288,6 @@ class IdeProtocolClient (
|
|||
|
||||
"setSuggestionsLocked" -> {}
|
||||
"getSessionId" -> {}
|
||||
"highlightedCode" -> {
|
||||
val rifWithContents = getHighlightedCode()
|
||||
val rifs: MutableList<RangeInFile> = mutableListOf()
|
||||
if (rifWithContents != null) {
|
||||
val rif = RangeInFile(rifWithContents.filepath, rifWithContents.range)
|
||||
rifs += rif
|
||||
}
|
||||
respond(mapOf("highlightedCode" to rifs))
|
||||
}
|
||||
|
||||
|
||||
// NEW //
|
||||
"getDiff" -> {
|
||||
|
|
@ -295,29 +308,6 @@ class IdeProtocolClient (
|
|||
|
||||
respond(output.toString());
|
||||
}
|
||||
"getSerializedConfig" -> {
|
||||
val configPath = getConfigJsonPath()
|
||||
var config = File(configPath).readText()
|
||||
|
||||
migrate("camelCaseConfig") {
|
||||
if (config.contains("_")) {
|
||||
config = config
|
||||
.replace(Regex("(_\\w)")) { it.value[1].uppercase() }
|
||||
.replace("openai-aiohttp", "openai")
|
||||
// Rewrite to config.json
|
||||
File(configPath).writeText(config)
|
||||
}
|
||||
}
|
||||
|
||||
migrate("renameFreeTrialProvider") {
|
||||
config = config.replace("openai-free-trial", "free-trial");
|
||||
File(configPath).writeText(config)
|
||||
}
|
||||
|
||||
val mapType = object : TypeToken<Map<String, Any>>() {}.type
|
||||
val parsed: Map<String, Any> = Gson().fromJson(config, mapType)
|
||||
respond(parsed)
|
||||
}
|
||||
"getConfigJsUrl" -> {
|
||||
// Calculate a data URL for the config.js file
|
||||
val configJsPath = getConfigJsPath()
|
||||
|
|
@ -326,7 +316,7 @@ class IdeProtocolClient (
|
|||
respond(configJsDataUrl)
|
||||
}
|
||||
"writeFile" -> {
|
||||
val msg = data["message"] as Map<String, String>;
|
||||
val msg = data as Map<String, String>;
|
||||
val file = File(msg["path"])
|
||||
file.writeText(msg["contents"] as String)
|
||||
respond(null);
|
||||
|
|
@ -335,7 +325,7 @@ class IdeProtocolClient (
|
|||
respond(getContinueGlobalPath())
|
||||
}
|
||||
"openFile" -> {
|
||||
setFileOpen((data["message"] as Map<String, Any>)["path"] as String)
|
||||
setFileOpen((data as Map<String, Any>)["path"] as String)
|
||||
respond(null)
|
||||
}
|
||||
"runCommand" -> {
|
||||
|
|
@ -343,7 +333,14 @@ class IdeProtocolClient (
|
|||
// Running commands not yet supported in JetBrains
|
||||
}
|
||||
"errorPopup" -> {
|
||||
showMessage(data["message"] as String)
|
||||
val data = data as Map<String, Any>
|
||||
val message = data["message"] as String
|
||||
showMessage(message)
|
||||
respond(null)
|
||||
}
|
||||
|
||||
"listFolders" -> {
|
||||
respond(null)
|
||||
}
|
||||
|
||||
// History
|
||||
|
|
@ -351,15 +348,15 @@ class IdeProtocolClient (
|
|||
respond(historyManager.list());
|
||||
}
|
||||
"saveSession" -> {
|
||||
historyManager.save(data["message"] as PersistedSessionInfo);
|
||||
historyManager.save(data as PersistedSessionInfo);
|
||||
respond(null);
|
||||
}
|
||||
"deleteSession" -> {
|
||||
historyManager.delete(data["message"] as String);
|
||||
historyManager.delete(data as String);
|
||||
respond(null);
|
||||
}
|
||||
"loadSession" -> {
|
||||
val session = historyManager.load(data["message"] as String)
|
||||
val session = historyManager.load(data as String)
|
||||
respond(session)
|
||||
}
|
||||
"getSearchResults" -> {
|
||||
|
|
@ -371,7 +368,12 @@ class IdeProtocolClient (
|
|||
val openFiles = visibleFiles()
|
||||
respond(openFiles)
|
||||
}
|
||||
"getPinnedFiles" -> {
|
||||
val openFiles = visibleFiles()
|
||||
respond(openFiles)
|
||||
}
|
||||
"logDevData" -> {
|
||||
val data = data as Map<String, Any>
|
||||
val filename = data["tableName"] as String
|
||||
val jsonLine = data["data"]
|
||||
val filepath = getDevDataFilepath(filename)
|
||||
|
|
@ -379,6 +381,7 @@ class IdeProtocolClient (
|
|||
File(filepath).appendText(contents)
|
||||
}
|
||||
"addModel" -> {
|
||||
val data = data as Map<String, Any>
|
||||
val model = data["model"] as Map<String, Any>
|
||||
val updatedConfig = editConfigJson {
|
||||
val models = it["models"] as MutableList<Map<String, Any>>
|
||||
|
|
@ -392,7 +395,7 @@ class IdeProtocolClient (
|
|||
"deleteModel" -> {
|
||||
val configJson = editConfigJson { config ->
|
||||
var models: MutableList<Map<String, Any>> = config["models"] as MutableList<Map<String, Any>>
|
||||
|
||||
val data = data as Map<String, Any>
|
||||
val model = data["title"] as String
|
||||
models = models.filter { it["title"] != model }.toMutableList()
|
||||
config["models"] = models
|
||||
|
|
@ -402,6 +405,7 @@ class IdeProtocolClient (
|
|||
}
|
||||
"addOpenAIKey" -> {
|
||||
val updatedConfig = editConfigJson { config ->
|
||||
val data = data as Map<String, Any>
|
||||
val key = data["key"] as String
|
||||
var models = config["models"] as MutableList<MutableMap<String, Any>>
|
||||
models = models.map {
|
||||
|
|
@ -432,12 +436,8 @@ class IdeProtocolClient (
|
|||
}
|
||||
|
||||
fun configUpdate(config: Map<String, Any>) {
|
||||
val data = mapOf(
|
||||
"type" to "configUpdate",
|
||||
"config" to config
|
||||
)
|
||||
val json = Gson().toJson(data)
|
||||
continuePluginService.dispatchCustomEvent(json)
|
||||
continuePluginService.coreMessenger?.request("config/reload", null, null) { _ -> }
|
||||
continuePluginService.sendToWebview("configUpdate", config)
|
||||
}
|
||||
|
||||
private fun editConfigJson(callback: (config: MutableMap<String, Any>) -> Map<String, Any>): Map<String, Any> {
|
||||
|
|
@ -581,20 +581,17 @@ class IdeProtocolClient (
|
|||
// edit
|
||||
// ))
|
||||
|
||||
continuePluginService.dispatchCustomEvent(
|
||||
Gson().toJson(mapOf(
|
||||
"type" to "highlightedCode",
|
||||
continuePluginService.sendToWebview(
|
||||
"highlightedCode",
|
||||
mapOf(
|
||||
"rangeInFileWithContents" to rif,
|
||||
"edit" to edit
|
||||
)))
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
fun sendMainUserInput(input: String) {
|
||||
val data = mapOf(
|
||||
"type" to "userInput",
|
||||
"input" to input,
|
||||
)
|
||||
continuePluginService.dispatchCustomEvent(Gson().toJson(data))
|
||||
continuePluginService.sendToWebview("userInput", mapOf("input" to input))
|
||||
}
|
||||
|
||||
fun sendAcceptRejectDiff(accepted: Boolean, stepIndex: Int) {
|
||||
|
|
@ -712,7 +709,7 @@ class IdeProtocolClient (
|
|||
return fileEditorManager.openFiles.toList().map { it.path }
|
||||
}
|
||||
|
||||
private fun showMessage(msg: String) {
|
||||
fun showMessage(msg: String) {
|
||||
val statusBar = WindowManager.getInstance().getStatusBar(project)
|
||||
|
||||
JBPopupFactory.getInstance()
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ class CustomResourceHandler : CefResourceHandler, DumbAware {
|
|||
): Boolean {
|
||||
val url = cefRequest.url
|
||||
return if (url != null) {
|
||||
val pathToResource = url.replace("http://continue", "webview/")
|
||||
val pathToResource = url.replace("http://continue", "webview/").replace("http://localhost:5173", "webview/")
|
||||
val newUrl = javaClass.classLoader.getResource(pathToResource)
|
||||
state = OpenedConnection(newUrl?.openConnection())
|
||||
currentUrl = url
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
package com.github.continuedev.continueintellijextension.services
|
||||
|
||||
import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger
|
||||
import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient
|
||||
import com.github.continuedev.continueintellijextension.`continue`.uuid
|
||||
import com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory
|
||||
import com.google.gson.Gson
|
||||
import com.intellij.openapi.Disposable
|
||||
|
|
@ -20,6 +22,7 @@ class ContinuePluginService(project: Project) : Disposable, DumbAware {
|
|||
var continuePluginWindow: ContinuePluginToolWindowFactory.ContinuePluginWindow? = null
|
||||
|
||||
var ideProtocolClient: IdeProtocolClient? = null
|
||||
var coreMessenger: CoreMessenger? = null
|
||||
var workspacePaths: Array<String>? = null
|
||||
var windowId: String = UUID.randomUUID().toString()
|
||||
|
||||
|
|
@ -33,10 +36,19 @@ class ContinuePluginService(project: Project) : Disposable, DumbAware {
|
|||
}
|
||||
}
|
||||
|
||||
fun dispatchCustomEvent(
|
||||
data: String
|
||||
fun sendToWebview(
|
||||
messageType: String,
|
||||
data: Any?,
|
||||
messageId: String = uuid()
|
||||
) {
|
||||
val jsCode = buildJavaScript(data)
|
||||
val jsonData = Gson().toJson(
|
||||
mapOf(
|
||||
"messageId" to messageId,
|
||||
"messageType" to messageType,
|
||||
"data" to data
|
||||
)
|
||||
)
|
||||
val jsCode = buildJavaScript(jsonData)
|
||||
|
||||
try {
|
||||
continuePluginWindow?.webView?.executeJavaScriptAsync(jsCode)
|
||||
|
|
|
|||
|
|
@ -1,10 +1,8 @@
|
|||
package com.github.continuedev.continueintellijextension.toolWindow
|
||||
|
||||
import com.github.continuedev.continueintellijextension.activities.showTutorial
|
||||
import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
|
||||
import com.github.continuedev.continueintellijextension.`continue`.Position
|
||||
import com.github.continuedev.continueintellijextension.`continue`.Range
|
||||
import com.github.continuedev.continueintellijextension.`continue`.RangeInFile
|
||||
import com.github.continuedev.continueintellijextension.`continue`.getMachineUniqueID
|
||||
import com.github.continuedev.continueintellijextension.`continue`.*
|
||||
import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.google.gson.Gson
|
||||
|
|
@ -55,12 +53,34 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
|
|||
|
||||
class ContinuePluginWindow(toolWindow: ToolWindow, project: Project) {
|
||||
|
||||
val PASS_THROUGH_TO_CORE = listOf(
|
||||
"abort",
|
||||
"getContinueDir",
|
||||
"history/list",
|
||||
"history/save",
|
||||
"history/delete",
|
||||
"history/load",
|
||||
"devdata/log",
|
||||
"config/addModel",
|
||||
"config/deleteModel",
|
||||
"config/addOpenAIKey",
|
||||
"llm/streamComplete",
|
||||
"llm/streamChat",
|
||||
"llm/complete",
|
||||
"command/run",
|
||||
"context/loadSubmenuItems",
|
||||
"context/getContextItems",
|
||||
"context/addDocs",
|
||||
"config/getBrowserSerialized",
|
||||
)
|
||||
|
||||
init {
|
||||
System.setProperty("ide.browser.jcef.jsQueryPoolSize", JS_QUERY_POOL_SIZE)
|
||||
System.setProperty("ide.browser.jcef.osr.enabled", "false")
|
||||
}
|
||||
|
||||
val webView: JBCefBrowser by lazy {
|
||||
val browser = JBCefBrowser()
|
||||
val browser = JBCefBrowser.createBuilder().setOffScreenRendering(false).build()
|
||||
browser.jbCefClient.setProperty(
|
||||
JBCefClient.Properties.JS_QUERY_POOL_SIZE,
|
||||
JS_QUERY_POOL_SIZE
|
||||
|
|
@ -68,6 +88,8 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
|
|||
registerAppSchemeHandler()
|
||||
|
||||
browser.loadURL("http://continue/index.html")
|
||||
// browser.loadHTML("<html><body><input type='text'/></body></html>")
|
||||
// browser.loadURL("http://localhost:5173/index.html")
|
||||
Disposer.register(project, browser)
|
||||
|
||||
val continuePluginService = ServiceManager.getService(
|
||||
|
|
@ -81,58 +103,46 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
|
|||
myJSQueryOpenInBrowser.addHandler { msg: String? ->
|
||||
val parser = JsonParser()
|
||||
val json: JsonObject = parser.parse(msg).asJsonObject
|
||||
val type = json.get("type").asString
|
||||
val data = json.get("data").asJsonObject
|
||||
val messageType = json.get("messageType").asString
|
||||
val data = json.get("data")
|
||||
val messageId = json.get("messageId")?.asString
|
||||
|
||||
val ide = continuePluginService.ideProtocolClient;
|
||||
|
||||
when (type) {
|
||||
val respond = fun(data: Any?) {
|
||||
val jsonData = mutableMapOf(
|
||||
"messageId" to messageId,
|
||||
"data" to data,
|
||||
"messageType" to messageType
|
||||
)
|
||||
val jsonString = Gson().toJson(jsonData)
|
||||
continuePluginService.sendToWebview(messageType, data, messageId ?: uuid())
|
||||
}
|
||||
|
||||
if (PASS_THROUGH_TO_CORE.contains(messageType)) {
|
||||
continuePluginService.coreMessenger?.request(messageType, data, messageId, respond)
|
||||
return@addHandler null
|
||||
}
|
||||
|
||||
when (messageType) {
|
||||
"onLoad" -> {
|
||||
GlobalScope.launch {
|
||||
// Set the colors to match Intellij theme
|
||||
val globalScheme = EditorColorsManager.getInstance().globalScheme
|
||||
val defaultBackground = globalScheme.defaultBackground
|
||||
val defaultForeground = globalScheme.defaultForeground
|
||||
val defaultBackgroundHex = String.format("#%02x%02x%02x", defaultBackground.red, defaultBackground.green, defaultBackground.blue)
|
||||
val defaultForegroundHex = String.format("#%02x%02x%02x", defaultForeground.red, defaultForeground.green, defaultForeground.blue)
|
||||
|
||||
val grayscale = (defaultBackground.red * 0.3 + defaultBackground.green * 0.59 + defaultBackground.blue * 0.11).toInt()
|
||||
|
||||
val adjustedRed: Int
|
||||
val adjustedGreen: Int
|
||||
val adjustedBlue: Int
|
||||
|
||||
val tint: Int = 20
|
||||
if (grayscale > 128) { // if closer to white
|
||||
adjustedRed = max(0, defaultBackground.red - tint)
|
||||
adjustedGreen = max(0, defaultBackground.green - tint)
|
||||
adjustedBlue = max(0, defaultBackground.blue - tint)
|
||||
} else { // if closer to black
|
||||
adjustedRed = min(255, defaultBackground.red + tint)
|
||||
adjustedGreen = min(255, defaultBackground.green + tint)
|
||||
adjustedBlue = min(255, defaultBackground.blue + tint)
|
||||
}
|
||||
|
||||
val secondaryDarkHex = String.format("#%02x%02x%02x", adjustedRed, adjustedGreen, adjustedBlue)
|
||||
|
||||
browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-editor-foreground\", \"$defaultForegroundHex\");")
|
||||
browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-sideBar-background\", \"$defaultBackgroundHex\");")
|
||||
browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-input-background\", \"$secondaryDarkHex\");")
|
||||
browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-editor-background\", \"$defaultBackgroundHex\");")
|
||||
val colors = GetTheme().getTheme();
|
||||
continuePluginService.sendToWebview("setColors", colors)
|
||||
|
||||
val jsonData = mutableMapOf(
|
||||
"type" to "onLoad",
|
||||
"windowId" to continuePluginService.windowId,
|
||||
"workspacePaths" to continuePluginService.workspacePaths,
|
||||
"vscMachineId" to getMachineUniqueID(),
|
||||
"vscMediaUrl" to "http://continue",
|
||||
)
|
||||
val jsonString = Gson().toJson(jsonData)
|
||||
browser.executeJavaScriptAsync("""window.postMessage($jsonString, "*");""")
|
||||
respond(jsonData)
|
||||
}
|
||||
|
||||
}
|
||||
"showLines" -> {
|
||||
val data = data.asJsonObject
|
||||
ide?.highlightCode(RangeInFile(
|
||||
data.get("filepath").asString,
|
||||
Range(Position(
|
||||
|
|
@ -145,10 +155,15 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
|
|||
|
||||
),"#00ff0022")
|
||||
}
|
||||
"showTutorial" -> {
|
||||
showTutorial(project)
|
||||
}
|
||||
"showVirtualFile" -> {
|
||||
val data = data.asJsonObject
|
||||
ide?.showVirtualFile(data.get("name").asString, data.get("content").asString)
|
||||
}
|
||||
"showFile" -> {
|
||||
val data = data.asJsonObject
|
||||
ide?.setFileOpen(data.get("filepath").asString)
|
||||
}
|
||||
"reloadWindow" -> {}
|
||||
|
|
@ -156,6 +171,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
|
|||
ide?.setFileOpen(getConfigJsonPath())
|
||||
}
|
||||
"readRangeInFile" -> {
|
||||
val data = data.asJsonObject
|
||||
ide?.readRangeInFile(RangeInFile(
|
||||
data.get("filepath").asString,
|
||||
Range(Position(
|
||||
|
|
@ -172,7 +188,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
|
|||
// IDE //
|
||||
else -> {
|
||||
if (msg != null) {
|
||||
ide?.handleWebsocketMessage(msg)
|
||||
ide?.handleMessage(msg, respond)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -201,8 +217,8 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
|
|||
|
||||
fun executeJavaScript(browser: CefBrowser?, myJSQueryOpenInBrowser: JBCefJSQuery) {
|
||||
// Execute JavaScript - you might want to handle potential exceptions here
|
||||
val script = """window.postIntellijMessage = function(type, data) {
|
||||
const msg = JSON.stringify({type, data});
|
||||
val script = """window.postIntellijMessage = function(messageType, data, messageId) {
|
||||
const msg = JSON.stringify({messageType, data, messageId});
|
||||
${myJSQueryOpenInBrowser.inject("msg")}
|
||||
}""".trimIndent()
|
||||
|
||||
|
|
|
|||
|
|
@ -6,6 +6,10 @@
|
|||
<depends>com.intellij.modules.platform</depends>
|
||||
<idea-version since-build="223.0"/>
|
||||
|
||||
<extensions defaultExtensionNs="JavaScript.JsonSchema">
|
||||
<ProviderFactory implementation="com.github.continuedev.continueintellijextension.continue.ConfigJsonSchemaProviderFactory"/>
|
||||
</extensions>
|
||||
|
||||
<extensions defaultExtensionNs="com.intellij">
|
||||
<toolWindow id="Continue" anchor="right" icon="/tool-window-icon.png"
|
||||
factoryClass="com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory"/>
|
||||
|
|
|
|||
1580
extensions/intellij/src/main/resources/config_schema.json
Normal file
1580
extensions/intellij/src/main/resources/config_schema.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1029,7 +1029,8 @@
|
|||
"docs",
|
||||
"tree",
|
||||
"highlights",
|
||||
"outline"
|
||||
"outline",
|
||||
"postgres"
|
||||
],
|
||||
"markdownEnumDescriptions": [
|
||||
"Reference the contents of the current changes as given by `git diff`",
|
||||
|
|
@ -1047,7 +1048,8 @@
|
|||
"Display a file tree of the current workspace",
|
||||
"Include a repo map showing important code objects",
|
||||
"Displays important snippets of code from the currently open files",
|
||||
"Displays definition lines from the currently open files"
|
||||
"Displays definition lines from the currently open files",
|
||||
"References Postgres table schema and sample rows"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -1154,6 +1156,67 @@
|
|||
"required": ["params"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["database"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"connections": {
|
||||
"type": "array",
|
||||
"description": "A list of database connections",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "A unique name for this database connection"
|
||||
},
|
||||
"connection_type": {
|
||||
"type": "string",
|
||||
"description": "The type of database (e.g., 'postgres', 'mysql')",
|
||||
"enum": ["postgres", "mysql", "sqlite"]
|
||||
},
|
||||
"connection": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"user": {
|
||||
"type": "string",
|
||||
"description": "The database user name"
|
||||
},
|
||||
"host": {
|
||||
"type": "string",
|
||||
"description": "The host address of the database server"
|
||||
},
|
||||
"database": {
|
||||
"type": "string",
|
||||
"description": "The name of the database to connect to"
|
||||
},
|
||||
"password": {
|
||||
"type": "string",
|
||||
"description": "The password for the database user"
|
||||
},
|
||||
"port": {
|
||||
"type": "integer",
|
||||
"description": "The port number to connect to at the host"
|
||||
},
|
||||
"filename": {
|
||||
"type": "string",
|
||||
"description": "File location for simple file DB's"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
},
|
||||
"required": ["name", "type", "connection"]
|
||||
}
|
||||
},
|
||||
"required": ["connections"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
|
|
@ -1246,6 +1309,65 @@
|
|||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["postgres"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"params": {
|
||||
"properties": {
|
||||
"host": {
|
||||
"title": "Host",
|
||||
"description": "Database host",
|
||||
"default": "localhost",
|
||||
"type": "string"
|
||||
},
|
||||
"port": {
|
||||
"title": "Port",
|
||||
"description": "Database port",
|
||||
"default": 5432,
|
||||
"type": "integer"
|
||||
},
|
||||
"user": {
|
||||
"title": "User",
|
||||
"description": "Database user",
|
||||
"default": "postgres",
|
||||
"type": "string"
|
||||
},
|
||||
"password": {
|
||||
"title": "Password",
|
||||
"description": "Database password",
|
||||
"type": "string"
|
||||
},
|
||||
"database": {
|
||||
"title": "Database",
|
||||
"description": "Database name",
|
||||
"default": "postgres",
|
||||
"type": "string"
|
||||
},
|
||||
"schema": {
|
||||
"title": "Schema",
|
||||
"description": "Database schema",
|
||||
"default": "public",
|
||||
"type": "string"
|
||||
},
|
||||
"sampleRows": {
|
||||
"title": "Sample Rows",
|
||||
"description": "Number of rows to sample from the database",
|
||||
"default": 3,
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["host", "port", "user", "password", "database"]
|
||||
}
|
||||
}
|
||||
],
|
||||
"required": ["name"]
|
||||
|
|
@ -1437,9 +1559,17 @@
|
|||
"type": "string",
|
||||
"description": "An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables."
|
||||
},
|
||||
"disableMultiLineCompletions": {
|
||||
"type": "boolean",
|
||||
"multilineCompletions": {
|
||||
"enum": ["always", "never", "auto"],
|
||||
"description": "If set to true, Continue will only complete a single line at a time."
|
||||
},
|
||||
"useCache": {
|
||||
"type": "boolean",
|
||||
"description": "Whether to cache completions"
|
||||
},
|
||||
"onlyMyCode": {
|
||||
"type": "boolean",
|
||||
"description": "If set to true, Continue will not include any snippets from go to definition unless they are within your repository"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
|
|
|
|||
|
|
@ -1148,7 +1148,8 @@
|
|||
"docs",
|
||||
"tree",
|
||||
"highlights",
|
||||
"outline"
|
||||
"outline",
|
||||
"postgres"
|
||||
],
|
||||
"markdownEnumDescriptions": [
|
||||
"Reference the contents of the current changes as given by `git diff`",
|
||||
|
|
@ -1166,7 +1167,8 @@
|
|||
"Display a file tree of the current workspace",
|
||||
"Include a repo map showing important code objects",
|
||||
"Displays important snippets of code from the currently open files",
|
||||
"Displays definition lines from the currently open files"
|
||||
"Displays definition lines from the currently open files",
|
||||
"References Postgres table schema and sample rows"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -1294,6 +1296,79 @@
|
|||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": [
|
||||
"database"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"connections": {
|
||||
"type": "array",
|
||||
"description": "A list of database connections",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "A unique name for this database connection"
|
||||
},
|
||||
"connection_type": {
|
||||
"type": "string",
|
||||
"description": "The type of database (e.g., 'postgres', 'mysql')",
|
||||
"enum": [
|
||||
"postgres",
|
||||
"mysql",
|
||||
"sqlite"
|
||||
]
|
||||
},
|
||||
"connection": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"user": {
|
||||
"type": "string",
|
||||
"description": "The database user name"
|
||||
},
|
||||
"host": {
|
||||
"type": "string",
|
||||
"description": "The host address of the database server"
|
||||
},
|
||||
"database": {
|
||||
"type": "string",
|
||||
"description": "The name of the database to connect to"
|
||||
},
|
||||
"password": {
|
||||
"type": "string",
|
||||
"description": "The password for the database user"
|
||||
},
|
||||
"port": {
|
||||
"type": "integer",
|
||||
"description": "The port number to connect to at the host"
|
||||
},
|
||||
"filename": {
|
||||
"type": "string",
|
||||
"description": "File location for simple file DB's"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"type",
|
||||
"connection"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"connections"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
|
|
@ -1403,6 +1478,73 @@
|
|||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": [
|
||||
"postgres"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"params": {
|
||||
"properties": {
|
||||
"host": {
|
||||
"title": "Host",
|
||||
"description": "Database host",
|
||||
"default": "localhost",
|
||||
"type": "string"
|
||||
},
|
||||
"port": {
|
||||
"title": "Port",
|
||||
"description": "Database port",
|
||||
"default": 5432,
|
||||
"type": "integer"
|
||||
},
|
||||
"user": {
|
||||
"title": "User",
|
||||
"description": "Database user",
|
||||
"default": "postgres",
|
||||
"type": "string"
|
||||
},
|
||||
"password": {
|
||||
"title": "Password",
|
||||
"description": "Database password",
|
||||
"type": "string"
|
||||
},
|
||||
"database": {
|
||||
"title": "Database",
|
||||
"description": "Database name",
|
||||
"default": "postgres",
|
||||
"type": "string"
|
||||
},
|
||||
"schema": {
|
||||
"title": "Schema",
|
||||
"description": "Database schema",
|
||||
"default": "public",
|
||||
"type": "string"
|
||||
},
|
||||
"sampleRows": {
|
||||
"title": "Sample Rows",
|
||||
"description": "Number of rows to sample from the database",
|
||||
"default": 3,
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"host",
|
||||
"port",
|
||||
"user",
|
||||
"password",
|
||||
"database"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"required": [
|
||||
|
|
@ -1608,9 +1750,21 @@
|
|||
"type": "string",
|
||||
"description": "An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables."
|
||||
},
|
||||
"disableMultiLineCompletions": {
|
||||
"type": "boolean",
|
||||
"multilineCompletions": {
|
||||
"enum": [
|
||||
"always",
|
||||
"never",
|
||||
"auto"
|
||||
],
|
||||
"description": "If set to true, Continue will only complete a single line at a time."
|
||||
},
|
||||
"useCache": {
|
||||
"type": "boolean",
|
||||
"description": "Whether to cache completions"
|
||||
},
|
||||
"onlyMyCode": {
|
||||
"type": "boolean",
|
||||
"description": "If set to true, Continue will not include any snippets from go to definition unless they are within your repository"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
|
|
|
|||
|
|
@ -1,25 +1,18 @@
|
|||
"""
|
||||
Welcome to Continue!
|
||||
|
||||
_________ _____ _____
|
||||
__ ____/______ _______ __ /____(_)_______ ____ _______
|
||||
_ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \
|
||||
/ /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/
|
||||
\____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/
|
||||
|
||||
This is a 2 minute tutorial.
|
||||
|
||||
It will walk you through the basic features:
|
||||
1. Ask a question
|
||||
2. Edit code
|
||||
3. Debug
|
||||
Welcome to Continue! This is a 2 minute tutorial.
|
||||
|
||||
You can either
|
||||
- follow the instructions on your own, or
|
||||
- follow along by clicking the gray CodeLens buttons above the lines, in order, starting with "Begin Section"
|
||||
"""
|
||||
|
||||
# region —————————————————————————— Part 1: Ask a question about code [⌘ M] ——————————————————————————
|
||||
# region —————————————————————————— Part 1: Ask a question about code [⌘ L] ——————————————————————————
|
||||
|
||||
|
||||
"""Step 1: Highlight the function below"""
|
||||
|
|
@ -34,14 +27,14 @@ def mysterious_function(x):
|
|||
return x
|
||||
|
||||
|
||||
"""Step 2: Use the keyboard shortcut [⌘ M] to
|
||||
"""Step 2: Use the keyboard shortcut [⌘ L] to
|
||||
select the code and toggle the Continue input box"""
|
||||
|
||||
"""Step 3: Ask a question and press Enter"""
|
||||
|
||||
# endregion
|
||||
|
||||
# region ————————————————————————————————— Part 2: Edit code [⌘ ⇧ L] —————————————————————————————————
|
||||
# region ————————————————————————————————— Part 2: Edit code [⌘ I] —————————————————————————————————
|
||||
|
||||
|
||||
"""Step 1: Highlight this code"""
|
||||
|
|
@ -60,7 +53,7 @@ def mysterious_function(x):
|
|||
return x
|
||||
|
||||
|
||||
"""Step 2: Use the keyboard shortcut [⌘ ⇧ L] to edit"""
|
||||
"""Step 2: Use the keyboard shortcut [⌘ I] to edit"""
|
||||
|
||||
"""Step 3: Type "<your edit request>" and press Enter"""
|
||||
|
||||
|
|
@ -72,7 +65,7 @@ accept [⌘ ⇧ ⏎] or reject [⌘ ⇧ ⌫] the edit"""
|
|||
# region ———————————————————————————— Part 3: Debug automatically [⌘ ⇧ R] ————————————————————————————
|
||||
|
||||
|
||||
"""Step 1: Run this Python file"""
|
||||
"""Step 1: Run this Python file (it should error!)"""
|
||||
|
||||
|
||||
def print_sum(list_to_print):
|
||||
|
|
|
|||
|
|
@ -1,25 +1,29 @@
|
|||
# 👋 Welcome to Continue
|
||||
|
||||
## 🔑 Most important shortcuts
|
||||
|
||||
> If you've been using Continue, these have changed. You can always customize them in VS Code settings.
|
||||
|
||||
<kbd>Cmd/Ctrl</kbd> + <kbd>L</kbd> = Select code
|
||||
|
||||
<kbd>Cmd/Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>L</kbd> = Select code for follow-up
|
||||
|
||||
<kbd>Cmd/Ctrl</kbd> + <kbd>I</kbd> = Quick edit
|
||||
|
||||
<kbd>Cmd/Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>R</kbd> = Automatically debug terminal
|
||||
|
||||
## ❗️ Before you get started
|
||||
|
||||
Continue is currently in the left sidebar, but we recommend moving it to the right. This way it won't cover your file explorer. You can move it back at any time.
|
||||
|
||||

|
||||
|
||||
## 🔑 Most important shortcuts
|
||||
|
||||
<kbd>Cmd/Ctrl</kbd> + <kbd>M</kbd> = Select code
|
||||
|
||||
<kbd>Cmd/Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>M</kbd> = Select code for follow-up
|
||||
|
||||
<kbd>Cmd/Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>L</kbd> = Quick edit
|
||||
|
||||
<kbd>Cmd/Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>R</kbd> = Automatically debug terminal
|
||||
|
||||
## ⚡️ Setting up tab autocomplete
|
||||
|
||||
1. Download [Ollama](https://ollama.ai)
|
||||
2. Download starcoder:3b by running `ollama run starcoder:3b` in the terminal
|
||||
3. Click the `Continue` button in the status bar (bottom right of the VS Code window) to enable autocomplete
|
||||
3. That's it! You can disable autocomplete at any time by clicking the `Continue` button in the status bar (bottom right of the VS Code window)
|
||||
|
||||
> Learn how to customize your autocomplete experience in [our walkthrough](https://continue.dev/docs/walkthroughs/tab-autocomplete)
|
||||
|
||||

|
||||
|
|
|
|||
594
extensions/vscode/package-lock.json
generated
594
extensions/vscode/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "continue",
|
||||
"version": "0.9.72",
|
||||
"version": "0.9.77",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "continue",
|
||||
"version": "0.9.72",
|
||||
"version": "0.9.77",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@electron/rebuild": "^3.2.10",
|
||||
|
|
@ -18,6 +18,7 @@
|
|||
"axios": "^1.2.5",
|
||||
"core": "file:../../core",
|
||||
"cors": "^2.8.5",
|
||||
"dbinfoz": "^0.1.4",
|
||||
"downshift": "^7.6.0",
|
||||
"express": "^4.18.2",
|
||||
"fkill": "^8.1.0",
|
||||
|
|
@ -91,15 +92,21 @@
|
|||
"adf-to-md": "^1.1.0",
|
||||
"axios": "^1.6.7",
|
||||
"cheerio": "^1.0.0-rc.12",
|
||||
"commander": "^12.0.0",
|
||||
"dbinfoz": "^0.1.4",
|
||||
"dotenv": "^16.3.1",
|
||||
"fastest-levenshtein": "^1.0.16",
|
||||
"follow-redirects": "^1.15.5",
|
||||
"handlebars": "^4.7.8",
|
||||
"http-proxy-agent": "^7.0.1",
|
||||
"https-proxy-agent": "^7.0.3",
|
||||
"js-tiktoken": "^1.0.8",
|
||||
"llm-code-highlighter": "^0.0.13",
|
||||
"llama-tokenizer-js": "^1.1.3",
|
||||
"node-fetch": "^3.3.2",
|
||||
"node-html-markdown": "^1.3.0",
|
||||
"ollama": "^0.4.6",
|
||||
"openai": "^4.20.1",
|
||||
"pg": "^8.11.3",
|
||||
"posthog-node": "^3.6.2",
|
||||
"replicate": "^0.26.0",
|
||||
"socket.io-client": "^4.7.3",
|
||||
|
|
@ -108,9 +115,10 @@
|
|||
"tree-sitter-wasms": "^0.1.6",
|
||||
"uuid": "^9.0.1",
|
||||
"vectordb": "^0.4.3",
|
||||
"web-tree-sitter": "^0.20.8"
|
||||
"web-tree-sitter": "^0.21.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/follow-redirects": "^1.14.4",
|
||||
"@types/handlebars": "^4.1.0",
|
||||
"@types/jest": "^29.5.11",
|
||||
"@types/jquery": "^3.5.29",
|
||||
|
|
@ -3697,6 +3705,14 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/bindings": {
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
|
||||
"integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",
|
||||
"dependencies": {
|
||||
"file-uri-to-path": "1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/bl": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
|
||||
|
|
@ -3862,6 +3878,14 @@
|
|||
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
|
||||
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="
|
||||
},
|
||||
"node_modules/buffer-writer": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/buffer-writer/-/buffer-writer-2.0.0.tgz",
|
||||
"integrity": "sha512-a7ZpuTZU1TRtnwyCNW3I5dc0wWNC3VR9S++Ewyk2HHZdrO3CQJqSpd+95Us590V6AL7JqUAH2IwZ/398PmNFgw==",
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/bytes": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
||||
|
|
@ -4803,6 +4827,16 @@
|
|||
"url": "https://opencollective.com/date-fns"
|
||||
}
|
||||
},
|
||||
"node_modules/dbinfoz": {
|
||||
"version": "0.1.4",
|
||||
"resolved": "https://registry.npmjs.org/dbinfoz/-/dbinfoz-0.1.4.tgz",
|
||||
"integrity": "sha512-MB56+xS571ip7qoXqxdnOUtXebbWaqoZN+S++W51SQYJRSjQFGEIPucNmxgeQlBGJ1vM4mQNV47wzV6fcrezZg==",
|
||||
"dependencies": {
|
||||
"mysql2": "^3.9.1",
|
||||
"pg": "^8.11.3",
|
||||
"sqlite3": "^5.1.7"
|
||||
}
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "4.3.4",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
|
||||
|
|
@ -4884,7 +4918,6 @@
|
|||
"version": "0.6.0",
|
||||
"resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",
|
||||
"integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==",
|
||||
"dev": true,
|
||||
"engines": {
|
||||
"node": ">=4.0.0"
|
||||
}
|
||||
|
|
@ -4951,6 +4984,14 @@
|
|||
"resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz",
|
||||
"integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ=="
|
||||
},
|
||||
"node_modules/denque": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz",
|
||||
"integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==",
|
||||
"engines": {
|
||||
"node": ">=0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/depd": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
|
||||
|
|
@ -5676,7 +5717,6 @@
|
|||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",
|
||||
"integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==",
|
||||
"dev": true,
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
|
|
@ -5939,6 +5979,11 @@
|
|||
"node": "^10.12.0 || >=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/file-uri-to-path": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
|
||||
"integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw=="
|
||||
},
|
||||
"node_modules/fill-range": {
|
||||
"version": "7.0.1",
|
||||
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz",
|
||||
|
|
@ -6198,8 +6243,7 @@
|
|||
"node_modules/fs-constants": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
|
||||
"integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
|
||||
"dev": true
|
||||
"integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="
|
||||
},
|
||||
"node_modules/fs-extra": {
|
||||
"version": "10.1.0",
|
||||
|
|
@ -6288,6 +6332,14 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/generate-function": {
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",
|
||||
"integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==",
|
||||
"dependencies": {
|
||||
"is-property": "^1.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/gensync": {
|
||||
"version": "1.0.0-beta.2",
|
||||
"resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
|
||||
|
|
@ -6364,8 +6416,7 @@
|
|||
"node_modules/github-from-package": {
|
||||
"version": "0.0.0",
|
||||
"resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz",
|
||||
"integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==",
|
||||
"dev": true
|
||||
"integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw=="
|
||||
},
|
||||
"node_modules/glob": {
|
||||
"version": "8.1.0",
|
||||
|
|
@ -6928,8 +6979,7 @@
|
|||
"node_modules/ini": {
|
||||
"version": "1.3.8",
|
||||
"resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
|
||||
"integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
|
||||
"dev": true
|
||||
"integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="
|
||||
},
|
||||
"node_modules/inline-style-parser": {
|
||||
"version": "0.1.1",
|
||||
|
|
@ -7152,6 +7202,11 @@
|
|||
"integrity": "sha512-+lP4/6lKUBfQjZ2pdxThZvLUAafmZb8OAxFb8XXtiQmS35INgr85hdOGoEs124ez1FCnZJt6jau/T+alh58QFQ==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/is-property": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",
|
||||
"integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g=="
|
||||
},
|
||||
"node_modules/is-stream": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",
|
||||
|
|
@ -8184,6 +8239,11 @@
|
|||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/long": {
|
||||
"version": "5.2.3",
|
||||
"resolved": "https://registry.npmjs.org/long/-/long-5.2.3.tgz",
|
||||
"integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q=="
|
||||
},
|
||||
"node_modules/loose-envify": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
|
||||
|
|
@ -9067,8 +9127,7 @@
|
|||
"node_modules/mkdirp-classic": {
|
||||
"version": "0.5.3",
|
||||
"resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",
|
||||
"integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==",
|
||||
"dev": true
|
||||
"integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="
|
||||
},
|
||||
"node_modules/mocha": {
|
||||
"version": "10.3.0",
|
||||
|
|
@ -9273,6 +9332,43 @@
|
|||
"integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/mysql2": {
|
||||
"version": "3.9.1",
|
||||
"resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.9.1.tgz",
|
||||
"integrity": "sha512-3njoWAAhGBYy0tWBabqUQcLtczZUxrmmtc2vszQUekg3kTJyZ5/IeLC3Fo04u6y6Iy5Sba7pIIa2P/gs8D3ZeQ==",
|
||||
"dependencies": {
|
||||
"denque": "^2.1.0",
|
||||
"generate-function": "^2.3.1",
|
||||
"iconv-lite": "^0.6.3",
|
||||
"long": "^5.2.1",
|
||||
"lru-cache": "^8.0.0",
|
||||
"named-placeholders": "^1.1.3",
|
||||
"seq-queue": "^0.0.5",
|
||||
"sqlstring": "^2.3.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/mysql2/node_modules/iconv-lite": {
|
||||
"version": "0.6.3",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
|
||||
"integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/mysql2/node_modules/lru-cache": {
|
||||
"version": "8.0.5",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-8.0.5.tgz",
|
||||
"integrity": "sha512-MhWWlVnuab1RG5/zMRRcVGXZLCXrZTgfwMikgzCegsPnG62yDQo5JnqKkrK4jO5iKqDAZGItAqN5CtKBCBWRUA==",
|
||||
"engines": {
|
||||
"node": ">=16.14"
|
||||
}
|
||||
},
|
||||
"node_modules/mz": {
|
||||
"version": "2.7.0",
|
||||
"resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz",
|
||||
|
|
@ -9283,6 +9379,25 @@
|
|||
"thenify-all": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/named-placeholders": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.3.tgz",
|
||||
"integrity": "sha512-eLoBxg6wE/rZkJPhU/xRX1WTpkFEwDJEN96oxFrTsqBdbT5ec295Q+CoHrL9IT0DipqKhmGcaZmwOt8OON5x1w==",
|
||||
"dependencies": {
|
||||
"lru-cache": "^7.14.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/named-placeholders/node_modules/lru-cache": {
|
||||
"version": "7.18.3",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz",
|
||||
"integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "3.3.7",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz",
|
||||
|
|
@ -9303,8 +9418,7 @@
|
|||
"node_modules/napi-build-utils": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-1.0.2.tgz",
|
||||
"integrity": "sha512-ONmRUqK7zj7DWX0D9ADe03wbwOBZxNAfF20PlGfCWQcD3+/MakShIHrMqx9YwPTfxDdF1zLeL+RGZiR9kGMLdg==",
|
||||
"dev": true
|
||||
"integrity": "sha512-ONmRUqK7zj7DWX0D9ADe03wbwOBZxNAfF20PlGfCWQcD3+/MakShIHrMqx9YwPTfxDdF1zLeL+RGZiR9kGMLdg=="
|
||||
},
|
||||
"node_modules/natural-compare": {
|
||||
"version": "1.4.0",
|
||||
|
|
@ -9794,6 +9908,11 @@
|
|||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/packet-reader": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/packet-reader/-/packet-reader-1.0.0.tgz",
|
||||
"integrity": "sha512-HAKu/fG3HpHFO0AA8WE8q2g+gBJaZ9MG7fcKk+IJPLTGAD6Psw4443l+9DGRbOIh3/aXr7Phy0TjilYivJo5XQ=="
|
||||
},
|
||||
"node_modules/pad-left": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/pad-left/-/pad-left-2.1.0.tgz",
|
||||
|
|
@ -9974,6 +10093,89 @@
|
|||
"resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz",
|
||||
"integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="
|
||||
},
|
||||
"node_modules/pg": {
|
||||
"version": "8.11.3",
|
||||
"resolved": "https://registry.npmjs.org/pg/-/pg-8.11.3.tgz",
|
||||
"integrity": "sha512-+9iuvG8QfaaUrrph+kpF24cXkH1YOOUeArRNYIxq1viYHZagBxrTno7cecY1Fa44tJeZvaoG+Djpkc3JwehN5g==",
|
||||
"dependencies": {
|
||||
"buffer-writer": "2.0.0",
|
||||
"packet-reader": "1.0.0",
|
||||
"pg-connection-string": "^2.6.2",
|
||||
"pg-pool": "^3.6.1",
|
||||
"pg-protocol": "^1.6.0",
|
||||
"pg-types": "^2.1.0",
|
||||
"pgpass": "1.x"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8.0.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"pg-cloudflare": "^1.1.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"pg-native": ">=3.0.1"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"pg-native": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/pg-cloudflare": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.1.1.tgz",
|
||||
"integrity": "sha512-xWPagP/4B6BgFO+EKz3JONXv3YDgvkbVrGw2mTo3D6tVDQRh1e7cqVGvyR3BE+eQgAvx1XhW/iEASj4/jCWl3Q==",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/pg-connection-string": {
|
||||
"version": "2.6.2",
|
||||
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.6.2.tgz",
|
||||
"integrity": "sha512-ch6OwaeaPYcova4kKZ15sbJ2hKb/VP48ZD2gE7i1J+L4MspCtBMAx8nMgz7bksc7IojCIIWuEhHibSMFH8m8oA=="
|
||||
},
|
||||
"node_modules/pg-int8": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
|
||||
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
|
||||
"engines": {
|
||||
"node": ">=4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/pg-pool": {
|
||||
"version": "3.6.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.6.1.tgz",
|
||||
"integrity": "sha512-jizsIzhkIitxCGfPRzJn1ZdcosIt3pz9Sh3V01fm1vZnbnCMgmGl5wvGGdNN2EL9Rmb0EcFoCkixH4Pu+sP9Og==",
|
||||
"peerDependencies": {
|
||||
"pg": ">=8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/pg-protocol": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.6.0.tgz",
|
||||
"integrity": "sha512-M+PDm637OY5WM307051+bsDia5Xej6d9IR4GwJse1qA1DIhiKlksvrneZOYQq42OM+spubpcNYEo2FcKQrDk+Q=="
|
||||
},
|
||||
"node_modules/pg-types": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
|
||||
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
|
||||
"dependencies": {
|
||||
"pg-int8": "1.0.1",
|
||||
"postgres-array": "~2.0.0",
|
||||
"postgres-bytea": "~1.0.0",
|
||||
"postgres-date": "~1.0.4",
|
||||
"postgres-interval": "^1.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/pgpass": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
|
||||
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
|
||||
"dependencies": {
|
||||
"split2": "^4.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/picocolors": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz",
|
||||
|
|
@ -10220,6 +10422,41 @@
|
|||
"resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",
|
||||
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ=="
|
||||
},
|
||||
"node_modules/postgres-array": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
|
||||
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-bytea": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.0.tgz",
|
||||
"integrity": "sha512-xy3pmLuQqRBZBXDULy7KbaitYqLcmxigw14Q5sj8QBVLqEwXfeybIKVWiqAXTlcvdvb0+xkOtDbfQMOf4lST1w==",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-date": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
|
||||
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/postgres-interval": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
|
||||
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
|
||||
"dependencies": {
|
||||
"xtend": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/posthog-node": {
|
||||
"version": "3.6.3",
|
||||
"resolved": "https://registry.npmjs.org/posthog-node/-/posthog-node-3.6.3.tgz",
|
||||
|
|
@ -10236,7 +10473,6 @@
|
|||
"version": "7.1.1",
|
||||
"resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.1.tgz",
|
||||
"integrity": "sha512-jAXscXWMcCK8GgCoHOfIr0ODh5ai8mj63L2nWrjuAgXE6tDyYGnx4/8o/rCgU+B4JSyZBKbeZqzhtwtC3ovxjw==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"detect-libc": "^2.0.0",
|
||||
"expand-template": "^2.0.3",
|
||||
|
|
@ -10534,7 +10770,6 @@
|
|||
"version": "1.2.8",
|
||||
"resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
|
||||
"integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"deep-extend": "^0.6.0",
|
||||
"ini": "~1.3.0",
|
||||
|
|
@ -10549,7 +10784,6 @@
|
|||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
|
||||
"integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",
|
||||
"dev": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
|
|
@ -11200,6 +11434,11 @@
|
|||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
|
||||
},
|
||||
"node_modules/seq-queue": {
|
||||
"version": "0.0.5",
|
||||
"resolved": "https://registry.npmjs.org/seq-queue/-/seq-queue-0.0.5.tgz",
|
||||
"integrity": "sha512-hr3Wtp/GZIc/6DAGPDcV4/9WoZhjrkXsi5B/07QgX8tsdc6ilr7BFM6PM6rbdAX1kFSDYeZGLipIZZKyQP0O5Q=="
|
||||
},
|
||||
"node_modules/serialize-javascript": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.0.tgz",
|
||||
|
|
@ -11298,7 +11537,6 @@
|
|||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",
|
||||
"integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
|
|
@ -11318,7 +11556,6 @@
|
|||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz",
|
||||
"integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
|
|
@ -11464,11 +11701,312 @@
|
|||
"integrity": "sha512-n98l9E2RMSJ9ON1AKisHzz7V42VDiBQGY6PB1BwRglz99wpVsSuGzQ+jOi6lFXBGVTCrRpltvjm+/XA+tpeJrg==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/split2": {
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
|
||||
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
|
||||
"engines": {
|
||||
"node": ">= 10.x"
|
||||
}
|
||||
},
|
||||
"node_modules/sprintf-js": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",
|
||||
"integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="
|
||||
},
|
||||
"node_modules/sqlite3": {
|
||||
"version": "5.1.7",
|
||||
"resolved": "https://registry.npmjs.org/sqlite3/-/sqlite3-5.1.7.tgz",
|
||||
"integrity": "sha512-GGIyOiFaG+TUra3JIfkI/zGP8yZYLPQ0pl1bH+ODjiX57sPhrLU5sQJn1y9bDKZUFYkX1crlrPfSYt0BKKdkog==",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"bindings": "^1.5.0",
|
||||
"node-addon-api": "^7.0.0",
|
||||
"prebuild-install": "^7.1.1",
|
||||
"tar": "^6.1.11"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"node-gyp": "8.x"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"node-gyp": "8.x"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"node-gyp": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/sqlite3/node_modules/@npmcli/fs": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@npmcli/fs/-/fs-1.1.1.tgz",
|
||||
"integrity": "sha512-8KG5RD0GVP4ydEzRn/I4BNDuxDtqVbOdm8675T49OIG/NGhaK0pjPX7ZcDlvKYbA+ulvVK3ztfcF4uBdOxuJbQ==",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@gar/promisify": "^1.0.1",
|
||||
"semver": "^7.3.5"
|
||||
}
|
||||
},
|
||||
"node_modules/sqlite3/node_modules/@npmcli/move-file": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@npmcli/move-file/-/move-file-1.1.2.tgz",
|
||||
"integrity": "sha512-1SUf/Cg2GzGDyaf15aR9St9TWlb+XvbZXWpDx8YKs7MLzMH/BCeopv+y9vzrzgkfykCGuWOlSu3mZhj2+FQcrg==",
|
||||
"deprecated": "This functionality has been moved to @npmcli/fs",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"mkdirp": "^1.0.4",
|
||||
"rimraf": "^3.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/sqlite3/node_modules/agent-base": {
|
||||
"version": "6.0.2",
|
||||
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
|
||||
"integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"debug": "4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/sqlite3/node_modules/cacache": {
|
||||
"version": "15.3.0",
|
||||
"resolved": "https://registry.npmjs.org/cacache/-/cacache-15.3.0.tgz",
|
||||
"integrity": "sha512-VVdYzXEn+cnbXpFgWs5hTT7OScegHVmLhJIR8Ufqk3iFD6A6j5iSX1KuBTfNEv4tdJWE2PzA6IVFtcLC7fN9wQ==",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@npmcli/fs": "^1.0.0",
|
||||
"@npmcli/move-file": "^1.0.1",
|
||||
"chownr": "^2.0.0",
|
||||
"fs-minipass": "^2.0.0",
|
||||
"glob": "^7.1.4",
|
||||
"infer-owner": "^1.0.4",
|
||||
"lru-cache": "^6.0.0",
|
||||
"minipass": "^3.1.1",
|
||||
"minipass-collect": "^1.0.2",
|
||||
"minipass-flush": "^1.0.5",
|
||||
"minipass-pipeline": "^1.2.2",
|
||||
"mkdirp": "^1.0.3",
|
||||
"p-map": "^4.0.0",
|
||||
"promise-inflight": "^1.0.1",
|
||||
"rimraf": "^3.0.2",
|
||||
"ssri": "^8.0.1",
|
||||
"tar": "^6.0.2",
|
||||
"unique-filename": "^1.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/sqlite3/node_modules/glob": {
|
||||
"version": "7.2.3",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
|
||||
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"fs.realpath": "^1.0.0",
|
||||
"inflight": "^1.0.4",
|
||||
"inherits": "2",
|
||||
"minimatch": "^3.1.1",
|
||||
"once": "^1.3.0",
|
||||
"path-is-absolute": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "*"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/sqlite3/node_modules/http-proxy-agent": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz",
|
||||
"integrity": "sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@tootallnate/once": "1",
|
||||
"agent-base": "6",
|
||||
"debug": "4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/sqlite3/node_modules/https-proxy-agent": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
|
||||
"integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"agent-base": "6",
|
||||
"debug": "4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/sqlite3/node_modules/make-fetch-happen": {
|
||||
"version": "9.1.0",
|
||||
"resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-9.1.0.tgz",
|
||||
"integrity": "sha512-+zopwDy7DNknmwPQplem5lAZX/eCOzSvSNNcSKm5eVwTkOBzoktEfXsa9L23J/GIRhxRsaxzkPEhrJEpE2F4Gg==",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"agentkeepalive": "^4.1.3",
|
||||
"cacache": "^15.2.0",
|
||||
"http-cache-semantics": "^4.1.0",
|
||||
"http-proxy-agent": "^4.0.1",
|
||||
"https-proxy-agent": "^5.0.0",
|
||||
"is-lambda": "^1.0.1",
|
||||
"lru-cache": "^6.0.0",
|
||||
"minipass": "^3.1.3",
|
||||
"minipass-collect": "^1.0.2",
|
||||
"minipass-fetch": "^1.3.2",
|
||||
"minipass-flush": "^1.0.5",
|
||||
"minipass-pipeline": "^1.2.4",
|
||||
"negotiator": "^0.6.2",
|
||||
"promise-retry": "^2.0.1",
|
||||
"socks-proxy-agent": "^6.0.0",
|
||||
"ssri": "^8.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/sqlite3/node_modules/minipass-fetch": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-1.4.1.tgz",
|
||||
"integrity": "sha512-CGH1eblLq26Y15+Azk7ey4xh0J/XfJfrCox5LDJiKqI2Q2iwOLOKrlmIaODiSQS8d18jalF6y2K2ePUm0CmShw==",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"minipass": "^3.1.0",
|
||||
"minipass-sized": "^1.0.3",
|
||||
"minizlib": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"encoding": "^0.1.12"
|
||||
}
|
||||
},
|
||||
"node_modules/sqlite3/node_modules/node-addon-api": {
|
||||
"version": "7.1.0",
|
||||
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.0.tgz",
|
||||
"integrity": "sha512-mNcltoe1R8o7STTegSOHdnJNN7s5EUvhoS7ShnTHDyOSd+8H+UdWODq6qSv67PjC8Zc5JRT8+oLAMCr0SIXw7g==",
|
||||
"engines": {
|
||||
"node": "^16 || ^18 || >= 20"
|
||||
}
|
||||
},
|
||||
"node_modules/sqlite3/node_modules/node-gyp": {
|
||||
"version": "8.4.1",
|
||||
"resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-8.4.1.tgz",
|
||||
"integrity": "sha512-olTJRgUtAb/hOXG0E93wZDs5YiJlgbXxTwQAFHyNlRsXQnYzUaF2aGgujZbw+hR8aF4ZG/rST57bWMWD16jr9w==",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"env-paths": "^2.2.0",
|
||||
"glob": "^7.1.4",
|
||||
"graceful-fs": "^4.2.6",
|
||||
"make-fetch-happen": "^9.1.0",
|
||||
"nopt": "^5.0.0",
|
||||
"npmlog": "^6.0.0",
|
||||
"rimraf": "^3.0.2",
|
||||
"semver": "^7.3.5",
|
||||
"tar": "^6.1.2",
|
||||
"which": "^2.0.2"
|
||||
},
|
||||
"bin": {
|
||||
"node-gyp": "bin/node-gyp.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 10.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/sqlite3/node_modules/nopt": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz",
|
||||
"integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"abbrev": "1"
|
||||
},
|
||||
"bin": {
|
||||
"nopt": "bin/nopt.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/sqlite3/node_modules/rimraf": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",
|
||||
"integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"glob": "^7.1.3"
|
||||
},
|
||||
"bin": {
|
||||
"rimraf": "bin.js"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/sqlite3/node_modules/socks-proxy-agent": {
|
||||
"version": "6.2.1",
|
||||
"resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-6.2.1.tgz",
|
||||
"integrity": "sha512-a6KW9G+6B3nWZ1yB8G7pJwL3ggLy1uTzKAgCb7ttblwqdz9fMGJUuTy3uFzEP48FAs9FLILlmzDlE2JJhVQaXQ==",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"agent-base": "^6.0.2",
|
||||
"debug": "^4.3.3",
|
||||
"socks": "^2.6.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/sqlite3/node_modules/ssri": {
|
||||
"version": "8.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ssri/-/ssri-8.0.1.tgz",
|
||||
"integrity": "sha512-97qShzy1AiyxvPNIkLWoGua7xoQzzPjQ0HAH4B0rWKo7SZ6USuPcrUiAFrws0UH8RrbWmgq3LMTObhPIHbbBeQ==",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"minipass": "^3.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/sqlite3/node_modules/unique-filename": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-1.1.1.tgz",
|
||||
"integrity": "sha512-Vmp0jIp2ln35UTXuryvjzkjGdRyf9b2lTXuSYUiPmzRcl3FDtYqAwOnTJkAngD9SWhnoJzDbTKwaOrZ+STtxNQ==",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"unique-slug": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/sqlite3/node_modules/unique-slug": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-2.0.2.tgz",
|
||||
"integrity": "sha512-zoWr9ObaxALD3DOPfjPSqxt4fnZiWblxHIgeWqW8x7UqDzEtHEQLzji2cuJYQFCU6KmoJikOYAZlrTHHebjx2w==",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"imurmurhash": "^0.1.4"
|
||||
}
|
||||
},
|
||||
"node_modules/sqlstring": {
|
||||
"version": "2.3.3",
|
||||
"resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.3.tgz",
|
||||
"integrity": "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/sshpk": {
|
||||
"version": "1.18.0",
|
||||
"resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.18.0.tgz",
|
||||
|
|
@ -11926,7 +12464,6 @@
|
|||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz",
|
||||
"integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"chownr": "^1.1.1",
|
||||
"mkdirp-classic": "^0.5.2",
|
||||
|
|
@ -11937,14 +12474,12 @@
|
|||
"node_modules/tar-fs/node_modules/chownr": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
|
||||
"integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",
|
||||
"dev": true
|
||||
"integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="
|
||||
},
|
||||
"node_modules/tar-stream": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
|
||||
"integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"bl": "^4.0.3",
|
||||
"end-of-stream": "^1.4.1",
|
||||
|
|
@ -11960,7 +12495,6 @@
|
|||
"version": "3.6.2",
|
||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
|
||||
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"inherits": "^2.0.3",
|
||||
"string_decoder": "^1.1.1",
|
||||
|
|
@ -13587,6 +14121,14 @@
|
|||
"node": ">=0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/xtend": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
||||
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
|
||||
"engines": {
|
||||
"node": ">=0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/y18n": {
|
||||
"version": "5.0.8",
|
||||
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "continue",
|
||||
"icon": "media/icon.png",
|
||||
"version": "0.9.72",
|
||||
"version": "0.9.77",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/continuedev/continue"
|
||||
|
|
@ -64,8 +64,8 @@
|
|||
},
|
||||
"continue.enableTabAutocomplete": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"markdownDescription": "Enable Continue's experimental tab autocomplete feature (pre-release only). Read our walkthrough to learn about configuration and how to share feedback: [continue.dev › Walkthrough: Tab Autocomplete](https://continue.dev/docs/walkthroughs/tab-autocomplete)"
|
||||
"default": true,
|
||||
"markdownDescription": "Enable Continue's tab autocomplete feature. Read our walkthrough to learn about configuration and how to share feedback: [continue.dev › Walkthrough: Tab Autocomplete](https://continue.dev/docs/walkthroughs/tab-autocomplete)"
|
||||
},
|
||||
"continue.remoteConfigServerUrl": {
|
||||
"type": "string",
|
||||
|
|
@ -195,13 +195,13 @@
|
|||
"keybindings": [
|
||||
{
|
||||
"command": "continue.focusContinueInput",
|
||||
"mac": "cmd+m",
|
||||
"key": "ctrl+m"
|
||||
"mac": "cmd+l",
|
||||
"key": "ctrl+l"
|
||||
},
|
||||
{
|
||||
"command": "continue.focusContinueInputWithoutClear",
|
||||
"mac": "cmd+shift+m",
|
||||
"key": "ctrl+shift+m"
|
||||
"mac": "cmd+shift+l",
|
||||
"key": "ctrl+shift+l"
|
||||
},
|
||||
{
|
||||
"command": "continue.acceptDiff",
|
||||
|
|
@ -221,13 +221,13 @@
|
|||
},
|
||||
{
|
||||
"command": "continue.quickEdit",
|
||||
"mac": "cmd+shift+l",
|
||||
"key": "ctrl+shift+l"
|
||||
"mac": "cmd+i",
|
||||
"key": "ctrl+i"
|
||||
},
|
||||
{
|
||||
"command": "continue.toggleAuxiliaryBar",
|
||||
"mac": "alt+cmd+m",
|
||||
"key": "alt+ctrl+m"
|
||||
"mac": "alt+cmd+l",
|
||||
"key": "alt+ctrl+l"
|
||||
},
|
||||
{
|
||||
"command": "continue.debugTerminal",
|
||||
|
|
@ -476,6 +476,7 @@
|
|||
"axios": "^1.2.5",
|
||||
"core": "file:../../core",
|
||||
"cors": "^2.8.5",
|
||||
"dbinfoz": "^0.1.4",
|
||||
"downshift": "^7.6.0",
|
||||
"express": "^4.18.2",
|
||||
"fkill": "^8.1.0",
|
||||
|
|
|
|||
|
|
@ -13,11 +13,22 @@ if (args[2] === "--target") {
|
|||
(async () => {
|
||||
console.log("[info] Packaging extension for target ", target);
|
||||
|
||||
// Copy config_schema.json to config.json in docs
|
||||
// Copy config_schema.json to config.json in docs and intellij
|
||||
fs.copyFileSync(
|
||||
"config_schema.json",
|
||||
path.join("..", "..", "docs", "static", "schemas", "config.json")
|
||||
);
|
||||
fs.copyFileSync(
|
||||
"config_schema.json",
|
||||
path.join(
|
||||
"..",
|
||||
"intellij",
|
||||
"src",
|
||||
"main",
|
||||
"resources",
|
||||
"config_schema.json"
|
||||
)
|
||||
);
|
||||
// Modify and copy for .continuerc.json
|
||||
const schema = JSON.parse(fs.readFileSync("config_schema.json", "utf8"));
|
||||
schema.definitions.SerializedContinueConfig.properties.mergeBehavior = {
|
||||
|
|
@ -61,7 +72,7 @@ if (args[2] === "--target") {
|
|||
|
||||
const indexHtmlPath = path.join(intellijExtensionWebviewPath, "index.html");
|
||||
fs.copyFileSync(indexHtmlPath, "tmp_index.html");
|
||||
fs.rmSync(intellijExtensionWebviewPath, { recursive: true });
|
||||
rimrafSync(intellijExtensionWebviewPath);
|
||||
fs.mkdirSync(intellijExtensionWebviewPath, { recursive: true });
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
|
|
@ -77,11 +88,19 @@ if (args[2] === "--target") {
|
|||
});
|
||||
});
|
||||
|
||||
// Put back index.html
|
||||
if (fs.existsSync(indexHtmlPath)) {
|
||||
fs.rmSync(indexHtmlPath, {});
|
||||
rimrafSync(indexHtmlPath);
|
||||
}
|
||||
fs.copyFileSync("tmp_index.html", indexHtmlPath);
|
||||
fs.unlinkSync("tmp_index.html");
|
||||
|
||||
// Copy over other misc. files
|
||||
fs.copyFileSync(
|
||||
"../extensions/vscode/gui/onigasm.wasm",
|
||||
path.join(intellijExtensionWebviewPath, "onigasm.wasm")
|
||||
);
|
||||
|
||||
console.log("[info] Copied gui build to Intellij extension");
|
||||
|
||||
// Then copy over the dist folder to the VSCode extension //
|
||||
|
|
@ -153,19 +172,13 @@ if (args[2] === "--target") {
|
|||
if (target) {
|
||||
// If building for production, only need the binaries for current platform
|
||||
if (!target.startsWith("darwin")) {
|
||||
fs.rmdirSync(path.join(__dirname, "../bin/napi-v3/darwin"), {
|
||||
recursive: true,
|
||||
});
|
||||
rimrafSync(path.join(__dirname, "../bin/napi-v3/darwin"));
|
||||
}
|
||||
if (!target.startsWith("linux")) {
|
||||
fs.rmdirSync(path.join(__dirname, "../bin/napi-v3/linux"), {
|
||||
recursive: true,
|
||||
});
|
||||
rimrafSync(path.join(__dirname, "../bin/napi-v3/linux"));
|
||||
}
|
||||
if (!target.startsWith("win")) {
|
||||
fs.rmdirSync(path.join(__dirname, "../bin/napi-v3/win32"), {
|
||||
recursive: true,
|
||||
});
|
||||
rimrafSync(path.join(__dirname, "../bin/napi-v3/win32"));
|
||||
}
|
||||
}
|
||||
console.log("[info] Copied onnxruntime-node");
|
||||
|
|
|
|||
|
|
@ -2,27 +2,12 @@ import { getTsConfigPath, migrate } from "core/util/paths";
|
|||
import { Telemetry } from "core/util/posthog";
|
||||
import * as fs from "fs";
|
||||
import path from "path";
|
||||
import { v4 } from "uuid";
|
||||
import * as vscode from "vscode";
|
||||
import { registerAllCommands } from "../commands";
|
||||
import IdeProtocolClient from "../continueIdeClient";
|
||||
import { ContinueGUIWebviewViewProvider } from "../debugPanel";
|
||||
import { VsCodeExtension } from "../extension/vscodeExtension";
|
||||
import registerQuickFixProvider from "../lang-server/codeActions";
|
||||
import { registerAllCodeLensProviders } from "../lang-server/codeLens";
|
||||
import {
|
||||
ContinueCompletionProvider,
|
||||
setupStatusBar,
|
||||
} from "../lang-server/completionProvider";
|
||||
import { vsCodeIndexCodebase } from "../util/indexCodebase";
|
||||
import { setupRemoteConfigSync } from "../util/remoteConfig";
|
||||
import { getExtensionVersion } from "../util/util";
|
||||
import { getExtensionUri } from "../util/vscode";
|
||||
import { setupInlineTips } from "./inlineTips";
|
||||
import { registerDebugTracker } from "../debug/debug";
|
||||
|
||||
export let extensionContext: vscode.ExtensionContext | undefined = undefined;
|
||||
export let ideProtocolClient: IdeProtocolClient;
|
||||
export let windowId: string = v4();
|
||||
|
||||
export async function showTutorial() {
|
||||
const tutorialPath = path.join(
|
||||
|
|
@ -49,7 +34,9 @@ async function openTutorialFirstTime(context: vscode.ExtensionContext) {
|
|||
}
|
||||
}
|
||||
|
||||
function showRefactorMigrationMessage() {
|
||||
function showRefactorMigrationMessage(
|
||||
extensionContext: vscode.ExtensionContext
|
||||
) {
|
||||
// Only if the vscode setting continue.manuallyRunningSserver is true
|
||||
const manuallyRunningServer =
|
||||
vscode.workspace
|
||||
|
|
@ -83,47 +70,15 @@ export async function activateExtension(context: vscode.ExtensionContext) {
|
|||
// Add necessary files
|
||||
getTsConfigPath();
|
||||
|
||||
extensionContext = context;
|
||||
|
||||
// Register commands and providers
|
||||
registerAllCodeLensProviders(context);
|
||||
registerAllCommands(context);
|
||||
registerQuickFixProvider();
|
||||
await openTutorialFirstTime(context);
|
||||
setupInlineTips(context);
|
||||
showRefactorMigrationMessage();
|
||||
const config = vscode.workspace.getConfiguration("continue");
|
||||
const enabled = config.get<boolean>("enableTabAutocomplete");
|
||||
showRefactorMigrationMessage(context);
|
||||
|
||||
// Register inline completion provider (odd versions are pre-release)
|
||||
if (parseInt(context.extension.packageJSON.version.split(".")[1]) % 2 !== 0) {
|
||||
setupStatusBar(enabled);
|
||||
context.subscriptions.push(
|
||||
vscode.languages.registerInlineCompletionItemProvider(
|
||||
[{ pattern: "**" }],
|
||||
new ContinueCompletionProvider()
|
||||
)
|
||||
);
|
||||
}
|
||||
const vscodeExtension = new VsCodeExtension(context);
|
||||
|
||||
ideProtocolClient = new IdeProtocolClient(context);
|
||||
|
||||
// Register Continue GUI as sidebar webview, and beginning a new session
|
||||
const provider = new ContinueGUIWebviewViewProvider();
|
||||
|
||||
context.subscriptions.push(
|
||||
vscode.window.registerWebviewViewProvider(
|
||||
"continue.continueGUIView",
|
||||
provider,
|
||||
{
|
||||
webviewOptions: { retainContextWhenHidden: true },
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
vsCodeIndexCodebase(ideProtocolClient.getWorkspaceDirectories());
|
||||
|
||||
migrate("showWelcome", () => {
|
||||
migrate("showWelcome_1", () => {
|
||||
vscode.commands.executeCommand(
|
||||
"markdown.showPreview",
|
||||
vscode.Uri.file(
|
||||
|
|
@ -132,27 +87,6 @@ export async function activateExtension(context: vscode.ExtensionContext) {
|
|||
);
|
||||
});
|
||||
|
||||
registerDebugTracker();
|
||||
|
||||
// (async () => {
|
||||
// const defaultDocsPages = [
|
||||
// ["Socket.IO", "https://python-socketio.readthedocs.io/en/stable"],
|
||||
// // ["Flask", "https://flask.palletsprojects.com/en/2.0.x/"],
|
||||
// ];
|
||||
|
||||
// const config = await configHandler.loadConfig(new VsCodeIde());
|
||||
|
||||
// defaultDocsPages.forEach(async ([title, url]) => {
|
||||
// for await (const update of indexDocs(
|
||||
// title,
|
||||
// new URL(url),
|
||||
// config.embeddingsProvider
|
||||
// )) {
|
||||
// console.log(update.progress, update.desc);
|
||||
// }
|
||||
// });
|
||||
// })();
|
||||
|
||||
// Load Continue configuration
|
||||
if (!context.globalState.get("hasBeenInstalled")) {
|
||||
context.globalState.update("hasBeenInstalled", true);
|
||||
|
|
@ -160,10 +94,4 @@ export async function activateExtension(context: vscode.ExtensionContext) {
|
|||
extensionVersion: getExtensionVersion(),
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
setupRemoteConfigSync();
|
||||
} catch (e) {
|
||||
console.warn(`Failed to sync remote config: ${e}`);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { getMetaKeyLabel } from "../util/util";
|
|||
|
||||
const inlineTipDecoration = vscode.window.createTextEditorDecorationType({
|
||||
after: {
|
||||
contentText: `${getMetaKeyLabel()} M to select code, ${getMetaKeyLabel()} ⇧ L to edit`,
|
||||
contentText: `${getMetaKeyLabel()} L to select code, ${getMetaKeyLabel()} I to edit`,
|
||||
color: "#888",
|
||||
margin: "0 0 0 6em",
|
||||
fontWeight: "bold",
|
||||
|
|
@ -31,7 +31,7 @@ function handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) {
|
|||
const line = Math.max(0, selection.start.line - 1);
|
||||
|
||||
const hoverMarkdown = new vscode.MarkdownString(
|
||||
`Use ${getMetaKeyLabel()} M to select code, or ${getMetaKeyLabel()} ⇧ L to edit highlighted code. Click [here](command:continue.hideInlineTip) if you don't want to see these inline suggestions.`
|
||||
`Use ${getMetaKeyLabel()} L to select code, or ${getMetaKeyLabel()} I to edit highlighted code. Click [here](command:continue.hideInlineTip) if you don't want to see these inline suggestions.`
|
||||
);
|
||||
hoverMarkdown.isTrusted = true;
|
||||
hoverMarkdown.supportHtml = true;
|
||||
|
|
@ -49,7 +49,7 @@ function handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) {
|
|||
const emptyFileTooltipDecoration = vscode.window.createTextEditorDecorationType(
|
||||
{
|
||||
after: {
|
||||
contentText: `Use ${getMetaKeyLabel()} ⇧ L to generate code`,
|
||||
contentText: `Use ${getMetaKeyLabel()} I to generate code`,
|
||||
color: "#888",
|
||||
margin: "2em 0 0 0",
|
||||
fontStyle: "italic",
|
||||
|
|
|
|||
115
extensions/vscode/src/autocomplete/completionProvider.ts
Normal file
115
extensions/vscode/src/autocomplete/completionProvider.ts
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
import { IDE } from "core";
|
||||
import AutocompleteLruCache from "core/autocomplete/cache";
|
||||
import { DEFAULT_AUTOCOMPLETE_OPTS } from "core/autocomplete/parameters";
|
||||
import { ConfigHandler } from "core/config/handler";
|
||||
import { logDevData } from "core/util/devdata";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import * as vscode from "vscode";
|
||||
import { TabAutocompleteModel } from "../util/loadAutocompleteModel";
|
||||
import { getTabCompletion } from "./getTabCompletion";
|
||||
import { stopStatusBarLoading } from "./statusBar";
|
||||
|
||||
export class ContinueCompletionProvider
|
||||
implements vscode.InlineCompletionItemProvider
|
||||
{
|
||||
private static debounceTimeout: NodeJS.Timeout | undefined = undefined;
|
||||
private static debouncing: boolean = false;
|
||||
private static lastUUID: string | undefined = undefined;
|
||||
|
||||
private static autocompleteCache = AutocompleteLruCache.get();
|
||||
|
||||
public static errorsShown: Set<string> = new Set();
|
||||
|
||||
constructor(private readonly configHandler: ConfigHandler, private readonly ide: IDE, private readonly tabAutocompleteModel: TabAutocompleteModel) {}
|
||||
|
||||
public async provideInlineCompletionItems(
|
||||
document: vscode.TextDocument,
|
||||
position: vscode.Position,
|
||||
context: vscode.InlineCompletionContext,
|
||||
token: vscode.CancellationToken
|
||||
//@ts-ignore
|
||||
): ProviderResult<InlineCompletionItem[] | InlineCompletionList> {
|
||||
// Debounce
|
||||
const uuid = uuidv4();
|
||||
ContinueCompletionProvider.lastUUID = uuid;
|
||||
|
||||
const config = await this.configHandler.loadConfig();
|
||||
const options = {
|
||||
...config.tabAutocompleteOptions,
|
||||
...DEFAULT_AUTOCOMPLETE_OPTS,
|
||||
};
|
||||
|
||||
if (ContinueCompletionProvider.debouncing) {
|
||||
ContinueCompletionProvider.debounceTimeout?.refresh();
|
||||
const lastUUID = await new Promise((resolve) =>
|
||||
setTimeout(() => {
|
||||
resolve(ContinueCompletionProvider.lastUUID);
|
||||
}, options.debounceDelay)
|
||||
);
|
||||
if (uuid !== lastUUID) {
|
||||
return [];
|
||||
}
|
||||
} else {
|
||||
ContinueCompletionProvider.debouncing = true;
|
||||
ContinueCompletionProvider.debounceTimeout = setTimeout(async () => {
|
||||
ContinueCompletionProvider.debouncing = false;
|
||||
}, options.debounceDelay);
|
||||
}
|
||||
|
||||
const enableTabAutocomplete =
|
||||
vscode.workspace
|
||||
.getConfiguration("continue")
|
||||
.get<boolean>("enableTabAutocomplete") || false;
|
||||
if (token.isCancellationRequested || !enableTabAutocomplete) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const outcome = await getTabCompletion(
|
||||
document,
|
||||
position,
|
||||
token,
|
||||
options,
|
||||
this.tabAutocompleteModel,
|
||||
this.ide
|
||||
);
|
||||
const completion = outcome?.completion;
|
||||
|
||||
if (!completion) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Do some stuff later so as not to block return. Latency matters
|
||||
setTimeout(async () => {
|
||||
if (!outcome.cacheHit) {
|
||||
(await ContinueCompletionProvider.autocompleteCache).put(
|
||||
outcome.prompt,
|
||||
completion
|
||||
);
|
||||
}
|
||||
}, 100);
|
||||
|
||||
const logRejectionTimeout = setTimeout(() => {
|
||||
// Wait 10 seconds, then assume it wasn't accepted
|
||||
outcome.accepted = false;
|
||||
logDevData("autocomplete", outcome);
|
||||
}, 10_000);
|
||||
|
||||
return [
|
||||
new vscode.InlineCompletionItem(
|
||||
completion,
|
||||
new vscode.Range(position, position.translate(0, completion.length)),
|
||||
{
|
||||
title: "Log Autocomplete Outcome",
|
||||
command: "continue.logAutocompleteOutcome",
|
||||
arguments: [outcome, logRejectionTimeout],
|
||||
}
|
||||
),
|
||||
];
|
||||
} catch (e: any) {
|
||||
console.warn("Error getting autocompletion: ", e.message);
|
||||
} finally {
|
||||
stopStatusBarLoading();
|
||||
}
|
||||
}
|
||||
}
|
||||
215
extensions/vscode/src/autocomplete/getTabCompletion.ts
Normal file
215
extensions/vscode/src/autocomplete/getTabCompletion.ts
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
import { IDE, TabAutocompleteOptions } from "core";
|
||||
import { AutocompleteLruCache } from "core/autocomplete/cache";
|
||||
import { onlyWhitespaceAfterEndOfLine } from "core/autocomplete/charStream";
|
||||
import {
|
||||
constructAutocompletePrompt,
|
||||
languageForFilepath,
|
||||
} from "core/autocomplete/constructPrompt";
|
||||
import {
|
||||
avoidPathLine,
|
||||
stopAtLines,
|
||||
stopAtSimilarLine,
|
||||
streamWithNewLines,
|
||||
} from "core/autocomplete/lineStream";
|
||||
import { AutocompleteSnippet } from "core/autocomplete/ranking";
|
||||
import { getTemplateForModel } from "core/autocomplete/templates";
|
||||
import { GeneratorReuseManager } from "core/autocomplete/util";
|
||||
import { streamLines } from "core/diff/util";
|
||||
import OpenAI from "core/llm/llms/OpenAI";
|
||||
import Handlebars from "handlebars";
|
||||
import * as vscode from "vscode";
|
||||
import { TabAutocompleteModel } from "../util/loadAutocompleteModel";
|
||||
import { ContinueCompletionProvider } from "./completionProvider";
|
||||
import { getDefinitionsFromLsp } from "./lsp";
|
||||
import { RecentlyEditedTracker } from "./recentlyEdited";
|
||||
import { setupStatusBar, stopStatusBarLoading } from "./statusBar";
|
||||
|
||||
export interface AutocompleteOutcome {
|
||||
accepted?: boolean;
|
||||
time: number;
|
||||
prompt: string;
|
||||
completion: string;
|
||||
modelProvider: string;
|
||||
modelName: string;
|
||||
completionOptions: any;
|
||||
cacheHit: boolean;
|
||||
}
|
||||
|
||||
const autocompleteCache = AutocompleteLruCache.get();
|
||||
const recentlyEditedTracker = new RecentlyEditedTracker();
|
||||
|
||||
export async function getTabCompletion(
|
||||
document: vscode.TextDocument,
|
||||
pos: vscode.Position,
|
||||
token: vscode.CancellationToken,
|
||||
options: TabAutocompleteOptions,
|
||||
tabAutocompleteModel: TabAutocompleteModel,
|
||||
ide: IDE
|
||||
): Promise<AutocompleteOutcome | undefined> {
|
||||
const startTime = Date.now();
|
||||
|
||||
// Filter
|
||||
const lang = languageForFilepath(document.fileName);
|
||||
const line = document.lineAt(pos).text;
|
||||
for (const endOfLine of lang.endOfLine) {
|
||||
if (line.endsWith(endOfLine) && pos.character >= line.length) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Model
|
||||
const llm = await tabAutocompleteModel.get()
|
||||
if (llm instanceof OpenAI) {
|
||||
llm.useLegacyCompletionsEndpoint = true;
|
||||
}
|
||||
if (!llm) return;
|
||||
|
||||
// Prompt
|
||||
const fullPrefix = document.getText(
|
||||
new vscode.Range(new vscode.Position(0, 0), pos)
|
||||
);
|
||||
const fullSuffix = document.getText(
|
||||
new vscode.Range(
|
||||
pos,
|
||||
new vscode.Position(document.lineCount, Number.MAX_SAFE_INTEGER)
|
||||
)
|
||||
);
|
||||
const lineBelowCursor = document.lineAt(
|
||||
Math.min(pos.line + 1, document.lineCount - 1)
|
||||
).text;
|
||||
const clipboardText = await vscode.env.clipboard.readText();
|
||||
|
||||
let extrasSnippets = (await Promise.race([
|
||||
getDefinitionsFromLsp(document.uri.fsPath, fullPrefix + fullSuffix, fullPrefix.length, ide),
|
||||
new Promise((resolve) => {
|
||||
setTimeout(() => resolve([]), 100);
|
||||
})
|
||||
])) as AutocompleteSnippet[]
|
||||
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
if (options.onlyMyCode) {
|
||||
extrasSnippets = extrasSnippets.filter((snippet) => {
|
||||
return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir));
|
||||
})
|
||||
}
|
||||
|
||||
const { prefix, suffix, completeMultiline } =
|
||||
await constructAutocompletePrompt(
|
||||
document.uri.toString(),
|
||||
pos.line,
|
||||
fullPrefix,
|
||||
fullSuffix,
|
||||
clipboardText,
|
||||
lang,
|
||||
options,
|
||||
await recentlyEditedTracker.getRecentlyEditedRanges(),
|
||||
await recentlyEditedTracker.getRecentlyEditedDocuments(),
|
||||
llm.model,
|
||||
extrasSnippets
|
||||
);
|
||||
|
||||
const { template, completionOptions } = options.template
|
||||
? { template: options.template, completionOptions: {} }
|
||||
: getTemplateForModel(llm.model);
|
||||
|
||||
const compiledTemplate = Handlebars.compile(template);
|
||||
const prompt = compiledTemplate({ prefix, suffix });
|
||||
|
||||
// Completion
|
||||
let completion = "";
|
||||
|
||||
const cache = await autocompleteCache;
|
||||
const cachedCompletion = options.useCache ? await cache.get(prompt) : undefined;
|
||||
let cacheHit = false;
|
||||
if (cachedCompletion) {
|
||||
// Cache
|
||||
cacheHit = true;
|
||||
completion = cachedCompletion;
|
||||
} else {
|
||||
setupStatusBar(true, true);
|
||||
|
||||
// Try to reuse pending requests if what the user typed matches start of completion
|
||||
let stop = [
|
||||
...(completionOptions?.stop || []),
|
||||
"\n\n",
|
||||
"```",
|
||||
...lang.stopWords,
|
||||
];
|
||||
if (
|
||||
options.multilineCompletions !== "always" &&
|
||||
(options.multilineCompletions === "never" || !completeMultiline)
|
||||
) {
|
||||
stop.unshift("\n");
|
||||
}
|
||||
let generator = GeneratorReuseManager.getGenerator(prefix, () =>
|
||||
llm.streamComplete(prompt, {
|
||||
...completionOptions,
|
||||
temperature: 0,
|
||||
raw: true,
|
||||
stop,
|
||||
})
|
||||
);
|
||||
|
||||
// LLM
|
||||
let cancelled = false;
|
||||
const generatorWithCancellation = async function* () {
|
||||
for await (const update of generator) {
|
||||
if (token.isCancellationRequested) {
|
||||
stopStatusBarLoading();
|
||||
cancelled = true;
|
||||
return undefined;
|
||||
}
|
||||
yield update;
|
||||
}
|
||||
};
|
||||
const gen2 = onlyWhitespaceAfterEndOfLine(
|
||||
generatorWithCancellation(),
|
||||
lang.endOfLine
|
||||
);
|
||||
const lineGenerator = streamWithNewLines(avoidPathLine(stopAtLines(streamLines(gen2)), lang.comment));
|
||||
const finalGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor);
|
||||
for await (const update of finalGenerator) {
|
||||
completion += update;
|
||||
}
|
||||
|
||||
if (cancelled) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Don't return empty
|
||||
if (completion.trim().length <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Post-processing
|
||||
completion = completion.trimEnd();
|
||||
}
|
||||
|
||||
const time = Date.now() - startTime;
|
||||
return {
|
||||
time,
|
||||
completion,
|
||||
prompt,
|
||||
modelProvider: llm.providerName,
|
||||
modelName: llm.model,
|
||||
completionOptions,
|
||||
cacheHit,
|
||||
};
|
||||
} catch (e: any) {
|
||||
console.warn("Error generating autocompletion: ", e);
|
||||
if (!ContinueCompletionProvider.errorsShown.has(e.message)) {
|
||||
ContinueCompletionProvider.errorsShown.add(e.message);
|
||||
vscode.window.showErrorMessage(e.message, "Documentation").then((val) => {
|
||||
if (val === "Documentation") {
|
||||
vscode.env.openExternal(
|
||||
vscode.Uri.parse(
|
||||
"https://continue.dev/docs/walkthroughs/tab-autocomplete"
|
||||
)
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
106
extensions/vscode/src/autocomplete/lsp.ts
Normal file
106
extensions/vscode/src/autocomplete/lsp.ts
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
import { IDE, RangeInFile } from "core";
|
||||
import { getAst, getTreePathAtCursor } from "core/autocomplete/ast";
|
||||
import { AutocompleteSnippet } from "core/autocomplete/ranking";
|
||||
import { RangeInFileWithContents } from "core/commands/util";
|
||||
import * as vscode from "vscode";
|
||||
import Parser from "web-tree-sitter";
|
||||
|
||||
type GotoProviderName =
|
||||
| "vscode.executeDefinitionProvider"
|
||||
| "vscode.executeTypeDefinitionProvider"
|
||||
| "vscode.executeDeclarationProvider"
|
||||
| "vscode.executeImplementationProvider"
|
||||
| "vscode.executeReferenceProvider";
|
||||
async function executeGotoProvider(
|
||||
uri: string,
|
||||
line: number,
|
||||
character: number,
|
||||
name: GotoProviderName
|
||||
): Promise<RangeInFile[]> {
|
||||
const definitions = (await vscode.commands.executeCommand(
|
||||
name,
|
||||
vscode.Uri.parse(uri),
|
||||
new vscode.Position(line, character)
|
||||
)) as any;
|
||||
|
||||
return definitions.map((d: any) => ({
|
||||
filepath: d.targetUri.fsPath,
|
||||
range: d.targetRange,
|
||||
}));
|
||||
}
|
||||
|
||||
async function getDefinitionsForNode(
|
||||
uri: string,
|
||||
node: Parser.SyntaxNode
|
||||
): Promise<RangeInFile[]> {
|
||||
const ranges: RangeInFile[] = [];
|
||||
switch (node.type) {
|
||||
case "call_expression":
|
||||
// function call -> function definition
|
||||
const defs = await executeGotoProvider(
|
||||
uri,
|
||||
node.startPosition.row,
|
||||
node.startPosition.column,
|
||||
"vscode.executeDefinitionProvider"
|
||||
);
|
||||
ranges.push(...defs);
|
||||
break;
|
||||
case "variable_declarator":
|
||||
// variable assignment -> variable definition/type
|
||||
// usages of the var that appear after the declaration
|
||||
break;
|
||||
case "impl_item":
|
||||
// impl of trait -> trait definition
|
||||
break;
|
||||
case "":
|
||||
// function definition -> implementations?
|
||||
break;
|
||||
}
|
||||
return ranges;
|
||||
}
|
||||
|
||||
/**
|
||||
* and other stuff not directly on the path:
|
||||
* - variables defined on line above
|
||||
* ...etc...
|
||||
*/
|
||||
|
||||
export async function getDefinitionsFromLsp(
|
||||
filepath: string,
|
||||
contents: string,
|
||||
cursorIndex: number,
|
||||
ide: IDE
|
||||
): Promise<AutocompleteSnippet[]> {
|
||||
const ast = await getAst(filepath, contents);
|
||||
if (!ast) return [];
|
||||
|
||||
const treePath = await getTreePathAtCursor(ast, cursorIndex);
|
||||
if (!treePath) return [];
|
||||
|
||||
const results: RangeInFileWithContents[] = [];
|
||||
for (const node of treePath.reverse()) {
|
||||
const definitions = await getDefinitionsForNode(filepath, node);
|
||||
results.push(
|
||||
...(await Promise.all(
|
||||
definitions.map(async (def) => ({
|
||||
...def,
|
||||
contents: await ide.readRangeInFile(
|
||||
def.filepath,
|
||||
new vscode.Range(
|
||||
new vscode.Position(
|
||||
def.range.start.line,
|
||||
def.range.start.character
|
||||
),
|
||||
new vscode.Position(def.range.end.line, def.range.end.character)
|
||||
)
|
||||
),
|
||||
}))
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
return results.map((result) => ({
|
||||
...result,
|
||||
score: 0.8
|
||||
}));
|
||||
}
|
||||
162
extensions/vscode/src/autocomplete/recentlyEdited.ts
Normal file
162
extensions/vscode/src/autocomplete/recentlyEdited.ts
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
import { RecentlyEditedRange } from "core/autocomplete/recentlyEdited";
|
||||
import { RangeInFileWithContents } from "core/commands/util";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
interface VsCodeRecentlyEditedRange {
|
||||
timestamp: number;
|
||||
uri: vscode.Uri;
|
||||
range: vscode.Range;
|
||||
}
|
||||
|
||||
interface VsCodeRecentlyEditedDocument {
|
||||
timestamp: number;
|
||||
uri: vscode.Uri;
|
||||
}
|
||||
|
||||
export class RecentlyEditedTracker {
|
||||
private static staleTime = 1000 * 60 * 2;
|
||||
private static maxRecentlyEditedRanges = 3;
|
||||
private recentlyEditedRanges: VsCodeRecentlyEditedRange[] = [];
|
||||
|
||||
private recentlyEditedDocuments: VsCodeRecentlyEditedDocument[] = [];
|
||||
private static maxRecentlyEditedDocuments = 10;
|
||||
|
||||
constructor() {
|
||||
vscode.workspace.onDidChangeTextDocument((event) => {
|
||||
if (event.document.uri.scheme !== "file") {
|
||||
return;
|
||||
}
|
||||
event.contentChanges.forEach((change) => {
|
||||
const editedRange = {
|
||||
uri: event.document.uri,
|
||||
range: new vscode.Range(
|
||||
new vscode.Position(change.range.start.line, 0),
|
||||
new vscode.Position(change.range.end.line + 1, 0),
|
||||
),
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
this.insertRange(editedRange);
|
||||
});
|
||||
|
||||
this.insertDocument(event.document.uri);
|
||||
});
|
||||
|
||||
setInterval(() => {
|
||||
this.removeOldEntries();
|
||||
}, 1000 * 15);
|
||||
}
|
||||
|
||||
private insertRange(editedRange: VsCodeRecentlyEditedRange): void {
|
||||
// Check for overlap with any existing ranges
|
||||
for (let i = 0; i < this.recentlyEditedRanges.length; i++) {
|
||||
let range = this.recentlyEditedRanges[i];
|
||||
if (range.range.intersection(editedRange.range)) {
|
||||
range = {
|
||||
...range,
|
||||
range: range.range.union(editedRange.range),
|
||||
};
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise, just add the new and maintain max size
|
||||
const newLength = this.recentlyEditedRanges.unshift(editedRange);
|
||||
if (newLength >= RecentlyEditedTracker.maxRecentlyEditedRanges) {
|
||||
this.recentlyEditedRanges = this.recentlyEditedRanges.slice(
|
||||
0,
|
||||
RecentlyEditedTracker.maxRecentlyEditedRanges,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private insertDocument(uri: vscode.Uri): void {
|
||||
// Don't add a duplicate
|
||||
if (this.recentlyEditedDocuments.some((doc) => doc.uri === uri)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const newLength = this.recentlyEditedDocuments.unshift({
|
||||
uri,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
if (newLength >= RecentlyEditedTracker.maxRecentlyEditedDocuments) {
|
||||
this.recentlyEditedDocuments = this.recentlyEditedDocuments.slice(
|
||||
0,
|
||||
RecentlyEditedTracker.maxRecentlyEditedDocuments,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private removeOldEntries() {
|
||||
this.recentlyEditedRanges = this.recentlyEditedRanges.filter(
|
||||
(entry) => entry.timestamp > Date.now() - RecentlyEditedTracker.staleTime,
|
||||
);
|
||||
}
|
||||
|
||||
public async getRecentlyEditedRanges(): Promise<RecentlyEditedRange[]> {
|
||||
const results = await Promise.all(
|
||||
this.recentlyEditedRanges.map(async (entry) => {
|
||||
try {
|
||||
const contents = await vscode.workspace.fs
|
||||
.readFile(entry.uri)
|
||||
.then((content) =>
|
||||
content
|
||||
.toString()
|
||||
.split("\n")
|
||||
.slice(entry.range.start.line, entry.range.end.line + 1)
|
||||
.join("\n"),
|
||||
);
|
||||
return {
|
||||
timestamp: entry.timestamp,
|
||||
filepath: entry.uri.fsPath,
|
||||
contents,
|
||||
range: {
|
||||
start: {
|
||||
line: entry.range.start.line,
|
||||
character: entry.range.start.character,
|
||||
},
|
||||
end: {
|
||||
line: entry.range.end.line,
|
||||
character: entry.range.end.character,
|
||||
},
|
||||
},
|
||||
};
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
return results.filter((result) => result !== null) as any;
|
||||
}
|
||||
|
||||
public async getRecentlyEditedDocuments(): Promise<
|
||||
RangeInFileWithContents[]
|
||||
> {
|
||||
const results = await Promise.all(
|
||||
this.recentlyEditedDocuments.map(async (entry) => {
|
||||
try {
|
||||
const contents = await vscode.workspace.fs
|
||||
.readFile(entry.uri)
|
||||
.then((content) => content.toString());
|
||||
const lines = contents.split("\n");
|
||||
|
||||
return {
|
||||
filepath: entry.uri.fsPath,
|
||||
contents,
|
||||
range: {
|
||||
start: { line: 0, character: 0 },
|
||||
end: {
|
||||
line: lines.length - 1,
|
||||
character: lines[lines.length - 1].length,
|
||||
},
|
||||
},
|
||||
};
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
return results.filter((result) => result !== null) as any;
|
||||
}
|
||||
}
|
||||
51
extensions/vscode/src/autocomplete/statusBar.ts
Normal file
51
extensions/vscode/src/autocomplete/statusBar.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import * as vscode from "vscode";
|
||||
|
||||
const statusBarItemText = (enabled: boolean | undefined) =>
|
||||
enabled ? "$(check) Continue" : "$(circle-slash) Continue";
|
||||
|
||||
const statusBarItemTooltip = (enabled: boolean | undefined) =>
|
||||
enabled ? "Tab autocomplete is enabled" : "Click to enable tab autocomplete";
|
||||
|
||||
let lastStatusBar: vscode.StatusBarItem | undefined = undefined;
|
||||
let statusBarFalseTimeout: NodeJS.Timeout | undefined = undefined;
|
||||
|
||||
export function stopStatusBarLoading() {
|
||||
statusBarFalseTimeout = setTimeout(() => {
|
||||
setupStatusBar(true, false);
|
||||
}, 100);
|
||||
}
|
||||
|
||||
export function setupStatusBar(
|
||||
enabled: boolean | undefined,
|
||||
loading?: boolean
|
||||
) {
|
||||
if (loading !== false) {
|
||||
clearTimeout(statusBarFalseTimeout);
|
||||
statusBarFalseTimeout = undefined;
|
||||
}
|
||||
|
||||
const statusBarItem = vscode.window.createStatusBarItem(
|
||||
vscode.StatusBarAlignment.Right
|
||||
);
|
||||
statusBarItem.text = loading
|
||||
? "$(loading~spin) Continue"
|
||||
: statusBarItemText(enabled);
|
||||
statusBarItem.tooltip = statusBarItemTooltip(enabled);
|
||||
statusBarItem.command = "continue.toggleTabAutocompleteEnabled";
|
||||
|
||||
// Swap out with old status bar
|
||||
if (lastStatusBar) {
|
||||
lastStatusBar.dispose();
|
||||
}
|
||||
statusBarItem.show();
|
||||
lastStatusBar = statusBarItem;
|
||||
|
||||
vscode.workspace.onDidChangeConfiguration((event) => {
|
||||
if (event.affectsConfiguration("continue")) {
|
||||
const config = vscode.workspace.getConfiguration("continue");
|
||||
const enabled = config.get<boolean>("enableTabAutocomplete");
|
||||
statusBarItem.dispose();
|
||||
setupStatusBar(enabled);
|
||||
}
|
||||
});
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue