Merge branch 'preview' into dev

This commit is contained in:
Nate Sesti 2024-06-19 14:37:08 -07:00
commit 2cf3a2a874
34 changed files with 1842 additions and 442 deletions

View file

@ -224,12 +224,17 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
);
// Copy to build directory for testing
const [platform, arch] = target.split("-");
if (platform === currentPlatform && arch === currentArch) {
fs.copyFileSync(
`${targetDir}/node_sqlite3.node`,
`build/node_sqlite3.node`,
);
try {
const [platform, arch] = target.split("-");
if (platform === currentPlatform && arch === currentArch) {
fs.copyFileSync(
`${targetDir}/node_sqlite3.node`,
`build/node_sqlite3.node`,
);
}
} catch (error) {
console.log("[warn] Could not copy node_sqlite to build");
console.log(error)
}
fs.unlinkSync(`${targetDir}/build.tar.gz`);

View file

@ -42,6 +42,7 @@
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@types/jsdom": "^21.1.6",

View file

@ -241,13 +241,20 @@ const EditSlashCommand: SlashCommand = {
part.text = part.text.replace("/edit", "").trimStart();
}
});
} else {
} else if (input?.startsWith("/edit")) {
content = input.replace("/edit", "").trimStart();
} else if (input?.startsWith("/comment")) {
content = input.replace("/comment", "").trimStart();
}
const userInput = stripImages(content).replace(
let userInput = stripImages(content).replace(
`\`\`\`${contextItemToEdit.name}\n${contextItemToEdit.content}\n\`\`\`\n`,
"",
);
// if the above replace fails to find a match, the code will still be present
// in the userInput. Replace it with input if available.
if (userInput.includes("\`\`\`") && (input !== "" || !input)) {
userInput = input;
}
const rif: RangeInFileWithContents =
contextItemToRangeInFileWithContents(contextItemToEdit);

View file

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

View file

@ -5,7 +5,7 @@ import {
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../index.js";
import { getBasename, getLastNPathParts } from "../../util/index.js";
import { getBasename, groupByLastNPathParts, getUniqueFilePath } from "../../util/index.js";
import { BaseContextProvider } from "../index.js";
const MAX_SUBMENU_ITEMS = 10_000;
@ -43,12 +43,14 @@ class FileContextProvider extends BaseContextProvider {
return args.ide.listWorkspaceContents(dir);
}),
);
const files = results.flat().slice(-MAX_SUBMENU_ITEMS);
const files = results.flat().slice(-MAX_SUBMENU_ITEMS);
const fileGroups = groupByLastNPathParts(files, 2);
return files.map((file) => {
return {
id: file,
title: getBasename(file),
description: getLastNPathParts(file, 2),
description: getUniqueFilePath(file, fileGroups),
};
});
}

View file

