Merge branch 'preview' into nate/code-context-provider

This commit is contained in:
Nate Sesti 2024-03-09 13:54:28 -08:00
commit 4bb20cd557
96 changed files with 21499 additions and 16091 deletions

View file

@ -0,0 +1,8 @@
## 0.0.34 - 2024-03-03
### Added
* diff context provider
### Changed
* Allow LLM servers to handle templating
### Fixed
* Fix a few context providers / slash commands
* Fixed issues preventing proper extension startup

View file

@ -0,0 +1,3 @@
## 0.8.15 - 2024-03-05
### Added
* Tab-autocomplete in beta

View file

@ -1,4 +0,0 @@
project: extensions/intellij
kind: Added
body: diff context provider
time: 2023-12-29T10:58:15.432508-05:00

View file

@ -1,4 +0,0 @@
project: extensions/vscode
kind: Added
body: Tab-autocomplete in beta
time: 2024-03-03T19:00:39.909292-05:00

View file

@ -1,4 +0,0 @@
project: extensions/intellij
kind: Changed
body: Allow LLM servers to handle templating
time: 2024-01-03T11:33:41.535094-05:00

View file

@ -1,4 +0,0 @@
project: extensions/intellij
kind: Fixed
body: Fix a few context providers / slash commands
time: 2024-01-03T01:52:17.592331-05:00

10
.vscode/tasks.json vendored
View file

@ -22,8 +22,9 @@
{
"label": "vscode-extension:esbuild",
"type": "npm",
"script": "esbuild",
"script": "esbuild-watch",
"path": "extensions/vscode",
"isBackground": true,
"problemMatcher": [
{
"pattern": [
@ -35,7 +36,12 @@
"severity": 4,
"message": 5
}
]
],
"background": {
"activeOnStart": true,
"beginsPattern": ">",
"endsPattern": ">"
}
}
]
},

View file

@ -24,3 +24,14 @@ export async function* onlyWhitespaceAfterEndOfLine(
}
yield pending;
}
export async function* noFirstCharNewline(stream: AsyncGenerator<string>) {
let first = true;
for await (let char of stream) {
if (first) {
first = false;
if (char === "\n") return;
}
yield char;
}
}

View file

@ -1,13 +1,12 @@
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 { getAst, getTreePathAtCursor } from "./ast";
import { AutocompleteLanguageInfo, LANGUAGES, Typescript } from "./languages";
import {
@ -24,23 +23,6 @@ export function languageForFilepath(
return LANGUAGES[filepath.split(".").slice(-1)[0]] || Typescript;
}
function formatExternalSnippet(
filepath: string,
snippet: string,
language: AutocompleteLanguageInfo,
) {
const comment = language.comment;
const lines = [
comment + " Path: " + getBasename(filepath),
...snippet
.trim()
.split("\n")
.map((line) => comment + " " + line),
comment,
];
return lines.join("\n");
}
const BLOCK_TYPES = ["body", "statement_block"];
function shouldCompleteMultilineAst(
@ -113,43 +95,8 @@ export async function constructAutocompletePrompt(
suffix: string;
useFim: boolean;
completeMultiline: boolean;
snippets: AutocompleteSnippet[];
}> {
// 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;
let prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens, modelName);
@ -161,44 +108,82 @@ export async function constructAutocompletePrompt(
);
let suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName);
// 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,
);
// Find external snippets
let snippets: AutocompleteSnippet[] = [];
// Filter snippets for those with best scores (must be above threshold)
finalSnippets = finalSnippets.filter(
(snippet) => snippet.score >= options.recentlyEditedSimilarityThreshold,
);
finalSnippets = fillPromptWithSnippets(
scoredSnippets,
maxSnippetTokens,
modelName,
);
if (options.useOtherFiles) {
snippets.push(...extraSnippets);
// 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;
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));
// Filter out empty snippets
snippets = snippets.filter(
(s) =>
s.contents.trim() !== "" &&
!(prefix + suffix).includes(s.contents.trim()),
);
// Rank / order the snippets
const scoredSnippets = rankSnippets(snippets, windowAroundCursor);
// Fill maxSnippetTokens with snippets
const maxSnippetTokens =
options.maxPromptTokens * options.maxSnippetPercentage;
// 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,
);
snippets = finalSnippets;
}
return {
@ -210,5 +195,6 @@ export async function constructAutocompletePrompt(
fullPrefix,
fullSuffix,
),
snippets,
};
}

View file

@ -9,7 +9,8 @@ export async function* avoidPathLine(
// 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: ")) {
// Also filter lines that are empty comments
if (line.startsWith(comment + " Path: ") || line.trim() === comment) {
continue;
}
yield line;

View file

@ -14,4 +14,5 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
recentlyEditedSimilarityThreshold: 0.3,
useCache: true,
onlyMyCode: true,
useOtherFiles: true,
};

View file

@ -1,9 +1,18 @@
// Fill in the middle prompts
import { CompletionOptions } from "..";
import { AutocompleteSnippet } from "./ranking";
interface AutocompleteTemplate {
template: string | ((prefix: string, suffix: string) => string);
template:
| string
| ((
prefix: string,
suffix: string,
filename: string,
reponame: string,
snippets: AutocompleteSnippet[],
) => string);
completionOptions?: Partial<CompletionOptions>;
}
@ -15,6 +24,41 @@ const stableCodeFimTemplate: AutocompleteTemplate = {
},
};
// https://arxiv.org/pdf/2402.19173.pdf section 5.1
const starcoder2FimTemplate: AutocompleteTemplate = {
template: (
prefix: string,
suffix: string,
filename: string,
reponame: string,
snippets: AutocompleteSnippet[],
): string => {
const otherFiles =
snippets.length === 0
? ""
: "<file_sep>" +
snippets
.map((snippet) => {
return snippet.contents;
// return `${getBasename(snippet.filepath)}\n${snippet.contents}`;
})
.join("<file_sep>") +
"<file_sep>";
let prompt = `${otherFiles}<fim_prefix>${prefix}<fim_suffix>${suffix}<fim_middle>`;
return prompt;
},
completionOptions: {
stop: [
"<fim_prefix>",
"<fim_suffix>",
"<fim_middle>",
"<|endoftext|>",
"<file_sep>",
],
},
};
const codeLlamaFimTemplate: AutocompleteTemplate = {
template: "<PRE> {{{prefix}}} <SUF>{{{suffix}}} <MID>",
completionOptions: { stop: ["<PRE>", "<SUF>", "<MID>", "<EOT>"] },
@ -46,10 +90,16 @@ The last line is incomplete, and you should provide the rest of that line. If th
export function getTemplateForModel(model: string): AutocompleteTemplate {
const lowerCaseModel = model.toLowerCase();
if (lowerCaseModel.includes("starcoder2")) {
return starcoder2FimTemplate;
}
if (
lowerCaseModel.includes("starcoder") ||
lowerCaseModel.includes("star-coder") ||
lowerCaseModel.includes("starchat") ||
lowerCaseModel.includes("octocoder") ||
lowerCaseModel.includes("stable")
) {
return stableCodeFimTemplate;

View file

@ -58,7 +58,7 @@ export async function getPromptParts(
) {
let maxTokens = Math.floor(model.contextLength / 2);
const TOKENS_TO_BE_CONSIDERED_LARGE_RANGE = tokenLimit || 1200;
const TOKENS_TO_BE_CONSIDERED_LARGE_RANGE = tokenLimit ?? 1200;
// if (model.countTokens(rif.contents) > TOKENS_TO_BE_CONSIDERED_LARGE_RANGE) {
// throw new Error(
// "\n\n**It looks like you've selected a large range to edit, which may take a while to complete. If you'd like to cancel, click the 'X' button above. If you highlight a more specific range, Continue will only edit within it.**"
@ -455,7 +455,7 @@ const EditSlashCommand: SlashCommand = {
userInput,
filePrefix: filePrefix,
fileSuffix: fileSuffix,
systemMessage: llm.systemMessage || "",
systemMessage: llm.systemMessage ?? "",
// "contextItems": (await sdk.getContextItemChatMessages()).map(x => x.content || "").join("\n\n"),
},
);
@ -516,7 +516,7 @@ const EditSlashCommand: SlashCommand = {
unfinishedLine = "";
chunkLines.pop(); // because this will be an empty string
} else {
unfinishedLine = chunkLines.pop() || "";
unfinishedLine = chunkLines.pop() ?? "";
}
// Deal with newly accumulated lines

View file

@ -36,15 +36,15 @@ async function fetchData(url: string): Promise<string | undefined> {
const doc = parser.parseFromString(htmlString, "text/html");
const h1 = doc.querySelector("h1.fs-headline1");
const title = h1?.textContent?.trim() || "No Title";
const title = h1?.textContent?.trim() ?? "No Title";
const bodies = doc.querySelectorAll("div.js-post-body");
if (bodies.length < 2) {
return undefined;
}
const question = bodies[0].textContent || "";
const answer = bodies[1].textContent || "";
const question = bodies[0].textContent ?? "";
const answer = bodies[1].textContent ?? "";
return `
# Question: [${title}](${url})

View file

@ -102,7 +102,7 @@ export class ConfigHandler {
);
}
let timeout = (llm.requestOptions?.timeout || TIMEOUT) * 1000; // measured in ms
let timeout = (llm.requestOptions?.timeout ?? TIMEOUT) * 1000; // measured in ms
const agentOptions = {
ca,

View file

@ -38,6 +38,7 @@ import {
getContinueDotEnv,
migrate,
} from "../util/paths";
import { defaultConfig } from "./default";
const { execSync } = require("child_process");
function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
@ -73,7 +74,14 @@ function loadSerializedConfig(
ideType: IdeType,
): SerializedContinueConfig {
const configPath = getConfigJsonPath(ideType);
let config = resolveSerializedConfig(configPath);
let config: SerializedContinueConfig;
try {
config = resolveSerializedConfig(configPath);
} catch (e) {
console.log("config.json is invalid. Falling back to default.");
config = defaultConfig;
}
if (config.allowAnonymousTelemetry === undefined) {
config.allowAnonymousTelemetry = true;
}
@ -311,7 +319,7 @@ function finalToBrowserConfig(
models: final.models.map((m) => ({
provider: m.providerName,
model: m.model,
title: m.title || m.model,
title: m.title ?? m.model,
apiKey: m.apiKey,
apiBase: m.apiBase,
contextLength: m.contextLength,

View file

@ -16,9 +16,9 @@ class CustomContextProviderClass implements IContextProvider {
get description(): ContextProviderDescription {
return {
title: this.custom.title,
displayTitle: this.custom.displayTitle || this.custom.title,
description: this.custom.description || "",
type: this.custom.type || "normal",
displayTitle: this.custom.displayTitle ?? this.custom.title,
description: this.custom.description ?? "",
type: this.custom.type ?? "normal",
renderInlineAs: this.custom.renderInlineAs,
};
}
@ -31,7 +31,7 @@ class CustomContextProviderClass implements IContextProvider {
}
async loadSubmenuItems(args: LoadSubmenuItemsArgs) {
return this.custom.loadSubmenuItems?.(args) || [];
return this.custom.loadSubmenuItems?.(args) ?? [];
}
}

View file

@ -6,13 +6,14 @@ import {
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../..";
import configs from "../../indexing/docs/preIndexedDocs";
import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider";
class DocsContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "docs",
displayTitle: "Docs",
description: "Search documentation",
description: "Type to search docs",
type: "submenu",
};
@ -29,10 +30,9 @@ class DocsContextProvider extends BaseContextProvider {
query,
vector,
this.options?.nRetrieve || 15,
embeddingsProvider.id,
);
console.log(chunks);
return [
...chunks
.map((chunk) => ({
@ -45,7 +45,7 @@ class DocsContextProvider extends BaseContextProvider {
.slice(1)
.join("/")
: chunk.otherMetadata?.title || chunk.filepath,
description: new URL(chunk.filepath, query).toString(),
description: chunk.filepath, // new URL(chunk.filepath, query).toString(),
content: chunk.content,
}))
.reverse(),
@ -53,7 +53,7 @@ class DocsContextProvider extends BaseContextProvider {
name: "Instructions",
description: "Instructions",
content:
"Use the above documentation to answer the following question. You should not reference anything outside of what is shown, unless it is a commonly known concept. Reference URLs whenever possible. If there isn't enough information to answer the question, suggest where the user might look to learn more.",
"Use the above documentation to answer the following question. You should not reference anything outside of what is shown, unless it is a commonly known concept. Reference URLs whenever possible using markdown formatting. If there isn't enough information to answer the question, suggest where the user might look to learn more.",
},
];
}
@ -63,11 +63,25 @@ class DocsContextProvider extends BaseContextProvider {
): Promise<ContextSubmenuItem[]> {
const { listDocs } = await import("../../indexing/docs/db");
const docs = await listDocs();
return docs.map((doc) => ({
const submenuItems = docs.map((doc) => ({
title: doc.title,
description: new URL(doc.baseUrl).hostname,
id: doc.baseUrl,
}));
submenuItems.push(
...configs
// After it's actually downloaded, we don't want to show twice
.filter(
(config) => !submenuItems.some((item) => item.id === config.startUrl),
)
.map((config) => ({
title: config.title,
description: new URL(config.startUrl).hostname,
id: config.startUrl,
})),
);
return submenuItems;
}
}

View file

@ -25,7 +25,7 @@ class FileContextProvider extends BaseContextProvider {
const content = await extras.ide.readFile(query);
return [
{
name: query.split(/[\\/]/).pop() || query,
name: query.split(/[\\/]/).pop() ?? query,
description: query,
content: `\`\`\`${query}\n${content}\n\`\`\``,
},

View file

@ -53,7 +53,7 @@ class FileTreeContextProvider extends BaseContextProvider {
const contents = await extras.ide.listWorkspaceContents(workspaceDir);
const subDirTree: Directory = {
name: splitPath(workspaceDir).pop() || "",
name: splitPath(workspaceDir).pop() ?? "",
files: [],
directories: [],
};

View file

@ -1,134 +0,0 @@
import type { AxiosInstance } from "axios";
import { BaseContextProvider } from "..";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../..";
const { convert } = require("adf-to-md");
interface JiraComment {
id: string;
created: string;
updated: string;
author: {
emailAddress: string;
displayName: string;
};
body: object;
}
interface JiraIssue {
id: string;
key: string;
fields: {
summary: string;
description: object;
comment: {
total: number;
comments: Array<JiraComment>;
};
};
}
interface QueryResults {
issues: JiraIssue[];
}
class JiraIssuesContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "jira",
displayTitle: "Jira Issues",
description: "Reference Jira issues",
type: "submenu",
};
private async createApi(): Promise<AxiosInstance> {
const { default: Axios } = await import("axios");
return Axios.create({
baseURL: `https://${this.options.domain}/rest/api/3/`,
auth: {
username: this.options.email,
password: this.options.token,
},
});
}
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const issueId = query;
const api = await this.createApi();
const issue = await api
.get<JiraIssue>(`/issue/${issueId}`, {
params: {
fields: "description,comment,summary",
},
})
.then((result) => result.data);
const parts = [
`# Jira Issue ${issue.key}: ${issue.fields.summary}`,
"## Description",
issue.fields.description
? convert(issue.fields.description).result
: "No description",
];
if (issue.fields.comment.comments.length > 0) {
parts.push("## Comments");
parts.push(
...issue.fields.comment.comments.map((comment) => {
const commentText = convert(comment.body).result;
return `### ${comment.author.displayName} on ${comment.created}\n\n${commentText}`;
}),
);
}
const content = parts.join("\n\n");
return [
{
name: `${issue.key}: ${issue.fields.summary}`,
content,
description: issue.key,
},
];
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const api = await this.createApi();
try {
const results = await api.get<QueryResults>("/search", {
params: {
jql:
this.options.issueQuery ??
`assignee = currentUser() AND resolution = Unresolved order by updated DESC`,
fields: "summary",
},
});
return results.data.issues.map((issue) => ({
id: issue.id,
title: `${issue.key}: ${issue.fields.summary}`,
description: "",
}));
} catch (ex) {
console.error(`Unable to get jira tickets: ${ex}`);
return [];
}
}
}
export default JiraIssuesContextProvider;

View file

@ -0,0 +1,157 @@
import type { AxiosInstance } from "axios";
const { convert: adf2md } = require("adf-to-md");
interface JiraClientOptions {
domain: string;
username: string;
password: string;
issueQuery?: string;
apiVersion?: string;
}
interface JiraComment {
id: string;
created: string;
updated: string;
author: {
emailAddress: string;
displayName: string;
};
body: object | string;
}
interface JiraIssue {
id: string;
key: string;
fields: {
summary: string;
description: object | string;
comment: {
total: number;
comments: Array<JiraComment>;
};
};
}
interface QueryResult {
id: string;
key: string;
summary: string;
}
interface QueryResults {
issues: JiraIssue[];
}
export interface Comment {
created: string;
updated: string;
author: {
emailAddress: string;
displayName: string;
};
body: string;
}
export interface Issue {
key: string;
summary: string;
description?: string;
comments: Array<Comment>;
}
export class JiraClient {
private readonly options: Required<JiraClientOptions>;
private _api: AxiosInstance | null = null;
constructor(options: JiraClientOptions) {
this.options = {
issueQuery: `assignee = currentUser() AND resolution = Unresolved order by updated DESC`,
apiVersion: '3',
...options
};
}
private async getApi() {
if (!this._api) {
const { default: Axios } = await import("axios");
this._api = Axios.create({
baseURL: `https://${this.options.domain}/rest/api/${this.options.apiVersion}/`,
...(this.options.username
? {
auth: {
username: this.options.username,
password: this.options.password,
},
}
: {
headers: {
Authorization: `Bearer ${this.options.password}`,
},
}),
});
}
return this._api;
}
async issue(issueId: string): Promise<Issue> {
const api = await this.getApi();
const result = {} as Issue;
const issue = await api
.get<JiraIssue>(`/issue/${issueId}`, {
params: {
fields: "description,comment,summary",
},
})
.then((result) => result.data);
result.key = issue.key;
result.summary = issue.fields.summary;
if (typeof issue.fields.description === 'string') {
result.description = issue.fields.description;
} else if(issue.fields.description) {
result.description = adf2md(issue.fields.description).result;
} else {
result.description = "";
}
result.comments = issue.fields.comment?.comments?.map((comment) => {
const body = typeof comment.body === 'string' ? comment.body : adf2md(comment.body).result;
return {
body,
author: comment.author,
created: comment.created,
updated: comment.updated,
};
}) ?? [];
return result;
}
async listIssues(): Promise<Array<QueryResult>> {
const api = await this.getApi();
const results = await api.get<QueryResults>("/search", {
params: {
jql:
this.options.issueQuery ??
`assignee = currentUser() AND resolution = Unresolved order by updated DESC`,
fields: "summary",
},
});
return results.data?.issues?.map((issue) => ({
id: issue.id,
key: issue.key,
summary: issue.fields.summary,
})) ?? [];
}
}

View file

@ -0,0 +1,85 @@
import { BaseContextProvider } from "../..";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../..";
import { JiraClient } from "./JiraClient";
class JiraIssuesContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "jira",
displayTitle: "Jira Issues",
description: "Reference Jira issues",
type: "submenu",
};
private getApi() {
return new JiraClient({
domain: this.options.domain,
username: this.options.email,
password: this.options.token,
issueQuery: this.options.issueQuery,
apiVersion: this.options.apiVersion,
});
}
async getContextItems(
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]> {
const issueId = query;
const api = this.getApi();
const issue = await api.issue(query);
const parts = [
`# Jira Issue ${issue.key}: ${issue.summary}`,
"## Description",
issue.description ?? "No description",
];
if (issue.comments.length > 0) {
parts.push("## Comments");
parts.push(
...issue.comments.map((comment) => {
return `### ${comment.author.displayName} on ${comment.created}\n\n${comment.body}`;
})
);
}
const content = parts.join("\n\n");
return [
{
name: `${issue.key}: ${issue.summary}`,
content,
description: issue.key,
},
];
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs
): Promise<ContextSubmenuItem[]> {
const api = await this.getApi();
try {
const issues = await api.listIssues();
return issues.map((issue) => ({
id: issue.id,
title: `${issue.key}: ${issue.summary}`,
description: "",
}));
} catch (ex) {
console.error(`Unable to get jira tickets: ${ex}`);
return [];
}
}
}
export default JiraIssuesContextProvider;