@ -5,7 +5,7 @@ import {
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../index.js";
import { getBasename, getLastNPathParts } from "../../util/index.js";
import { getBasename, groupByLastNPathParts, getUniqueFilePath } from "../../util/index.js";
import { BaseContextProvider } from "../index.js";
class FolderContextProvider extends BaseContextProvider {
@ -29,11 +29,13 @@ class FolderContextProvider extends BaseContextProvider {
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const folders = await args.ide.listFolders();
const folderGroups = groupByLastNPathParts(folders, 2);
return folders.map((folder) => {
return {
id: folder,
title: getBasename(folder),
description: getLastNPathParts(folder, 2),
description: getUniqueFilePath(folder, folderGroups)
};
});
}

2
core/index.d.ts vendored
View file

@ -614,7 +614,9 @@ export type ModelName =
// Gemini
| "gemini-pro"
| "gemini-1.5-pro-latest"
| "gemini-1.5-pro"
| "gemini-1.5-flash-latest"
| "gemini-1.5-flash"
// Mistral
| "mistral-tiny"
| "mistral-small"

View file

@ -79,15 +79,26 @@ export class LanceDbIndex implements CodebaseIndex {
const content = contents[i];
const chunks: Chunk[] = [];
let hasEmptyChunks = false;
for await (const chunk of chunkDocument(
items[i].path,
content,
LanceDbIndex.MAX_CHUNK_SIZE,
items[i].cacheKey,
)) {
if (chunk.content.length == 0) {
hasEmptyChunks = true;
break;
}
chunks.push(chunk);
}
if (hasEmptyChunks) {
// File did not chunk properly, let's skip it.
continue;
}
if (chunks.length > 20) {
// Too many chunks to index, probably a larger file than we want to include
continue;

View file

@ -2,33 +2,19 @@ import {
BedrockRuntimeClient,
InvokeModelWithResponseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";
import * as fs from "node:fs";
import os from "node:os";
import { join as joinPath } from "node:path";
import { promisify } from "util";
import { fromIni } from "@aws-sdk/credential-providers";
import {
ChatMessage,
CompletionOptions,
LLMOptions,
MessageContent,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../countTokens.js";
import { BaseLLM } from "../index.js";
const aws4 = require("aws4");
const readFile = promisify(fs.readFile);
namespace BedrockCommon {
export enum Method {
Chat = "invoke-with-response-stream",
Completion = "invoke-with-response-stream",
}
export const Service: string = "bedrock";
export const AuthAlgo: string = "AWS4-HMAC-SHA256";
export const HashAlgo: string = "sha256";
}
class Bedrock extends BaseLLM {
private static PROFILE_NAME: string = "bedrock";
static providerName: ModelProvider = "bedrock";
static defaultOptions: Partial<LLMOptions> = {
region: "us-east-1",
@ -43,130 +29,6 @@ class Bedrock extends BaseLLM {
}
}
private _convertModelName(model: string): string {
return (
{
"claude-3-sonnet-20240229": "anthropic.claude-3-sonnet-20240229-v1:0",
"claude-3-haiku-20240307": "anthropic.claude-3-haiku-20240307-v1:0",
"claude-2": "anthropic.claude-v2:1",
}[model] ?? model
);
}
private _convertArgs(options: CompletionOptions) {
const finalOptions = {
top_k: options.topK,
top_p: options.topP,
temperature: options.temperature,
max_tokens: options.maxTokens ?? 4096,
stop_sequences: options.stop,
};
return finalOptions;
}
private _convertMessages(msgs: ChatMessage[]): any[] {
const messages = msgs
.filter((m) => m.role !== "system")
.map((message) => {
if (typeof message.content === "string") {
return message;
}
return {
...message,
content: message.content.map((part) => {
if (part.type === "text") {
return part;
}
return {
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
}),
};
});
return messages;
}
private _parseCredentialsFile(fileContents: string) {
const profiles: { [key: string]: any } = {};
const lines = fileContents.trim().split("\n");
let currentProfile: string | null = null;
for (const line of lines) {
const trimmedLine = line.trim();
if (trimmedLine.startsWith("[") && trimmedLine.endsWith("]")) {
currentProfile = trimmedLine.slice(1, -1);
profiles[currentProfile] = {};
} else if (currentProfile !== null && trimmedLine.includes("=")) {
const [key, value] = trimmedLine.split("=");
const trimmedKey = key.trim();
const trimmedValue = value.trim();
if (trimmedKey === "aws_access_key_id") {
profiles[currentProfile].accessKeyId = trimmedValue;
} else if (trimmedKey === "aws_secret_access_key") {
profiles[currentProfile].secretAccessKey = trimmedValue;
} else if (trimmedKey === "aws_session_token") {
profiles[currentProfile].sessionToken = trimmedValue;
}
}
}
return profiles;
}
private async _fetchWithAwsAuthSigV4(
apiMethod: BedrockCommon.Method,
body: string,
model: string,
): Promise<Response> {
const path = `/model/${model}/${apiMethod}`;
const opts = {
headers: {
accept: "application/vnd.amazon.eventstream",
"content-type": "application/json",
"x-amzn-bedrock-accept": "*/*",
},
path: path,
body: body,
service: "bedrock",
host: new URL(this.apiBase!).host,
region: this.region,
};
let accessKeyId: string;
let secretAccessKey: string;
let sessionToken: string;
try {
const data = await readFile(
joinPath(process.env.HOME ?? os.homedir(), ".aws", "credentials"),
"utf8",
);
const credentialsFile = this._parseCredentialsFile(data);
const credentials = credentialsFile.bedrock ?? credentialsFile.default;
accessKeyId = credentials.accessKeyId;
secretAccessKey = credentials.secretAccessKey;
sessionToken = credentials.sessionToken || "";
} catch (err) {
console.error("Error reading AWS credentials", err);
return new Response("403");
}
return await this.fetch(new URL(`${this.apiBase}${path}`), {
method: "POST",
headers: aws4.sign(opts, { accessKeyId, secretAccessKey, sessionToken })
.headers,
body: body,
});
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
@ -181,51 +43,172 @@ class Bedrock extends BaseLLM {
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const data = await readFile(
joinPath(process.env.HOME ?? os.homedir(), ".aws", "credentials"),
"utf8",
);
const credentialsFile = this._parseCredentialsFile(data);
const credentials = credentialsFile.bedrock ?? credentialsFile.default;
const accessKeyId = credentials.accessKeyId;
const secretAccessKey = credentials.secretAccessKey;
const sessionToken = credentials.sessionToken || "";
const credentials = await this._getCredentials();
const client = new BedrockRuntimeClient({
region: this.region,
credentials: {
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
sessionToken: sessionToken,
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken || "",
},
});
const command = new InvokeModelWithResponseStreamCommand({
body: new TextEncoder().encode(
JSON.stringify({
anthropic_version: "bedrock-2023-05-31",
max_tokens: options.maxTokens,
system: this.systemMessage,
messages: this._convertMessages(messages),
temperature: options.temperature,
top_p: options.topP,
top_k: options.topK,
stop_sequences: options.stop,
}),
),
contentType: "application/json",
modelId: options.model,
});
const toolkit = this._getToolkit(options.model);
const command = toolkit.generateCommand(messages, options);
const response = await client.send(command);
if (response.body) {
for await (const value of response.body) {
const binaryChunk = value.chunk?.bytes;
const textChunk = new TextDecoder().decode(binaryChunk);
const chunk = JSON.parse(textChunk).delta?.text;
if (chunk) {
yield { role: "assistant", content: chunk };
const text = toolkit.unwrapResponseChunk(value);
if (text) {
yield { role: "assistant", content: text };
}
}
}
}
private async _getCredentials() {
try {
return await fromIni({
profile: Bedrock.PROFILE_NAME,
})();
} catch (e) {
console.warn(
`AWS profile with name ${Bedrock.PROFILE_NAME} not found in ~/.aws/credentials, using default profile`,
);
return await fromIni()();
}
}
private _getToolkit(model: string): BedrockModelToolkit {
if (model.includes("claude-3")) {
return new AnthropicClaude3Toolkit(this);
} else if (model.includes("llama")) {
return new Llama3Toolkit(this);
} else {
throw new Error(
`Model ${model} is currently not supported in Continue for Bedrock`,
);
}
}
}
interface BedrockModelToolkit {
generateCommand(
messages: ChatMessage[],
options: CompletionOptions,
): InvokeModelWithResponseStreamCommand;
unwrapResponseChunk(rawValue: any): string;
}
class AnthropicClaude3Toolkit implements BedrockModelToolkit {
constructor(private bedrock: Bedrock) {}
generateCommand(
messages: ChatMessage[],
options: CompletionOptions,
): InvokeModelWithResponseStreamCommand {
const payload = {
anthropic_version: "bedrock-2023-05-31",
max_tokens: options.maxTokens,
system: this.bedrock.systemMessage,
messages: this._convertMessages(messages),
temperature: options.temperature,
top_p: options.topP,
top_k: options.topK,
stop_sequences: options.stop,
};
return new InvokeModelWithResponseStreamCommand({
body: new TextEncoder().encode(JSON.stringify(payload)),
contentType: "application/json",
modelId: options.model,
});
}
private _convertMessages(msgs: ChatMessage[]): any[] {
return msgs
.filter((m) => m.role !== "system")
.map((message) => this._convertMessage(message));
}
private _convertMessage(message: ChatMessage): any {
return {
role: message.role,
content: this._convertMessageContent(message.content),
};
}
private _convertMessageContent(messageContent: MessageContent): any {
if (typeof messageContent === "string") {
return messageContent;
}
return messageContent.map((part) => {
if (part.type === "text") {
return part;
}
return {
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
});
}
unwrapResponseChunk(rawValue: any): string {
const binaryChunk = rawValue.chunk?.bytes;
const textChunk = new TextDecoder().decode(binaryChunk);
const chunk = JSON.parse(textChunk).delta?.text;
return chunk;
}
}
class Llama3Toolkit implements BedrockModelToolkit {
constructor(private bedrock: Bedrock) {}
generateCommand(
messages: ChatMessage[],
options: CompletionOptions,
): InvokeModelWithResponseStreamCommand {
let prompt = "<|begin_of_text|>";
if (this.bedrock.systemMessage) {
prompt += `<|start_header_id|>system<|end_header_id|>${this.bedrock.systemMessage}<|eot_id|>`;
}
for (const message of messages) {
let content = "";
if (typeof message.content === "string") {
content = message.content;
} else {
for (const part of message.content) {
if (part.type === "text") {
content += part.text || "";
} else {
console.warn("Skipping non-text message part", part);
}
}
}
if (content) {
prompt += `<|start_header_id|>${message.role}<|end_header_id|>${content}<|eot_id|>`;
}
}
prompt += "<|start_header_id|>assistant<|end_header_id|>";
const payload = {
prompt,
max_gen_len: options.maxTokens,
temperature: options.temperature,
top_p: options.topP,
};
return new InvokeModelWithResponseStreamCommand({
body: new TextEncoder().encode(JSON.stringify(payload)),
contentType: "application/json",
modelId: options.model,
});
}
unwrapResponseChunk(rawValue: any): string {
const binaryChunk = rawValue.chunk?.bytes;
const textChunk = new TextDecoder().decode(binaryChunk);
const chunk = JSON.parse(textChunk).generation;
return chunk;
}
}
export default Bedrock;

View file

@ -12,6 +12,7 @@ class Deepseek extends OpenAI {
},
useLegacyCompletionsEndpoint: false,
};
protected maxStopWords: number | undefined = 4;
}
export default Deepseek;

View file

@ -181,23 +181,28 @@ class Gemini extends BaseLLM {
data = JSON.parse(part);
} catch (e) {
foundIncomplete = true;
continue;
continue; // yo!
}
if (data.error) {
throw new Error(data.error.message);
}
// Incrementally stream the content to make it smoother
const content = data.candidates[0].content.parts[0].text;
const words = content.split(/(\s+)/);
const delaySeconds = Math.min(4.0 / (words.length + 1), 0.1);
while (words.length > 0) {
const wordsToYield = Math.min(3, words.length);
yield {
role: "assistant",
content: words.splice(0, wordsToYield).join(""),
};
await delay(delaySeconds);
// Check for existence of each level before accessing the final 'text' property
if (data?.candidates?.[0]?.content?.parts?.[0]?.text) {
// Incrementally stream the content to make it smoother
const content = data.candidates[0].content.parts[0].text;
const words = content.split(/(\s+)/);
const delaySeconds = Math.min(4.0 / (words.length + 1), 0.1);
while (words.length > 0) {
const wordsToYield = Math.min(3, words.length);
yield {
role: "assistant",
content: words.splice(0, wordsToYield).join(""),
};
await delay(delaySeconds);
}
} else {
// Handle the case where the expected data structure is not found
console.warn('Unexpected response format:', data);
}
}
if (foundIncomplete) {

View file

@ -9,13 +9,9 @@ export async function* streamResponse(
throw new Error("No response body returned.");
}
const stream = response.body as any;
const stream = (ReadableStream as any).from(response.body);
const decoder = new TextDecoder("utf-8");
for await (const chunk of stream) {
yield decoder.decode(chunk, { stream: true, });
}
yield* stream.pipeThrough(new TextDecoderStream("utf-8"));
}
function parseDataLine(line: string): any {

1505
core/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -30,6 +30,7 @@
},
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@types/jsdom": "^21.1.6",

View file

@ -99,6 +99,37 @@ export function getLastNPathParts(filepath: string, n: number): string {
return filepath.split(SEP_REGEX).slice(-n).join("/");
}
export function groupByLastNPathParts(filepaths: string[], n: number): Record<string, string[]> {
return filepaths.reduce((groups, item) => {
const lastNParts = getLastNPathParts(item, n);
if (!groups[lastNParts]) {
groups[lastNParts] = [];
}
groups[lastNParts].push(item);
return groups;
}, {} as Record<string, string[]>);
}
export function getUniqueFilePath(item: string, itemGroups: Record<string, string[]>): string {
const lastTwoParts = getLastNPathParts(item, 2);
const group = itemGroups[lastTwoParts];
let n = 2;
if (group.length > 1) {
while (
group.some(
(otherItem) =>
otherItem !== item &&
getLastNPathParts(otherItem, n) === getLastNPathParts(item, n)
)
) {
n++;
}
}
return getLastNPathParts(item, n);
}
export function shortestRelativePaths(paths: string[]): string[] {
if (paths.length === 0) return [];

View file

@ -1,6 +1,6 @@
# Code Configuration
To allow added flexibility and eventually support an entire plugin ecosystem, Continue can be configured programmatically in a Python file, `~/.continue/config.ts`.
To allow added flexibility and eventually support an entire plugin ecosystem, Continue can be configured programmatically in a TypeScript file, `~/.continue/config.ts`.
Whenever Continue loads, it carries out the following steps:

View file

@ -27,7 +27,7 @@ This uses Claude 3 Opus for chat, Codestral for autocomplete, and Voyage AI for
"tabAutocompleteModel": {
"title": "Codestral",
"provider": "mistral",
"model": "codestral:latest",
"model": "codestral-latest",
"apiKey": "[CODESTRAL_API_KEY]"
},
"embeddingsProvider": {

View file

@ -685,7 +685,9 @@
"chat-bison-001",
"gemini-pro",
"gemini-1.5-pro-latest",
"gemini-1.5-flash-latest"
"gemini-1.5-pro",
"gemini-1.5-flash-latest",
"gemini-1.5-flash"
]
}
}
@ -1094,7 +1096,9 @@
"chat-bison-001",
"gemini-pro",
"gemini-1.5-pro-latest",
"gemini-1.5-pro",
"gemini-1.5-flash-latest",
"gemini-1.5-flash",
"mistral-tiny",
"mistral-small",
"mistral-medium",

View file

@ -685,7 +685,9 @@
"chat-bison-001",
"gemini-pro",
"gemini-1.5-pro-latest",
"gemini-1.5-flash-latest"
"gemini-1.5-pro",
"gemini-1.5-flash-latest",
"gemini-1.5-flash"
]
}
}
@ -1094,7 +1096,9 @@
"chat-bison-001",
"gemini-pro",
"gemini-1.5-pro-latest",
"gemini-1.5-pro",
"gemini-1.5-flash-latest",
"gemini-1.5-flash",
"mistral-tiny",
"mistral-small",
"mistral-medium",

View file

@ -685,7 +685,9 @@
"chat-bison-001",
"gemini-pro",
"gemini-1.5-pro-latest",
"gemini-1.5-flash-latest"
"gemini-1.5-pro",
"gemini-1.5-flash-latest",
"gemini-1.5-flash"
]
}
}
@ -1094,7 +1096,9 @@
"chat-bison-001",
"gemini-pro",
"gemini-1.5-pro-latest",
"gemini-1.5-pro",
"gemini-1.5-flash-latest",
"gemini-1.5-flash",
"mistral-tiny",
"mistral-small",
"mistral-medium",

View file

@ -748,7 +748,9 @@
"chat-bison-001",
"gemini-pro",
"gemini-1.5-pro-latest",
"gemini-1.5-flash-latest"
"gemini-1.5-pro",
"gemini-1.5-flash-latest",
"gemini-1.5-flash"
]
}
}
@ -1218,7 +1220,9 @@
"chat-bison-001",
"gemini-pro",
"gemini-1.5-pro-latest",
"gemini-1.5-pro",
"gemini-1.5-flash-latest",
"gemini-1.5-flash",
"mistral-tiny",
"mistral-small",
"mistral-medium",

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.159",
"version": "0.9.163",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.159",
"version": "0.9.163",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",
@ -94,6 +94,7 @@
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@types/jsdom": "^21.1.6",

View file

@ -1,7 +1,7 @@
{
"name": "continue",
"icon": "media/icon.png",
"version": "0.9.159",
"version": "0.9.163",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -488,6 +488,7 @@
"quick-test": "npm run build-test && node ./out/runTestOnVSCodeHost.js",
"prepackage": "node scripts/prepackage.js",
"package": "node scripts/package.js",
"package-all": "node scripts/package-all.js",
"package:pre-release": "node scripts/package.js --pre-release",
"build:rust": "cargo-cp-artifact -ac sync sync.node -- cargo build --manifest-path ../../sync/Cargo.toml --message-format=json-render-diagnostics",
"build-debug:rust": "npm run build:rust --",

View file

@ -0,0 +1,33 @@
const { execSync } = require("child_process");
const PLATFORMS = [
"win32-x64",
// "win32-arm64", can't be built due to no sqlite3 binaries
"linux-x64",
"linux-arm64",
"darwin-x64",
"darwin-arm64",
]
const args = process.argv.slice(2);
const isPreRelease = args.includes("--pre-release");
(async () => {
for (const i in PLATFORMS) {
const platform = PLATFORMS[i];
const pkgCommand = isPreRelease
? "node scripts/package.js --pre-release --target " + platform // --yarn"
: "node scripts/package.js --target " + platform; // --yarn";
execSync(
"node scripts/prepackage-cross-platform.js --target "+ platform,
{stdio: 'inherit'}
);
execSync(
pkgCommand,
{stdio: 'inherit'}
);
}
})();

View file

@ -2,15 +2,23 @@ const { exec } = require("child_process");
const fs = require("fs");
const args = process.argv.slice(2);
const isPreRelease = args.includes("--pre-release");
let target;
if (args[0] === "--target") {
target = args[1];
}
if (!fs.existsSync("build")) {
fs.mkdirSync("build");
}
const command = isPreRelease
? "npx vsce package --out ./build patch --pre-release --no-dependencies" // --yarn"
: "npx vsce package --out ./build patch --no-dependencies"; // --yarn";
const isPreRelease = args.includes("--pre-release");
let command = isPreRelease
? "npx vsce package --out ./build patch --pre-release --no-dependencies" // --yarn"
: "npx vsce package --out ./build patch --no-dependencies"; // --yarn";
if (target) command += ` --target ${target}`;
exec(command, (error) => {
if (error) throw error;

View file

@ -20,6 +20,7 @@ const {
copyTreeSitterTagQryFiles,
copyNodeModules,
downloadEsbuildBinary,
downloadRipgrepBinary,
copySqliteBinary,
installNodeModuleInTempDirAndCopyToCurrent,
downloadSqliteBinary,
@ -62,6 +63,8 @@ console.log("[info] Using target: ", target);
const exe = os === "win32" ? ".exe" : "";
console.log("[info] Using target: ", target);
function ghAction() {
return !!process.env.GITHUB_ACTIONS;
}
@ -78,7 +81,7 @@ function isWin() {
return target?.startsWith("win");
}
(async () => {
async function package(target, os, arch, exe) {
console.log("[info] Packaging extension for target ", target);
// Copy config_schema.json to config.json in docs and intellij
@ -102,7 +105,7 @@ function isWin() {
await copyOnnxRuntimeFromNodeModules(target);
// *** Install @lancedb binary ***
const packageToInstall = {
const lancePackageToInstall = {
"darwin-arm64": "@lancedb/vectordb-darwin-arm64",
"darwin-x64": "@lancedb/vectordb-darwin-x64",
"linux-arm64": "@lancedb/vectordb-linux-arm64-gnu",
@ -111,20 +114,22 @@ function isWin() {
"win32-arm64": "@lancedb/vectordb-win32-x64-msvc", // they don't have a win32-arm64 build
}[target];
await installNodeModuleInTempDirAndCopyToCurrent(
packageToInstall,
lancePackageToInstall,
"@lancedb",
);
// *** esbuild ***
await installNodeModuleInTempDirAndCopyToCurrent(
"esbuild@0.17.19",
"@esbuild",
);
// await installNodeModuleInTempDirAndCopyToCurrent(
// "esbuild@0.17.19",
// "@esbuild",
// );
await downloadEsbuildBinary(target);
// *** sqlite ***
await downloadSqliteBinary(target);
await copySqliteBinary();
await downloadRipgrepBinary(target);
// copy node_modules to out/node_modules
await copyNodeModules();
@ -199,4 +204,8 @@ function isWin() {
`out/node_modules/esbuild/lib/main.js`,
`out/node_modules/esbuild/bin/esbuild`,
]);
}
(async () => {
await package(target, os, arch, exe);
})();

View file

@ -193,7 +193,7 @@ async function copyOnnxRuntimeFromNodeModules(target) {
}
async function copyTreeSitterWasms() {
process.chdir(path.join(continueDir, "extensioins", "vscode"));
process.chdir(path.join(continueDir, "extensions", "vscode"));
fs.mkdirSync("out", { recursive: true });
await new Promise((resolve, reject) => {
@ -271,27 +271,79 @@ async function copyNodeModules() {
console.log(`[info] Copied ${NODE_MODULES_TO_COPY.join(", ")}`);
}
async function downloadEsbuildBinary(isGhAction, isArm, target) {
process.chdir(path.join(continueDir, "extensions", "vscode"));
// async function downloadEsbuildBinary(isGhAction, isArm, target) {
// process.chdir(path.join(continueDir, "extensions", "vscode"));
if (isGhAction && isArm) {
// Download and unzip esbuild
console.log("[info] Downloading pre-built esbuild binary");
rimrafSync("node_modules/@esbuild");
fs.mkdirSync("node_modules/@esbuild", { recursive: true });
execCmdSync(
`curl -o node_modules/@esbuild/esbuild.zip https://continue-server-binaries.s3.us-west-1.amazonaws.com/${target}/esbuild.zip`,
);
execCmdSync(`cd node_modules/@esbuild && unzip esbuild.zip`);
fs.unlinkSync("node_modules/@esbuild/esbuild.zip");
} else {
// Download esbuild from npm in tmp and copy over
console.log("npm installing esbuild binary");
await installNodeModuleInTempDirAndCopyToCurrent(
"esbuild@0.17.19",
"@esbuild",
);
// if (isGhAction && isArm) {
// // Download and unzip esbuild
// console.log("[info] Downloading pre-built esbuild binary");
// rimrafSync("node_modules/@esbuild");
// fs.mkdirSync("node_modules/@esbuild", { recursive: true });
// execCmdSync(
// `curl -o node_modules/@esbuild/esbuild.zip https://continue-server-binaries.s3.us-west-1.amazonaws.com/${target}/esbuild.zip`,
// );
// execCmdSync(`cd node_modules/@esbuild && unzip esbuild.zip`);
// fs.unlinkSync("node_modules/@esbuild/esbuild.zip");
// } else {
// // Download esbuild from npm in tmp and copy over
// console.log("npm installing esbuild binary");
// await installNodeModuleInTempDirAndCopyToCurrent(
// "esbuild@0.17.19",
// "@esbuild",
// );
// }
// }
async function downloadEsbuildBinary(target) {
console.log("[info] Downloading pre-built esbuild binary");
rimrafSync("out/node_modules/@esbuild");
fs.mkdirSync(`out/node_modules/@esbuild/${target}/bin`, { recursive: true });
fs.mkdirSync(`out/tmp`, { recursive: true });
const downloadUrl = {
"darwin-arm64":
"https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.17.19.tgz",
"linux-arm64":
"https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.17.19.tgz",
"win32-arm64":
"https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.17.19.tgz",
"linux-x64":
"https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.17.19.tgz",
"darwin-x64":
"https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.17.19.tgz",
"win32-x64":
"https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.19.tgz",
}[target];
execCmdSync(
`curl -L -o out/tmp/esbuild.tgz ${downloadUrl}`,
);
execCmdSync("cd out/tmp && tar -xvzf esbuild.tgz");
// Copy the installed package back to the current directory
let tmpPath = "out/tmp/package/bin";
let outPath = `out/node_modules/@esbuild/${target}/bin`;
if (target.startsWith("win")) {
tmpPath = 'out/tmp/package';
outPath = `out/node_modules/@esbuild/${target}`;
}
await new Promise((resolve, reject) => {
ncp(
path.join(tmpPath),
path.join(outPath),
{ dereference: true },
(error) => {
if (error) {
console.error(
`[error] Error copying esbuild package`,
error,
);
reject(error);
} else {
resolve();
}
},
);
});
rimrafSync("out/tmp")
}
async function downloadSqliteBinary(target) {
@ -338,6 +390,41 @@ async function copySqliteBinary() {
});
}
async function downloadRipgrepBinary(target) {
console.log("[info] Downloading pre-built ripgrep binary");
rimrafSync("node_modules/@vscode/ripgrep/bin");
fs.mkdirSync("node_modules/@vscode/ripgrep/bin", { recursive: true });4
const downloadUrl = {
"darwin-arm64":
"https://github.com/microsoft/ripgrep-prebuilt/releases/download/v13.0.0-10/ripgrep-v13.0.0-10-aarch64-apple-darwin.tar.gz",
"linux-arm64":
"https://github.com/microsoft/ripgrep-prebuilt/releases/download/v13.0.0-10/ripgrep-v13.0.0-10-aarch64-unknown-linux-gnu.tar.gz",
"win32-arm64":
"https://github.com/microsoft/ripgrep-prebuilt/releases/download/v13.0.0-10/ripgrep-v13.0.0-10-aarch64-pc-windows-msvc.zip",
"linux-x64":
"https://github.com/microsoft/ripgrep-prebuilt/releases/download/v13.0.0-10/ripgrep-v13.0.0-10-x86_64-unknown-linux-musl.tar.gz",
"darwin-x64":
"https://github.com/microsoft/ripgrep-prebuilt/releases/download/v13.0.0-10/ripgrep-v13.0.0-10-x86_64-apple-darwin.tar.gz",
"win32-x64":
"https://github.com/microsoft/ripgrep-prebuilt/releases/download/v13.0.0-10/ripgrep-v13.0.0-10-x86_64-pc-windows-msvc.zip",
}[target];
if(target.startsWith("win")) {
execCmdSync(
`curl -L -o node_modules/@vscode/ripgrep/bin/build.zip ${downloadUrl}`,
);
execCmdSync("cd node_modules/@vscode/ripgrep/bin && unzip build.zip");
fs.unlinkSync("node_modules/@vscode/ripgrep/bin/build.zip");
} else {
execCmdSync(
`curl -L -o node_modules/@vscode/ripgrep/bin/build.tar.gz ${downloadUrl}`,
);
execCmdSync("cd node_modules/@vscode/ripgrep/bin && tar -xvzf build.tar.gz");
fs.unlinkSync("node_modules/@vscode/ripgrep/bin/build.tar.gz");
}
}
async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
console.log(`Copying ${packageName} to ${toCopy}`);
// This is a way to install only one package without npm trying to install all the dependencies
@ -409,4 +496,5 @@ module.exports = {
copySqliteBinary,
installNodeModuleInTempDirAndCopyToCurrent,
downloadSqliteBinary,
downloadRipgrepBinary,
};

View file

@ -12,7 +12,8 @@
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
"resolveJsonModule": true /* Enable importing .json files */
"resolveJsonModule": true /* Enable importing .json files */,
"types": ["mocha"] // This solves conflict between jest and mocha: https://github.com/cypress-io/cypress/issues/7435#issuecomment-631695007
},
"include": ["src/**/*", "../../core/**/*.ts", "../../core/**/*.d.ts"],
// core/test uses @types/jest, which conflicts with @types/mocha

1
gui/package-lock.json generated
View file

@ -87,6 +87,7 @@
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@types/jsdom": "^21.1.6",

View file

@ -12,7 +12,7 @@ import {
RangeInFile,
} from "core";
import { modelSupportsImages } from "core/llm/autodetect";
import { getBasename } from "core/util";
import { getBasename, getRelativePath } from "core/util";
import { useContext, useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import styled from "styled-components";
@ -590,12 +590,13 @@ function TipTapEditor(props: TipTapEditorProps) {
const rif: RangeInFile & { contents: string } =
data.rangeInFileWithContents;
const basename = getBasename(rif.filepath);
const relativePath = getRelativePath(rif.filepath, await ideMessenger.ide.getWorkspaceDirs());
const rangeStr = `(${rif.range.start.line + 1}-${rif.range.end.line + 1})`;
const item: ContextItemWithId = {
content: rif.contents,
name: `${basename} (${rif.range.start.line + 1}-${
rif.range.end.line + 1
})`,
description: rif.filepath,
name: `${basename} ${rangeStr}`,
// Description is passed on to the LLM to give more context on file path
description: `${relativePath} ${rangeStr}`,
id: {
providerTitle: "code",
itemId: rif.filepath,

View file

@ -55,7 +55,7 @@ async function resolveEditorContent(
} else if (p.type === "codeBlock") {
if (!p.attrs.item.editing) {
const text =
"```" + p.attrs.item.name + "\n" + p.attrs.item.content + "\n```";
"```" + p.attrs.item.description + "\n" + p.attrs.item.content + "\n```";
if (parts[parts.length - 1]?.type === "text") {
parts[parts.length - 1].text += "\n" + text;
} else {

View file

@ -107,29 +107,44 @@ function LinkableCode(props: any) {
const [filepath, rest] =
contextItemContentMatch.description.split(" (");
const [startLine, endLine] = rest.split(")")[0]?.split("-") || [
"0",
"0",
];
const start = parseInt(startLine);
const end = parseInt(endLine);
setIsLink(true);
setRif({
filepath,
range: {
start: {
line: start + line,
character: 0,
},
end: {
line: start + line + 1,
character: 0,
},
},
});
console.log("MATCH: ", content, contextItemContentMatch, line);
if (rest) {
const [startLine, endLine] = rest.split(")")[0]?.split("-") || [
"0",
"0",
];
const start = parseInt(startLine);
const end = parseInt(endLine);
setRif({
filepath,
range: {
start: {
line: start + line,
character: 0,
},
end: {
line: start + line + 1,
character: 0,
},
},
});
} else {
setRif({
filepath,
range: {
start: {
line: 0,
character: 0,
},
end: {
line: 0,
character: 0,
},
},
});
}
}
}
}, [linkingDone, contextItems]);

View file

@ -1,5 +1,5 @@
import { ContextSubmenuItem } from "core";
import { deduplicateArray, getBasename, getLastNPathParts } from "core/util";
import { deduplicateArray, getBasename, groupByLastNPathParts, getUniqueFilePath } from "core/util";
import MiniSearch, { SearchResult } from "minisearch";
import { useContext, useEffect, useState } from "react";
import { useSelector } from "react-redux";
@ -34,11 +34,13 @@ function useSubmenuContextProviders() {
async function getOpenFileItems() {
const openFiles = await ideMessenger.ide.getOpenFiles();
const openFileGroups = groupByLastNPathParts(openFiles, 2);
return openFiles.map((file) => {
return {
id: file,
title: getBasename(file),
description: getLastNPathParts(file, 2),
description: getUniqueFilePath(file, openFileGroups),
providerTitle: "file",
};
});

View file

@ -14,6 +14,7 @@ function execCmdSync(cmd) {
function autodetectPlatformAndArch() {
platform = {
aix: "linux",
alpine: "linux",
darwin: "darwin",
freebsd: "linux",
linux: "linux",
@ -23,6 +24,7 @@ function autodetectPlatformAndArch() {
}[process.platform];
arch = {
arm: "arm64",
armhf: "arm64",
arm64: "arm64",
ia32: "x64",
loong64: "arm64",