View file

@ -29,7 +29,7 @@ class OpenFilesContextProvider extends BaseContextProvider {
content: `\`\`\`${getBasename(filepath)}\n${await ide.readFile(
filepath,
)}\n\`\`\``,
name: (filepath.split("/").pop() || "").split("\\").pop() || "",
name: (filepath.split("/").pop() ?? "").split("\\").pop() ?? "",
};
}),
);

View file

@ -1,4 +1,6 @@
import { distance } from "fastest-levenshtein";
import { ChatMessage } from "..";
import { stripImages } from "../llm/countTokens";
export type LineStream = AsyncGenerator<string>;
@ -57,10 +59,12 @@ export function matchLine(
* Convert a stream of arbitrary chunks to a stream of lines
*/
export async function* streamLines(
streamCompletion: AsyncGenerator<string>,
streamCompletion: AsyncGenerator<string | ChatMessage>,
): LineStream {
let buffer = "";
for await (const chunk of streamCompletion) {
for await (const update of streamCompletion) {
const chunk =
typeof update === "string" ? update : stripImages(update.content);
buffer += chunk;
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";

5
core/index.d.ts vendored
View file

@ -495,6 +495,9 @@ export type ModelName =
| "neural-chat-7b"
// Anthropic
| "claude-2"
| "claude-3-opus-20240229"
| "claude-3-sonnet-20240229"
| "claude-2.1"
// Google PaLM
| "chat-bison-001"
// Gemini
@ -551,6 +554,7 @@ interface BaseCompletionOptions {
stop?: string[];
maxTokens?: number;
numThreads?: number;
keepAlive?: number;
}
export interface ModelDescription {
@ -599,6 +603,7 @@ export interface TabAutocompleteOptions {
recentlyEditedSimilarityThreshold: number;
useCache: boolean;
onlyMyCode: boolean;
useOtherFiles: boolean;
}
export interface SerializedContinueConfig {

View file

@ -2,7 +2,9 @@ import { ChunkWithoutID } from "../..";
import { countTokens } from "../../llm/countTokens";
import { basicChunker } from "./basic";
function cleanFragment(fragment: string | undefined): string | undefined {
export function cleanFragment(
fragment: string | undefined,
): string | undefined {
if (!fragment) {
return undefined;
}
@ -17,7 +19,7 @@ function cleanFragment(fragment: string | undefined): string | undefined {
}
// Remove all special characters except alphanumeric, hyphen, space, and underscore
fragment = fragment.replace(/[^\w\d-\s]/g, "").trim();
fragment = fragment.replace(/[^\w-\s]/g, "").trim();
// Convert to lowercase
fragment = fragment.toLowerCase();
@ -28,7 +30,7 @@ function cleanFragment(fragment: string | undefined): string | undefined {
return fragment;
}
function cleanHeader(header: string | undefined): string | undefined {
export function cleanHeader(header: string | undefined): string | undefined {
if (!header) {
return undefined;
}
@ -43,7 +45,10 @@ function cleanHeader(header: string | undefined): string | undefined {
}
// Remove all special characters except alphanumeric, hyphen, space, and underscore
header = header.replace(/[^\w\d-\s]/g, "").trim();
header = header
.replace(/[^\w-\s]/g, "")
.replace("¶", "")
.trim();
return header;
}

View file

@ -0,0 +1,162 @@
import { Readability } from "@mozilla/readability";
import { JSDOM } from "jsdom";
import { Chunk } from "../..";
import { MAX_CHUNK_SIZE } from "../../llm/constants";
import { cleanFragment, cleanHeader } from "../chunk/markdown";
type ArticleComponent = {
title: string;
body: string;
};
type Article = {
url: string;
subpath: string;
title: string;
article_components: ArticleComponent[];
};
function breakdownArticleComponent(
url: string,
article: ArticleComponent,
subpath: string,
): Chunk[] {
let chunks: Chunk[] = [];
let lines = article.body.split("\n");
let startLine = 0;
let endLine = 0;
let content = "";
let index = 0;
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
if (content.length + line.length <= MAX_CHUNK_SIZE) {
content += line + "\n";
endLine = i;
} else {
chunks.push({
content: content.trim(),
startLine: startLine,
endLine: endLine,
otherMetadata: {
title: cleanHeader(article.title),
},
index: index,
filepath: new URL(
subpath + `#${cleanFragment(article.title)}`,
url,
).toString(),
digest: subpath,
});
content = line + "\n";
startLine = i;
endLine = i;
index += 1;
}
}
// Push the last chunk
if (content) {
chunks.push({
content: content.trim(),
startLine: startLine,
endLine: endLine,
otherMetadata: {
title: cleanHeader(article.title),
},
index: index,
filepath: new URL(
subpath + `#${cleanFragment(article.title)}`,
url,
).toString(),
digest: subpath,
});
}
// Don't use small chunks. Probably they're a mistake. Definitely they'll confuse the embeddings model.
return chunks.filter((c) => c.content.trim().length > 20);
}
export function chunkArticle(articleResult: Article): Chunk[] {
let chunks: Chunk[] = [];
for (let article of articleResult.article_components) {
let articleChunks = breakdownArticleComponent(
articleResult.url,
article,
articleResult.subpath,
);
chunks = [...chunks, ...articleChunks];
}
return chunks;
}
function extractTitlesAndBodies(html: string): ArticleComponent[] {
const dom = new JSDOM(html);
const document = dom.window.document;
const titles = Array.from(document.querySelectorAll("h2"));
const result = titles.map((titleElement) => {
const title = titleElement.textContent || "";
let body = "";
let nextSibling = titleElement.nextElementSibling;
while (nextSibling && nextSibling.tagName !== "H2") {
body += nextSibling.textContent || "";
nextSibling = nextSibling.nextElementSibling;
}
return { title, body };
});
return result;
}
export async function stringToArticle(
url: string,
htmlContent: string,
subpath: string,
): Promise<Article | undefined> {
try {
const dom = new JSDOM(htmlContent);
let reader = new Readability(dom.window.document);
let article = reader.parse();
if (!article) {
return undefined;
}
let article_components = extractTitlesAndBodies(article.content);
return {
url,
subpath,
title: article.title,
article_components,
};
} catch (err) {
console.error("Error converting URL to article components", err);
return undefined;
}
}
export async function urlToArticle(
subpath: string,
baseUrl: URL,
): Promise<Article | undefined> {
const url = new URL(subpath, baseUrl);
try {
const response = await fetch(url.toString());
if (!response.ok) {
return undefined;
}
const htmlContent = await response.text();
return stringToArticle(baseUrl.toString(), htmlContent, subpath);
} catch (err) {
console.error("Error converting URL to article components", err);
return undefined;
}
}

View file

@ -43,17 +43,17 @@ function shouldFilterPath(pathname: string, baseUrl: URL): boolean {
}
async function* crawlLinks(
path: string,
pathname: string,
baseUrl: URL,
visited: Set<string>,
): AsyncGenerator<number> {
if (visited.has(path) || shouldFilterPath(path, baseUrl)) {
if (visited.has(pathname) || shouldFilterPath(pathname, baseUrl)) {
return;
}
visited.add(path);
visited.add(pathname);
yield visited.size;
const response = await fetch(new URL(path, baseUrl));
const response = await fetch(new URL(pathname, baseUrl));
const text = await response.text();
const $ = cheerio.load(text);
@ -67,8 +67,8 @@ async function* crawlLinks(
const parsedUrl = new URL(href, baseUrl);
if (
parsedUrl.hostname === baseUrl.hostname &&
!visited.has(parsedUrl.pathname) &&
parsedUrl.pathname.startsWith(baseUrl.pathname)
!visited.has(parsedUrl.pathname)
// parsedUrl.pathname.startsWith(baseUrl.pathname)
) {
children.push(parsedUrl.pathname);
}

View file

@ -2,6 +2,10 @@ import { Database, open } from "sqlite";
import sqlite3 from "sqlite3";
import { Chunk } from "../..";
import { getDocsSqlitePath, getLanceDbPath } from "../../util/paths";
import { SqliteDb } from "../refreshIndex";
import { downloadPreIndexedDocs } from "./preIndexed";
import { default as configs } from "./preIndexedDocs";
const DOCS_TABLE_NAME = "docs";
@ -29,16 +33,49 @@ export async function retrieveDocs(
baseUrl: string,
vector: number[],
nRetrieve: number,
embeddingsProviderId: string,
nested: boolean = false,
): Promise<Chunk[]> {
const lancedb = await import("vectordb");
const db = await SqliteDb.get();
await createDocsTable(db);
const lance = await lancedb.connect(getLanceDbPath());
const downloadDocs = async () => {
const config = configs.find((config) => config.startUrl === baseUrl);
if (config) {
await downloadPreIndexedDocs(embeddingsProviderId, config.title);
return await retrieveDocs(
baseUrl,
vector,
nRetrieve,
embeddingsProviderId,
true,
);
}
return undefined;
};
const tableNames = await lance.tableNames();
if (!tableNames.includes(DOCS_TABLE_NAME)) {
const downloaded = await downloadDocs();
if (downloaded) return downloaded;
}
const table = await lance.openTable(DOCS_TABLE_NAME);
const docs: LanceDbDocsRow[] = await table
let docs: LanceDbDocsRow[] = await table
.search(vector)
.limit(nRetrieve)
.where(`baseUrl = '${baseUrl}'`)
.execute();
docs = docs.filter((doc) => doc.baseUrl === baseUrl);
if ((!docs || docs.length === 0) && !nested) {
const downloaded = await downloadDocs();
if (downloaded) return downloaded;
}
return docs.map((doc) => ({
digest: doc.path,
filepath: doc.path,

View file

@ -1,18 +0,0 @@
const esbuild = require("esbuild");
(async () => {
// Bundles the extension into one file
await esbuild.build({
entryPoints: ["crawl.ts"],
bundle: true,
outfile: "crawl.js",
external: ["jquery"],
format: "cjs",
platform: "node",
sourcemap: true,
loader: {
// eslint-disable-next-line @typescript-eslint/naming-convention
".node": "file",
},
});
})();

View file

@ -1,14 +1,12 @@
import {
Chunk,
ChunkWithoutID,
EmbeddingsProvider,
IndexingProgressUpdate,
} from "../..";
import { MAX_CHUNK_SIZE } from "../../llm/constants";
import { markdownChunker } from "../chunk/markdown";
import { crawlSubpages } from "./crawl";
import { addDocs, listDocs } from "./db";
import { convertURLToMarkdown } from "./urlToMarkdown";
import { urlToArticle, chunkArticle } from "./article";
export async function* indexDocs(
title: string,
@ -31,6 +29,7 @@ export async function* indexDocs(
const subpathGenerator = crawlSubpages(baseUrl);
let { value, done } = await subpathGenerator.next();
while (true) {
if (done) {
break;
@ -49,52 +48,26 @@ export async function* indexDocs(
const chunks: Chunk[] = [];
const embeddings: number[][] = [];
let markdownForSubpaths = await Promise.all(
subpaths.map((subpath) => convertURLToMarkdown(new URL(subpath, baseUrl))),
let articles = await Promise.all(
subpaths.map(subpath => urlToArticle(subpath, baseUrl)),
);
// Filter out undefineds
let filteredSubpaths: string[] = [];
let filteredMarkdown: string[] = [];
for (let i = 0; i < subpaths.length; i++) {
if (markdownForSubpaths[i]) {
filteredSubpaths.push(subpaths[i]);
filteredMarkdown.push(markdownForSubpaths[i]!);
}
}
subpaths = filteredSubpaths;
markdownForSubpaths = filteredMarkdown;
for (const article of articles) {
if (!article) continue;
for (let i = 0; i < subpaths.length; i++) {
const subpath = subpaths[i];
yield {
progress: Math.max(1, Math.floor(100 / (subpaths.length + 1))),
desc: `${subpath}`,
desc: `${article.subpath}`,
};
const markdown = markdownForSubpaths[i]!;
const markdownChunks: ChunkWithoutID[] = [];
for await (const chunk of markdownChunker(markdown, MAX_CHUNK_SIZE, 0)) {
markdownChunks.push(chunk);
}
const subpathEmbeddings = await embeddingsProvider.embed(
markdownChunks.map((chunk) => chunk.content),
chunkArticle(article).map(chunk => {
chunks.push(chunk);
return chunk.content;
})
);
markdownChunks.forEach((chunk, index) => {
chunks.push({
...chunk,
filepath:
subpath +
(chunk.otherMetadata?.fragment
? `#${chunk.otherMetadata.fragment}`
: ""),
otherMetadata: chunk.otherMetadata,
index,
digest: subpath,
});
});
embeddings.push(...subpathEmbeddings);
}

View file

@ -0,0 +1,59 @@
import { Chunk } from "../..";
import { addDocs } from "./db";
const request = require("request");
export async function downloadFromS3(
bucket: string,
fileName: string,
region: string,
): Promise<string> {
return new Promise<string>((resolve, reject) => {
let data = "";
const download = request({
url: `https://${bucket}.s3.${region}.amazonaws.com/${fileName}`,
});
download.on("response", (response: any) => {
if (response.statusCode !== 200) {
reject(new Error("No body returned when downloading from S3 bucket"));
}
});
download.on("error", (err: any) => {
reject(err);
});
download.on("data", (chunk: any) => {
data += chunk;
});
download.on("end", () => {
resolve(data);
});
});
}
export interface SiteIndexingResults {
chunks: (Chunk & { embedding: number[] })[];
url: string;
title: string;
}
export async function downloadPreIndexedDocs(
embeddingsProviderId: string,
title: string,
) {
const data = await downloadFromS3(
"continue-indexed-docs",
`${embeddingsProviderId}/${title}`,
"us-west-1",
);
const results = JSON.parse(data) as SiteIndexingResults;
await addDocs(
results.title,
new URL(results.url),
results.chunks,
results.chunks.map((c) => c.embedding),
);
}

View file

@ -0,0 +1,216 @@
export interface SiteIndexingConfig {
startUrl: string;
title: string;
rootUrl: string;
}
const configs: SiteIndexingConfig[] = [
{
title: "Jinja",
startUrl: "https://jinja.palletsprojects.com/en/3.1.x/",
rootUrl: "https://jinja.palletsprojects.com/en/3.1.x/",
},
{
title: "React",
startUrl: "https://react.dev/reference/",
rootUrl: "https://react.dev/reference/",
},
{
title: "PostHog",
startUrl: "https://posthog.com/docs",
rootUrl: "https://posthog.com/docs",
},
{
title: "Express",
startUrl: "https://expressjs.com/en/5x/api.html",
rootUrl: "https://expressjs.com/en/5x/",
},
{
title: "OpenAI",
startUrl: "https://platform.openai.com/docs/",
rootUrl: "https://platform.openai.com/docs/",
},
{
title: "Prisma",
startUrl: "https://www.prisma.io/docs",
rootUrl: "https://www.prisma.io/docs",
},
{
title: "Boto3",
startUrl:
"https://boto3.amazonaws.com/v1/documentation/api/latest/index.html",
rootUrl: "https://boto3.amazonaws.com/v1/documentation/api/latest/",
},
{
title: "Pytorch",
startUrl: "https://pytorch.org/docs/stable/",
rootUrl: "https://pytorch.org/docs/stable/",
},
{
title: "Redis",
startUrl: "https://redis.io/docs/",
rootUrl: "https://redis.io/docs/",
},
{
title: "Axios",
startUrl: "https://axios-http.com/docs/intro",
rootUrl: "https://axios-http.com/docs",
},
{
title: "Redwood JS",
startUrl: "https://redwoodjs.com/docs/introduction",
rootUrl: "https://redwoodjs.com/docs",
},
{
title: "GraphQL",
startUrl: "https://graphql.org/learn/",
rootUrl: "https://graphql.org/learn/",
},
{
title: "Typescript",
startUrl: "https://www.typescriptlang.org/docs/",
rootUrl: "https://www.typescriptlang.org/docs/",
},
{
title: "Jest",
startUrl: "https://jestjs.io/docs/getting-started",
rootUrl: "https://jestjs.io/docs",
},
{
title: "Tailwind CSS",
startUrl: "https://tailwindcss.com/docs/installation",
rootUrl: "https://tailwindcss.com/docs",
},
{
title: "Vue.js",
startUrl: "https://vuejs.org/guide/introduction.html",
rootUrl: "https://vuejs.org",
},
{
title: "Svelte",
startUrl: "https://svelte.dev/docs/introduction",
rootUrl: "https://svelte.dev/docs",
},
{
title: "GitHub Actions",
startUrl: "https://docs.github.com/en/actions",
rootUrl: "https://docs.github.com/en/actions",
},
{
title: "NodeJS",
startUrl: "https://nodejs.org/docs/latest/api/",
rootUrl: "https://nodejs.org/docs/latest/api/",
},
{
title: "Socket.io",
startUrl: "https://socket.io/docs/v4/",
rootUrl: "https://socket.io/docs/v4/",
},
{
title: "Gradle",
startUrl: "https://docs.gradle.org/current/userguide/userguide.html",
rootUrl: "https://docs.gradle.org/current",
},
{
title: "Redux Toolkit",
startUrl: "https://redux-toolkit.js.org/introduction/getting-started",
rootUrl: "https://redux-toolkit.js.org",
},
{
title: "Chroma",
startUrl: "https://docs.trychroma.com/",
rootUrl: "https://docs.trychroma.com/",
},
{
title: "SQLite",
startUrl: "https://www.sqlite.org/docs.html",
rootUrl: "https://www.sqlite.org",
},
{
title: "Redux",
startUrl: "https://redux.js.org/introduction/getting-started",
rootUrl: "https://redux.js.org",
},
{
title: "Prettier",
startUrl: "https://prettier.io/docs/en/",
rootUrl: "https://prettier.io/docs/en/",
},
{
title: "VS Code Extension API",
startUrl: "https://code.visualstudio.com/api",
rootUrl: "https://code.visualstudio.com/api",
},
{
title: "Continue",
startUrl: "https://continue.dev/docs/intro",
rootUrl: "https://continue.dev/docs",
},
{
title: "jQuery",
startUrl: "https://api.jquery.com/",
rootUrl: "https://api.jquery.com/",
},
{
title: "Python",
startUrl: "https://docs.python.org/3/",
rootUrl: "https://docs.python.org/3/",
},
{
title: "Rust",
startUrl: "https://doc.rust-lang.org/book/",
rootUrl: "https://doc.rust-lang.org/book/",
},
{
title: "IntelliJ Platform SDK",
startUrl: "https://plugins.jetbrains.com/docs/intellij/welcome.html",
rootUrl: "https://plugins.jetbrains.com/docs/intellij",
},
{
title: "Docker",
startUrl: "https://docs.docker.com/",
rootUrl: "https://docs.docker.com/",
},
{
title: "NPM",
startUrl: "https://docs.npmjs.com/",
rootUrl: "https://docs.npmjs.com/",
},
{
title: "TipTap",
startUrl: "https://tiptap.dev/docs/editor/introduction",
rootUrl: "https://tiptap.dev/docs",
},
{
title: "esbuild",
startUrl: "https://esbuild.github.io/",
rootUrl: "https://esbuild.github.io/",
},
{
title: "Tree Sitter",
startUrl: "https://tree-sitter.github.io/tree-sitter/",
rootUrl: "https://tree-sitter.github.io/tree-sitter/",
},
{
title: "Netlify",
startUrl: "https://docs.netlify.com/",
rootUrl: "https://docs.netlify.com/",
},
{
title: "Replicate",
startUrl: "https://replicate.com/docs",
rootUrl: "https://replicate.com/docs",
},
{
title: "HTML",
startUrl: "https://www.w3schools.com/html/default.asp",
rootUrl: "https://www.w3schools.com/html",
},
{
title: "CSS",
startUrl: "https://www.w3schools.com/css/default.asp",
rootUrl: "https://www.w3schools.com/css",
},
];
export default configs;

View file

@ -1,94 +0,0 @@
import { Octokit } from "@octokit/rest";
import { NodeHtmlMarkdown, PostProcessResult } from "node-html-markdown";
const nhm = new NodeHtmlMarkdown(
{},
{
a: {
postprocess: (ctx) => {
if (ctx.node.tagName === "A") {
// Remove sections links (e.g. '<a href="#section-name" title="Link to this heading">#</a>')
if (ctx.content.length <= 1) {
return PostProcessResult.RemoveNode;
}
}
return ctx.content;
},
},
},
undefined,
);
const STRIP_BEFORE = ["\n# "];
const STRIP_AFTER_AND_INCLUDING = ["Was this page helpful?"];
const octokit = new Octokit({
auth: undefined,
});
async function retrieveGitHubBlob(url: URL): Promise<string | undefined> {
const [_, owner, repo, _tree, _main, ...path] = url.pathname.split("/");
const response = await octokit.repos.getContent({
owner,
repo,
path: path.join("/"),
});
if (response.status !== 200) {
return undefined;
}
const content = Buffer.from(
(response.data as any).content || "",
"base64",
).toString();
const fileExtension = url.pathname.split(".").slice(-1)[0];
if (fileExtension === "md") {
return content;
}
return `\`\`\`${fileExtension} title=${path.join("/")}\n${content}\n\`\`\``;
}
export async function convertURLToMarkdown(
url: URL,
): Promise<string | undefined> {
try {
if (url.hostname === "github.com") {
return await retrieveGitHubBlob(url);
}
const response = await fetch(url);
if (!response.ok) {
return undefined;
}
const htmlContent = await response.text();
let markdown = nhm.translate(htmlContent).trimEnd();
// Check for 404
if (markdown.includes("404 Not Found")) {
return undefined;
}
// Strip above and below certain phrases
STRIP_BEFORE.forEach((phrase) => {
const index = markdown.indexOf(phrase);
if (index !== -1) {
markdown = markdown.slice(index);
}
});
STRIP_AFTER_AND_INCLUDING.forEach((phrase) => {
const index = markdown.lastIndexOf(phrase);
if (index !== -1) {
markdown = markdown.slice(0, index);
}
});
return markdown;
} catch (err) {
console.error("Error converting URL to markdown", err);
return undefined;
}
}

View file

@ -0,0 +1,30 @@
import { EmbedOptions } from "../..";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider";
import { fetchWithExponentialBackoff } from "./util";
class DeepInfraEmbeddingsProvider extends BaseEmbeddingsProvider {
static defaultOptions: Partial<EmbedOptions> | undefined = {
model: "sentence-transformers/all-MiniLM-L6-v2",
};
get id(): string {
return this.options.model ?? "deepinfra";
}
async embed(chunks: string[]) {
const resp = await fetchWithExponentialBackoff(
`https://api.deepinfra.com/v1/inference/${this.options.model}`,
{
method: "POST",
headers: {
Authorization: `bearer ${this.options.apiKey}`,
},
body: JSON.stringify({ inputs: chunks }),
},
);
const data = await resp.json();
return data.embeddings;
}
}
export default DeepInfraEmbeddingsProvider;

View file

@ -23,7 +23,7 @@ class OllamaEmbeddingsProvider extends BaseEmbeddingsProvider {
};
get id(): string {
return "ollama::" + this.options.model;
return this.options.model ?? "ollama";
}
async embed(chunks: string[]) {

View file

@ -1,14 +1,15 @@
import { EmbedOptions } from "../..";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider";
import { fetchWithExponentialBackoff } from "./util";
class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider {
static defaultOptions: Partial<EmbedOptions> | undefined = {
apiBase: "https://api.openai.com/v1",
model: "text-embedding-3-large",
model: "text-embedding-3-small",
};
get id(): string {
return "openai::" + this.options.model;
return this.options.model ?? "openai";
}
async embed(chunks: string[]) {
@ -19,17 +20,20 @@ class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider {
return await Promise.all(
chunks.map(async (chunk) => {
const resp = await fetch(`${apiBase}/embeddings`, {
method: "POST",
body: JSON.stringify({
input: chunk,
model: this.options.model,
}),
headers: {
Authorization: `Bearer ${this.options.apiKey}`,
"Content-Type": "application/json",
const resp = await fetchWithExponentialBackoff(
`${apiBase}/embeddings`,
{
method: "POST",
body: JSON.stringify({
input: chunk,
model: this.options.model,
}),
headers: {
Authorization: `Bearer ${this.options.apiKey}`,
"Content-Type": "application/json",
},
},
});
);
const data = await resp.json();
return data.data[0].embedding;
}),

View file

@ -36,7 +36,7 @@ class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider {
}
get id(): string {
return "transformers-js";
return "sentence-transformers/all-MiniLM-L6-v2";
}
async embed(chunks: string[]) {

View file

@ -0,0 +1,23 @@
export const fetchWithExponentialBackoff = async (
url: string,
options: RequestInit,
retries: number = 5,
delay: number = 1000,
): Promise<Response> => {
try {
const response = await fetch(url, options);
if (!response.ok && response.status === 429 && retries > 0) {
// Wait for delay milliseconds and retry
await new Promise((resolve) => setTimeout(resolve, delay));
return fetchWithExponentialBackoff(url, options, retries - 1, delay * 2);
}
return response;
} catch (error) {
if (retries > 0) {
// Wait for delay milliseconds and retry
await new Promise((resolve) => setTimeout(resolve, delay));
return fetchWithExponentialBackoff(url, options, retries - 1, delay * 2);
}
throw error;
}
};

View file

@ -16,6 +16,7 @@ import {
} from "./templates/chat";
import {
alpacaEditPrompt,
claudeEditPrompt,
codeLlama70bEditPrompt,
codellamaEditPrompt,
deepseekEditPrompt,
@ -34,6 +35,7 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [
"openai",
"ollama",
"together",
"anthropic",
];
const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [
@ -177,7 +179,7 @@ function autodetectTemplateFunction(
return null;
}
const templateType = explicitTemplate || autodetectTemplateType(model);
const templateType = explicitTemplate ?? autodetectTemplateType(model);
if (templateType) {
const mapping: Record<TemplateType, any> = {
@ -207,7 +209,7 @@ function autodetectPromptTemplates(
model: string,
explicitTemplate: TemplateType | undefined = undefined,
) {
const templateType = explicitTemplate || autodetectTemplateType(model);
const templateType = explicitTemplate ?? autodetectTemplateType(model);
const templates: Record<string, any> = {};
let editTemplate = null;
@ -236,6 +238,8 @@ function autodetectPromptTemplates(
editTemplate = neuralChatEditPrompt;
} else if (templateType === "codellama-70b") {
editTemplate = codeLlama70bEditPrompt;
} else if (templateType === "anthropic") {
editTemplate = claudeEditPrompt;
} else if (templateType) {
editTemplate = simplestEditPrompt;
}

View file

@ -44,7 +44,7 @@ function countTokens(
return content.reduce((acc, part) => {
return acc + part.type === "imageUrl"
? countImageTokens(part)
: encoding.encode(part.text || "", "all", []).length;
: encoding.encode(part.text ?? "", "all", []).length;
}, 0);
} else {
return encoding.encode(content, "all", []).length;

View file

@ -79,22 +79,22 @@ export abstract class BaseLLM implements ILLM {
};
const templateType =
options.template || autodetectTemplateType(options.model);
options.template ?? autodetectTemplateType(options.model);
this.title = options.title;
this.uniqueId = options.uniqueId || "None";
this.uniqueId = options.uniqueId ?? "None";
this.model = options.model;
this.systemMessage = options.systemMessage;
this.contextLength = options.contextLength || DEFAULT_CONTEXT_LENGTH;
this.contextLength = options.contextLength ?? DEFAULT_CONTEXT_LENGTH;
this.completionOptions = {
...options.completionOptions,
model: options.model || "gpt-4",
maxTokens: options.completionOptions?.maxTokens || DEFAULT_MAX_TOKENS,
maxTokens: options.completionOptions?.maxTokens ?? DEFAULT_MAX_TOKENS,
};
if (CompletionOptionsForModels[options.model as ModelName]) {
this.completionOptions = mergeJson(
this.completionOptions,
CompletionOptionsForModels[options.model as ModelName] || {},
CompletionOptionsForModels[options.model as ModelName] ?? {},
);
}
this.requestOptions = options.requestOptions;
@ -103,7 +103,7 @@ export abstract class BaseLLM implements ILLM {
...options.promptTemplates,
};
this.templateMessages =
options.templateMessages ||
options.templateMessages ??
autodetectTemplateFunction(
options.model,
this.providerName,
@ -146,7 +146,7 @@ export abstract class BaseLLM implements ILLM {
options.model,
messages,
contextLength,
options.maxTokens || DEFAULT_MAX_TOKENS,
options.maxTokens ?? DEFAULT_MAX_TOKENS,
this.supportsImages(),
undefined,
functions,
@ -219,7 +219,7 @@ ${prompt}`;
// Most of the requestOptions aren't available in the browser
const headers = new Headers(init?.headers);
for (const [key, value] of Object.entries(
this.requestOptions?.headers || {},
this.requestOptions?.headers ?? {},
)) {
headers.append(key, value as string);
}
@ -263,7 +263,7 @@ ${prompt}`;
completionOptions.model,
this.contextLength,
prompt,
completionOptions.maxTokens || DEFAULT_MAX_TOKENS,
completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
);
if (!raw) {
@ -302,7 +302,7 @@ ${prompt}`;
completionOptions.model,
this.contextLength,
prompt,
completionOptions.maxTokens || DEFAULT_MAX_TOKENS,
completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
);
if (!raw) {

View file

@ -1,16 +1,19 @@
import { BaseLLM } from "..";
import { CompletionOptions, LLMOptions, ModelProvider } from "../..";
import {
ChatMessage,
CompletionOptions,
LLMOptions,
ModelProvider,
} from "../..";
import { streamSse } from "../stream";
import { anthropicTemplateMessages } from "../templates/chat";
class Anthropic extends BaseLLM {
static providerName: ModelProvider = "anthropic";
static defaultOptions: Partial<LLMOptions> = {
model: "claude-2",
templateMessages: anthropicTemplateMessages,
contextLength: 100_000,
model: "claude-3-opus-20240229",
contextLength: 200_000,
completionOptions: {
model: "claude-2",
model: "claude-3-opus-20240229",
maxTokens: 4096,
},
apiBase: "https://api.anthropic.com/v1",
@ -20,25 +23,24 @@ class Anthropic extends BaseLLM {
super(options);
}
private _convertArgs(options: CompletionOptions, prompt: string) {
private _convertArgs(options: CompletionOptions) {
const finalOptions = {
prompt,
top_k: options.topK,
top_p: options.topP,
temperature: options.temperature,
max_tokens_to_sample: options.maxTokens,
model: options.model,
max_tokens: options.maxTokens ?? 2048,
model: options.model === "claude-2" ? "claude-2.1" : options.model,
stop_sequences: options.stop,
};
return finalOptions;
}
protected async _complete(
prompt: string,
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): Promise<string> {
const response = await this.fetch(this.apiBase + "/complete", {
): AsyncGenerator<ChatMessage> {
const response = await this.fetch(this.apiBase + "/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
@ -47,35 +49,16 @@ class Anthropic extends BaseLLM {
"x-api-key": this.apiKey as string,
},
body: JSON.stringify({
...this._convertArgs(options, prompt),
stream: false,
}),
});
const result = await response.json();
return result.completion;
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const response = await this.fetch(this.apiBase + "/complete", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": this.apiKey as string,
},
body: JSON.stringify({
...this._convertArgs(options, prompt),
...this._convertArgs(options),
messages: messages.filter((m) => m.role !== "system"),
system: this.systemMessage,
stream: true,
}),
});
for await (const value of streamSse(response)) {
if (value.completion) {
yield value.completion;
if (value.delta?.text) {
yield { role: "assistant", content: value.delta.text };
}
}
}

View file

@ -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-green-l6vsfbzhba-uw.a.run.app";
const SERVER_URL = "https://node-proxy-server-blue-l6vsfbzhba-uw.a.run.app";
class FreeTrial extends BaseLLM {
static providerName: ModelProvider = "free-trial";
@ -21,7 +21,7 @@ class FreeTrial extends BaseLLM {
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
max_tokens: options.maxTokens,
stop: options.stop?.slice(0, 4),
stop: options.stop?.slice(0, 2),
temperature: options.temperature,
top_p: options.topP,
};

View file

@ -90,7 +90,7 @@ class Ollama extends BaseLLM {
"starcoder-1b": "starcoder:1b",
"starcoder-3b": "starcoder:3b",
"stable-code-3b": "stable-code:3b",
}[this.model] || this.model
}[this.model] ?? this.model
);
}
@ -115,7 +115,7 @@ class Ollama extends BaseLLM {
const finalOptions: any = {
model: this._getModel(),
raw: true,
keep_alive: 60 * 30, // 30 minutes
keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
options: {
temperature: options.temperature,
top_p: options.topP,

View file

@ -139,7 +139,7 @@ class OpenAI extends BaseLLM {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
"api-key": this.apiKey || "", // For Azure
"api-key": this.apiKey ?? "", // For Azure
},
body: JSON.stringify({
...args,
@ -148,7 +148,7 @@ class OpenAI extends BaseLLM {
});
for await (const value of streamSse(response)) {
if (value.choices?.[0]?.text) {
if (value.choices?.[0]?.text && value.finish_reason !== "eos") {
yield value.choices[0].text;
}
}
@ -189,7 +189,7 @@ class OpenAI extends BaseLLM {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
"api-key": this.apiKey || "", // For Azure
"api-key": this.apiKey ?? "", // For Azure
},
body: JSON.stringify(body),
});
@ -206,7 +206,7 @@ class OpenAI extends BaseLLM {
method: "GET",
headers: {
Authorization: `Bearer ${this.apiKey}`,
"api-key": this.apiKey || "", // For Azure
"api-key": this.apiKey ?? "", // For Azure
},
});

View file

@ -113,7 +113,7 @@ export async function llmFromDescription(
...desc.completionOptions,
};
systemMessage = desc.systemMessage || systemMessage;
systemMessage = desc.systemMessage ?? systemMessage;
if (systemMessage !== undefined) {
systemMessage = await renderTemplatedString(systemMessage, readFile);
}
@ -122,14 +122,14 @@ export async function llmFromDescription(
...desc,
completionOptions: {
...finalCompletionOptions,
model: desc.model || cls.defaultOptions?.model || "codellama-7b", // TODO: Fix up all the ?'s
maxTokens:
finalCompletionOptions.maxTokens ||
cls.defaultOptions?.completionOptions?.maxTokens ||
DEFAULT_MAX_TOKENS,
model: (desc.model || cls.defaultOptions?.model) ?? "codellama-7b",
maxTokens: (
finalCompletionOptions.maxTokens ??
cls.defaultOptions?.completionOptions?.maxTokens
) ?? DEFAULT_MAX_TOKENS,
},
systemMessage,
};
};
return new cls(options);
}

View file

@ -1,3 +1,6 @@
import { ChatMessage } from "../..";
import { PromptTemplate } from "../../util";
const simplifiedEditPrompt = `Consider the following code:
\`\`\`{{{language}}}
{{{codeToEdit}}}
@ -144,8 +147,33 @@ const codeLlama70bEditPrompt = `<s>Source: system\n\n You are an expert programm
{{{codeToEdit}}}
\`\`\` <step> Source: assistant\nDestination: user\n\n `;
const claudeEditPrompt: PromptTemplate = (
history: ChatMessage[],
otherData: Record<string, string>,
) => [
{
role: "user",
content: `\
\`\`\`${otherData.language}
${otherData.codeToEdit}
\`\`\`
You are an expert programmer. You will rewrite the above code to do the following:
${otherData.userInput}
Output only a code block with the rewritten code:
`,
},
{
role: "assistant",
content: `Sure! Here is the rewritten code:
\`\`\`${otherData.language}`,
},
];
export {
alpacaEditPrompt,
claudeEditPrompt,
codeLlama70bEditPrompt,
codellamaEditPrompt,
codellamaInfillEditPrompt,

2531
core/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -19,7 +19,10 @@
"ts-jest": "^29.1.1"
},
"dependencies": {
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@types/jsdom": "^21.1.6",
"@types/mozilla-readability": "^0.2.1",
"@types/node-fetch": "^2.6.11",
"@xenova/transformers": "^2.14.0",
"adf-to-md": "^1.1.0",
@ -34,7 +37,9 @@
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"js-tiktoken": "^1.0.8",
"jsdom": "^24.0.0",
"llama-tokenizer-js": "^1.1.3",
"llm-code-highlighter": "^0.0.14",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",
"ollama": "^0.4.6",
@ -42,6 +47,7 @@
"pg": "^8.11.3",
"posthog-node": "^3.6.2",
"replicate": "^0.26.0",
"request": "^2.88.2",
"socket.io-client": "^4.7.3",
"sqlite": "^5.1.1",
"sqlite3": "^5.1.7",

View file

@ -34,6 +34,14 @@ export type Protocol = {
{ model: SerializedContinueConfig["models"][number] },
void,
];
"config/updateRemoteConfigSettings": [
{
remoteConfigServerUrl: string;
remoteConfigSyncPeriod: number;
userToken: string;
},
void,
];
"config/getBrowserSerialized": [
undefined,
Promise<BrowserSerializedContinueConfig>,

View file

@ -92,7 +92,7 @@ export function dedentAndGetCommonWhitespace(s: string): [string, string] {
return [lines.map((x) => x.replace(lcp, "")).join("\n"), lcp];
}
type PromptTemplate =
export type PromptTemplate =
| string
| ((
history: ChatMessage[],
@ -121,7 +121,7 @@ export function renderPromptTemplate(
}
export function getBasename(filepath: string, n: number = 1): string {
return filepath.split(/[\\/]/).pop() || "";
return filepath.split(/[\\/]/).pop() ?? "";
}
export function getLastNPathParts(filepath: string, n: number): string {
@ -187,5 +187,6 @@ export function getMarkdownLanguageTagForFile(filepath: string): string {
}
export function copyOf(obj: any): any {
if (obj === null || obj === undefined) return obj;
return JSON.parse(JSON.stringify(obj));
}

View file

@ -16,6 +16,7 @@ export class Telemetry {
}
static async setup(allow: boolean, uniqueId: string) {
Telemetry.uniqueId = uniqueId;
if (!allow) {
Telemetry.client = undefined;
} else {

View file

@ -1,4 +1,4 @@
import { DiffLine, ILLM } from "..";
import { ChatMessage, DiffLine, ILLM } from "..";
import {
filterCodeBlockLines,
filterEnglishLinesAtEnd,
@ -8,7 +8,6 @@ import {
} 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";
@ -17,16 +16,13 @@ function constructPrompt(
llm: ILLM,
userInput: string,
language: string | undefined,
): string {
): string | ChatMessage[] {
const template = llm.promptTemplates?.edit ?? gptEditPrompt;
const rendered = renderPromptTemplate(template, [], {
return renderPromptTemplate(template, [], {
userInput,
codeToEdit,
language: language || "",
language: language ?? "",
});
return typeof rendered === "string"
? rendered
: stripImages(rendered[rendered.length - 1].content);
}
async function* addIndentation(
@ -59,7 +55,10 @@ export async function* streamDiffLines(
const prompt = constructPrompt(oldCode, llm, input, language);
const inept = modelIsInept(llm.model);
const completion = llm.streamComplete(prompt);
const completion =
typeof prompt === "string"
? llm.streamComplete(prompt)
: llm.streamChat(prompt);
let lines = streamLines(completion);

5944
core/yarn.lock Normal file

File diff suppressed because it is too large Load diff

View file

@ -118,7 +118,7 @@ Type '@jira' to reference the conversation in a Jira issue. Make sure to include
```json
{
"name": "issue",
"name": "jira",
"params": {
"domain": "company.atlassian.net",
"email": "someone@somewhere.com",
@ -127,13 +127,25 @@ Type '@jira' to reference the conversation in a Jira issue. Make sure to include
}
```
#### Jira Datacenter Support
This context provider supports both Jira API version 2 and 3. It will use version 3 by default since
that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need
to set the API Version to 2 using the `apiVersion` property.
````json
"params": {
"apiVersion": "2",
...
}
#### Issue Query
By default, the following query will be used to find issues:
```jql
assignee = currentUser() AND resolution = Unresolved order by updated DESC
```
````
You can override this query by setting the `issueQuery` parameter.
@ -230,7 +242,7 @@ interface CustomContextProvider {
description?: string;
getContextItems(
query: string,
extras: ContextProviderExtras
extras: ContextProviderExtras,
): Promise<ContextItem[]>;
}
```
@ -250,7 +262,7 @@ const RagContextProvider: CustomContextProvider = {
getContextItems: async (
query: string,
extras: ContextProviderExtras
extras: ContextProviderExtras,
): Promise<ContextItem[]> => {
const response = await fetch("https://internal_rag_server.com/retrieve", {
method: "POST",
@ -299,7 +311,7 @@ const ReadMeContextProvider: CustomContextProvider = {
getContextItems: async (
query: string,
extras: ContextProviderExtras
extras: ContextProviderExtras,
): Promise<ContextItem[]> => {
// 'query' is the filepath of the README selected from the dropdown
const content = await extras.ide.readFile(query);
@ -313,12 +325,12 @@ const ReadMeContextProvider: CustomContextProvider = {
},
loadSubmenuItems: async (
args: LoadSubmenuItemsArgs
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> => {
// Filter all workspace files for READMEs
const allFiles = await args.ide.listWorkspaceContents();
const readmes = allFiles.filter((filepath) =>
filepath.endsWith("README.md")
filepath.endsWith("README.md"),
);
// Return the items that will be shown in the dropdown

View file

@ -14,3 +14,5 @@ Currently, you can customize the following:
- [Context Providers](./context-providers.md) - Type '@' to easily add attachments to your prompt. Define which sources you want to reference, including GitHub Issues, terminal output, or automatically retrieved snippets from your codebase.
- [Slash Commands](./slash-commands.md) - Call custom prompts or programs written with our SDK by typing `/`.
- [Other Configuration](../reference/config.mdx) - Configure other settings like the system message and temperature.
If you'd like to share Continue configuration with others, you can add a `.continuerc.json` to the root of your project. It has the same JSON Schema definition as `config.json`, and will automatically be applied on top of the local `config.json`.

View file

@ -14,7 +14,8 @@ Many developers have begun to use ChatGPT while coding; however, the experience
Some examples of what you can achieve are:
- Use cmd/ctrl + shift + L to generate boilerplate code from natural language
- Use cmd/ctrl + I to generate boilerplate code from natural language
- Use our local tab-autocomplete to get inline suggestions and write boilerplate code quickly
- Highlight code, describe how to refactor it, and have changes streamed into your editor
- Ask high-level questions about your codebase, with Continue automatically finding relevant files
- Quickly generate unit tests for any function or class

View file

@ -17,6 +17,7 @@ You can run a model on your local computer using:
- [Ollama](../reference/Model%20Providers/ollama.md)
- [LM Studio](../reference/Model%20Providers/lmstudio.md)
- [Llama.cpp](../reference/Model%20Providers/llamacpp.md)
- [llamafile](../reference/Model%20Providers/llamafile) ((OpenAI compatible server)
- [LocalAI](../reference/Model%20Providers/openai.md) (OpenAI compatible server)
- [Text generation web UI](../reference/Model%20Providers/openai.md) (OpenAI compatible server)
- [FastChat](../reference/Model%20Providers/openai.md) (OpenAI compatible server)

View file

@ -8,8 +8,7 @@ The following shows the JSON Schema definition for `config.json`. You can also d
<JSONSchemaViewer
schema={Schema}
resolverOptions={{
jsonPointer:
"#/definitions/continuedev__core__config__serialized_config__SerializedContinueConfig",
jsonPointer: "#/definitions/SerializedContinueConfig",
}}
/>

View file

@ -98,7 +98,7 @@ We also support other methods of generating embeddings, which can be configured
OpenAI's [embeddings](https://platform.openai.com/docs/guides/embeddings) are high dimensional embeddings that give great performance on both text and code.
Configuration for text-embedding-3-small Model
Configuration for text-embedding-3-small Model. This is default.
The text-embedding-3-small model offers an outstanding balance between performance and efficiency, suitable for a versatile range of applications.
```json title="~/.continue/config.json"

View file

@ -54,6 +54,11 @@
"title": "Number of threads",
"description": "The number of threads used in the generation process. Only available for Ollama (this is the num_thread parameter)",
"type": "integer"
},
"keepAlive": {
"title": "Ollama keep_alive",
"description": "The number of seconds after no requests are made to unload the model from memory. Defaults to 60*30 = 30min",
"type": "integer"
}
}
},
@ -141,7 +146,7 @@
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.py where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/anthropicllm)",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama pull <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/ollama)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/ollama)",
"### Huggingface TGI\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfacetgi)",
"### Huggingface Inference API\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfaceinferenceapi)",
"### Llama.cpp\nllama.cpp comes with a [built-in server](https://github.com/ggerganov/llama.cpp/tree/master/examples/server#llamacppexampleserver) that can be run from source. To do this:\n\n1. Clone the repository with `git clone https://github.com/ggerganov/llama.cpp`.\n2. `cd llama.cpp`\n3. Run `make` to build the server.\n4. Download the model you'd like to use and place it in the `llama.cpp/models` directory (the best place to find models is [The Bloke on HuggingFace](https://huggingface.co/TheBloke))\n5. Run the llama.cpp server with the command below (replacing with the model you downloaded):\n\n```shell\n.\\server.exe -c 4096 --host 0.0.0.0 -t 16 --mlock -m models/codellama-7b-instruct.Q8_0.gguf\n```\n\nAfter it's up and running, you can start using Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/llamacpp)",
@ -493,7 +498,13 @@
"model": {
"anyOf": [
{
"enum": ["claude-2", "claude-instant-1"]
"enum": [
"claude-2",
"claude-instant-1",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-2.1"
]
},
{
"type": "string"
@ -837,6 +848,10 @@
"deepseek-7b",
"deepseek-33b",
"claude-2",
"claude-instant-1",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-2.1",
"chat-bison-001",
"gemini-pro",
"mistral-tiny",
@ -1377,12 +1392,13 @@
"properties": {
"allowAnonymousTelemetry": {
"title": "Allow Anonymous Telemetry",
"markdownDescription": "If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data.",
"markdownDescription": "If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in [the docs](https://continue.dev/docs/telemetry).",
"default": true,
"type": "boolean"
},
"models": {
"title": "Models",
"markdownDescription": "Learn about setting up models in [the documentation](https://continue.dev/docs/model-setup/overview).",
"default": [
{
"title": "GPT-4 (trial)",
@ -1421,7 +1437,7 @@
},
"slashCommands": {
"title": "Slash Commands",
"description": "An array of slash commands that let you map custom Steps to a shortcut.",
"markdownDescription": "An array of slash commands that let you take custom actions from the sidebar. Learn more in the [documentation](https://continue.dev/docs/customization/slash-commands).",
"default": [],
"type": "array",
"items": {
@ -1430,7 +1446,7 @@
},
"customCommands": {
"title": "Custom Commands",
"description": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter /<name> in the text input, it will act as a shortcut to the prompt.",
"markdownDescription": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter /<name> in the text input, it will act as a shortcut to the prompt. Learn more in the [documentation](https://continue.dev/docs/customization/slash-commands#custom-commands-use-natural-language).",
"default": [
{
"name": "test",
@ -1445,7 +1461,7 @@
},
"contextProviders": {
"title": "Context Providers",
"description": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.",
"markdownDescription": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in [the documentation](https://continue.dev/docs/customization/context-providers).",
"default": [],
"type": "array",
"items": {
@ -1483,7 +1499,7 @@
},
"embeddingsProvider": {
"title": "Embeddings Provider",
"description": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser.",
"markdownDescription": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser. Learn about the other options [here](https://continue.dev/docs/walkthroughs/codebase-embeddings#embeddings-providers).",
"type": "object",
"properties": {
"provider": {
@ -1529,6 +1545,7 @@
"tabAutocompleteOptions": {
"title": "TabAutocompleteOptions",
"type": "object",
"markdownDescription": "These options let you customize your tab-autocomplete experience. Read about all options in [the docs](https://continue.dev/docs/walkthroughs/tab-autocomplete#configuration-options).",
"properties": {
"useCopyBuffer": {
"type": "boolean",
@ -1569,6 +1586,10 @@
"onlyMyCode": {
"type": "boolean",
"description": "If set to true, Continue will not include any snippets from go to definition unless they are within your repository"
},
"useOtherFiles": {
"type": "boolean",
"description": "Defaults to true. If set to false, Continue will not attempt to include snippets from other files."
}
},
"required": []

View file

@ -6,13 +6,14 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
and is generated by [Changie](https://github.com/miniscruff/changie).
Pre-release Changes
## 0.0.34 - 2024-03-03
### Added
* diff context provider
### Changed
* Allow LLM servers to handle templating
### Fixed
* Fix a few context providers / slash commands
* Fixed issues preventing proper extension startup
## v0.0.26 - 2023-12-28
### Added

View file

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

View file

@ -223,9 +223,27 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
}
val target = "$os-$arch"
val continueCorePath = Paths.get(pluginPath.toString(), "core", target, "pkg").toString()
println("Identified OS: $os, Arch: $arch")
val coreMessenger = CoreMessenger(continueCorePath, ideProtocolClient);
val corePath = Paths.get(pluginPath.toString(), "core").toString()
val targetPath = Paths.get(corePath, target).toString()
val continueCorePath = Paths.get(targetPath, "pkg" + (if (os == "win32") ".exe" else "")).toString()
// Copy targetPath / node_sqlite3.node to core / node_sqlite3.node
val nodeSqlite3Path = Paths.get(targetPath, "node_sqlite3.node")
// Create the build/Release path first
File(Paths.get(corePath, "build", "Release").toString()).mkdirs()
val coreNodeSqlite3Path = Paths.get(corePath, "build", "Release", "node_sqlite3.node")
if (!File(coreNodeSqlite3Path.toString()).exists()) {
Files.copy(nodeSqlite3Path, coreNodeSqlite3Path)
}
// esbuild needs permissions
val esbuildPath = Paths.get(targetPath, "esbuild"+ (if (os == "win32") ".exe" else "")).toString()
val coreMessenger = CoreMessenger(esbuildPath, continueCorePath, ideProtocolClient);
continuePluginService.coreMessenger = coreMessenger
}
}

View file

@ -10,7 +10,7 @@ import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.PosixFilePermission
class CoreMessenger(continueCorePath: String, ideProtocolClient: IdeProtocolClient) {
class CoreMessenger(esbuildPath: String, continueCorePath: String, ideProtocolClient: IdeProtocolClient) {
private val writer: OutputStreamWriter
private val reader: BufferedReader
private val process: Process
@ -135,6 +135,7 @@ class CoreMessenger(continueCorePath: String, ideProtocolClient: IdeProtocolClie
init {
// Set proper permissions
setPermissions(continueCorePath)
setPermissions(esbuildPath)
// Start the subprocess
val processBuilder = ProcessBuilder(continueCorePath)

View file

@ -11,48 +11,53 @@ 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)
try {
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 grayscale = (defaultBackground.red * 0.3 + defaultBackground.green * 0.59 + defaultBackground.blue * 0.11).toInt()
val adjustedRed: Int
val adjustedGreen: Int
val adjustedBlue: Int
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 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"
)
} catch (error: Error) {
return mapOf()
}
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"
)
}
}

View file

@ -93,7 +93,7 @@ class AsyncFileSaveListener : AsyncFileListener {
return object : AsyncFileListener.ChangeApplier {
override fun afterVfsChange() {
val config = readConfigJson()
ideProtocolClient.configUpdate(config)
ideProtocolClient.configUpdate()
}
}
}
@ -389,7 +389,7 @@ class IdeProtocolClient (
it
}
configUpdate(updatedConfig)
configUpdate()
setFileOpen(getConfigJsonPath())
}
"deleteModel" -> {
@ -401,7 +401,7 @@ class IdeProtocolClient (
config["models"] = models
config
}
configUpdate(configJson)
configUpdate()
}
"addOpenAIKey" -> {
val updatedConfig = editConfigJson { config ->
@ -420,7 +420,7 @@ class IdeProtocolClient (
config["models"] = models
config
}
configUpdate(updatedConfig)
configUpdate()
}
@ -435,9 +435,8 @@ class IdeProtocolClient (
}
}
fun configUpdate(config: Map<String, Any>) {
fun configUpdate() {
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> {

View file

@ -16,6 +16,9 @@ import javax.swing.JTextField
class ContinueSettingsComponent: DumbAware {
val panel: JPanel = JPanel(GridBagLayout())
val remoteConfigServerUrl: JTextField = JTextField()
val remoteConfigSyncPeriod: JTextField = JTextField()
val userToken: JTextField = JTextField()
init {
val constraints = GridBagConstraints()
@ -26,13 +29,25 @@ class ContinueSettingsComponent: DumbAware {
constraints.gridx = 0
constraints.gridy = GridBagConstraints.RELATIVE
panel.add(JLabel("Remote Config Server URL:"), constraints)
constraints.gridy++
constraints.gridy++
panel.add(remoteConfigServerUrl, constraints)
constraints.gridy++
panel.add(JLabel("Remote Config Sync Period (in minutes):"), constraints)
constraints.gridy++
panel.add(remoteConfigSyncPeriod, constraints)
constraints.gridy++
panel.add(JLabel("User Token:"), constraints)
constraints.gridy++
panel.add(userToken, constraints)
constraints.gridy++
// Add a "filler" component that takes up all remaining vertical space
constraints.weighty = 1.0
val filler = JPanel()
panel.add(filler, constraints)
}
}
@State(
@ -43,6 +58,9 @@ open class ContinueExtensionSettings : PersistentStateComponent<ContinueExtensio
class ContinueState {
var shownWelcomeDialog: Boolean = false
var remoteConfigServerUrl: String? = null
var remoteConfigSyncPeriod: Int = 60
var userToken: String? = null
}
var continueState: ContinueState = ContinueState()
@ -70,18 +88,28 @@ class ContinueExtensionConfigurable : Configurable {
}
override fun isModified(): Boolean {
val settings = ServiceManager.getService(ContinueExtensionSettings::class.java)
return false;
val settings = ContinueExtensionSettings.instance
val modified = mySettingsComponent?.remoteConfigServerUrl?.text != settings.continueState.remoteConfigServerUrl ||
mySettingsComponent?.remoteConfigSyncPeriod?.text?.toInt() != settings.continueState.remoteConfigSyncPeriod ||
mySettingsComponent?.userToken?.text != settings.continueState.userToken
return modified;
}
override fun apply() {
val settings =
ServiceManager.getService(ContinueExtensionSettings::class.java)
val settings = ContinueExtensionSettings.instance
settings.continueState.remoteConfigServerUrl = mySettingsComponent?.remoteConfigServerUrl?.text
settings.continueState.remoteConfigSyncPeriod = mySettingsComponent?.remoteConfigSyncPeriod?.text?.toInt() ?: 60
settings.continueState.userToken = mySettingsComponent?.userToken?.text
val continuePluginService = ServiceManager.getService(ContinuePluginService::class.java)
continuePluginService.coreMessenger?.request("config/updateRemoteConfigSettings", settings.continueState, null) { _ -> }
}
override fun reset() {
val settings =
ServiceManager.getService(ContinueExtensionSettings::class.java)
val settings = ContinueExtensionSettings.instance
mySettingsComponent?.remoteConfigServerUrl?.text = settings.continueState.remoteConfigServerUrl
mySettingsComponent?.remoteConfigSyncPeriod?.text = settings.continueState.remoteConfigSyncPeriod.toString()
mySettingsComponent?.userToken?.text = settings.continueState.userToken
}
override fun disposeUIResources() {

View file

@ -54,6 +54,11 @@
"title": "Number of threads",
"description": "The number of threads used in the generation process. Only available for Ollama (this is the num_thread parameter)",
"type": "integer"
},
"keepAlive": {
"title": "Ollama keep_alive",
"description": "The number of seconds after no requests are made to unload the model from memory. Defaults to 60*30 = 30min",
"type": "integer"
}
}
},
@ -141,7 +146,7 @@
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.py where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/anthropicllm)",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama pull <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/ollama)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/ollama)",
"### Huggingface TGI\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfacetgi)",
"### Huggingface Inference API\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfaceinferenceapi)",
"### Llama.cpp\nllama.cpp comes with a [built-in server](https://github.com/ggerganov/llama.cpp/tree/master/examples/server#llamacppexampleserver) that can be run from source. To do this:\n\n1. Clone the repository with `git clone https://github.com/ggerganov/llama.cpp`.\n2. `cd llama.cpp`\n3. Run `make` to build the server.\n4. Download the model you'd like to use and place it in the `llama.cpp/models` directory (the best place to find models is [The Bloke on HuggingFace](https://huggingface.co/TheBloke))\n5. Run the llama.cpp server with the command below (replacing with the model you downloaded):\n\n```shell\n.\\server.exe -c 4096 --host 0.0.0.0 -t 16 --mlock -m models/codellama-7b-instruct.Q8_0.gguf\n```\n\nAfter it's up and running, you can start using Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/llamacpp)",
@ -493,7 +498,13 @@
"model": {
"anyOf": [
{
"enum": ["claude-2", "claude-instant-1"]
"enum": [
"claude-2",
"claude-instant-1",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-2.1"
]
},
{
"type": "string"
@ -837,6 +848,10 @@
"deepseek-7b",
"deepseek-33b",
"claude-2",
"claude-instant-1",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-2.1",
"chat-bison-001",
"gemini-pro",
"mistral-tiny",
@ -1377,12 +1392,13 @@
"properties": {
"allowAnonymousTelemetry": {
"title": "Allow Anonymous Telemetry",
"markdownDescription": "If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data.",
"markdownDescription": "If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in [the docs](https://continue.dev/docs/telemetry).",
"default": true,
"type": "boolean"
},
"models": {
"title": "Models",
"markdownDescription": "Learn about setting up models in [the documentation](https://continue.dev/docs/model-setup/overview).",
"default": [
{
"title": "GPT-4 (trial)",
@ -1421,7 +1437,7 @@
},
"slashCommands": {
"title": "Slash Commands",
"description": "An array of slash commands that let you map custom Steps to a shortcut.",
"markdownDescription": "An array of slash commands that let you take custom actions from the sidebar. Learn more in the [documentation](https://continue.dev/docs/customization/slash-commands).",
"default": [],
"type": "array",
"items": {
@ -1430,7 +1446,7 @@
},
"customCommands": {
"title": "Custom Commands",
"description": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter /<name> in the text input, it will act as a shortcut to the prompt.",
"markdownDescription": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter /<name> in the text input, it will act as a shortcut to the prompt. Learn more in the [documentation](https://continue.dev/docs/customization/slash-commands#custom-commands-use-natural-language).",
"default": [
{
"name": "test",
@ -1445,7 +1461,7 @@
},
"contextProviders": {
"title": "Context Providers",
"description": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.",
"markdownDescription": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in [the documentation](https://continue.dev/docs/customization/context-providers).",
"default": [],
"type": "array",
"items": {
@ -1483,7 +1499,7 @@
},
"embeddingsProvider": {
"title": "Embeddings Provider",
"description": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser.",
"markdownDescription": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser. Learn about the other options [here](https://continue.dev/docs/walkthroughs/codebase-embeddings#embeddings-providers).",
"type": "object",
"properties": {
"provider": {
@ -1529,6 +1545,7 @@
"tabAutocompleteOptions": {
"title": "TabAutocompleteOptions",
"type": "object",
"markdownDescription": "These options let you customize your tab-autocomplete experience. Read about all options in [the docs](https://continue.dev/docs/walkthroughs/tab-autocomplete#configuration-options).",
"properties": {
"useCopyBuffer": {
"type": "boolean",
@ -1569,6 +1586,10 @@
"onlyMyCode": {
"type": "boolean",
"description": "If set to true, Continue will not include any snippets from go to definition unless they are within your repository"
},
"useOtherFiles": {
"type": "boolean",
"description": "Defaults to true. If set to false, Continue will not attempt to include snippets from other files."
}
},
"required": []

View file

@ -1,9 +1,9 @@
{
"customCommands": [
{
"name": "hello",
"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": "This is an example custom command. Use /config to edit it and create more"
}
]
}
"customCommands": [
{
"name": "hello",
"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": "This is an example custom command. Use /config to edit it and create more"
}
]
}

View file

@ -54,6 +54,11 @@
"title": "Number of threads",
"description": "The number of threads used in the generation process. Only available for Ollama (this is the num_thread parameter)",
"type": "integer"
},
"keepAlive": {
"title": "Ollama keep_alive",
"description": "The number of seconds after no requests are made to unload the model from memory. Defaults to 60*30 = 30min",
"type": "integer"
}
}
},
@ -141,7 +146,7 @@
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.py where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/anthropicllm)",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama pull <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/ollama)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/ollama)",
"### Huggingface TGI\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfacetgi)",
"### Huggingface Inference API\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfaceinferenceapi)",
"### Llama.cpp\nllama.cpp comes with a [built-in server](https://github.com/ggerganov/llama.cpp/tree/master/examples/server#llamacppexampleserver) that can be run from source. To do this:\n\n1. Clone the repository with `git clone https://github.com/ggerganov/llama.cpp`.\n2. `cd llama.cpp`\n3. Run `make` to build the server.\n4. Download the model you'd like to use and place it in the `llama.cpp/models` directory (the best place to find models is [The Bloke on HuggingFace](https://huggingface.co/TheBloke))\n5. Run the llama.cpp server with the command below (replacing with the model you downloaded):\n\n```shell\n.\\server.exe -c 4096 --host 0.0.0.0 -t 16 --mlock -m models/codellama-7b-instruct.Q8_0.gguf\n```\n\nAfter it's up and running, you can start using Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/llamacpp)",
@ -493,7 +498,13 @@
"model": {
"anyOf": [
{
"enum": ["claude-2", "claude-instant-1"]
"enum": [
"claude-2",
"claude-instant-1",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-2.1"
]
},
{
"type": "string"
@ -837,6 +848,10 @@
"deepseek-7b",
"deepseek-33b",
"claude-2",
"claude-instant-1",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-2.1",
"chat-bison-001",
"gemini-pro",
"mistral-tiny",
@ -1377,12 +1392,13 @@
"properties": {
"allowAnonymousTelemetry": {
"title": "Allow Anonymous Telemetry",
"markdownDescription": "If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data.",
"markdownDescription": "If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in [the docs](https://continue.dev/docs/telemetry).",
"default": true,
"type": "boolean"
},
"models": {
"title": "Models",
"markdownDescription": "Learn about setting up models in [the documentation](https://continue.dev/docs/model-setup/overview).",
"default": [
{
"title": "GPT-4 (trial)",
@ -1421,7 +1437,7 @@
},
"slashCommands": {
"title": "Slash Commands",
"description": "An array of slash commands that let you map custom Steps to a shortcut.",
"markdownDescription": "An array of slash commands that let you take custom actions from the sidebar. Learn more in the [documentation](https://continue.dev/docs/customization/slash-commands).",
"default": [],
"type": "array",
"items": {
@ -1430,7 +1446,7 @@
},
"customCommands": {
"title": "Custom Commands",
"description": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter /<name> in the text input, it will act as a shortcut to the prompt.",
"markdownDescription": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter /<name> in the text input, it will act as a shortcut to the prompt. Learn more in the [documentation](https://continue.dev/docs/customization/slash-commands#custom-commands-use-natural-language).",
"default": [
{
"name": "test",
@ -1445,7 +1461,7 @@
},
"contextProviders": {
"title": "Context Providers",
"description": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.",
"markdownDescription": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in [the documentation](https://continue.dev/docs/customization/context-providers).",
"default": [],
"type": "array",
"items": {
@ -1483,7 +1499,7 @@
},
"embeddingsProvider": {
"title": "Embeddings Provider",
"description": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser.",
"markdownDescription": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser. Learn about the other options [here](https://continue.dev/docs/walkthroughs/codebase-embeddings#embeddings-providers).",
"type": "object",
"properties": {
"provider": {
@ -1529,6 +1545,7 @@
"tabAutocompleteOptions": {
"title": "TabAutocompleteOptions",
"type": "object",
"markdownDescription": "These options let you customize your tab-autocomplete experience. Read about all options in [the docs](https://continue.dev/docs/walkthroughs/tab-autocomplete#configuration-options).",
"properties": {
"useCopyBuffer": {
"type": "boolean",
@ -1569,6 +1586,10 @@
"onlyMyCode": {
"type": "boolean",
"description": "If set to true, Continue will not include any snippets from go to definition unless they are within your repository"
},
"useOtherFiles": {
"type": "boolean",
"description": "Defaults to true. If set to false, Continue will not attempt to include snippets from other files."
}
},
"required": []

View file

@ -54,6 +54,11 @@
"title": "Number of threads",
"description": "The number of threads used in the generation process. Only available for Ollama (this is the num_thread parameter)",
"type": "integer"
},
"keepAlive": {
"title": "Ollama keep_alive",
"description": "The number of seconds after no requests are made to unload the model from memory. Defaults to 60*30 = 30min",
"type": "integer"
}
}
},
@ -141,7 +146,7 @@
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.py where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/anthropicllm)",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama pull <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/ollama)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/ollama)",
"### Huggingface TGI\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfacetgi)",
"### Huggingface Inference API\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfaceinferenceapi)",
"### Llama.cpp\nllama.cpp comes with a [built-in server](https://github.com/ggerganov/llama.cpp/tree/master/examples/server#llamacppexampleserver) that can be run from source. To do this:\n\n1. Clone the repository with `git clone https://github.com/ggerganov/llama.cpp`.\n2. `cd llama.cpp`\n3. Run `make` to build the server.\n4. Download the model you'd like to use and place it in the `llama.cpp/models` directory (the best place to find models is [The Bloke on HuggingFace](https://huggingface.co/TheBloke))\n5. Run the llama.cpp server with the command below (replacing with the model you downloaded):\n\n```shell\n.\\server.exe -c 4096 --host 0.0.0.0 -t 16 --mlock -m models/codellama-7b-instruct.Q8_0.gguf\n```\n\nAfter it's up and running, you can start using Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/llamacpp)",
@ -539,7 +544,10 @@
{
"enum": [
"claude-2",
"claude-instant-1"
"claude-instant-1",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-2.1"
]
},
{
@ -939,6 +947,10 @@
"deepseek-7b",
"deepseek-33b",
"claude-2",
"claude-instant-1",
"claude-3-opus-20240229",
"claude-3-sonnet-20240229",
"claude-2.1",
"chat-bison-001",
"gemini-pro",
"mistral-tiny",
@ -1556,12 +1568,13 @@
"properties": {
"allowAnonymousTelemetry": {
"title": "Allow Anonymous Telemetry",
"markdownDescription": "If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data.",
"markdownDescription": "If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to `false`, we will not collect any data. Learn more in [the docs](https://continue.dev/docs/telemetry).",
"default": true,
"type": "boolean"
},
"models": {
"title": "Models",
"markdownDescription": "Learn about setting up models in [the documentation](https://continue.dev/docs/model-setup/overview).",
"default": [
{
"title": "GPT-4 (trial)",
@ -1600,7 +1613,7 @@
},
"slashCommands": {
"title": "Slash Commands",
"description": "An array of slash commands that let you map custom Steps to a shortcut.",
"markdownDescription": "An array of slash commands that let you take custom actions from the sidebar. Learn more in the [documentation](https://continue.dev/docs/customization/slash-commands).",
"default": [],
"type": "array",
"items": {
@ -1609,7 +1622,7 @@
},
"customCommands": {
"title": "Custom Commands",
"description": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter /<name> in the text input, it will act as a shortcut to the prompt.",
"markdownDescription": "An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter /<name> in the text input, it will act as a shortcut to the prompt. Learn more in the [documentation](https://continue.dev/docs/customization/slash-commands#custom-commands-use-natural-language).",
"default": [
{
"name": "test",
@ -1624,7 +1637,7 @@
},
"contextProviders": {
"title": "Context Providers",
"description": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in the documentation.",
"markdownDescription": "A list of ContextProvider objects that can be used to provide context to the LLM by typing '@'. Read more about ContextProviders in [the documentation](https://continue.dev/docs/customization/context-providers).",
"default": [],
"type": "array",
"items": {
@ -1662,7 +1675,7 @@
},
"embeddingsProvider": {
"title": "Embeddings Provider",
"description": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser.",
"markdownDescription": "The method that will be used to generate codebase embeddings. The default is transformers.js, which will run locally in the browser. Learn about the other options [here](https://continue.dev/docs/walkthroughs/codebase-embeddings#embeddings-providers).",
"type": "object",
"properties": {
"provider": {
@ -1720,6 +1733,7 @@
"tabAutocompleteOptions": {
"title": "TabAutocompleteOptions",
"type": "object",
"markdownDescription": "These options let you customize your tab-autocomplete experience. Read about all options in [the docs](https://continue.dev/docs/walkthroughs/tab-autocomplete#configuration-options).",
"properties": {
"useCopyBuffer": {
"type": "boolean",
@ -1764,6 +1778,10 @@
"onlyMyCode": {
"type": "boolean",
"description": "If set to true, Continue will not include any snippets from go to definition unless they are within your repository"
},
"useOtherFiles": {
"type": "boolean",
"description": "Defaults to true. If set to false, Continue will not attempt to include snippets from other files."
}
},
"required": []

View file

@ -1,23 +1,32 @@
const esbuild = require("esbuild");
const flags = process.argv.slice(2);
const esbuildConfig = {
entryPoints: ["src/extension.ts"],
bundle: true,
outfile: "out/extension.js",
external: ["vscode", "esbuild", "jsdom"],
format: "cjs",
platform: "node",
sourcemap: true,
loader: {
// eslint-disable-next-line @typescript-eslint/naming-convention
".node": "file",
},
// To allow import.meta.path for transformers.js
// https://github.com/evanw/esbuild/issues/1492#issuecomment-893144483
inject: ["./importMetaUrl.js"],
define: { "import.meta.url": "importMetaUrl" },
};
(async () => {
// Bundles the extension into one file
await esbuild.build({
entryPoints: ["src/extension.ts"],
bundle: true,
outfile: "out/extension.js",
external: ["vscode", "esbuild"],
format: "cjs",
platform: "node",
sourcemap: true,
loader: {
// eslint-disable-next-line @typescript-eslint/naming-convention
".node": "file",
},
// To allow import.meta.path for transformers.js
// https://github.com/evanw/esbuild/issues/1492#issuecomment-893144483
inject: ["./importMetaUrl.js"],
define: { "import.meta.url": "importMetaUrl" },
});
if (flags.includes("--watch")) {
const ctx = await esbuild.context(esbuildConfig);
await ctx.watch();
} else {
await esbuild.build(esbuildConfig);
}
})();

View file

@ -9,5 +9,4 @@ let d = repeat(5, "a");
console.log(d);
let e = factorial(3);
console.log(e);
console.log(e);

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,7 @@
{
"name": "continue",
"icon": "media/icon.png",
"version": "0.9.78",
"version": "0.9.81",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -490,6 +490,7 @@
"https-proxy-agent": "^7.0.2",
"ignore": "^5.3.0",
"jest": "^29.7.0",
"jsdom": "^24.0.0",
"mocha": "^10.3.0",
"monaco-editor": "^0.45.0",
"monaco-vscode-textmate-theme-converter": "^0.1.7",

View file

@ -16,7 +16,7 @@ if (args[2] === "--target") {
// Copy config_schema.json to config.json in docs and intellij
fs.copyFileSync(
"config_schema.json",
path.join("..", "..", "docs", "static", "schemas", "config.json")
path.join("..", "..", "docs", "static", "schemas", "config.json"),
);
fs.copyFileSync(
"config_schema.json",
@ -26,8 +26,8 @@ if (args[2] === "--target") {
"src",
"main",
"resources",
"config_schema.json"
)
"config_schema.json",
),
);
// Modify and copy for .continuerc.json
const schema = JSON.parse(fs.readFileSync("config_schema.json", "utf8"));
@ -67,7 +67,7 @@ if (args[2] === "--target") {
"src",
"main",
"resources",
"webview"
"webview",
);
const indexHtmlPath = path.join(intellijExtensionWebviewPath, "index.html");
@ -80,7 +80,7 @@ if (args[2] === "--target") {
if (error) {
console.warn(
"[error] Error copying React app build to Intellij extension: ",
error
error,
);
reject(error);
}
@ -98,7 +98,7 @@ if (args[2] === "--target") {
// Copy over other misc. files
fs.copyFileSync(
"../extensions/vscode/gui/onigasm.wasm",
path.join(intellijExtensionWebviewPath, "onigasm.wasm")
path.join(intellijExtensionWebviewPath, "onigasm.wasm"),
);
console.log("[info] Copied gui build to Intellij extension");
@ -166,7 +166,7 @@ if (args[2] === "--target") {
reject(error);
}
resolve();
}
},
);
});
if (target) {
@ -197,28 +197,28 @@ if (args[2] === "--target") {
} else {
resolve();
}
}
},
);
});
fs.copyFileSync(
path.join(__dirname, "../../../core/vendor/tree-sitter.wasm"),
path.join(__dirname, "../out/tree-sitter.wasm")
path.join(__dirname, "../out/tree-sitter.wasm"),
);
console.log("[info] Copied tree-sitter wasms");
// tree-sitter tag query files
ncp(
path.join(
__dirname,
"../../../core/node_modules/llm-code-highlighter/dist/tag-qry"
),
path.join(__dirname, "../out/tag-qry"),
(error) => {
if (error)
console.warn("Error copying code-highlighter tag-qry files", error);
}
);
// ncp(
// path.join(
// __dirname,
// "../../../core/node_modules/llm-code-highlighter/dist/tag-qry"
// ),
// path.join(__dirname, "../out/tag-qry"),
// (error) => {
// if (error)
// console.warn("Error copying code-highlighter tag-qry files", error);
// }
// );
// textmate-syntaxes
await new Promise((resolve, reject) => {
@ -232,7 +232,7 @@ if (args[2] === "--target") {
} else {
resolve();
}
}
},
);
});
@ -271,7 +271,7 @@ if (args[2] === "--target") {
rimrafSync("node_modules/@esbuild");
fs.mkdirSync("node_modules/@esbuild", { recursive: true });
execSync(
`curl -o node_modules/@esbuild/esbuild.zip https://continue-server-binaries.s3.us-west-1.amazonaws.com/${target}/esbuild.zip`
`curl -o node_modules/@esbuild/esbuild.zip https://continue-server-binaries.s3.us-west-1.amazonaws.com/${target}/esbuild.zip`,
);
execSync(`cd node_modules/@esbuild && unzip esbuild.zip`);
fs.unlinkSync("node_modules/@esbuild/esbuild.zip");
@ -290,7 +290,7 @@ if (args[2] === "--target") {
"https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v3-linux-arm64.tar.gz",
}[target];
execSync(
`curl -L -o ../../core/node_modules/sqlite3/build.tar.gz ${downloadUrl}`
`curl -L -o ../../core/node_modules/sqlite3/build.tar.gz ${downloadUrl}`,
);
execSync("cd ../../core/node_modules/sqlite3 && tar -xvzf build.tar.gz");
fs.unlinkSync("../../core/node_modules/sqlite3/build.tar.gz");
@ -308,12 +308,12 @@ if (args[2] === "--target") {
} else {
resolve();
}
}
},
);
});
// Copy node_modules for pre-built binaries
const NODE_MODULES_TO_COPY = ["esbuild", "@esbuild", "@lancedb"];
const NODE_MODULES_TO_COPY = ["esbuild", "@esbuild", "@lancedb", "jsdom"];
fs.mkdirSync("out/node_modules", { recursive: true });
await Promise.all(
@ -330,10 +330,10 @@ if (args[2] === "--target") {
} else {
resolve();
}
}
)
)
)
},
),
),
),
);
console.log(`[info] Copied ${NODE_MODULES_TO_COPY.join(", ")}`);
})();

View file

@ -10,6 +10,12 @@ const inlineTipDecoration = vscode.window.createTextEditorDecorationType({
},
});
function showInlineTip() {
return vscode.workspace
.getConfiguration("continue")
.get<boolean>("showInlineTip");
}
function handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) {
const selection = e.selections[0];
const editor = e.textEditor;
@ -18,12 +24,7 @@ function handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) {
return;
}
if (
selection.isEmpty ||
vscode.workspace
.getConfiguration("continue")
.get<boolean>("showInlineTip") === false
) {
if (selection.isEmpty || showInlineTip() === false) {
editor.setDecorations(inlineTipDecoration, []);
return;
}
@ -73,7 +74,7 @@ export function setupInlineTips(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.window.onDidChangeActiveTextEditor((editor) => {
if (editor?.document.getText() === "") {
if (editor?.document.getText() === "" && showInlineTip() === true) {
if (
editor.document.uri.toString().startsWith("output:") ||
editor.document.uri.scheme === "comment"
@ -98,7 +99,7 @@ export function setupInlineTips(context: vscode.ExtensionContext) {
if (e.document.uri.toString().startsWith("vscode://inline-chat")) {
return;
}
if (e.document.getText() === "") {
if (e.document.getText() === "" && showInlineTip() === true) {
vscode.window.visibleTextEditors.forEach((editor) => {
editor.setDecorations(emptyFileTooltipDecoration, [
{

View file

@ -4,6 +4,7 @@ import { DEFAULT_AUTOCOMPLETE_OPTS } from "core/autocomplete/parameters";
import { GeneratorReuseManager } from "core/autocomplete/util";
import { ConfigHandler } from "core/config/handler";
import { logDevData } from "core/util/devdata";
import { Telemetry } from "core/util/posthog";
import { v4 as uuidv4 } from "uuid";
import * as vscode from "vscode";
import { TabAutocompleteModel } from "../util/loadAutocompleteModel";
@ -17,11 +18,25 @@ export class ContinueCompletionProvider
private static debouncing: boolean = false;
private static lastUUID: string | undefined = undefined;
private generatorReuseManager = new GeneratorReuseManager((err: any) => {
vscode.window.showErrorMessage(
`Error generating autocomplete response: ${err}`,
);
});
private onError(e: any) {
console.warn("Error generating autocompletion: ", e);
if (!this.errorsShown.has(e.message)) {
this.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",
),
);
}
});
}
}
private generatorReuseManager = new GeneratorReuseManager(
this.onError.bind(this),
);
private autocompleteCache = AutocompleteLruCache.get();
public errorsShown: Set<string> = new Set();
@ -44,8 +59,8 @@ export class ContinueCompletionProvider
const config = await this.configHandler.loadConfig();
const options = {
...config.tabAutocompleteOptions,
...DEFAULT_AUTOCOMPLETE_OPTS,
...config.tabAutocompleteOptions,
};
if (ContinueCompletionProvider.debouncing) {
@ -100,6 +115,13 @@ export class ContinueCompletionProvider
// Wait 10 seconds, then assume it wasn't accepted
outcome.accepted = false;
logDevData("autocomplete", outcome);
Telemetry.capture("autocomplete", {
accepted: outcome.accepted,
modelName: outcome.modelName,
modelProvider: outcome.modelProvider,
time: outcome.time,
cacheHit: outcome.cacheHit,
});
}, 10_000);
return [
@ -114,21 +136,7 @@ export class ContinueCompletionProvider
),
];
} catch (e: any) {
console.warn("Error generating autocompletion: ", e);
if (!this.errorsShown.has(e.message)) {
this.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",
),
);
}
});
}
this.onError(e);
} finally {
stopStatusBarLoading();
}

View file

@ -1,10 +1,14 @@
import { IDE, TabAutocompleteOptions } from "core";
import { AutocompleteLruCache } from "core/autocomplete/cache";
import { onlyWhitespaceAfterEndOfLine } from "core/autocomplete/charStream";
import {
noFirstCharNewline,
onlyWhitespaceAfterEndOfLine,
} from "core/autocomplete/charStream";
import {
constructAutocompletePrompt,
languageForFilepath,
} from "core/autocomplete/constructPrompt";
import { AutocompleteLanguageInfo } from "core/autocomplete/languages";
import {
avoidPathLine,
stopAtLines,
@ -17,6 +21,7 @@ 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 { getBasename } from "core/util";
import Handlebars from "handlebars";
import * as vscode from "vscode";
import { TabAutocompleteModel } from "../util/loadAutocompleteModel";
@ -38,6 +43,23 @@ export interface AutocompleteOutcome {
const autocompleteCache = AutocompleteLruCache.get();
const recentlyEditedTracker = new RecentlyEditedTracker();
function formatExternalSnippet(
filepath: string,
snippet: string,
language: AutocompleteLanguageInfo,
) {
const comment = language.comment;
const lines = [
comment + " Path: " + getBasename(filepath),
...snippet
.trim()
.split("\n")
.map((line) => comment + " " + line),
comment,
];
return lines.join("\n");
}
export async function getTabCompletion(
document: vscode.TextDocument,
pos: vscode.Position,
@ -99,7 +121,7 @@ export async function getTabCompletion(
});
}
const { prefix, suffix, completeMultiline } =
let { prefix, suffix, completeMultiline, snippets } =
await constructAutocompletePrompt(
document.uri.toString(),
pos.line,
@ -114,12 +136,37 @@ export async function getTabCompletion(
extrasSnippets,
);
// Template prompt
const { template, completionOptions } = options.template
? { template: options.template, completionOptions: {} }
: getTemplateForModel(llm.model);
const compiledTemplate = Handlebars.compile(template);
const prompt = compiledTemplate({ prefix, suffix });
let prompt: string;
const filename = getBasename(document.uri.fsPath);
const reponame = getBasename(workspaceDirs[0] ?? "myproject");
if (typeof template === "string") {
const compiledTemplate = Handlebars.compile(template);
// Format snippets as comments and prepend to prefix
const formattedSnippets = snippets
.map((snippet) =>
formatExternalSnippet(snippet.filepath, snippet.contents, lang),
)
.join("\n");
if (formattedSnippets.length > 0) {
prefix = formattedSnippets + "\n\n" + prefix;
}
prompt = compiledTemplate({
prefix,
suffix,
filename,
reponame,
});
} else {
// Let the template function format snippets
prompt = template(prefix, suffix, filename, reponame, snippets);
}
// Completion
let completion = "";
@ -172,8 +219,9 @@ export async function getTabCompletion(
yield update;
}
};
let chars = generatorWithCancellation();
const gen2 = onlyWhitespaceAfterEndOfLine(
generatorWithCancellation(),
noFirstCharNewline(chars),
lang.endOfLine,
);
const lineGenerator = streamWithNewLines(

View file

@ -116,23 +116,18 @@ export class VsCodeExtension {
const config = vscode.workspace.getConfiguration("continue");
const enabled = config.get<boolean>("enableTabAutocomplete");
// 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(
this.configHandler,
this.ide,
this.tabAutocompleteModel,
),
// Register inline completion provider
setupStatusBar(enabled);
context.subscriptions.push(
vscode.languages.registerInlineCompletionItemProvider(
[{ pattern: "**" }],
new ContinueCompletionProvider(
this.configHandler,
this.ide,
this.tabAutocompleteModel,
),
);
}
),
);
// Commands
registerAllCommands(

View file

@ -29,7 +29,7 @@ function parseThemeString(themeString: string | undefined): any {
return !line.trim().startsWith("//");
})
.join("\n");
return JSON.parse(themeString || "{}");
return JSON.parse(themeString ?? "{}");
}
export function getTheme() {

View file

@ -268,7 +268,7 @@ export class VsCodeIdeUtils {
}
}
for await (const file of traverseDirectory(
gitRoot || directory,
gitRoot ?? directory,
[],
true,
gitRoot === directory ? undefined : onlyThisDirectory,

View file

@ -21,7 +21,7 @@ export class VsCodeWebviewProtocol {
abortedMessageIds: Set<string> = new Set();
private send(messageType: string, data: any, messageId?: string): string {
const id = messageId || uuidv4();
const id = messageId ?? uuidv4();
this.webview?.postMessage({
messageType,
data,

View file

@ -2362,7 +2362,10 @@ core-util-is@1.0.2:
version "1.0.0"
resolved "file:../../core"
dependencies:
"@mozilla/readability" "^0.5.0"
"@octokit/rest" "^20.0.2"
"@types/jsdom" "^21.1.6"
"@types/mozilla-readability" "^0.2.1"
"@types/node-fetch" "^2.6.11"
"@xenova/transformers" "^2.14.0"
adf-to-md "^1.1.0"
@ -2377,7 +2380,9 @@ core-util-is@1.0.2:
http-proxy-agent "^7.0.1"
https-proxy-agent "^7.0.3"
js-tiktoken "^1.0.8"
jsdom "^24.0.0"
llama-tokenizer-js "^1.1.3"
llm-code-highlighter "^0.0.14"
node-fetch "^3.3.2"
node-html-markdown "^1.3.0"
ollama "^0.4.6"
@ -2385,6 +2390,7 @@ core-util-is@1.0.2:
pg "^8.11.3"
posthog-node "^3.6.2"
replicate "^0.26.0"
request "^2.88.2"
socket.io-client "^4.7.3"
sqlite "^5.1.1"
sqlite3 "^5.1.7"
@ -2444,6 +2450,13 @@ cssesc@^3.0.0:
resolved "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz"
integrity sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==
cssstyle@^4.0.1:
version "4.0.1"
resolved "https://registry.npmjs.org/cssstyle/-/cssstyle-4.0.1.tgz"
integrity sha512-8ZYiJ3A/3OkDd093CBT/0UKDWry7ak4BdPTFP2+QEP7cmhouyq/Up709ASSj2cK02BbZiMgk7kYjZNS4QP5qrQ==
dependencies:
rrweb-cssom "^0.6.0"
csstype@^3.0.2:
version "3.1.3"
resolved "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz"
@ -2469,6 +2482,14 @@ data-uri-to-buffer@^4.0.0:
resolved "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz"
integrity sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==
data-urls@^5.0.0:
version "5.0.0"
resolved "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz"
integrity sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==
dependencies:
whatwg-mimetype "^4.0.0"
whatwg-url "^14.0.0"
date-fns@^2.16.1:
version "2.30.0"
resolved "https://registry.npmjs.org/date-fns/-/date-fns-2.30.0.tgz"
@ -2504,6 +2525,11 @@ decamelize@^4.0.0:
resolved "https://registry.npmjs.org/decamelize/-/decamelize-4.0.0.tgz"
integrity sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ==
decimal.js@^10.4.3:
version "10.4.3"
resolved "https://registry.npmjs.org/decimal.js/-/decimal.js-10.4.3.tgz"
integrity sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==
decode-named-character-reference@^1.0.0:
version "1.0.2"
resolved "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.0.2.tgz"
@ -3793,6 +3819,13 @@ hosted-git-info@^4.0.2:
dependencies:
lru-cache "^6.0.0"
html-encoding-sniffer@^4.0.0:
version "4.0.0"
resolved "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz"
integrity sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==
dependencies:
whatwg-encoding "^3.1.1"
html-escaper@^2.0.0:
version "2.0.2"
resolved "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz"
@ -3936,6 +3969,13 @@ iconv-lite@^0.6.3:
dependencies:
safer-buffer ">= 2.1.2 < 3.0.0"
iconv-lite@0.6.3:
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"
ieee754@^1.1.13:
version "1.2.1"
resolved "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz"
@ -4137,6 +4177,11 @@ is-plain-obj@^4.0.0:
resolved "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz"
integrity sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==
is-potential-custom-element-name@^1.0.1:
version "1.0.1"
resolved "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz"
integrity sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==
is-promise@^2.2.2:
version "2.2.2"
resolved "https://registry.npmjs.org/is-promise/-/is-promise-2.2.2.tgz"
@ -4637,6 +4682,33 @@ jsbn@1.1.0:
resolved "https://registry.npmjs.org/jsbn/-/jsbn-1.1.0.tgz"
integrity sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A==
jsdom@^24.0.0:
version "24.0.0"
resolved "https://registry.npmjs.org/jsdom/-/jsdom-24.0.0.tgz"
integrity sha512-UDS2NayCvmXSXVP6mpTj+73JnNQadZlr9N68189xib2tx5Mls7swlTNao26IoHv46BZJFvXygyRtyXd1feAk1A==
dependencies:
cssstyle "^4.0.1"
data-urls "^5.0.0"
decimal.js "^10.4.3"
form-data "^4.0.0"
html-encoding-sniffer "^4.0.0"
http-proxy-agent "^7.0.0"
https-proxy-agent "^7.0.2"
is-potential-custom-element-name "^1.0.1"
nwsapi "^2.2.7"
parse5 "^7.1.2"
rrweb-cssom "^0.6.0"
saxes "^6.0.0"
symbol-tree "^3.2.4"
tough-cookie "^4.1.3"
w3c-xmlserializer "^5.0.0"
webidl-conversions "^7.0.0"
whatwg-encoding "^3.1.1"
whatwg-mimetype "^4.0.0"
whatwg-url "^14.0.0"
ws "^8.16.0"
xml-name-validator "^5.0.0"
jsesc@^2.5.1:
version "2.5.2"
resolved "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz"
@ -5706,6 +5778,11 @@ nth-check@^2.0.1:
dependencies:
boolbase "^1.0.0"
nwsapi@^2.2.7:
version "2.2.7"
resolved "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.7.tgz"
integrity sha512-ub5E4+FBPKwAZx0UwIQOjYWGHTEq5sPqHQNRN8Z9e4A7u3Tj1weLJsL59yH9vmvqEtBHaOmT6cYQKIZOxp35FQ==
oauth-sign@~0.9.0:
version "0.9.0"
resolved "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz"
@ -5886,7 +5963,7 @@ parse5-htmlparser2-tree-adapter@^7.0.0:
domhandler "^5.0.2"
parse5 "^7.0.0"
parse5@^7.0.0:
parse5@^7.0.0, parse5@^7.1.2:
version "7.1.2"
resolved "https://registry.npmjs.org/parse5/-/parse5-7.1.2.tgz"
integrity sha512-Czj1WaSVpaoj0wbhMzLmWD69anp2WH7FXMB9n1Sy8/ZFF9jolSQVMu1Ij5WIyGmcBmhk7EOndpO4mIpihVqAXw==
@ -6233,7 +6310,7 @@ ps-list@^7.2.0:
resolved "https://registry.npmjs.org/ps-list/-/ps-list-7.2.0.tgz"
integrity sha512-v4Bl6I3f2kJfr5o80ShABNHAokIgY+wFDTQfE+X3zWYgSGQOCBeYptLZUpoOALBqO5EawmDN/tjTldJesd0ujQ==
psl@^1.1.28:
psl@^1.1.28, psl@^1.1.33:
version "1.9.0"
resolved "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz"
integrity sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==
@ -6246,7 +6323,7 @@ pump@^3.0.0:
end-of-stream "^1.1.0"
once "^1.3.1"
punycode@^2.1.0, punycode@^2.1.1:
punycode@^2.1.0, punycode@^2.1.1, punycode@^2.3.1:
version "2.3.1"
resolved "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz"
integrity sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==
@ -6268,6 +6345,11 @@ qs@~6.5.2:
resolved "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz"
integrity sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==
querystringify@^2.1.1:
version "2.2.0"
resolved "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz"
integrity sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==
queue-microtask@^1.2.2:
version "1.2.3"
resolved "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz"
@ -6627,6 +6709,11 @@ rollup@^3.27.1:
optionalDependencies:
fsevents "~2.3.2"
rrweb-cssom@^0.6.0:
version "0.6.0"
resolved "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.6.0.tgz"
integrity sha512-APM0Gt1KoXBz0iIkkdB/kfvGOwC4UuJFeG/c+yV7wSc7q96cG/kJ0HiYCnzivD9SB53cLV1MlHFNfOuPaadYSw==
run-async@^2.4.0:
version "2.4.1"
resolved "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz"
@ -6690,6 +6777,13 @@ sax@>=0.6.0:
resolved "https://registry.npmjs.org/sax/-/sax-1.3.0.tgz"
integrity sha512-0s+oAmw9zLl1V1cS9BtZN7JAd0cW5e0QH4W3LWEK6a4LaLEA2OTpGYWDY+6XasBLtz6wkm3u1xRw95mRuJ59WA==
saxes@^6.0.0:
version "6.0.0"
resolved "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz"
integrity sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==
dependencies:
xmlchars "^2.2.0"
scheduler@^0.23.0:
version "0.23.0"
resolved "https://registry.npmjs.org/scheduler/-/scheduler-0.23.0.tgz"
@ -7148,6 +7242,11 @@ supports-preserve-symlinks-flag@^1.0.0:
resolved "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz"
integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==
symbol-tree@^3.2.4:
version "3.2.4"
resolved "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz"
integrity sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==
table-layout@^3.0.0:
version "3.0.2"
resolved "https://registry.npmjs.org/table-layout/-/table-layout-3.0.2.tgz"
@ -7307,6 +7406,16 @@ toidentifier@1.0.1:
resolved "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz"
integrity sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==
tough-cookie@^4.1.3:
version "4.1.3"
resolved "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.3.tgz"
integrity sha512-aX/y5pVRkfRnfmuX+OdbSdXvPe6ieKX/G2s7e98f4poJHnqH3281gDPm/metm6E/WRamfx7WC4HUqkWHfQHprw==
dependencies:
psl "^1.1.33"
punycode "^2.1.1"
universalify "^0.2.0"
url-parse "^1.5.3"
tough-cookie@~2.5.0:
version "2.5.0"
resolved "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz"
@ -7315,6 +7424,13 @@ tough-cookie@~2.5.0:
psl "^1.1.28"
punycode "^2.1.1"
tr46@^5.0.0:
version "5.0.0"
resolved "https://registry.npmjs.org/tr46/-/tr46-5.0.0.tgz"
integrity sha512-tk2G5R2KRwBd+ZN0zaEXpmzdKyOYksXwywulIX95MBODjSzMIuQnQ3m8JxgbhnL1LeVo7lqQKsYa1O3Htl7K5g==
dependencies:
punycode "^2.3.1"
tr46@~0.0.3:
version "0.0.3"
resolved "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz"
@ -7571,6 +7687,11 @@ universalify@^0.1.0:
resolved "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz"
integrity sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==
universalify@^0.2.0:
version "0.2.0"
resolved "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz"
integrity sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==
universalify@^2.0.0:
version "2.0.1"
resolved "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz"
@ -7601,6 +7722,14 @@ url-join@^4.0.1:
resolved "https://registry.npmjs.org/url-join/-/url-join-4.0.1.tgz"
integrity sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA==
url-parse@^1.5.3:
version "1.5.10"
resolved "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz"
integrity sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==
dependencies:
querystringify "^2.1.1"
requires-port "^1.0.0"
use-sync-external-store@^1.0.0:
version "1.2.0"
resolved "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz"
@ -7765,6 +7894,13 @@ vscode-languageserver-types@3.17.3:
resolved "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.3.tgz"
integrity sha512-SYU4z1dL0PyIMd4Vj8YOqFvHu7Hz/enbWtpfnVbJHU4Nd1YNYx8u0ennumc6h48GQNeOLxmwySmnADouT/AuZA==
w3c-xmlserializer@^5.0.0:
version "5.0.0"
resolved "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz"
integrity sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==
dependencies:
xml-name-validator "^5.0.0"
walker@^1.0.8:
version "1.0.8"
resolved "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz"
@ -7789,6 +7925,31 @@ webidl-conversions@^3.0.0:
resolved "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz"
integrity sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==
webidl-conversions@^7.0.0:
version "7.0.0"
resolved "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz"
integrity sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==
whatwg-encoding@^3.1.1:
version "3.1.1"
resolved "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz"
integrity sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==
dependencies:
iconv-lite "0.6.3"
whatwg-mimetype@^4.0.0:
version "4.0.0"
resolved "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz"
integrity sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==
whatwg-url@^14.0.0:
version "14.0.0"
resolved "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.0.0.tgz"
integrity sha512-1lfMEm2IEr7RIV+f4lUNPOqfFL+pO+Xw3fJSqmjX9AbXcXcYOkCe1P6+9VBZB6n94af16NfZf+sSk0JCBZC9aw==
dependencies:
tr46 "^5.0.0"
webidl-conversions "^7.0.0"
whatwg-url@^5.0.0:
version "5.0.0"
resolved "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz"
@ -7875,7 +8036,7 @@ write-file-atomic@^4.0.2:
imurmurhash "^0.1.4"
signal-exit "^3.0.7"
ws@^8.13.0:
ws@^8.13.0, ws@^8.16.0:
version "8.16.0"
resolved "https://registry.npmjs.org/ws/-/ws-8.16.0.tgz"
integrity sha512-HS0c//TP7Ina87TfiPUz1rQzMhHrl/SG2guqRcTOIUYD2q8uhUdNHZYJUaQ8aTGPzCh+c6oawMKW35nFl1dxyQ==
@ -7885,6 +8046,11 @@ ws@~8.11.0:
resolved "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz"
integrity sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==
xml-name-validator@^5.0.0:
version "5.0.0"
resolved "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz"
integrity sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==
xml2js@^0.4.23:
version "0.4.23"
resolved "https://registry.npmjs.org/xml2js/-/xml2js-0.4.23.tgz"
@ -7906,6 +8072,11 @@ xmlbuilder@~11.0.0:
resolved "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz"
integrity sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==
xmlchars@^2.2.0:
version "2.2.0"
resolved "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz"
integrity sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==
xmlhttprequest-ssl@~2.0.0:
version "2.0.0"
resolved "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.0.0.tgz"

6
gui/package-lock.json generated
View file

@ -73,7 +73,10 @@
"version": "1.0.0",
"license": "Apache-2.0",
"dependencies": {
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@types/jsdom": "^21.1.6",
"@types/mozilla-readability": "^0.2.1",
"@types/node-fetch": "^2.6.11",
"@xenova/transformers": "^2.14.0",
"adf-to-md": "^1.1.0",
@ -88,7 +91,9 @@
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"js-tiktoken": "^1.0.8",
"jsdom": "^24.0.0",
"llama-tokenizer-js": "^1.1.3",
"llm-code-highlighter": "^0.0.14",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",
"ollama": "^0.4.6",
@ -96,6 +101,7 @@
"pg": "^8.11.3",
"posthog-node": "^3.6.2",
"replicate": "^0.26.0",
"request": "^2.88.2",
"socket.io-client": "^4.7.3",
"sqlite": "^5.1.1",
"sqlite3": "^5.1.7",

View file

@ -68,7 +68,7 @@ interface KeyboardShortcutProps {
}
function KeyboardShortcut(props: KeyboardShortcutProps) {
const shortcut = getPlatform() === "windows" ? props.windows : props.mac;
const shortcut = getPlatform() === "mac" ? props.mac : props.windows;
return (
<div className="flex justify-between w-full items-center">
<span
@ -174,7 +174,7 @@ const jetbrainsShortcuts: KeyboardShortcutProps[] = [
{
mac: "⌘ ⌫",
windows: "⌃ ⌫",
description: "Cancel respoonse",
description: "Cancel response",
},
{
mac: "⌘ '",

View file

@ -52,7 +52,7 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => {
new WebviewIde().showLines(
rif.filepath,
rif.range.start.line,
rif.range.end.line
rif.range.end.line,
);
} else {
new WebviewIde().openFile(contextItem.description);

View file

@ -420,6 +420,7 @@ function TipTapEditor(props: TipTapEditorProps) {
saveSession();
}
setTimeout(() => {
editor?.commands.blur();
editor?.commands.focus("end");
}, 20);
},
@ -493,8 +494,9 @@ function TipTapEditor(props: TipTapEditorProps) {
})
.run();
setTimeout(() => {
editor.commands.blur();
editor.commands.focus("end");
}, 200);
}, 20);
}
setIgnoreHighlightedCode(false);
},
@ -507,15 +509,16 @@ function TipTapEditor(props: TipTapEditorProps) {
],
);
useEffect(() => {
if (props.isMainInput && editor && document.hasFocus()) {
editor.commands.focus();
// setTimeout(() => {
// // https://github.com/continuedev/continue/pull/881
// editor.commands.blur();
// }, 0);
}
}, [editor, props.isMainInput, historyLength, ignoreHighlightedCode]);
// On linux+jetbrains only was stealing focus
// useEffect(() => {
// if (props.isMainInput && editor && document.hasFocus()) {
// editor.commands.focus();
// // setTimeout(() => {
// // // https://github.com/continuedev/continue/pull/881
// // editor.commands.blur();
// // }, 0);
// }
// }, [editor, props.isMainInput, historyLength, ignoreHighlightedCode]);
const [showDragOverMsg, setShowDragOverMsg] = useState(false);

View file

@ -93,7 +93,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
new WebviewIde().showLines(
props.item.description,
parseInt(lines[0]) - 1,
parseInt(lines[1]) - 1
parseInt(lines[1]) - 1,
);
} else {
postToIde("showVirtualFile", {
@ -144,7 +144,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
height: collapsed
? `${Math.min(
MAX_PREVIEW_HEIGHT,
codeBlockRef.current?.scrollHeight
codeBlockRef.current?.scrollHeight,
)}px`
: undefined,
overflow: collapsed ? "hidden" : "auto",
@ -152,7 +152,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
>
<StyledMarkdownPreview
source={`${fence}${getMarkdownLanguageTagForFile(
props.item.description
props.item.description,
)}\n${props.item.content.trim()}\n${fence}`}
showCodeBorder={false}
/>

View file

@ -34,11 +34,11 @@ function useChatHandler(dispatch: Dispatch) {
const defaultModel = useSelector(defaultModelSelector);
const slashCommands = useSelector(
(store: RootState) => store.state.config.slashCommands || []
(store: RootState) => store.state.config.slashCommands || [],
);
const contextItems = useSelector(
(state: RootState) => state.state.contextItems
(state: RootState) => state.state.contextItems,
);
const history = useSelector((store: RootState) => store.state.history);
@ -70,7 +70,7 @@ function useChatHandler(dispatch: Dispatch) {
}
const getSlashCommandForInput = (
input: MessageContent
input: MessageContent,
): [SlashCommandDescription, string] | undefined => {
let slashCommand: SlashCommandDescription | undefined;
let slashCommandName: string | undefined;
@ -83,7 +83,7 @@ function useChatHandler(dispatch: Dispatch) {
if (lastText.startsWith("/")) {
slashCommandName = lastText.split(" ")[0].substring(1);
slashCommand = slashCommands.find(
(command) => command.name === slashCommandName
(command) => command.name === slashCommandName,
);
}
if (!slashCommand || !slashCommandName) {
@ -99,7 +99,7 @@ function useChatHandler(dispatch: Dispatch) {
slashCommand: SlashCommandDescription,
input: string,
historyIndex: number,
selectedCode: RangeInFile[]
selectedCode: RangeInFile[],
) {
const abortController = new AbortController();
const cancelToken = abortController.signal;
@ -117,7 +117,7 @@ function useChatHandler(dispatch: Dispatch) {
historyIndex,
selectedCode,
},
cancelToken
cancelToken,
)) {
if (!activeRef.current) {
abortController.abort();
@ -161,7 +161,7 @@ function useChatHandler(dispatch: Dispatch) {
message,
index: historyIndex,
contextItems,
})
}),
);
// TODO: hacky way to allow rerender
@ -169,13 +169,9 @@ function useChatHandler(dispatch: Dispatch) {
posthog.capture("step run", {
step_name: "User Input",
params: {
user_input: content,
},
});
posthog.capture("userInput", {
input: content,
params: {},
});
posthog.capture("userInput", {});
const messages = constructMessages(newHistory);
@ -188,16 +184,14 @@ function useChatHandler(dispatch: Dispatch) {
const [slashCommand, commandInput] = commandAndInput;
posthog.capture("step run", {
step_name: slashCommand.name,
params: {
user_input: commandInput,
},
params: {},
});
await _streamSlashCommand(
messages,
slashCommand,
commandInput,
historyIndex,
selectedCode
selectedCode,
);
}
} catch (e) {

View file

@ -526,12 +526,54 @@ const gpt35turbo: ModelPackage = {
};
const claude2: ModelPackage = {
title: "Claude-2",
title: "Claude 2",
description: "A highly capable model with a 100k context length",
params: {
model: "claude-2.1",
contextLength: 100_000,
title: "Claude 2",
apiKey: "",
},
providerOptions: ["anthropic"],
icon: "anthropic.png",
};
const claude3Opus: ModelPackage = {
title: "Claude 3 Opus",
description:
"Anthropic's most capable model, beating GPT-4 on many benchmarks",
params: {
model: "claude-3-opus-20240229",
contextLength: 200_000,
title: "Claude 3 Opus",
apiKey: "",
},
providerOptions: ["anthropic"],
icon: "anthropic.png",
};
const claude3Sonnet: ModelPackage = {
title: "Claude 3 Sonnet",
description:
"The second most capable model in the Claude 3 series: ideal balance of intelligence and speed",
params: {
model: "claude-3-sonnet-20240229",
contextLength: 200_000,
title: "Claude 3 Sonnet",
apiKey: "",
},
providerOptions: ["anthropic"],
icon: "anthropic.png",
};
const claude3Haiku: ModelPackage = {
title: "Claude 3 Haiku",
description:
"The third most capable model in the Claude 3 series: fastest and most compact model for near-instant responsiveness",
params: {
model: "claude-2",
contextLength: 100000,
title: "Claude-2",
contextLength: 200_000,
title: "Claude 3 Haiku",
apiKey: "",
},
providerOptions: ["anthropic"],
@ -567,6 +609,8 @@ export const MODEL_INFO: ModelPackage[] = [
gpt4,
gpt35turbo,
geminiPro,
claude3Opus,
claude3Sonnet,
claude2,
deepseek,
mistral,
@ -616,7 +660,7 @@ export const PROVIDER_INFO: { [key: string]: ModelInfo } = {
provider: "anthropic",
refPage: "anthropicllm",
description:
"Claude-2 is a highly capable model with a 100k context length",
"Anthropic builds state-of-the-art models with large context length and high recall",
icon: "anthropic.png",
tags: [ModelProviderTag["Requires API Key"]],
longDescription:
@ -635,17 +679,7 @@ export const PROVIDER_INFO: { [key: string]: ModelInfo } = {
defaultValue: 100_000,
},
],
packages: [
{
title: "Claude-2",
description: "A highly capable model with a 100k context length",
params: {
model: "claude-2",
contextLength: 100000,
title: "Claude-2",
},
},
],
packages: [claude3Opus, claude3Sonnet, claude2],
},
ollama: {
title: "Ollama",
@ -653,7 +687,7 @@ export const PROVIDER_INFO: { [key: string]: ModelInfo } = {
description:
"One of the fastest ways to get started with local models on Mac, Linux, or Windows",
longDescription:
'To get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama pull <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model="codellama:7b-instruct"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.',
'To get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model="codellama:7b-instruct"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.',
icon: "ollama.png",
tags: [ModelProviderTag["Local"], ModelProviderTag["Open-Source"]],
packages: [

View file

@ -3,7 +3,7 @@ import { ConfigHandler } from "core/config/handler";
import { addModel, addOpenAIKey, deleteModel } from "core/config/util";
import { indexDocs } from "core/indexing/docs";
import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider";
import { CodebaseIndexer } from "core/indexing/indexCodebase";
import { CodebaseIndexer, PauseToken } from "core/indexing/indexCodebase";
import { logDevData } from "core/util/devdata";
import historyManager from "core/util/history";
import { Message } from "core/util/messenger";
@ -32,8 +32,17 @@ export class Core {
constructor(messenger: IpcMessenger, ide: IDE) {
this.messenger = messenger;
this.ide = ide;
this.configHandler = new ConfigHandler(this.ide);
this.codebaseIndexer = new CodebaseIndexer(this.configHandler, this.ide);
this.configHandler = new ConfigHandler(
this.ide,
undefined,
(text: string) => {},
() => {},
);
this.codebaseIndexer = new CodebaseIndexer(
this.configHandler,
this.ide,
new PauseToken(false),
);
const on = this.messenger.on.bind(this.messenger);
@ -87,13 +96,14 @@ export class Core {
this.configHandler.reloadConfig();
return this.configHandler.getSerializedConfig();
});
on("config/updateRemoteConfigSettings", (msg) => {});
// Context providers
on("context/addDocs", async (msg) => {
for await (const _ of indexDocs(
msg.data.title,
new URL(msg.data.url),
new TransformersJsEmbeddingsProvider()
new TransformersJsEmbeddingsProvider(),
)) {
}
});
@ -108,7 +118,7 @@ export class Core {
const config = await this.config();
const llm = await this.getSelectedModel();
const provider = config.contextProviders?.find(
(provider) => provider.description.title === msg.data.name
(provider) => provider.description.title === msg.data.name,
);
if (!provider) return [];
@ -136,12 +146,12 @@ export class Core {
async function* llmStreamChat(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<Protocol["llm/streamChat"][0]>
msg: Message<Protocol["llm/streamChat"][0]>,
) {
const model = await configHandler.llmFromTitle(msg.data.title);
const gen = model.streamChat(
msg.data.messages,
msg.data.completionOptions
msg.data.completionOptions,
);
let next = await gen.next();
while (!next.done) {
@ -158,19 +168,19 @@ export class Core {
}
on("llm/streamChat", (msg) =>
llmStreamChat(this.configHandler, this.abortedMessageIds, msg)
llmStreamChat(this.configHandler, this.abortedMessageIds, msg),
);
async function* llmStreamComplete(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<Protocol["llm/streamComplete"][0]>
msg: Message<Protocol["llm/streamComplete"][0]>,
) {
const model = await configHandler.llmFromTitle(msg.data.title);
const gen = model.streamComplete(
msg.data.prompt,
msg.data.completionOptions
msg.data.completionOptions,
);
let next = await gen.next();
while (!next.done) {
@ -187,13 +197,13 @@ export class Core {
}
on("llm/streamComplete", (msg) =>
llmStreamComplete(this.configHandler, this.abortedMessageIds, msg)
llmStreamComplete(this.configHandler, this.abortedMessageIds, msg),
);
async function* runNodeJsSlashCommand(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<Protocol["command/run"][0]>
msg: Message<Protocol["command/run"][0]>,
) {
const {
input,
@ -209,7 +219,7 @@ export class Core {
const config = await configHandler.loadConfig();
const llm = await configHandler.llmFromTitle(modelTitle);
const slashCommand = config.slashCommands?.find(
(sc) => sc.name === slashCommandName
(sc) => sc.name === slashCommandName,
);
if (!slashCommand) {
throw new Error(`Unknown slash command ${slashCommandName}`);
@ -239,13 +249,13 @@ export class Core {
yield { done: true, content: "" };
}
on("command/run", (msg) =>
runNodeJsSlashCommand(this.configHandler, this.abortedMessageIds, msg)
runNodeJsSlashCommand(this.configHandler, this.abortedMessageIds, msg),
);
}
public invoke<T extends keyof Protocol>(
method: keyof Protocol,
data: Protocol[T][0]
data: Protocol[T][0],
): Protocol[T][1] {
const response = this.messenger.invoke(method, data);
return response;

View file

@ -385,12 +385,38 @@ const GLOBAL_IGNORE_PATTERNS: &[&str] = &[
"*.mpeg",
"*.mov",
"*.mp3",
"*.mp4",
"*.mkv",
"*.mkv",
"*.webm",
"*.jar",
"*.onnx",
"*.tmp",
"*.swp",
"*.bak",
"*.dmp",
"**/node_modules/",
"**/.git",
"*.class",
"*.pyc",
"*.pyo",
"*.whl",
"*.egg-info",
"*.db",
"*.sql",
"*.sqlite",
"*.sqlite3",
"**/__pycache__/",
"**/.pytest_cache/",
"**/.env",
"*.pem",
"*.cert",
"*.key",
"*.csr",
"**/.idea/",
"**/.vscode/",
"**/.history/",
"*.sass-cache",
"*.scssc",
"*.parquet",
];
fn global_ignore_path() -> PathBuf {