From c3d4b69a2106f8d2eb737975d99af19552a43f87 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 5 Feb 2024 16:12:01 -0800 Subject: [PATCH 01/59] =?UTF-8?q?=F0=9F=9A=A7=20Start=20of=20Typescript=20?= =?UTF-8?q?IPC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/ipc/IpcIde.ts | 101 +++++++++++++++++++++++++++++++++++++++++ core/ipc/cli.ts | 9 ++++ core/ipc/interface.ts | 8 ++++ core/ipc/messenger.ts | 16 +++++++ core/package-lock.json | 17 +++++-- core/package.json | 1 + core/yarn.lock | 13 ++++-- 7 files changed, 157 insertions(+), 8 deletions(-) create mode 100644 core/ipc/IpcIde.ts create mode 100644 core/ipc/cli.ts create mode 100644 core/ipc/interface.ts create mode 100644 core/ipc/messenger.ts diff --git a/core/ipc/IpcIde.ts b/core/ipc/IpcIde.ts new file mode 100644 index 000000000..2606b34eb --- /dev/null +++ b/core/ipc/IpcIde.ts @@ -0,0 +1,101 @@ +import { Chunk, DiffLine, IDE, Problem } from ".."; +import { BrowserSerializedContinueConfig } from "../config/load"; + +export class IpcIde implements IDE { + getSerializedConfig(): Promise { + throw new Error("Method not implemented."); + } + getDiff(): Promise { + throw new Error("Method not implemented."); + } + getTerminalContents(): Promise { + throw new Error("Method not implemented."); + } + listWorkspaceContents(directory?: string | undefined): Promise { + throw new Error("Method not implemented."); + } + listFolders(): Promise { + throw new Error("Method not implemented."); + } + getWorkspaceDirs(): Promise { + throw new Error("Method not implemented."); + } + writeFile(path: string, contents: string): Promise { + throw new Error("Method not implemented."); + } + showVirtualFile(title: string, contents: string): Promise { + throw new Error("Method not implemented."); + } + getContinueDir(): Promise { + throw new Error("Method not implemented."); + } + openFile(path: string): Promise { + throw new Error("Method not implemented."); + } + runCommand(command: string): Promise { + throw new Error("Method not implemented."); + } + saveFile(filepath: string): Promise { + throw new Error("Method not implemented."); + } + readFile(filepath: string): Promise { + throw new Error("Method not implemented."); + } + showLines( + filepath: string, + startLine: number, + endLine: number + ): Promise { + throw new Error("Method not implemented."); + } + showDiff( + filepath: string, + newContents: string, + stepIndex: number + ): Promise { + throw new Error("Method not implemented."); + } + verticalDiffUpdate( + filepath: string, + startLine: number, + endLine: number, + diffLine: DiffLine + ): Promise { + throw new Error("Method not implemented."); + } + getOpenFiles(): Promise { + throw new Error("Method not implemented."); + } + getPinnedFiles(): Promise { + throw new Error("Method not implemented."); + } + getSearchResults(query: string): Promise { + throw new Error("Method not implemented."); + } + subprocess(command: string): Promise<[string, string]> { + throw new Error("Method not implemented."); + } + getProblems(filepath?: string | undefined): Promise { + throw new Error("Method not implemented."); + } + getBranch(dir: string): Promise { + throw new Error("Method not implemented."); + } + getFilesToEmbed(providerId: string): Promise<[string, string, string][]> { + throw new Error("Method not implemented."); + } + sendEmbeddingForChunk( + chunk: Chunk, + embedding: number[], + tags: string[] + ): void { + throw new Error("Method not implemented."); + } + retrieveChunks( + text: string, + n: number, + directory: string | undefined + ): Promise { + throw new Error("Method not implemented."); + } +} diff --git a/core/ipc/cli.ts b/core/ipc/cli.ts new file mode 100644 index 000000000..e70859803 --- /dev/null +++ b/core/ipc/cli.ts @@ -0,0 +1,9 @@ +import { Command } from "commander"; + +const program = new Command(); + +program.argument("", "input name").action((name) => { + console.log(`Hello, ${name}`); +}); + +program.parse(process.argv); diff --git a/core/ipc/interface.ts b/core/ipc/interface.ts new file mode 100644 index 000000000..67d77ddd6 --- /dev/null +++ b/core/ipc/interface.ts @@ -0,0 +1,8 @@ +import { Messenger } from "./messenger"; + +export class IpcInterface { + private messenger: Messenger; + constructor(messenger: Messenger) { + this.messenger = messenger; + } +} diff --git a/core/ipc/messenger.ts b/core/ipc/messenger.ts new file mode 100644 index 000000000..4b3d68769 --- /dev/null +++ b/core/ipc/messenger.ts @@ -0,0 +1,16 @@ +export abstract class Messenger { + abstract send(messageType: string, message: any): void; + abstract onMessage( + messageType: string, + handler: (message: any) => void + ): void; +} + +export class IpcMessenger extends Messenger { + send(messageType: string, message: any): void { + console.log(`Sending message: ${messageType}`); + } + onMessage(messageType: string, handler: (message: any) => void): void { + console.log(`Registering handler for message: ${messageType}`); + } +} diff --git a/core/package-lock.json b/core/package-lock.json index d33a76ad5..a292adfd3 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,11 +13,12 @@ "@types/node-fetch": "^2.6.11", "@xenova/transformers": "^2.14.0", "cheerio": "^1.0.0-rc.12", + "commander": "^12.0.0", "dotenv": "^16.3.1", "fastest-levenshtein": "^1.0.16", "handlebars": "^4.7.8", "js-tiktoken": "^1.0.8", - "llm-code-highlighter": "^0.0.1", + "llm-code-highlighter": "^0.0.3", "node-fetch": "^3.3.2", "node-html-markdown": "^1.3.0", "openai": "^4.20.1", @@ -2805,6 +2806,14 @@ "node": ">=12.17" } }, + "node_modules/commander": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.0.0.tgz", + "integrity": "sha512-MwVNWlYjDTtOjX5PiD7o5pK0UrFU/OYgcJfjjK4RaHZETNtjJqrZa9Y9ds88+A+f+d5lv+561eZ+yCKoS3gbAA==", + "engines": { + "node": ">=18" + } + }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", @@ -4770,9 +4779,9 @@ "dev": true }, "node_modules/llm-code-highlighter": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/llm-code-highlighter/-/llm-code-highlighter-0.0.1.tgz", - "integrity": "sha512-26PExkQxeh5EiBNroldpV82pZDrjC6C5v4PLcm5ZpGIKExrHs9Hqw36B+1Fg+dxXGZMnwlCZ+6EbC2FEVocmcw==", + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/llm-code-highlighter/-/llm-code-highlighter-0.0.3.tgz", + "integrity": "sha512-l/R+m6ngXRTYxzoCzqpBk5TiSVpS4Ek9fKx/PIy25HV6XDbCC6iOfVITPPSTGkh7NlI+tN5vWjdqUfN3YW+HwQ==", "dependencies": { "graphology": "^0.25.4", "graphology-metrics": "^2.2.0", diff --git a/core/package.json b/core/package.json index 50e0fdf21..46d891d3a 100644 --- a/core/package.json +++ b/core/package.json @@ -22,6 +22,7 @@ "@types/node-fetch": "^2.6.11", "@xenova/transformers": "^2.14.0", "cheerio": "^1.0.0-rc.12", + "commander": "^12.0.0", "dotenv": "^16.3.1", "fastest-levenshtein": "^1.0.16", "handlebars": "^4.7.8", diff --git a/core/yarn.lock b/core/yarn.lock index 3c04d91f7..cb3565a72 100644 --- a/core/yarn.lock +++ b/core/yarn.lock @@ -1465,6 +1465,11 @@ command-line-usage@^7.0.0, command-line-usage@7.0.1: table-layout "^3.0.0" typical "^7.1.1" +commander@^12.0.0: + version "12.0.0" + resolved "https://registry.npmjs.org/commander/-/commander-12.0.0.tgz" + integrity sha512-MwVNWlYjDTtOjX5PiD7o5pK0UrFU/OYgcJfjjK4RaHZETNtjJqrZa9Y9ds88+A+f+d5lv+561eZ+yCKoS3gbAA== + concat-map@0.0.1: version "0.0.1" resolved "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz" @@ -2695,10 +2700,10 @@ lines-and-columns@^1.1.6: resolved "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz" integrity sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg== -llm-code-highlighter@^0.0.1: - version "0.0.1" - resolved "https://registry.npmjs.org/llm-code-highlighter/-/llm-code-highlighter-0.0.1.tgz" - integrity sha512-26PExkQxeh5EiBNroldpV82pZDrjC6C5v4PLcm5ZpGIKExrHs9Hqw36B+1Fg+dxXGZMnwlCZ+6EbC2FEVocmcw== +llm-code-highlighter@^0.0.3: + version "0.0.3" + resolved "https://registry.npmjs.org/llm-code-highlighter/-/llm-code-highlighter-0.0.3.tgz" + integrity sha512-l/R+m6ngXRTYxzoCzqpBk5TiSVpS4Ek9fKx/PIy25HV6XDbCC6iOfVITPPSTGkh7NlI+tN5vWjdqUfN3YW+HwQ== dependencies: graphology "^0.25.4" graphology-metrics "^2.2.0" From 7dd14fb2d0bf5876c22f236b38785460b585be40 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 9 Feb 2024 20:10:46 -0800 Subject: [PATCH 02/59] =?UTF-8?q?=F0=9F=9A=A7=20stdin/out=20messenger?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/ipc/IpcIde.ts | 7 +++++ core/ipc/interface.ts | 8 ----- core/ipc/messenger.ts | 68 +++++++++++++++++++++++++++++++++++++++---- 3 files changed, 69 insertions(+), 14 deletions(-) delete mode 100644 core/ipc/interface.ts diff --git a/core/ipc/IpcIde.ts b/core/ipc/IpcIde.ts index 2606b34eb..11d187daa 100644 --- a/core/ipc/IpcIde.ts +++ b/core/ipc/IpcIde.ts @@ -1,7 +1,14 @@ import { Chunk, DiffLine, IDE, Problem } from ".."; import { BrowserSerializedContinueConfig } from "../config/load"; +import { IpcMessenger } from "./messenger"; export class IpcIde implements IDE { + private messenger: IpcMessenger; + + constructor() { + this.messenger = new IpcMessenger(); + } + getSerializedConfig(): Promise { throw new Error("Method not implemented."); } diff --git a/core/ipc/interface.ts b/core/ipc/interface.ts deleted file mode 100644 index 67d77ddd6..000000000 --- a/core/ipc/interface.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Messenger } from "./messenger"; - -export class IpcInterface { - private messenger: Messenger; - constructor(messenger: Messenger) { - this.messenger = messenger; - } -} diff --git a/core/ipc/messenger.ts b/core/ipc/messenger.ts index 4b3d68769..fb2759247 100644 --- a/core/ipc/messenger.ts +++ b/core/ipc/messenger.ts @@ -1,16 +1,72 @@ +import { v4 as uuidv4 } from "uuid"; + export abstract class Messenger { - abstract send(messageType: string, message: any): void; + abstract send(messageType: string, message: any, messageId?: string): string; abstract onMessage( messageType: string, - handler: (message: any) => void + handler: (message: any) => Promise | undefined ): void; } +export interface Message { + messageType: string; + messageId: string; + message: any; +} + export class IpcMessenger extends Messenger { - send(messageType: string, message: any): void { - console.log(`Sending message: ${messageType}`); + listeners = new Map< + string, + ((message: Message) => Promise | undefined)[] + >(); + + constructor() { + super(); + + console.log = console.error; + + process.stdin.on("data", (data) => { + const d = data.toString(); + try { + const msg: Message = JSON.parse(d); + if ( + msg.message !== undefined || + msg.messageType !== undefined || + msg.messageId !== undefined + ) { + throw new Error("Invalid message sent: " + JSON.stringify(msg)); + } + + this.listeners.get(msg.messageType)?.forEach(async (handler) => { + const response = await handler(msg); + this.send(msg.messageType, response, msg.messageId); + }); + } catch (e) { + console.error("Invalid JSON:", d); + return; + } + }); } - onMessage(messageType: string, handler: (message: any) => void): void { - console.log(`Registering handler for message: ${messageType}`); + + send(messageType: string, message: any, messageId?: string): string { + messageId = messageId ?? uuidv4(); + const data: Message = { + messageType, + message, + messageId, + }; + // process.send?.(data); + process.stdout?.write(JSON.stringify(data)); + return messageId; + } + + onMessage( + messageType: string, + handler: (message: Message) => Promise | undefined + ): void { + if (!this.listeners.has(messageType)) { + this.listeners.set(messageType, []); + } + this.listeners.get(messageType)?.push(handler); } } From 70bf23c3fa29e5f7c57fa7e0f3ef7978f98d7a49 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 9 Feb 2024 22:34:33 -0800 Subject: [PATCH 03/59] =?UTF-8?q?=F0=9F=9A=A7=20working=20on=20core=20prot?= =?UTF-8?q?ocol?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/ipc/IpcIde.ts | 4 +- core/ipc/cli.ts | 7 +++- core/ipc/core.ts | 19 ++++++++++ core/ipc/messenger.ts | 38 +++++++++++-------- .../vscode/src => core/util}/history.ts | 4 +- extensions/vscode/src/debugPanel.ts | 2 +- 6 files changed, 52 insertions(+), 22 deletions(-) create mode 100644 core/ipc/core.ts rename {extensions/vscode/src => core/util}/history.ts (96%) diff --git a/core/ipc/IpcIde.ts b/core/ipc/IpcIde.ts index 11d187daa..97fa9ada2 100644 --- a/core/ipc/IpcIde.ts +++ b/core/ipc/IpcIde.ts @@ -5,8 +5,8 @@ import { IpcMessenger } from "./messenger"; export class IpcIde implements IDE { private messenger: IpcMessenger; - constructor() { - this.messenger = new IpcMessenger(); + constructor(messenger: IpcMessenger) { + this.messenger = messenger; } getSerializedConfig(): Promise { diff --git a/core/ipc/cli.ts b/core/ipc/cli.ts index e70859803..7b36a919b 100644 --- a/core/ipc/cli.ts +++ b/core/ipc/cli.ts @@ -1,9 +1,12 @@ import { Command } from "commander"; +import { Core } from "./core"; +import { IpcMessenger } from "./messenger"; const program = new Command(); -program.argument("", "input name").action((name) => { - console.log(`Hello, ${name}`); +program.action(() => { + const messenger = new IpcMessenger(); + const core = new Core(messenger); }); program.parse(process.argv); diff --git a/core/ipc/core.ts b/core/ipc/core.ts new file mode 100644 index 000000000..1c750ebd5 --- /dev/null +++ b/core/ipc/core.ts @@ -0,0 +1,19 @@ +import historyManager from "../util/history"; +import { IpcIde } from "./IpcIde"; +import { IpcMessenger } from "./messenger"; + +export class Core { + private messenger: IpcMessenger; + private ide: IpcIde; + constructor(messenger: IpcMessenger) { + this.messenger = messenger; + this.ide = new IpcIde(messenger); + + this.messenger.on("history/list", (msg) => { + return historyManager.list(); + }); + this.messenger.on("history/delete", (msg) => { + historyManager.delete(msg.data.id); + }); + } +} diff --git a/core/ipc/messenger.ts b/core/ipc/messenger.ts index fb2759247..e5217b5d1 100644 --- a/core/ipc/messenger.ts +++ b/core/ipc/messenger.ts @@ -1,24 +1,32 @@ import { v4 as uuidv4 } from "uuid"; +import { PersistedSessionInfo } from ".."; export abstract class Messenger { abstract send(messageType: string, message: any, messageId?: string): string; - abstract onMessage( - messageType: string, - handler: (message: any) => Promise | undefined - ): void; + abstract on(messageType: string, handler: (message: any) => any): void; } -export interface Message { +export interface Message { messageType: string; messageId: string; - message: any; + data: T; } +type Protocol = { + "history/list": [undefined, PersistedSessionInfo[]]; + "history/delete": [{ id: string }, void]; + "history/load": [{ id: string }, PersistedSessionInfo]; + "history/save": [PersistedSessionInfo, void]; + "devdata/log": [{ tableName: string; data: any }, void]; +}; +type ProtocolKeys = keyof Protocol; + +type ProtocolCallbacks = { + [K in ProtocolKeys]: (msg: Protocol[K][0]) => Protocol[K][1]; +}; + export class IpcMessenger extends Messenger { - listeners = new Map< - string, - ((message: Message) => Promise | undefined)[] - >(); + listeners = new Map any)[]>(); constructor() { super(); @@ -30,7 +38,7 @@ export class IpcMessenger extends Messenger { try { const msg: Message = JSON.parse(d); if ( - msg.message !== undefined || + msg.data !== undefined || msg.messageType !== undefined || msg.messageId !== undefined ) { @@ -52,7 +60,7 @@ export class IpcMessenger extends Messenger { messageId = messageId ?? uuidv4(); const data: Message = { messageType, - message, + data: message, messageId, }; // process.send?.(data); @@ -60,9 +68,9 @@ export class IpcMessenger extends Messenger { return messageId; } - onMessage( - messageType: string, - handler: (message: Message) => Promise | undefined + on( + messageType: T, + handler: (message: Message) => Protocol[T][1] ): void { if (!this.listeners.has(messageType)) { this.listeners.set(messageType, []); diff --git a/extensions/vscode/src/history.ts b/core/util/history.ts similarity index 96% rename from extensions/vscode/src/history.ts rename to core/util/history.ts index 87ed290d9..777af8805 100644 --- a/extensions/vscode/src/history.ts +++ b/core/util/history.ts @@ -1,6 +1,6 @@ -import { PersistedSessionInfo, SessionInfo } from "core"; -import { getSessionFilePath, getSessionsListPath } from "core/util/paths"; import * as fs from "fs"; +import { PersistedSessionInfo, SessionInfo } from ".."; +import { getSessionFilePath, getSessionsListPath } from "./paths"; class HistoryManager { list(): PersistedSessionInfo[] { diff --git a/extensions/vscode/src/debugPanel.ts b/extensions/vscode/src/debugPanel.ts index 2b06b7e7f..3a22c43f8 100644 --- a/extensions/vscode/src/debugPanel.ts +++ b/extensions/vscode/src/debugPanel.ts @@ -1,6 +1,7 @@ import { ContextItemId, DiffLine, FileEdit, ModelDescription } from "core"; import { indexDocs } from "core/indexing/docs"; import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider"; +import historyManager from "core/util/history"; import { editConfigJson, getConfigJsonPath } from "core/util/paths"; import { readFileSync, writeFileSync } from "fs"; import { v4 as uuidv4 } from "uuid"; @@ -12,7 +13,6 @@ import { windowId, } from "./activation/activate"; import { streamEdit } from "./diff/verticalPerLine/manager"; -import historyManager from "./history"; import { VsCodeIde } from "./ideProtocol"; import { configHandler, llmFromTitle } from "./loadConfig"; import { getTheme } from "./util/getTheme"; From 5073f09ab75af2685a8f5c11b1664b3c52bbeb22 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sat, 10 Feb 2024 16:24:35 -0800 Subject: [PATCH 04/59] =?UTF-8?q?=F0=9F=9A=A7=20fill=20out=20rest=20of=20c?= =?UTF-8?q?ore=20protocol?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/ipc/messenger.ts | 68 ++++++++++++++++++++++++++++- extensions/vscode/src/debugPanel.ts | 25 ----------- 2 files changed, 67 insertions(+), 26 deletions(-) diff --git a/core/ipc/messenger.ts b/core/ipc/messenger.ts index e5217b5d1..cf884f3d9 100644 --- a/core/ipc/messenger.ts +++ b/core/ipc/messenger.ts @@ -1,5 +1,13 @@ import { v4 as uuidv4 } from "uuid"; -import { PersistedSessionInfo } from ".."; +import { + ChatMessage, + CompletionOptions, + ContextItem, + ContextSubmenuItem, + PersistedSessionInfo, + RangeInFile, + SerializedContinueConfig, +} from ".."; export abstract class Messenger { abstract send(messageType: string, message: any, messageId?: string): string; @@ -13,11 +21,69 @@ export interface Message { } type Protocol = { + abort: [undefined, void]; "history/list": [undefined, PersistedSessionInfo[]]; "history/delete": [{ id: string }, void]; "history/load": [{ id: string }, PersistedSessionInfo]; "history/save": [PersistedSessionInfo, void]; "devdata/log": [{ tableName: string; data: any }, void]; + "config/addOpenAiKey": [string, void]; + "config/addModel": [ + { model: SerializedContinueConfig["models"][number] }, + void, + ]; + "config/deleteModel": [{ title: string }, void]; + "context/getContextItems": [ + { + name: string; + query: string; + fullInput: string; + selectedCode: RangeInFile[]; + }, + ContextItem[], + ]; + "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; + "context/addDocs": [{ title: string; url: string }, void]; + "autocomplete/complete": [ + { filepath: string; line: number; column: number }, + string[], + ]; + "command/run": [ + { + input: string; + history: ChatMessage[]; + modelTitle: string; + slashCommandName: string; + contextItems: ContextItem[]; + params: any; + historyIndex: number; + }, + AsyncGenerator, + ]; + "llm/complete": [ + { + prompt: string; + completionOptions: CompletionOptions; + title: string; + }, + AsyncGenerator, + ]; + "llm/streamComplete": [ + { + prompt: string; + completionOptions: CompletionOptions; + title: string; + }, + AsyncGenerator, + ]; + "llm/streamChat": [ + { + messages: ChatMessage[]; + completionOptions: CompletionOptions; + title: string; + }, + AsyncGenerator, + ]; }; type ProtocolKeys = keyof Protocol; diff --git a/extensions/vscode/src/debugPanel.ts b/extensions/vscode/src/debugPanel.ts index 3a22c43f8..3d16cb291 100644 --- a/extensions/vscode/src/debugPanel.ts +++ b/extensions/vscode/src/debugPanel.ts @@ -247,31 +247,6 @@ export function getSidebarContent( respond(await ide.subprocess(data.message.command)); break; } - case "getFilesToEmbed": { - let filesToEmbed = await ide.getFilesToEmbed(data.message.providerId); - respond(filesToEmbed); - break; - } - case "sendChunkForFile": { - respond( - await ide.sendEmbeddingForChunk( - data.message.chunk, - data.message.embedding, - data.message.tags - ) - ); - break; - } - case "retrieveChunks": { - respond( - await ide.retrieveChunks( - data.message.text, - data.message.n, - data.message.directory - ) - ); - break; - } // History case "history": { respond(historyManager.list()); From 060431e0bbf5cc3eee6a973b0e2d6a1e9a6a38df Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 13 Feb 2024 20:58:29 -0800 Subject: [PATCH 05/59] =?UTF-8?q?=F0=9F=9A=A7=20dep=20injection=20(roughly?= =?UTF-8?q?)=20in=20vscode=20extension?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/commands/slash/index.ts | 2 - core/config/handler.ts | 166 ++++ core/config/types.ts | 7 - core/config/util.ts | 38 + core/context/retrieval.ts | 7 +- core/index.d.ts | 30 +- core/indexing/indexCodebase.ts | 91 ++ core/ipc/IpcIde.ts | 28 +- core/ipc/cli.ts | 4 +- core/ipc/core.ts | 125 ++- core/ipc/messenger.ts | 44 +- core/package-lock.json | 87 +- core/package.json | 4 + core/test/edit.test.ts | 2 +- core/util/devdata.ts | 8 + core/{ide => util}/filesystem.ts | 45 +- core/util/messenger.ts | 5 + core/{commands/slash => util}/verticalEdit.ts | 55 +- core/{ide/messaging.ts => web/message.ts} | 1 - core/{ide/index.ts => web/webviewIde.ts} | 50 +- core/web/webviewProtocol.ts | 108 +++ core/yarn.lock | 41 +- extensions/vscode/package-lock.json | 5 + extensions/vscode/src/activation/activate.ts | 74 +- extensions/vscode/src/commands.ts | 185 ++-- extensions/vscode/src/debugPanel.ts | 887 ++++-------------- extensions/vscode/src/diff/horizontal.ts | 40 +- .../src/diff/verticalPerLine/handler.ts | 25 +- .../src/diff/verticalPerLine/manager.ts | 178 ++-- .../vscode/src/extension/autocomplete.ts | 0 extensions/vscode/src/extension/indexing.ts | 0 .../vscode/src/extension/vscodeExtension.ts | 183 ++++ extensions/vscode/src/ideProtocol.ts | 183 ++-- .../lang-server/autocompletePromptBuilder.ts | 31 + extensions/vscode/src/lang-server/codeLens.ts | 31 +- .../src/lang-server/completionProvider.ts | 357 ++++--- extensions/vscode/src/loadConfig.ts | 300 ------ extensions/vscode/src/suggestions.ts | 11 +- .../ideUtils.ts} | 145 +-- extensions/vscode/src/util/indexCodebase.ts | 100 -- .../vscode/src/util/loadAutocompleteModel.ts | 90 ++ extensions/vscode/src/webviewProtocol.ts | 490 ++++++++++ extensions/vscode/yarn.lock | 11 +- gui/package-lock.json | 5 + gui/src/hooks/useSetup.ts | 5 +- gui/src/util/ide.ts | 7 - 46 files changed, 2301 insertions(+), 1990 deletions(-) create mode 100644 core/config/handler.ts create mode 100644 core/config/util.ts create mode 100644 core/indexing/indexCodebase.ts create mode 100644 core/util/devdata.ts rename core/{ide => util}/filesystem.ts (76%) create mode 100644 core/util/messenger.ts rename core/{commands/slash => util}/verticalEdit.ts (76%) rename core/{ide/messaging.ts => web/message.ts} (99%) rename core/{ide/index.ts => web/webviewIde.ts} (71%) create mode 100644 core/web/webviewProtocol.ts create mode 100644 extensions/vscode/src/extension/autocomplete.ts create mode 100644 extensions/vscode/src/extension/indexing.ts create mode 100644 extensions/vscode/src/extension/vscodeExtension.ts create mode 100644 extensions/vscode/src/lang-server/autocompletePromptBuilder.ts delete mode 100644 extensions/vscode/src/loadConfig.ts rename extensions/vscode/src/{continueIdeClient.ts => util/ideUtils.ts} (74%) delete mode 100644 extensions/vscode/src/util/indexCodebase.ts create mode 100644 extensions/vscode/src/util/loadAutocompleteModel.ts create mode 100644 extensions/vscode/src/webviewProtocol.ts diff --git a/core/commands/slash/index.ts b/core/commands/slash/index.ts index ca0907674..0c95060f5 100644 --- a/core/commands/slash/index.ts +++ b/core/commands/slash/index.ts @@ -6,7 +6,6 @@ import EditSlashCommand from "./edit"; import HttpSlashCommand from "./http"; import ShareSlashCommand from "./share"; import StackOverflowSlashCommand from "./stackOverflow"; -import VerticalEditSlashCommand from "./verticalEdit"; export default [ DraftIssueCommand, @@ -17,5 +16,4 @@ export default [ CommentSlashCommand, HttpSlashCommand, CommitMessageCommand, - VerticalEditSlashCommand, ]; diff --git a/core/config/handler.ts b/core/config/handler.ts new file mode 100644 index 000000000..f83ff8638 --- /dev/null +++ b/core/config/handler.ts @@ -0,0 +1,166 @@ +import { http, https } from "follow-redirects"; +import * as fs from "fs"; +import { HttpProxyAgent } from "http-proxy-agent"; +import { HttpsProxyAgent } from "https-proxy-agent"; +import fetch from "node-fetch"; +import { ContinueConfig, ContinueRcJson, IDE, ILLM } from ".."; +import { Telemetry } from "../util/posthog"; +import { + BrowserSerializedContinueConfig, + finalToBrowserConfig, + loadFullConfigNode, +} from "./load"; +const tls = require("tls"); +export class ConfigHandler { + private savedConfig: ContinueConfig | undefined; + private savedBrowserConfig?: BrowserSerializedContinueConfig; + + private readonly ide: IDE; + constructor(ide: IDE) { + this.ide = ide; + this.loadConfig(); + } + + reloadConfig() { + this.savedConfig = undefined; + this.savedBrowserConfig = undefined; + this.loadConfig(); + } + + async getSerializedConfig(): Promise { + if (!this.savedBrowserConfig) { + this.savedConfig = await this.loadConfig(); + this.savedBrowserConfig = finalToBrowserConfig(this.savedConfig); + } + return this.savedBrowserConfig; + } + + async loadConfig(): Promise { + try { + if (this.savedConfig) { + return this.savedConfig; + } + + let workspaceConfigs: ContinueRcJson[] = []; + try { + workspaceConfigs = await this.ide.getWorkspaceConfigs(); + } catch (e) { + console.warn("Failed to load workspace configs"); + } + + this.savedConfig = await loadFullConfigNode( + this.ide.readFile, + workspaceConfigs + ); + this.savedConfig.allowAnonymousTelemetry = + this.savedConfig.allowAnonymousTelemetry && + (await this.ide.isTelemetryEnabled()); + + // Setup telemetry only after (and if) we know it is enabled + await Telemetry.setup( + this.savedConfig.allowAnonymousTelemetry ?? true, + await this.ide.getUniqueId() + ); + + return this.savedConfig; + } catch (e) { + throw new Error("Failed to load config"); + } + } + + setupLlm(llm: ILLM): ILLM { + const TIMEOUT = 7200; // 7200 seconds = 2 hours + // Since we know this is happening in Node.js, we can add requestOptions through a custom agent + const ca = [...tls.rootCertificates]; + const customCerts = + typeof llm.requestOptions?.caBundlePath === "string" + ? [llm.requestOptions?.caBundlePath] + : llm.requestOptions?.caBundlePath; + if (customCerts) { + ca.push( + ...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8")) + ); + } + + let timeout = (llm.requestOptions?.timeout || TIMEOUT) * 1000; // measured in ms + + const agentOptions = { + ca, + rejectUnauthorized: llm.requestOptions?.verifySsl, + timeout, + sessionTimeout: timeout, + keepAlive: true, + keepAliveMsecs: timeout, + }; + + const proxy = llm.requestOptions?.proxy; + + llm._fetch = async (input, init) => { + // Create agent + const protocol = new URL(input).protocol === "https:" ? https : http; + const agent = proxy + ? new URL(input).protocol === "https:" + ? new HttpsProxyAgent(proxy, agentOptions) + : new HttpProxyAgent(proxy, agentOptions) + : new protocol.Agent(agentOptions); + + const headers: { [key: string]: string } = + llm!.requestOptions?.headers || {}; + for (const [key, value] of Object.entries(init?.headers || {})) { + headers[key] = value as string; + } + + const resp = await fetch(input, { + ...init, + headers, + agent, + }); + + if (!resp.ok) { + let text = await resp.text(); + if (resp.status === 404 && !resp.url.includes("/v1")) { + if (text.includes("try pulling it first")) { + const model = JSON.parse(text).error.split(" ")[1].slice(1, -1); + text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`; + } else if (text.includes("/api/chat")) { + text = + "The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue."; + } else { + text = + "This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json."; + } + } + throw new Error( + `HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}` + ); + } + + return resp; + }; + + llm.writeLog = async (log: string) => { + // const outputChannel = vscode.window.createOutputChannel( + // "Continue - LLM Prompt/Completion" + // ); + // outputChannel.appendLine( + // "==========================================================================" + // ); + // outputChannel.appendLine( + // "==========================================================================" + // ); + // outputChannel.append(log); + }; + return llm; + } + + async llmFromTitle(title?: string): Promise { + const config = await this.loadConfig(); + const model = + config.models.find((m) => m.title === title) || config.models[0]; + if (!model) { + throw new Error("No model found"); + } + + return this.setupLlm(model); + } +} diff --git a/core/config/types.ts b/core/config/types.ts index 82d71289e..df8a19603 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -288,7 +288,6 @@ declare global { } export interface IDE { - getSerializedConfig(): Promise; getConfigJsUrl(): Promise; getDiff(): Promise; getTerminalContents(): Promise; @@ -307,12 +306,6 @@ declare global { newContents: string, stepIndex: number ): Promise; - verticalDiffUpdate( - filepath: string, - startLine: number, - endLine: number, - diffLine: DiffLine - ): Promise; getOpenFiles(): Promise; getPinnedFiles(): Promise; getSearchResults(query: string): Promise; diff --git a/core/config/util.ts b/core/config/util.ts new file mode 100644 index 000000000..94ebda6b8 --- /dev/null +++ b/core/config/util.ts @@ -0,0 +1,38 @@ +import { readFileSync, writeFileSync } from "fs"; +import { ModelDescription } from ".."; +import { editConfigJson, getConfigJsonPath } from "../util/paths"; + +export function addModel(model: ModelDescription) { + const config = readFileSync(getConfigJsonPath(), "utf8"); + const configJson = JSON.parse(config); + configJson.models.push(model); + const newConfigString = JSON.stringify( + configJson, + (key, value) => { + return value === null ? undefined : value; + }, + 2 + ); + writeFileSync(getConfigJsonPath(), newConfigString); + return newConfigString; +} + +export function addOpenAIKey(key: string) { + editConfigJson((config) => { + config.models = config.models.map((m: ModelDescription) => { + if (m.provider === "free-trial") { + m.apiKey = key; + m.provider = "openai"; + } + return m; + }); + return config; + }); +} + +export function deleteModel(title: string) { + editConfigJson((config) => { + config.models = config.models.filter((m: any) => m.title !== title); + return config; + }); +} diff --git a/core/context/retrieval.ts b/core/context/retrieval.ts index 6d9a26925..57c95405d 100644 --- a/core/context/retrieval.ts +++ b/core/context/retrieval.ts @@ -1,5 +1,6 @@ import { Chunk, ContextItem, ContextProviderExtras, ILLM } from ".."; import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch"; +import { LanceDbIndex } from "../indexing/LanceDbIndex"; import { ChunkCodebaseIndex } from "../indexing/chunk/ChunkCodebaseIndex"; import { IndexTag } from "../indexing/types"; import { llmCanGenerateInParallel } from "../llm/autodetect"; @@ -147,7 +148,11 @@ export async function retrieveContextItemsFromEmbeddings( console.warn("Error retrieving from FTS:", e); } - let vecResults = await extras.ide.retrieveChunks( + const lanceDbIndex = new LanceDbIndex(extras.embeddingsProvider, (path) => + extras.ide.readFile(path) + ); + let vecResults = await lanceDbIndex.retrieve( + tags, extras.fullInput, nRetrieve, filterDirectory diff --git a/core/index.d.ts b/core/index.d.ts index bbef8b0b6..66fdd06a8 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,5 +1,3 @@ -import { BrowserSerializedContinueConfig } from "./config/load"; - export interface ChunkWithoutID { content: string; startLine: number; @@ -293,12 +291,14 @@ export class Problem { } export interface IDE { - getSerializedConfig(): Promise; getDiff(): Promise; + isTelemetryEnabled(): Promise; + getUniqueId(): Promise; getTerminalContents(): Promise; listWorkspaceContents(directory?: string): Promise; listFolders(): Promise; getWorkspaceDirs(): Promise; + getWorkspaceConfigs(): Promise; writeFile(path: string, contents: string): Promise; showVirtualFile(title: string, contents: string): Promise; getContinueDir(): Promise; @@ -306,6 +306,7 @@ export interface IDE { runCommand(command: string): Promise; saveFile(filepath: string): Promise; readFile(filepath: string): Promise; + readRangeInFile(filepath: string, range: Range): Promise; showLines( filepath: string, startLine: number, @@ -316,34 +317,13 @@ export interface IDE { newContents: string, stepIndex: number ): Promise; - verticalDiffUpdate( - filepath: string, - startLine: number, - endLine: number, - diffLine: DiffLine - ): Promise; getOpenFiles(): Promise; getPinnedFiles(): Promise; getSearchResults(query: string): Promise; subprocess(command: string): Promise<[string, string]>; getProblems(filepath?: string | undefined): Promise; getBranch(dir: string): Promise; - - // Embeddings - /** - * Returns list of [tag, filepath, hash of contents] that need to be embedded - */ - getFilesToEmbed(providerId: string): Promise<[string, string, string][]>; - sendEmbeddingForChunk( - chunk: Chunk, - embedding: number[], - tags: string[] - ): void; - retrieveChunks( - text: string, - n: number, - directory: string | undefined - ): Promise; + getStats(directory: string): Promise<{ [path: string]: number }>; } // Slash Commands diff --git a/core/indexing/indexCodebase.ts b/core/indexing/indexCodebase.ts new file mode 100644 index 000000000..f4797b0b8 --- /dev/null +++ b/core/indexing/indexCodebase.ts @@ -0,0 +1,91 @@ +import { IDE, IndexingProgressUpdate } from ".."; +import { ConfigHandler } from "../config/handler"; +import { FullTextSearchCodebaseIndex } from "./FullTextSearch"; +import { LanceDbIndex } from "./LanceDbIndex"; +import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex"; +import { getComputeDeleteAddRemove } from "./refreshIndex"; +import { CodebaseIndex, IndexTag } from "./types"; + +export class CodebaseIndexer { + configHandler: ConfigHandler; + ide: IDE; + constructor(configHandler: ConfigHandler, ide: IDE) { + this.configHandler = configHandler; + this.ide = ide; + } + + private async getIndexesToBuild(): Promise { + const config = await this.configHandler.loadConfig(); + + const indexes = [ + new ChunkCodebaseIndex(this.ide.readFile.bind(this.ide)), // Chunking must come first + new LanceDbIndex(config.embeddingsProvider, this.ide.readFile), + new FullTextSearchCodebaseIndex(), + ]; + + return indexes; + } + + async *refresh( + workspaceDirs: string[] + ): AsyncGenerator { + const config = await this.configHandler.loadConfig(); + if (config.disableIndexing) { + return; + } + + const indexesToBuild = await this.getIndexesToBuild(); + + let completedDirs = 0; + + for (let directory of workspaceDirs) { + const stats = await this.ide.getStats(directory); + const branch = await this.ide.getBranch(directory); + let completedIndexes = 0; + + try { + for (let codebaseIndex of indexesToBuild) { + const tag: IndexTag = { + directory, + branch, + artifactId: codebaseIndex.artifactId, + }; + const [results, markComplete] = await getComputeDeleteAddRemove( + tag, + { ...stats }, + (filepath) => this.ide.readFile(filepath) + ); + + for await (let { progress, desc } of codebaseIndex.update( + tag, + results, + markComplete + )) { + yield { + progress: + (completedDirs + + (completedIndexes + progress) / indexesToBuild.length) / + workspaceDirs.length, + desc, + }; + } + completedIndexes++; + yield { + progress: + (completedDirs + completedIndexes / indexesToBuild.length) / + workspaceDirs.length, + desc: "Completed indexing " + codebaseIndex.artifactId, + }; + } + } catch (e) { + console.warn("Error refreshing index: ", e); + } + + completedDirs++; + yield { + progress: completedDirs / workspaceDirs.length, + desc: "Indexing Complete", + }; + } + } +} diff --git a/core/ipc/IpcIde.ts b/core/ipc/IpcIde.ts index 97fa9ada2..38f0e08b8 100644 --- a/core/ipc/IpcIde.ts +++ b/core/ipc/IpcIde.ts @@ -1,5 +1,4 @@ -import { Chunk, DiffLine, IDE, Problem } from ".."; -import { BrowserSerializedContinueConfig } from "../config/load"; +import { Chunk, ContinueRcJson, IDE, Problem, Range } from ".."; import { IpcMessenger } from "./messenger"; export class IpcIde implements IDE { @@ -8,8 +7,23 @@ export class IpcIde implements IDE { constructor(messenger: IpcMessenger) { this.messenger = messenger; } + readRangeInFile(filepath: string, range: Range): Promise { + throw new Error("Method not implemented."); + } - getSerializedConfig(): Promise { + getStats(directory: string): Promise<{ [path: string]: number }> { + throw new Error("Method not implemented."); + } + + isTelemetryEnabled(): Promise { + throw new Error("Method not implemented."); + } + + getUniqueId(): Promise { + throw new Error("Method not implemented."); + } + + getWorkspaceConfigs(): Promise { throw new Error("Method not implemented."); } getDiff(): Promise { @@ -62,14 +76,6 @@ export class IpcIde implements IDE { ): Promise { throw new Error("Method not implemented."); } - verticalDiffUpdate( - filepath: string, - startLine: number, - endLine: number, - diffLine: DiffLine - ): Promise { - throw new Error("Method not implemented."); - } getOpenFiles(): Promise { throw new Error("Method not implemented."); } diff --git a/core/ipc/cli.ts b/core/ipc/cli.ts index 7b36a919b..8122fe2ff 100644 --- a/core/ipc/cli.ts +++ b/core/ipc/cli.ts @@ -1,4 +1,5 @@ import { Command } from "commander"; +import { IpcIde } from "./IpcIde"; import { Core } from "./core"; import { IpcMessenger } from "./messenger"; @@ -6,7 +7,8 @@ const program = new Command(); program.action(() => { const messenger = new IpcMessenger(); - const core = new Core(messenger); + const ide = new IpcIde(messenger); + const core = new Core(messenger, ide); }); program.parse(process.argv); diff --git a/core/ipc/core.ts b/core/ipc/core.ts index 1c750ebd5..63a666dbc 100644 --- a/core/ipc/core.ts +++ b/core/ipc/core.ts @@ -1,19 +1,126 @@ +import { v4 as uuidv4 } from "uuid"; +import { ContextItemId, IDE } from ".."; +import { ConfigHandler } from "../config/handler"; +import { addModel, addOpenAIKey, deleteModel } from "../config/util"; +import { indexDocs } from "../indexing/docs"; +import TransformersJsEmbeddingsProvider from "../indexing/embeddings/TransformersJsEmbeddingsProvider"; +import { CodebaseIndexer } from "../indexing/indexCodebase"; +import { logDevData } from "../util/devdata"; import historyManager from "../util/history"; -import { IpcIde } from "./IpcIde"; -import { IpcMessenger } from "./messenger"; +import { Messenger, Protocol } from "./messenger"; export class Core { - private messenger: IpcMessenger; - private ide: IpcIde; - constructor(messenger: IpcMessenger) { - this.messenger = messenger; - this.ide = new IpcIde(messenger); + private messenger: Messenger; + private readonly ide: IDE; + private readonly configHandler: ConfigHandler; + private readonly codebaseIndexer: CodebaseIndexer; - this.messenger.on("history/list", (msg) => { + private selectedModelTitle: string | undefined; + + private async config() { + return this.configHandler.loadConfig(); + } + + private async getSelectedModel() { + return await this.configHandler.llmFromTitle(this.selectedModelTitle); + } + + constructor(messenger: Messenger, ide: IDE) { + this.messenger = messenger; + this.ide = ide; + this.configHandler = new ConfigHandler(this.ide); + this.codebaseIndexer = new CodebaseIndexer(this.configHandler, this.ide); + + const on = this.messenger.on; + + // New + on("update/modelChange", (msg) => { + this.selectedModelTitle = msg.data; + }); + + // History + on("history/list", (msg) => { return historyManager.list(); }); - this.messenger.on("history/delete", (msg) => { + on("history/delete", (msg) => { historyManager.delete(msg.data.id); }); + on("history/load", (msg) => { + return historyManager.load(msg.data.id); + }); + on("history/save", (msg) => { + historyManager.save(msg.data); + }); + + // Dev data + on("devdata/log", (msg) => { + logDevData(msg.data.tableName, msg.data.data); + }); + + // Edit config + on("config/addModel", (msg) => { + addModel(msg.data.model); + }); + on("config/addOpenAiKey", (msg) => { + addOpenAIKey(msg.data); + }); + on("config/deleteModel", (msg) => { + deleteModel(msg.data.title); + }); + on("config/reload", (msg) => {}); + + // Context providers + on("context/addDocs", async (msg) => { + for await (const _ of indexDocs( + msg.data.title, + new URL(msg.data.url), + new TransformersJsEmbeddingsProvider() + )) { + } + }); + on("context/loadSubmenuItems", async (msg) => { + const config = await this.config(); + const items = config.contextProviders + ?.find((provider) => provider.description.title === msg.data.title) + ?.loadSubmenuItems({ ide: this.ide }); + return items || []; + }); + on("context/getContextItems", async (msg) => { + const config = await this.config(); + const llm = await this.getSelectedModel(); + const provider = config.contextProviders?.find( + (provider) => provider.description.title === msg.data.name + ); + if (!provider) return []; + + const id: ContextItemId = { + providerTitle: provider.description.title, + itemId: uuidv4(), + }; + const items = await provider.getContextItems(msg.data.query, { + llm, + embeddingsProvider: config.embeddingsProvider, + fullInput: msg.data.fullInput, + ide, + selectedCode: msg.data.selectedCode, + }); + return items; + }); + } + + public invoke( + method: keyof Protocol, + data: Protocol[T][0] + ): Protocol[T][1] { + const response = this.messenger.invoke(method, data); + return response; } } + +/** + * configHandler should be in core? Probably everything should be in core? + * - get rc files (define in IpcIde) + * - override anonymous telemetry (telemetryAllowed) + * - send config to browser whenever it loads (triggers come from IDE so that should happen there) + * - access to a "readFile" function (ide.readFile) + */ diff --git a/core/ipc/messenger.ts b/core/ipc/messenger.ts index cf884f3d9..54819140a 100644 --- a/core/ipc/messenger.ts +++ b/core/ipc/messenger.ts @@ -8,20 +8,27 @@ import { RangeInFile, SerializedContinueConfig, } from ".."; +import { Message } from "../util/messenger"; export abstract class Messenger { abstract send(messageType: string, message: any, messageId?: string): string; - abstract on(messageType: string, handler: (message: any) => any): void; + abstract on( + messageType: T, + handler: (message: Message) => Protocol[T][1] + ): void; + abstract invoke( + messageType: T, + data: Protocol[T][0] + ): Protocol[T][1]; } -export interface Message { - messageType: string; - messageId: string; - data: T; -} - -type Protocol = { +export type Protocol = { + // New + "update/modelChange": [string, void]; + // Special abort: [undefined, void]; + + // History "history/list": [undefined, PersistedSessionInfo[]]; "history/delete": [{ id: string }, void]; "history/load": [{ id: string }, PersistedSessionInfo]; @@ -33,6 +40,7 @@ type Protocol = { void, ]; "config/deleteModel": [{ title: string }, void]; + "config/reload": [undefined, void]; "context/getContextItems": [ { name: string; @@ -40,9 +48,12 @@ type Protocol = { fullInput: string; selectedCode: RangeInFile[]; }, - ContextItem[], + Promise, + ]; + "context/loadSubmenuItems": [ + { title: string }, + Promise, ]; - "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]]; "context/addDocs": [{ title: string; url: string }, void]; "autocomplete/complete": [ { filepath: string; line: number; column: number }, @@ -92,7 +103,7 @@ type ProtocolCallbacks = { }; export class IpcMessenger extends Messenger { - listeners = new Map any)[]>(); + listeners = new Map any)[]>(); constructor() { super(); @@ -143,4 +154,15 @@ export class IpcMessenger extends Messenger { } this.listeners.get(messageType)?.push(handler); } + + invoke( + messageType: T, + data: Protocol[T][0] + ): Protocol[T][1] { + return this.listeners.get(messageType)?.[0]?.({ + messageId: uuidv4(), + messageType, + data, + }); + } } diff --git a/core/package-lock.json b/core/package-lock.json index 53d99ffea..88ae15d27 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -16,7 +16,10 @@ "commander": "^12.0.0", "dotenv": "^16.3.1", "fastest-levenshtein": "^1.0.16", + "follow-redirects": "^1.15.5", "handlebars": "^4.7.8", + "http-proxy-agent": "^7.0.1", + "https-proxy-agent": "^7.0.3", "js-tiktoken": "^1.0.8", "llm-code-highlighter": "^0.0.5", "node-fetch": "^3.3.2", @@ -34,6 +37,7 @@ "web-tree-sitter": "^0.20.8" }, "devDependencies": { + "@types/follow-redirects": "^1.14.4", "@types/handlebars": "^4.1.0", "@types/jest": "^29.5.11", "@types/jquery": "^3.5.29", @@ -1867,6 +1871,15 @@ "resolved": "https://registry.npmjs.org/@types/command-line-usage/-/command-line-usage-5.0.2.tgz", "integrity": "sha512-n7RlEEJ+4x4TS7ZQddTmNSxP+zziEG0TNsMfiRIxcIVXt71ENJ9ojeXmGO3wPoTdn7pJcU2xc3CJYMktNT6DPg==" }, + "node_modules/@types/follow-redirects": { + "version": "1.14.4", + "resolved": "https://registry.npmjs.org/@types/follow-redirects/-/follow-redirects-1.14.4.tgz", + "integrity": "sha512-GWXfsD0Jc1RWiFmMuMFCpXMzi9L7oPDVwxUnZdg89kDNnqsRfUKXEtUYtA98A6lig1WXH/CYY/fvPW9HuN5fTA==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/graceful-fs": { "version": "4.1.9", "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz", @@ -3787,30 +3800,49 @@ "optional": true }, "node_modules/http-proxy-agent": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz", - "integrity": "sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==", - "optional": true, + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.1.tgz", + "integrity": "sha512-My1KCEPs6A0hb4qCVzYp8iEvA8j8YqcvXLZZH8C9OFuTYpYjHE7N2dtG3mRl1HMD4+VGXpF3XcDVcxGBT7yDZQ==", "dependencies": { - "@tootallnate/once": "1", - "agent-base": "6", - "debug": "4" + "agent-base": "^7.1.0", + "debug": "^4.3.4" }, "engines": { - "node": ">= 6" + "node": ">= 14" + } + }, + "node_modules/http-proxy-agent/node_modules/agent-base": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.0.tgz", + "integrity": "sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg==", + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" } }, "node_modules/https-proxy-agent": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", - "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", - "optional": true, + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.3.tgz", + "integrity": "sha512-kCnwztfX0KZJSLOBrcL0emLeFako55NWMovvyPP2AjsghNk9RB1yjSI+jVumPHYZsNXegNoqupSW9IY3afSH8w==", "dependencies": { - "agent-base": "6", + "agent-base": "^7.0.2", "debug": "4" }, "engines": { - "node": ">= 6" + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent/node_modules/agent-base": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.0.tgz", + "integrity": "sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg==", + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" } }, "node_modules/human-signals": { @@ -4920,6 +4952,33 @@ "node": ">= 10" } }, + "node_modules/make-fetch-happen/node_modules/http-proxy-agent": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz", + "integrity": "sha512-k0zdNgqWTGA6aeIRVpvfVob4fL52dTfaehylg0Y4UvSySvOq/Y+BOyPrgpUrA7HylqvU8vIZGsRuXmspskV0Tg==", + "optional": true, + "dependencies": { + "@tootallnate/once": "1", + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/make-fetch-happen/node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "optional": true, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/make-fetch-happen/node_modules/lru-cache": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", diff --git a/core/package.json b/core/package.json index 5c5a921ab..e0098d33d 100644 --- a/core/package.json +++ b/core/package.json @@ -8,6 +8,7 @@ "author": "Nate Sesti and Ty Dunn", "license": "Apache-2.0", "devDependencies": { + "@types/follow-redirects": "^1.14.4", "@types/handlebars": "^4.1.0", "@types/jest": "^29.5.11", "@types/jquery": "^3.5.29", @@ -25,7 +26,10 @@ "commander": "^12.0.0", "dotenv": "^16.3.1", "fastest-levenshtein": "^1.0.16", + "follow-redirects": "^1.15.5", "handlebars": "^4.7.8", + "http-proxy-agent": "^7.0.1", + "https-proxy-agent": "^7.0.3", "js-tiktoken": "^1.0.8", "llm-code-highlighter": "^0.0.5", "node-fetch": "^3.3.2", diff --git a/core/test/edit.test.ts b/core/test/edit.test.ts index 4682601d1..48543ce4b 100644 --- a/core/test/edit.test.ts +++ b/core/test/edit.test.ts @@ -2,10 +2,10 @@ import * as dotenv from "dotenv"; import { ContinueSDK } from ".."; import EditSlashCommand, { getPromptParts } from "../commands/slash/edit"; import { contextItemToRangeInFileWithContents } from "../commands/util"; -import FileSystemIde from "../ide/filesystem"; import FreeTrial from "../llm/llms/FreeTrial"; import Ollama from "../llm/llms/Ollama"; import { dedentAndGetCommonWhitespace } from "../util"; +import FileSystemIde from "../util/filesystem"; jest.setTimeout(100_000); diff --git a/core/util/devdata.ts b/core/util/devdata.ts new file mode 100644 index 000000000..bb98b2527 --- /dev/null +++ b/core/util/devdata.ts @@ -0,0 +1,8 @@ +import { writeFileSync } from "fs"; +import { getDevDataFilePath } from "./paths"; + +export function logDevData(tableName: string, data: any) { + const filepath: string = getDevDataFilePath(tableName); + const jsonLine = JSON.stringify(data); + writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" }); +} diff --git a/core/ide/filesystem.ts b/core/util/filesystem.ts similarity index 76% rename from core/ide/filesystem.ts rename to core/util/filesystem.ts index 910dd022a..9ce3de29c 100644 --- a/core/ide/filesystem.ts +++ b/core/util/filesystem.ts @@ -1,12 +1,22 @@ import * as fs from "fs"; -import { DiffLine, IDE, Problem } from ".."; -import { BrowserSerializedContinueConfig } from "../config/load"; -import { Chunk } from "../index"; -import { getContinueGlobalPath } from "../util/paths"; +import { ContinueRcJson, IDE, Problem, Range } from ".."; +import { getContinueGlobalPath } from "./paths"; class FileSystemIde implements IDE { - async getSerializedConfig(): Promise { - throw new Error("Not implemented"); + readRangeInFile(filepath: string, range: Range): Promise { + return Promise.resolve(""); + } + getStats(directory: string): Promise<{ [path: string]: number }> { + return Promise.resolve({}); + } + isTelemetryEnabled(): Promise { + return Promise.resolve(false); + } + getUniqueId(): Promise { + return Promise.resolve("NOT_UNIQUE"); + } + getWorkspaceConfigs(): Promise { + return Promise.resolve([]); } getDiff(): Promise { @@ -92,15 +102,6 @@ class FileSystemIde implements IDE { return Promise.resolve(""); } - async verticalDiffUpdate( - filepath: string, - startLine: number, - endLine: number, - diffLine: DiffLine - ) { - return Promise.resolve(); - } - getOpenFiles(): Promise { return Promise.resolve([]); } @@ -120,20 +121,6 @@ class FileSystemIde implements IDE { async subprocess(command: string): Promise<[string, string]> { return ["", ""]; } - - getFilesToEmbed(providerId: string): Promise<[string, string, string][]> { - return Promise.resolve([]); - } - - sendEmbeddingForChunk(chunk: Chunk, embedding: number[], tags: string[]) {} - - retrieveChunks( - text: string, - n: number, - directory: string | undefined - ): Promise { - return Promise.resolve([]); - } } export default FileSystemIde; diff --git a/core/util/messenger.ts b/core/util/messenger.ts new file mode 100644 index 000000000..9f12b9630 --- /dev/null +++ b/core/util/messenger.ts @@ -0,0 +1,5 @@ +export interface Message { + messageType: string; + messageId: string; + data: T; +} diff --git a/core/commands/slash/verticalEdit.ts b/core/util/verticalEdit.ts similarity index 76% rename from core/commands/slash/verticalEdit.ts rename to core/util/verticalEdit.ts index 7cd0ba4d9..d3d69ef66 100644 --- a/core/commands/slash/verticalEdit.ts +++ b/core/util/verticalEdit.ts @@ -1,17 +1,9 @@ -import { ContextItemWithId, DiffLine, ILLM, SlashCommand } from "../.."; -import { streamDiff } from "../../diff/streamDiff"; -import { LineStream, streamLines } from "../../diff/util"; -import { stripImages } from "../../llm/countTokens"; -import { gptEditPrompt } from "../../llm/templates/edit"; -import { - dedentAndGetCommonWhitespace, - getMarkdownLanguageTagForFile, - renderPromptTemplate, -} from "../../util"; -import { - RangeInFileWithContents, - contextItemToRangeInFileWithContents, -} from "../util"; +import { dedentAndGetCommonWhitespace, renderPromptTemplate } from "."; +import { DiffLine, ILLM } from ".."; +import { streamDiff } from "../diff/streamDiff"; +import { LineStream, streamLines } from "../diff/util"; +import { stripImages } from "../llm/countTokens"; +import { gptEditPrompt } from "../llm/templates/edit"; function shouldRemoveLineBeforeStart(line: string): boolean { return ( @@ -215,38 +207,3 @@ export async function* streamDiffLines( yield diffLine; } } - -const VerticalEditSlashCommand: SlashCommand = { - name: "verticalEdit", - description: "Edit selected code with vertical diff", - run: async function* ({ ide, llm, input, contextItems }) { - const contextItemToEdit = contextItems.find( - (item: ContextItemWithId) => - item.editing && item.id.providerTitle === "code" - ); - - if (!contextItemToEdit) { - yield "Highlight the code that you want to edit first"; - return; - } - - const rif: RangeInFileWithContents = - contextItemToRangeInFileWithContents(contextItemToEdit); - const startLine = rif.range.start.line; - const endLine = rif.range.end.line; - const filepath = rif.filepath; - - const diffLineGenerator = streamDiffLines( - rif.contents, - llm, - input, - getMarkdownLanguageTagForFile(rif.filepath) - ); - - for await (const diffLine of diffLineGenerator) { - await ide.verticalDiffUpdate(filepath, startLine, endLine, diffLine); - } - }, -}; - -export default VerticalEditSlashCommand; diff --git a/core/ide/messaging.ts b/core/web/message.ts similarity index 99% rename from core/ide/messaging.ts rename to core/web/message.ts index f8876a363..f0e9416cd 100644 --- a/core/ide/messaging.ts +++ b/core/web/message.ts @@ -1,4 +1,3 @@ -// import "vscode-webview"; import { v4 as uuidv4 } from "uuid"; import { ChatMessage, LLMFullCompletionOptions, LLMReturnValue } from ".."; interface vscode { diff --git a/core/ide/index.ts b/core/web/webviewIde.ts similarity index 71% rename from core/ide/index.ts rename to core/web/webviewIde.ts index 255c26a8e..b7b5584da 100644 --- a/core/ide/index.ts +++ b/core/web/webviewIde.ts @@ -1,14 +1,27 @@ -import { Chunk, DiffLine, Problem } from ".."; -import { BrowserSerializedContinueConfig } from "../config/load"; +import { ContinueRcJson, Problem, Range } from ".."; import { IDE } from "../index"; -import { ideRequest } from "./messaging"; +import { ideRequest } from "./message"; async function r(messageType: string, options: any = {}) { return await ideRequest(messageType, options); } -export class ExtensionIde implements IDE { - async getSerializedConfig(): Promise { - return await r("getSerializedConfig"); +export class WebviewIde implements IDE { + readRangeInFile(filepath: string, range: Range): Promise { + return r("readRangeInFile", { filepath, range }); + } + getStats(directory: string): Promise<{ [path: string]: number }> { + return r("getStats", { directory }); + } + isTelemetryEnabled(): Promise { + return r("isTelemetryEnabled"); + } + + getUniqueId(): Promise { + return r("getUniqueId"); + } + + getWorkspaceConfigs(): Promise { + return r("getWorkspaceConfigs"); } async getDiff() { @@ -80,15 +93,6 @@ export class ExtensionIde implements IDE { await r("showDiff", { filepath, newContents, stepIndex }); } - async verticalDiffUpdate( - filepath: string, - startLine: number, - endLine: number, - diffLine: DiffLine - ) { - await r("diffLine", { filepath, startLine, endLine, diffLine }); - } - getOpenFiles(): Promise { return r("getOpenFiles"); } @@ -109,23 +113,7 @@ export class ExtensionIde implements IDE { return r("subprocess", { command }); } - getFilesToEmbed(providerId: string): Promise<[string, string, string][]> { - return r("getFilesToEmbed", { providerId }); - } - - sendEmbeddingForChunk(chunk: Chunk, embedding: number[], tags: string[]) { - return r("sendChunkForFile", { chunk, embedding, tags }); - } - async getBranch(dir: string): Promise { return r("getBranch", { dir }); } - - retrieveChunks( - text: string, - n: number, - directory: string | undefined - ): Promise { - return r("retrieveChunks", { text, n, directory }); - } } diff --git a/core/web/webviewProtocol.ts b/core/web/webviewProtocol.ts new file mode 100644 index 000000000..c0bf50deb --- /dev/null +++ b/core/web/webviewProtocol.ts @@ -0,0 +1,108 @@ +import { + ChatMessage, + CompletionOptions, + ContextItem, + ContextItemWithId, + ContextSubmenuItem, + DiffLine, + MessageContent, + ModelDescription, + PersistedSessionInfo, + Problem, + RangeInFile, +} from ".."; +import { BrowserSerializedContinueConfig } from "../config/load"; + +export type WebviewProtocol = { + abort: [undefined, void]; + listWorkspaceContents: [undefined, Promise]; + getWorkspaceDirs: [undefined, Promise]; + listFolders: [undefined, Promise]; + writeFile: [{ path: string; contents: string }, void]; + showVirtualFile: [{ name: string; content: string }, void]; + getContinueDir: [undefined, Promise]; + openFile: [{ path: string }, void]; + runCommand: [{ command: string }, void]; + getSearchResults: [{ query: string }, Promise]; + subprocess: [{ command: string }, Promise<[string, string]>]; + history: [undefined, PersistedSessionInfo[]]; + saveSession: [PersistedSessionInfo, void]; + deleteSession: [string, void]; + loadSession: [string, PersistedSessionInfo]; + saveFile: [{ filepath: string }, void]; + readFile: [{ filepath: string }, Promise]; + showDiff: [ + { filepath: string; newContents: string; stepIndex: number }, + void, + ]; + diffLine: [ + { + diffLine: DiffLine; + filepath: string; + startLine: number; + endLine: number; + }, + void, + ]; + getProblems: [{ filepath: string }, Promise]; + getBranch: [{ dir: string }, Promise]; + getOpenFiles: [undefined, Promise]; + getPinnedFiles: [undefined, Promise]; + showLines: [{ filepath: string; startLine: number; endLine: number }, void]; + errorPopup: [{ message: string }, void]; + logDevData: [{ tableName: string; data: any }, void]; + addModel: [ModelDescription, void]; + deleteModel: [{ title: string }, void]; + addOpenAIKey: [{ key: string }, void]; + llmStreamComplete: [ + { title: string; prompt: string; completionOptions: CompletionOptions }, + AsyncGenerator<{ content: string; done?: boolean }>, + ]; + llmStreamChat: [ + { + title: string; + messages: ChatMessage[]; + completionOptions: CompletionOptions; + }, + AsyncGenerator<{ content: MessageContent; done?: boolean }>, + ]; + llmComplete: [ + { title: string; prompt: string; completionOptions: CompletionOptions }, + Promise<{ content: string }>, + ]; + runNodeJsSlashCommand: [ + { + input: string; + history: ChatMessage[]; + modelTitle: string; + slashCommandName: string; + contextItems: ContextItemWithId[]; + params: { [key: string]: any } | undefined; + historyIndex: number; + }, + AsyncGenerator<{ content: string; done?: boolean }>, + ]; + loadSubmenuItems: [{ title: string }, Promise]; + getContextItems: [ + { + name: string; + query: string; + fullInput: string; + selectedCode: RangeInFile[]; + }, + Promise, + ]; + addDocs: [{ url: string; title: string }, void]; + applyToCurrentFile: [{ text: string }, void]; + showTutorial: [undefined, void]; + showFile: [{ filepath: string }, void]; + openConfigJson: [undefined, void]; + readRangeInFile: [{ filepath: string }, void]; + toggleDevTools: [undefined, void]; + reloadWindow: [undefined, void]; + focusEditor: [undefined, void]; + toggleFullScreen: [undefined, void]; + getDiff: [undefined, Promise]; + getSerializedConfig: [undefined, Promise]; + getTerminalContents: [undefined, Promise]; +}; diff --git a/core/yarn.lock b/core/yarn.lock index 37739acab..25c0f5df8 100644 --- a/core/yarn.lock +++ b/core/yarn.lock @@ -822,6 +822,13 @@ resolved "https://registry.npmjs.org/@types/command-line-usage/-/command-line-usage-5.0.2.tgz" integrity sha512-n7RlEEJ+4x4TS7ZQddTmNSxP+zziEG0TNsMfiRIxcIVXt71ENJ9ojeXmGO3wPoTdn7pJcU2xc3CJYMktNT6DPg== +"@types/follow-redirects@^1.14.4": + version "1.14.4" + resolved "https://registry.npmjs.org/@types/follow-redirects/-/follow-redirects-1.14.4.tgz" + integrity sha512-GWXfsD0Jc1RWiFmMuMFCpXMzi9L7oPDVwxUnZdg89kDNnqsRfUKXEtUYtA98A6lig1WXH/CYY/fvPW9HuN5fTA== + dependencies: + "@types/node" "*" + "@types/graceful-fs@^4.1.3": version "4.1.9" resolved "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz" @@ -974,6 +981,20 @@ agent-base@^6.0.2, agent-base@6: dependencies: debug "4" +agent-base@^7.0.2: + version "7.1.0" + resolved "https://registry.npmjs.org/agent-base/-/agent-base-7.1.0.tgz" + integrity sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg== + dependencies: + debug "^4.3.4" + +agent-base@^7.1.0: + version "7.1.0" + resolved "https://registry.npmjs.org/agent-base/-/agent-base-7.1.0.tgz" + integrity sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg== + dependencies: + debug "^4.3.4" + agentkeepalive@^4.1.3, agentkeepalive@^4.2.1: version "4.5.0" resolved "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.5.0.tgz" @@ -1541,7 +1562,7 @@ 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== -debug@^4.1.0, debug@^4.1.1, debug@^4.3.1, debug@^4.3.3, debug@~4.3.1, debug@~4.3.2, debug@4: +debug@^4.1.0, debug@^4.1.1, debug@^4.3.1, debug@^4.3.3, debug@^4.3.4, debug@~4.3.1, debug@~4.3.2, debug@4: version "4.3.4" resolved "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz" integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ== @@ -1872,7 +1893,7 @@ flatbuffers@23.5.26: resolved "https://registry.npmjs.org/flatbuffers/-/flatbuffers-23.5.26.tgz" integrity sha512-vE+SI9vrJDwi1oETtTIFldC/o9GsVKRM+s6EL0nQgxXlYV1Vc4Tk30hj4xGICftInKQKj1F3up2n8UbIVobISQ== -follow-redirects@^1.15.4: +follow-redirects@^1.15.4, follow-redirects@^1.15.5: version "1.15.5" resolved "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz" integrity sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw== @@ -2112,6 +2133,14 @@ http-proxy-agent@^4.0.1: agent-base "6" debug "4" +http-proxy-agent@^7.0.1: + version "7.0.1" + resolved "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.1.tgz" + integrity sha512-My1KCEPs6A0hb4qCVzYp8iEvA8j8YqcvXLZZH8C9OFuTYpYjHE7N2dtG3mRl1HMD4+VGXpF3XcDVcxGBT7yDZQ== + dependencies: + agent-base "^7.1.0" + debug "^4.3.4" + https-proxy-agent@^5.0.0: version "5.0.1" resolved "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz" @@ -2120,6 +2149,14 @@ https-proxy-agent@^5.0.0: agent-base "6" debug "4" +https-proxy-agent@^7.0.3: + version "7.0.3" + resolved "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.3.tgz" + integrity sha512-kCnwztfX0KZJSLOBrcL0emLeFako55NWMovvyPP2AjsghNk9RB1yjSI+jVumPHYZsNXegNoqupSW9IY3afSH8w== + dependencies: + agent-base "^7.0.2" + debug "4" + human-signals@^2.1.0: version "2.1.0" resolved "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz" diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 294225b91..8ff6a2c00 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -89,9 +89,13 @@ "@types/node-fetch": "^2.6.11", "@xenova/transformers": "^2.14.0", "cheerio": "^1.0.0-rc.12", + "commander": "^12.0.0", "dotenv": "^16.3.1", "fastest-levenshtein": "^1.0.16", + "follow-redirects": "^1.15.5", "handlebars": "^4.7.8", + "http-proxy-agent": "^7.0.1", + "https-proxy-agent": "^7.0.3", "js-tiktoken": "^1.0.8", "llm-code-highlighter": "^0.0.5", "node-fetch": "^3.3.2", @@ -109,6 +113,7 @@ "web-tree-sitter": "^0.20.8" }, "devDependencies": { + "@types/follow-redirects": "^1.14.4", "@types/handlebars": "^4.1.0", "@types/jest": "^29.5.11", "@types/jquery": "^3.5.29", diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index 7b197e6b9..59344c564 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -2,26 +2,13 @@ import { getTsConfigPath, migrate } from "core/util/paths"; import { Telemetry } from "core/util/posthog"; import * as fs from "fs"; import path from "path"; -import { v4 } from "uuid"; import * as vscode from "vscode"; -import { registerAllCommands } from "../commands"; -import IdeProtocolClient from "../continueIdeClient"; -import { ContinueGUIWebviewViewProvider } from "../debugPanel"; +import { VsCodeExtension } from "../extension/vscodeExtension"; import registerQuickFixProvider from "../lang-server/codeActions"; -import { registerAllCodeLensProviders } from "../lang-server/codeLens"; -import { - ContinueCompletionProvider, - setupStatusBar, -} from "../lang-server/completionProvider"; -import { vsCodeIndexCodebase } from "../util/indexCodebase"; import { getExtensionVersion, getPlatform } from "../util/util"; import { getExtensionUri } from "../util/vscode"; import { setupInlineTips } from "./inlineTips"; -export let extensionContext: vscode.ExtensionContext | undefined = undefined; -export let ideProtocolClient: IdeProtocolClient; -export let windowId: string = v4(); - export async function showTutorial() { const tutorialPath = path.join( getExtensionUri().fsPath, @@ -47,7 +34,9 @@ async function openTutorialFirstTime(context: vscode.ExtensionContext) { } } -function showRefactorMigrationMessage() { +function showRefactorMigrationMessage( + extensionContext: vscode.ExtensionContext +) { // Only if the vscode setting continue.manuallyRunningSserver is true const manuallyRunningServer = vscode.workspace @@ -81,45 +70,13 @@ export async function activateExtension(context: vscode.ExtensionContext) { // Add necessary files getTsConfigPath(); - extensionContext = context; - // Register commands and providers - registerAllCodeLensProviders(context); - registerAllCommands(context); registerQuickFixProvider(); await openTutorialFirstTime(context); setupInlineTips(context); - showRefactorMigrationMessage(); - const config = vscode.workspace.getConfiguration("continue"); - const enabled = config.get("enableTabAutocomplete"); + showRefactorMigrationMessage(context); - // Register inline completion provider (odd versions are pre-release) - if (parseInt(context.extension.packageJSON.version.split(".")[1]) % 2 !== 0) { - setupStatusBar(enabled); - context.subscriptions.push( - vscode.languages.registerInlineCompletionItemProvider( - [{ pattern: "**" }], - new ContinueCompletionProvider() - ) - ); - } - - ideProtocolClient = new IdeProtocolClient(context); - - // Register Continue GUI as sidebar webview, and beginning a new session - const provider = new ContinueGUIWebviewViewProvider(); - - context.subscriptions.push( - vscode.window.registerWebviewViewProvider( - "continue.continueGUIView", - provider, - { - webviewOptions: { retainContextWhenHidden: true }, - } - ) - ); - - vsCodeIndexCodebase(ideProtocolClient.getWorkspaceDirectories()); + const vscodeExtension = new VsCodeExtension(context); migrate("showWelcome", () => { vscode.commands.executeCommand( @@ -130,25 +87,6 @@ export async function activateExtension(context: vscode.ExtensionContext) { ); }); - // (async () => { - // const defaultDocsPages = [ - // ["Socket.IO", "https://python-socketio.readthedocs.io/en/stable"], - // // ["Flask", "https://flask.palletsprojects.com/en/2.0.x/"], - // ]; - - // const config = await configHandler.loadConfig(new VsCodeIde()); - - // defaultDocsPages.forEach(async ([title, url]) => { - // for await (const update of indexDocs( - // title, - // new URL(url), - // config.embeddingsProvider - // )) { - // console.log(update.progress, update.desc); - // } - // }); - // })(); - if (getPlatform() === "mac") { // Icon is too large and distracting on other platforms try { diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index a8484c105..ab1f83e28 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -3,19 +3,18 @@ import * as os from "os"; import * as path from "path"; import * as vscode from "vscode"; -import { extensionContext, ideProtocolClient } from "./activation/activate"; -import { debugPanelWebview, getSidebarContent } from "./debugPanel"; -import { acceptDiffCommand, rejectDiffCommand } from "./diff/horizontal"; -import { - editorToVerticalDiffCodeLens, - streamEdit, - verticalPerLineDiffManager, -} from "./diff/verticalPerLine/manager"; -import { VsCodeIde } from "./ideProtocol"; +import { IDE } from "core"; +import { ConfigHandler } from "core/config/handler"; +import { logDevData } from "core/util/devdata"; +import { ContinueGUIWebviewViewProvider } from "./debugPanel"; +import { DiffManager } from "./diff/horizontal"; +import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager"; import { AutocompleteOutcome } from "./lang-server/completionProvider"; -import { configHandler, llmFromTitle } from "./loadConfig"; -function addHighlightedCodeToContext(edit: boolean) { +function addHighlightedCodeToContext( + edit: boolean, + webview: vscode.Webview | undefined +) { const editor = vscode.window.activeTextEditor; if (editor) { const selection = editor.selection; @@ -37,7 +36,7 @@ function addHighlightedCodeToContext(edit: boolean) { }, }; - debugPanelWebview?.postMessage({ + webview?.postMessage({ type: "highlightedCode", rangeInFileWithContents, edit, @@ -45,14 +44,22 @@ function addHighlightedCodeToContext(edit: boolean) { } } -async function addEntireFileToContext(filepath: vscode.Uri, edit: boolean) { +async function addEntireFileToContext( + filepath: vscode.Uri, + edit: boolean, + debugPanelWebview: vscode.Webview | undefined +) { // If a directory, add all files in the directory const stat = await vscode.workspace.fs.stat(filepath); if (stat.type === vscode.FileType.Directory) { const files = await vscode.workspace.fs.readDirectory(filepath); for (const [filename, type] of files) { if (type === vscode.FileType.File) { - addEntireFileToContext(vscode.Uri.joinPath(filepath, filename), edit); + addEntireFileToContext( + vscode.Uri.joinPath(filepath, filename), + edit, + debugPanelWebview + ); } } return; @@ -82,50 +89,44 @@ async function addEntireFileToContext(filepath: vscode.Uri, edit: boolean) { }); } -function acceptRejectVerticalDiffBlock( - accept: boolean, - filepath?: string, - index?: number -) { - if (!filepath) { - const activeEditor = vscode.window.activeTextEditor; - if (!activeEditor) { - return; - } - filepath = activeEditor.document.uri.fsPath; - } - - if (typeof index === "undefined") { - index = 0; - } - - let blocks = editorToVerticalDiffCodeLens.get(filepath); - const block = blocks?.[index]; - if (!blocks || !block) { - return; - } - - const handler = verticalPerLineDiffManager.getHandlerForFile(filepath); - if (!handler) { - return; - } - - // CodeLens object removed from editorToVerticalDiffCodeLens here - handler.acceptRejectBlock(accept, block.start, block.numGreen, block.numRed); -} - // Copy everything over from extension.ts -const commandsMap: { [command: string]: (...args: any) => any } = { - "continue.acceptDiff": acceptDiffCommand, - "continue.rejectDiff": rejectDiffCommand, +const commandsMap: ( + ide: IDE, + extensionContext: vscode.ExtensionContext, + sidebar: ContinueGUIWebviewViewProvider, + configHandler: ConfigHandler, + diffManager: DiffManager, + verticalDiffManager: VerticalPerLineDiffManager +) => { [command: string]: (...args: any) => any } = ( + ide, + extensionContext, + sidebar, + configHandler, + diffManager, + verticalDiffManager +) => ({ + "continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => { + if (newFilepath instanceof vscode.Uri) { + newFilepath = newFilepath.fsPath; + } + verticalDiffManager.clearForFilepath(newFilepath, true); + await diffManager.acceptDiff(newFilepath); + }, + "continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => { + if (newFilepath instanceof vscode.Uri) { + newFilepath = newFilepath.fsPath; + } + verticalDiffManager.clearForFilepath(newFilepath, false); + await diffManager.rejectDiff(newFilepath); + }, "continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => { - acceptRejectVerticalDiffBlock(true, filepath, index); + verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index); }, "continue.rejectVerticalDiffBlock": (filepath?: string, index?: number) => { - acceptRejectVerticalDiffBlock(false, filepath, index); + verticalDiffManager.acceptRejectVerticalDiffBlock(false, filepath, index); }, "continue.quickFix": async (message: string, code: string, edit: boolean) => { - debugPanelWebview?.postMessage({ + sidebar.webview?.postMessage({ type: "newSessionWithPrompt", prompt: `${ edit ? "/edit " : "" @@ -137,17 +138,17 @@ const commandsMap: { [command: string]: (...args: any) => any } = { }, "continue.focusContinueInput": async () => { vscode.commands.executeCommand("continue.continueGUIView.focus"); - debugPanelWebview?.postMessage({ + sidebar.webview?.postMessage({ type: "focusContinueInput", }); - addHighlightedCodeToContext(false); + addHighlightedCodeToContext(false, sidebar.webview); }, "continue.focusContinueInputWithoutClear": async () => { vscode.commands.executeCommand("continue.continueGUIView.focus"); - debugPanelWebview?.postMessage({ + sidebar.webview?.postMessage({ type: "focusContinueInputWithoutClear", }); - addHighlightedCodeToContext(true); + addHighlightedCodeToContext(true, sidebar.webview); }, "continue.toggleAuxiliaryBar": () => { vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar"); @@ -167,7 +168,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = { } if (text.length > 0) { - await streamEdit(text); + await verticalDiffManager.streamEdit(text); } else { // Pick context first const quickPickItems: Promise = configHandler @@ -201,7 +202,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = { title: "Continue Quick Edit", }); if (text) { - const llm = await llmFromTitle(); + const llm = await configHandler.llmFromTitle(); const config = await configHandler.loadConfig(); const context = ( await Promise.all( @@ -216,7 +217,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = { return provider.getContextItems("", { embeddingsProvider: config.embeddingsProvider, - ide: new VsCodeIde(), + ide, llm, fullInput: text || "", selectedCode: [], @@ -230,24 +231,24 @@ const commandsMap: { [command: string]: (...args: any) => any } = { "\n\n---\n\n" + text; - await streamEdit(text); + await verticalDiffManager.streamEdit(text); } } }, "continue.writeCommentsForCode": async () => { - await streamEdit("Write comments for this code"); + await verticalDiffManager.streamEdit("Write comments for this code"); }, "continue.writeDocstringForCode": async () => { - await streamEdit("Write a docstring for this code"); + await verticalDiffManager.streamEdit("Write a docstring for this code"); }, "continue.fixCode": async () => { - await streamEdit("Fix this code"); + await verticalDiffManager.streamEdit("Fix this code"); }, "continue.optimizeCode": async () => { - await streamEdit("Optimize this code"); + await verticalDiffManager.streamEdit("Optimize this code"); }, "continue.fixGrammar": async () => { - await streamEdit( + await verticalDiffManager.streamEdit( "If there are any grammar or spelling mistakes in this writing, fix them" ); }, @@ -264,9 +265,9 @@ const commandsMap: { [command: string]: (...args: any) => any } = { await vscode.window.showTextDocument(uri); }, "continue.debugTerminal": async () => { - const terminalContents = await ideProtocolClient.getTerminalContents(1); + const terminalContents = await ide.getTerminalContents(); vscode.commands.executeCommand("continue.continueGUIView.focus"); - debugPanelWebview?.postMessage({ + sidebar.webview?.postMessage({ type: "userInput", input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents}`, }); @@ -280,21 +281,21 @@ const commandsMap: { [command: string]: (...args: any) => any } = { // Commands without keyboard shortcuts "continue.addModel": () => { vscode.commands.executeCommand("continue.continueGUIView.focus"); - debugPanelWebview?.postMessage({ + sidebar.webview?.postMessage({ type: "addModel", }); }, "continue.openSettingsUI": () => { vscode.commands.executeCommand("continue.continueGUIView.focus"); - debugPanelWebview?.postMessage({ + sidebar.webview?.postMessage({ type: "openSettings", }); }, "continue.sendMainUserInput": (text: string) => { - ideProtocolClient.sendMainUserInput(text); + sidebar.sendMainUserInput(text); }, "continue.shareSession": () => { - ideProtocolClient.sendMainUserInput("/share"); + sidebar.sendMainUserInput("/share"); }, "continue.selectRange": (startLine: number, endLine: number) => { if (!vscode.window.activeTextEditor) { @@ -319,15 +320,15 @@ const commandsMap: { [command: string]: (...args: any) => any } = { }); }, "continue.sendToTerminal": (text: string) => { - ideProtocolClient.runCommand(text); + ide.runCommand(text); }, "continue.newSession": () => { - debugPanelWebview?.postMessage({ + sidebar.webview?.postMessage({ type: "newSession", }); }, "continue.viewHistory": () => { - debugPanelWebview?.postMessage({ + sidebar.webview?.postMessage({ type: "viewHistory", }); }, @@ -364,7 +365,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = { return; } - // Close the sidebars + // Close the sidebar.webviews // vscode.commands.executeCommand("workbench.action.closeSidebar"); vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar"); // vscode.commands.executeCommand("workbench.action.toggleZenMode"); @@ -373,9 +374,12 @@ const commandsMap: { [command: string]: (...args: any) => any } = { "Continue", vscode.ViewColumn.One ); - panel.webview.html = getSidebarContent( + panel.webview.html = sidebar.getSidebarContent( extensionContext, panel, + ide, + configHandler, + verticalDiffManager, undefined, undefined, true @@ -388,7 +392,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = { vscode.commands.executeCommand("continue.continueGUIView.focus"); for (const uri of uris) { - addEntireFileToContext(uri, false); + addEntireFileToContext(uri, false, sidebar.webview); } }, "continue.updateAllReferences": (filepath: vscode.Uri) => { @@ -398,7 +402,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = { return; } const position = editor.selection.active; - ideProtocolClient.sendMainUserInput( + sidebar.sendMainUserInput( `/references ${filepath.fsPath} ${position.line} ${position.character}` ); }, @@ -408,7 +412,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = { ) => { clearTimeout(logRejectionTimeout); outcome.accepted = true; - ideProtocolClient.logDevData("autocomplete", outcome); + logDevData("autocomplete", outcome); }, "continue.toggleTabAutocompleteEnabled": () => { const config = vscode.workspace.getConfiguration("continue"); @@ -419,10 +423,27 @@ const commandsMap: { [command: string]: (...args: any) => any } = { vscode.ConfigurationTarget.Global ); }, -}; +}); -export function registerAllCommands(context: vscode.ExtensionContext) { - for (const [command, callback] of Object.entries(commandsMap)) { +export function registerAllCommands( + context: vscode.ExtensionContext, + ide: IDE, + extensionContext: vscode.ExtensionContext, + sidebar: ContinueGUIWebviewViewProvider, + configHandler: ConfigHandler, + diffManager: DiffManager, + verticalDiffManager: VerticalPerLineDiffManager +) { + for (const [command, callback] of Object.entries( + commandsMap( + ide, + extensionContext, + sidebar, + configHandler, + diffManager, + verticalDiffManager + ) + )) { context.subscriptions.push( vscode.commands.registerCommand(command, callback) ); diff --git a/extensions/vscode/src/debugPanel.ts b/extensions/vscode/src/debugPanel.ts index 3d16cb291..15e2c6cbe 100644 --- a/extensions/vscode/src/debugPanel.ts +++ b/extensions/vscode/src/debugPanel.ts @@ -1,721 +1,10 @@ -import { ContextItemId, DiffLine, FileEdit, ModelDescription } from "core"; -import { indexDocs } from "core/indexing/docs"; -import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider"; -import historyManager from "core/util/history"; -import { editConfigJson, getConfigJsonPath } from "core/util/paths"; -import { readFileSync, writeFileSync } from "fs"; -import { v4 as uuidv4 } from "uuid"; +import { FileEdit, IDE } from "core"; +import { ConfigHandler } from "core/config/handler"; import * as vscode from "vscode"; -import { - extensionContext, - ideProtocolClient, - showTutorial, - windowId, -} from "./activation/activate"; -import { streamEdit } from "./diff/verticalPerLine/manager"; -import { VsCodeIde } from "./ideProtocol"; -import { configHandler, llmFromTitle } from "./loadConfig"; +import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager"; import { getTheme } from "./util/getTheme"; import { getExtensionUri, getNonce, getUniqueId } from "./util/vscode"; - -export let debugPanelWebview: vscode.Webview | undefined; - -export async function webviewRequest( - messageType: string, - data: any = {} -): Promise { - return new Promise((resolve, reject) => { - if (!debugPanelWebview) { - resolve(undefined); - } - - const listener = debugPanelWebview?.onDidReceiveMessage((data) => { - if (data.type === messageType) { - resolve(data); - listener?.dispose(); - } - }); - - debugPanelWebview?.postMessage({ type: messageType, data }); - - setTimeout(() => { - reject("Error communciating with Continue side panel: timed out"); - listener?.dispose(); - }, 500); - }); -} - -const abortedMessageIds: Set = new Set(); - -export function getSidebarContent( - context: vscode.ExtensionContext | undefined, - panel: vscode.WebviewPanel | vscode.WebviewView, - page: string | undefined = undefined, - edits: FileEdit[] | undefined = undefined, - isFullScreen: boolean = false -): string { - if (!isFullScreen) { - debugPanelWebview = panel.webview; - panel.onDidDispose(() => { - debugPanelWebview = undefined; - }); - } - - let extensionUri = getExtensionUri(); - let scriptUri: string; - let styleMainUri: string; - let vscMediaUrl: string = panel.webview - .asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui")) - .toString(); - - const inDevelopmentMode = - context?.extensionMode === vscode.ExtensionMode.Development; - if (!inDevelopmentMode) { - scriptUri = panel.webview - .asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui/assets/index.js")) - .toString(); - styleMainUri = panel.webview - .asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui/assets/index.css")) - .toString(); - } else { - scriptUri = "http://localhost:5173/src/main.tsx"; - styleMainUri = "http://localhost:5173/src/index.css"; - } - - panel.webview.options = { - enableScripts: true, - localResourceRoots: [ - vscode.Uri.joinPath(extensionUri, "gui"), - vscode.Uri.joinPath(extensionUri, "assets"), - ], - enableCommandUris: true, - portMapping: [ - { - webviewPort: 65433, - extensionHostPort: 65433, - }, - ], - }; - - const nonce = getNonce(); - - panel.webview.onDidReceiveMessage(async (data) => { - const ide = new VsCodeIde(); - const respond = (message: any) => { - panel.webview.postMessage({ - type: data.type, - messageId: data.messageId, - message: message, - }); - }; - try { - switch (data.type) { - case "abort": { - abortedMessageIds.add(data.messageId); - break; - } - case "showFile": { - ideProtocolClient.openFile(data.filepath); - break; - } - case "openConfigJson": { - ideProtocolClient.openFile(getConfigJsonPath()); - break; - } - case "readRangeInFile": { - vscode.workspace.openTextDocument(data.filepath).then((document) => { - let start = new vscode.Position(0, 0); - let end = new vscode.Position(5, 0); - let range = new vscode.Range(start, end); - - let contents = document.getText(range); - panel.webview.postMessage({ - type: "readRangeInFile", - messageId: data.messageId, - contents, - }); - }); - break; - } - case "toggleDevTools": { - vscode.commands.executeCommand("workbench.action.toggleDevTools"); - vscode.commands.executeCommand("continue.viewLogs"); - break; - } - case "reloadWindow": { - vscode.commands.executeCommand("workbench.action.reloadWindow"); - break; - } - case "focusEditor": { - vscode.commands.executeCommand( - "workbench.action.focusActiveEditorGroup" - ); - break; - } - case "toggleFullScreen": { - vscode.commands.executeCommand("continue.toggleFullScreen"); - break; - } - case "withProgress": { - // This message allows withProgress to be used in the webview - if (data.done) { - // Will be caught in the listener created below - break; - } - let title = data.title; - vscode.window.withProgress( - { - location: vscode.ProgressLocation.Notification, - title, - cancellable: false, - }, - async () => { - return new Promise((resolve, reject) => { - let listener = panel.webview.onDidReceiveMessage( - async (data) => { - if ( - data.type === "withProgress" && - data.done && - data.title === title - ) { - listener.dispose(); - resolve(); - } - } - ); - }); - } - ); - - break; - } - - // IDE - case "getDiff": { - respond(await ide.getDiff()); - break; - } - case "getSerializedConfig": { - respond(await ide.getSerializedConfig()); - break; - } - case "getTerminalContents": { - respond(await ide.getTerminalContents()); - break; - } - case "listWorkspaceContents": { - respond(await ide.listWorkspaceContents()); - break; - } - case "getWorkspaceDirs": { - respond(await ide.getWorkspaceDirs()); - break; - } - case "listFolders": { - respond(await ide.listFolders()); - break; - } - case "writeFile": { - respond( - await ide.writeFile(data.message.path, data.message.contents) - ); - break; - } - case "showVirtualFile": { - respond( - await ide.showVirtualFile(data.message.name, data.message.content) - ); - break; - } - case "getContinueDir": { - respond(await ide.getContinueDir()); - break; - } - case "openFile": { - respond(await ide.openFile(data.message.path)); - break; - } - case "runCommand": { - respond(await ide.runCommand(data.message.command)); - break; - } - case "getSearchResults": { - respond(await ide.getSearchResults(data.message.query)); - break; - } - case "subprocess": { - respond(await ide.subprocess(data.message.command)); - break; - } - // History - case "history": { - respond(historyManager.list()); - break; - } - case "saveSession": { - historyManager.save(data.message); - respond({}); - break; - } - case "deleteSession": { - historyManager.delete(data.message); - respond({}); - break; - } - case "loadSession": { - respond(historyManager.load(data.message)); - break; - } - case "saveFile": { - respond(await ide.saveFile(data.message.filepath)); - break; - } - case "readFile": { - respond(await ide.readFile(data.message.filepath)); - break; - } - case "showDiff": { - respond( - await ide.showDiff( - data.message.filepath, - data.message.newContents, - data.message.stepIndex - ) - ); - break; - } - case "diffLine": { - const { - diffLine, - filepath, - startLine, - endLine, - }: { - diffLine: DiffLine; - filepath: string; - startLine: number; - endLine: number; - } = data.message; - - respond( - await ide.verticalDiffUpdate(filepath, startLine, endLine, diffLine) - ); - break; - } - case "getProblems": { - respond(await ide.getProblems(data.message.filepath)); - break; - } - case "getBranch": { - const { dir } = data.message; - respond(await ide.getBranch(dir)); - break; - } - case "getOpenFiles": { - respond(await ide.getOpenFiles()); - break; - } - case "getPinnedFiles": { - respond(await ide.getPinnedFiles()); - break; - } - case "showLines": { - const { filepath, startLine, endLine } = data.message; - respond(await ide.showLines(filepath, startLine, endLine)); - break; - } - // Other - case "errorPopup": { - vscode.window - .showErrorMessage(data.message, "Show Logs") - .then((selection) => { - if (selection === "Show Logs") { - vscode.commands.executeCommand( - "workbench.action.toggleDevTools" - ); - } - }); - break; - } - case "logDevData": { - ideProtocolClient.logDevData(data.tableName, data.data); - break; - } - case "addModel": { - const model = data.model; - const config = readFileSync(getConfigJsonPath(), "utf8"); - const configJson = JSON.parse(config); - configJson.models.push(model); - const newConfigString = JSON.stringify( - configJson, - (key, value) => { - return value === null ? undefined : value; - }, - 2 - ); - writeFileSync(getConfigJsonPath(), newConfigString); - configHandler.reloadConfig(); - ideProtocolClient.openFile(getConfigJsonPath()); - - // Find the range where it was added and highlight - let lines = newConfigString.split("\n"); - let startLine; - let endLine; - for (let i = 0; i < lines.length; i++) { - let line = lines[i]; - - if (!startLine) { - if (line.trim() === `"title": "${data.model.title}",`) { - startLine = i - 1; - } - } else { - if (line.startsWith(" }")) { - endLine = i; - break; - } - } - } - - if (startLine && endLine) { - ideProtocolClient.highlightCode( - { - filepath: getConfigJsonPath(), - range: { - start: { character: 0, line: startLine }, - end: { character: 0, line: endLine }, - }, - }, - "#fff1" - ); - } - vscode.window.showInformationMessage( - "🎉 Your model has been successfully added to config.json. You can use this file to further edit its configuration." - ); - break; - } - case "deleteModel": { - const configJson = editConfigJson((config) => { - config.models = config.models.filter( - (m: any) => m.title !== data.title - ); - return config; - }); - configHandler.reloadConfig(); - break; - } - case "addOpenAIKey": { - const configJson = editConfigJson((config) => { - config.models = config.models.map((m: ModelDescription) => { - if (m.provider === "free-trial") { - m.apiKey = data.key; - m.provider = "openai"; - } - return m; - }); - return config; - }); - configHandler.reloadConfig(); - break; - } - case "llmStreamComplete": { - const model = await llmFromTitle(data.message.title); - const gen = model.streamComplete( - data.message.prompt, - data.message.completionOptions - ); - let next = await gen.next(); - while (!next.done) { - if (abortedMessageIds.has(data.messageId)) { - abortedMessageIds.delete(data.messageId); - next = await gen.return({ completion: "", prompt: "" }); - break; - } - respond({ content: next.value }); - next = await gen.next(); - } - - respond({ done: true, data: next.value }); - break; - } - case "llmStreamChat": { - const model = await llmFromTitle(data.message.title); - const gen = model.streamChat( - data.message.messages, - data.message.completionOptions - ); - let next = await gen.next(); - while (!next.done) { - if (abortedMessageIds.has(data.messageId)) { - abortedMessageIds.delete(data.messageId); - next = await gen.return({ completion: "", prompt: "" }); - break; - } - respond({ content: next.value.content }); - next = await gen.next(); - } - - respond({ done: true, data: next.value }); - break; - } - case "llmComplete": { - const model = await llmFromTitle(data.message.title); - const completion = await model.complete( - data.message.prompt, - data.message.completionOptions - ); - respond({ content: completion }); - break; - } - case "runNodeJsSlashCommand": { - const { - input, - history, - modelTitle, - slashCommandName, - contextItems, - params, - historyIndex, - } = data.message; - - const config = await configHandler.loadConfig(); - const llm = await llmFromTitle(modelTitle); - const slashCommand = config.slashCommands?.find( - (sc) => sc.name === slashCommandName - ); - if (!slashCommand) { - throw new Error(`Unknown slash command ${slashCommandName}`); - } - - for await (const update of slashCommand.run({ - input, - history, - llm, - contextItems, - params, - ide, - addContextItem: (item) => { - debugPanelWebview?.postMessage({ - type: "addContextItem", - message: { item, historyIndex }, - }); - }, - })) { - if (update) { - respond({ content: update }); - } - } - respond({ done: true }); - break; - } - case "loadSubmenuItems": { - const { title } = data.message; - const config = await configHandler.loadConfig(); - const provider = config.contextProviders?.find( - (p) => p.description.title === title - ); - if (!provider) { - vscode.window.showErrorMessage( - `Unknown provider ${title}. Existing providers: ${config.contextProviders - ?.map((p) => p.description.title) - .join(", ")}` - ); - respond({ items: [] }); - break; - } - - try { - const items = await provider.loadSubmenuItems({ ide }); - respond({ items }); - } catch (e) { - vscode.window.showErrorMessage( - `Error loading submenu items from ${title}: ${e}` - ); - respond({ items: [] }); - } - break; - } - case "getContextItems": { - const { name, query, fullInput, selectedCode } = data.message; - const config = await configHandler.loadConfig(); - const llm = await llmFromTitle(); - const provider = config.contextProviders?.find( - (p) => p.description.title === name - ); - if (!provider) { - vscode.window.showErrorMessage( - `Unknown provider ${name}. Existing providers: ${config.contextProviders - ?.map((p) => p.description.title) - .join(", ")}` - ); - respond({ items: [] }); - break; - } - - try { - const id: ContextItemId = { - providerTitle: provider.description.title, - itemId: uuidv4(), - }; - const items = await provider.getContextItems(query, { - llm, - embeddingsProvider: config.embeddingsProvider, - fullInput, - ide, - selectedCode, - }); - respond({ items: items.map((item) => ({ ...item, id })) }); - } catch (e) { - vscode.window.showErrorMessage( - `Error getting context items from ${name}: ${e}` - ); - respond({ items: [] }); - } - break; - } - case "addDocs": { - const { url, title } = data; - const embeddingsProvider = new TransformersJsEmbeddingsProvider(); - vscode.window.withProgress( - { - location: vscode.ProgressLocation.Notification, - title: `Indexing ${title}`, - cancellable: false, - }, - async (progress) => { - for await (const update of indexDocs( - title, - new URL(url), - embeddingsProvider - )) { - progress.report({ - increment: update.progress, - message: update.desc, - }); - } - - vscode.window.showInformationMessage( - `🎉 Successfully indexed ${title}` - ); - - debugPanelWebview?.postMessage({ - type: "refreshSubmenuItems", - }); - } - ); - break; - } - case "applyToCurrentFile": { - // Select the entire current file - const editor = vscode.window.activeTextEditor; - if (!editor) { - vscode.window.showErrorMessage( - "No active editor to apply edits to" - ); - break; - } - const document = editor.document; - const start = new vscode.Position(0, 0); - const end = new vscode.Position( - document.lineCount - 1, - document.lineAt(document.lineCount - 1).text.length - ); - editor.selection = new vscode.Selection(start, end); - - streamEdit( - `The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.` - ); - break; - } - case "showTutorial": { - showTutorial(); - break; - } - } - } catch (e: any) { - let message = `Continue error: ${e.message}`; - if (e.cause) { - if (e.cause.name === "ConnectTimeoutError") { - message = `Connection timed out. If you expect it to take a long time to connect, you can increase the timeout in config.json by setting "requestOptions": { "timeout": 10000 }. You can find the full config reference here: https://continue.dev/docs/reference/config`; - } else if (e.cause.code === "ECONNREFUSED") { - message = `Connection was refused. This likely means that there is no server running at the specified URL. If you are running your own server you may need to set the "apiBase" parameter in config.json. For example, you can set up an OpenAI-compatible server like here: https://continue.dev/docs/reference/Model%20Providers/openai#openai-compatible-servers--apis`; - } else { - message = `The request failed with "${e.cause.name}": ${e.cause.message}. If you're having trouble setting up Continue, please see the troubleshooting guide for help.`; - } - } - - vscode.window - .showErrorMessage(message, "Show Logs", "Troubleshooting") - .then((selection) => { - if (selection === "Show Logs") { - vscode.commands.executeCommand("workbench.action.toggleDevTools"); - } else if (selection === "Troubleshooting") { - vscode.env.openExternal( - vscode.Uri.parse("https://continue.dev/docs/troubleshooting") - ); - } - }); - respond({ done: true, data: {} }); - } - }); - - const currentTheme = getTheme(); - vscode.workspace.onDidChangeConfiguration((e) => { - if (e.affectsConfiguration("workbench.colorTheme")) { - // Send new theme to GUI to update embedded Monaco themes - debugPanelWebview?.postMessage({ type: "setTheme", theme: getTheme() }); - } - }); - - return ` - - - - - - - - Continue - - -
- - ${ - inDevelopmentMode - ? `` - : "" - } - - - - - - - - - - - - - - ${ - edits - ? `` - : "" - } - ${page ? `` : ""} - - `; -} +import { VsCodeWebviewProtocol } from "./webviewProtocol"; export class ContinueGUIWebviewViewProvider implements vscode.WebviewViewProvider @@ -727,6 +16,172 @@ export class ContinueGUIWebviewViewProvider _context: vscode.WebviewViewResolveContext, _token: vscode.CancellationToken ): void | Thenable { - webviewView.webview.html = getSidebarContent(extensionContext, webviewView); + this._webview = webviewView.webview; + webviewView.webview.html = this.getSidebarContent( + this.extensionContext, + webviewView, + this.ide, + this.configHandler, + this.verticalDiffManager + ); + } + + private _webview?: vscode.Webview; + + get webview() { + return this._webview; + } + + sendMainUserInput(input: string) { + this.webview?.postMessage({ + type: "userInput", + input, + }); + } + + constructor( + private readonly configHandler: ConfigHandler, + private readonly ide: IDE, + private readonly windowId: string, + private readonly extensionContext: vscode.ExtensionContext, + private readonly verticalDiffManager: VerticalPerLineDiffManager + ) {} + + async webviewRequest(messageType: string, data: any = {}): Promise { + return new Promise((resolve, reject) => { + if (!this._webview) { + resolve(undefined); + } + + const listener = this._webview?.onDidReceiveMessage((data) => { + if (data.type === messageType) { + resolve(data); + listener?.dispose(); + } + }); + + this._webview?.postMessage({ type: messageType, data }); + + setTimeout(() => { + reject("Error communciating with Continue side panel: timed out"); + listener?.dispose(); + }, 500); + }); + } + + getSidebarContent( + context: vscode.ExtensionContext | undefined, + panel: vscode.WebviewPanel | vscode.WebviewView, + ide: IDE, + configHandler: ConfigHandler, + verticalDiffManager: VerticalPerLineDiffManager, + page: string | undefined = undefined, + edits: FileEdit[] | undefined = undefined, + isFullScreen: boolean = false + ): string { + let extensionUri = getExtensionUri(); + let scriptUri: string; + let styleMainUri: string; + let vscMediaUrl: string = panel.webview + .asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui")) + .toString(); + + const inDevelopmentMode = + context?.extensionMode === vscode.ExtensionMode.Development; + if (!inDevelopmentMode) { + scriptUri = panel.webview + .asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui/assets/index.js")) + .toString(); + styleMainUri = panel.webview + .asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui/assets/index.css")) + .toString(); + } else { + scriptUri = "http://localhost:5173/src/main.tsx"; + styleMainUri = "http://localhost:5173/src/index.css"; + } + + panel.webview.options = { + enableScripts: true, + localResourceRoots: [ + vscode.Uri.joinPath(extensionUri, "gui"), + vscode.Uri.joinPath(extensionUri, "assets"), + ], + enableCommandUris: true, + portMapping: [ + { + webviewPort: 65433, + extensionHostPort: 65433, + }, + ], + }; + + const nonce = getNonce(); + + const currentTheme = getTheme(); + vscode.workspace.onDidChangeConfiguration((e) => { + if (e.affectsConfiguration("workbench.colorTheme")) { + // Send new theme to GUI to update embedded Monaco themes + this._webview?.postMessage({ type: "setTheme", theme: getTheme() }); + } + }); + + const webviewProtocol = new VsCodeWebviewProtocol( + panel.webview, + ide, + configHandler, + verticalDiffManager + ); + + return ` + + + + + + + + Continue + + +
+ + ${ + inDevelopmentMode + ? `` + : "" + } + + + + + + + + + + + + + + ${ + edits + ? `` + : "" + } + ${page ? `` : ""} + + `; } } diff --git a/extensions/vscode/src/diff/horizontal.ts b/extensions/vscode/src/diff/horizontal.ts index d9c89bdd8..f07dec3e8 100644 --- a/extensions/vscode/src/diff/horizontal.ts +++ b/extensions/vscode/src/diff/horizontal.ts @@ -3,11 +3,8 @@ import * as fs from "fs"; import * as os from "os"; import * as path from "path"; import * as vscode from "vscode"; -import { extensionContext } from "../activation/activate"; -import { debugPanelWebview } from "../debugPanel"; import { getMetaKeyLabel, getPlatform } from "../util/util"; import { uriFromFilePath } from "../util/vscode"; -import { verticalPerLineDiffManager } from "./verticalPerLine/manager"; interface DiffInfo { originalFilepath: string; @@ -32,7 +29,7 @@ export const DIFF_DIRECTORY = path .join(os.homedir(), ".continue", "diffs") .replace(/^C:/, "c:"); -class DiffManager { +export class DiffManager { // Create a temporary file in the global .continue directory which displays the updated version // Doing this because virtual files are read-only private diffs: Map = new Map(); @@ -50,7 +47,16 @@ class DiffManager { } } - constructor() { + webview: vscode.Webview | undefined; + private readonly extensionContext: vscode.ExtensionContext; + + constructor( + webview: vscode.Webview | undefined, + extensionContext: vscode.ExtensionContext + ) { + this.webview = webview; + this.extensionContext = extensionContext; + this.setupDirectory(); // Listen for file closes, and if it's a diff file, clean up @@ -123,7 +129,7 @@ class DiffManager { .update("codeLens", true, vscode.ConfigurationTarget.Global); if ( - extensionContext?.globalState.get( + this.extensionContext.globalState.get( "continue.showDiffInfoMessage" ) !== false ) { @@ -136,7 +142,7 @@ class DiffManager { .then((selection) => { if (selection === "Don't show again") { // Get the global state - extensionContext?.globalState.update( + this.extensionContext.globalState.update( "continue.showDiffInfoMessage", false ); @@ -297,7 +303,7 @@ class DiffManager { } // Stop the step at step_index in case it is still streaming - debugPanelWebview?.postMessage({ type: "setInactive" }); + this.webview?.postMessage({ type: "setInactive" }); vscode.workspace.textDocuments .find((doc) => doc.uri.fsPath === newFilepath) @@ -310,8 +316,6 @@ class DiffManager { } } -export const diffManager = new DiffManager(); - async function recordAcceptReject(accepted: boolean, diffInfo: DiffInfo) { const devDataDir = devDataPath(); const suggestionsPath = path.join(devDataDir, "suggestions.json"); @@ -341,19 +345,3 @@ async function recordAcceptReject(accepted: boolean, diffInfo: DiffInfo) { JSON.stringify(suggestions, null, 4) ); } - -export async function acceptDiffCommand(newFilepath?: string | vscode.Uri) { - if (newFilepath instanceof vscode.Uri) { - newFilepath = newFilepath.fsPath; - } - verticalPerLineDiffManager.clearForFilepath(newFilepath, true); - await diffManager.acceptDiff(newFilepath); -} - -export async function rejectDiffCommand(newFilepath?: string | vscode.Uri) { - if (newFilepath instanceof vscode.Uri) { - newFilepath = newFilepath.fsPath; - } - verticalPerLineDiffManager.clearForFilepath(newFilepath, false); - await diffManager.rejectDiff(newFilepath); -} diff --git a/extensions/vscode/src/diff/verticalPerLine/handler.ts b/extensions/vscode/src/diff/verticalPerLine/handler.ts index d6b6e9704..7b7cbe1cf 100644 --- a/extensions/vscode/src/diff/verticalPerLine/handler.ts +++ b/extensions/vscode/src/diff/verticalPerLine/handler.ts @@ -7,10 +7,7 @@ import { indexDecorationType, redDecorationType, } from "./decorations"; -import { - editorToVerticalDiffCodeLens, - verticalPerLineDiffManager, -} from "./manager"; +import { VerticalDiffCodeLens } from "./manager"; export class VerticalPerLineDiffHandler { private editor: vscode.TextEditor; @@ -33,6 +30,14 @@ export class VerticalPerLineDiffHandler { startLine: number, endLine: number, editor: vscode.TextEditor, + private readonly editorToVerticalDiffCodeLens: Map< + string, + VerticalDiffCodeLens[] + >, + private readonly clearForFilepath: ( + filepath: string | undefined, + accept: boolean + ) => void, input?: string ) { this.currentLineIndex = startLine; @@ -71,13 +76,13 @@ export class VerticalPerLineDiffHandler { } if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) { - const blocks = editorToVerticalDiffCodeLens.get(this.filepath) || []; + const blocks = this.editorToVerticalDiffCodeLens.get(this.filepath) || []; blocks.push({ start: this.currentLineIndex - this.insertedInCurrentBlock, numRed: this.deletionBuffer.length, numGreen: this.insertedInCurrentBlock, }); - editorToVerticalDiffCodeLens.set(this.filepath, blocks); + this.editorToVerticalDiffCodeLens.set(this.filepath, blocks); } if (this.deletionBuffer.length === 0) { @@ -183,7 +188,7 @@ export class VerticalPerLineDiffHandler { this.greenDecorationManager.clear(); this.clearIndexLineDecorations(); - editorToVerticalDiffCodeLens.delete(this.filepath); + this.editorToVerticalDiffCodeLens.delete(this.filepath); this.editor.edit((editBuilder) => { for (const range of rangesToDelete) { @@ -246,7 +251,7 @@ export class VerticalPerLineDiffHandler { // } // }); } catch (e) { - verticalPerLineDiffManager.clearForFilepath(this.filepath, false); + this.clearForFilepath(this.filepath, false); throw e; } } @@ -283,7 +288,7 @@ export class VerticalPerLineDiffHandler { // Shift the codelens objects const blocks = - editorToVerticalDiffCodeLens + this.editorToVerticalDiffCodeLens .get(this.filepath) ?.filter((x) => x.start !== startLine) .map((x) => { @@ -292,6 +297,6 @@ export class VerticalPerLineDiffHandler { } return x; }) || []; - editorToVerticalDiffCodeLens.set(this.filepath, blocks); + this.editorToVerticalDiffCodeLens.set(this.filepath, blocks); } } diff --git a/extensions/vscode/src/diff/verticalPerLine/manager.ts b/extensions/vscode/src/diff/verticalPerLine/manager.ts index ed32376b0..e4dff637e 100644 --- a/extensions/vscode/src/diff/verticalPerLine/manager.ts +++ b/extensions/vscode/src/diff/verticalPerLine/manager.ts @@ -1,13 +1,23 @@ -import { streamDiffLines } from "core/commands/slash/verticalEdit"; +import { ConfigHandler } from "core/config/handler"; import { getMarkdownLanguageTagForFile } from "core/util"; +import { streamDiffLines } from "core/util/verticalEdit"; import * as vscode from "vscode"; -import { llmFromTitle } from "../../loadConfig"; import { VerticalPerLineDiffHandler } from "./handler"; -class VerticalPerLineDiffManager { +export interface VerticalDiffCodeLens { + start: number; + numRed: number; + numGreen: number; +} + +export class VerticalPerLineDiffManager { private filepathToEditorMap: Map = new Map(); + editorToVerticalDiffCodeLens: Map = new Map(); + + constructor(private readonly configHandler: ConfigHandler) {} + createVerticalPerLineDiffHandler( filepath: string, startLine: number, @@ -24,6 +34,8 @@ class VerticalPerLineDiffManager { startLine, endLine, editor, + this.editorToVerticalDiffCodeLens, + this.clearForFilepath, input ); this.filepathToEditorMap.set(filepath, handler); @@ -46,7 +58,9 @@ class VerticalPerLineDiffManager { const handler = new VerticalPerLineDiffHandler( startLine, endLine, - editor + editor, + this.editorToVerticalDiffCodeLens, + this.clearForFilepath ); this.filepathToEditorMap.set(filepath, handler); return handler; @@ -75,85 +89,113 @@ class VerticalPerLineDiffManager { this.filepathToEditorMap.delete(filepath); } } -} -export const verticalPerLineDiffManager = new VerticalPerLineDiffManager(); + acceptRejectVerticalDiffBlock( + accept: boolean, + filepath?: string, + index?: number + ) { + if (!filepath) { + const activeEditor = vscode.window.activeTextEditor; + if (!activeEditor) { + return; + } + filepath = activeEditor.document.uri.fsPath; + } -export async function streamEdit(input: string) { - const editor = vscode.window.activeTextEditor; - if (!editor) { - return; + if (typeof index === "undefined") { + index = 0; + } + + let blocks = this.editorToVerticalDiffCodeLens.get(filepath); + const block = blocks?.[index]; + if (!blocks || !block) { + return; + } + + const handler = this.getHandlerForFile(filepath); + if (!handler) { + return; + } + + // CodeLens object removed from editorToVerticalDiffCodeLens here + handler.acceptRejectBlock( + accept, + block.start, + block.numGreen, + block.numRed + ); } - const filepath = editor.document.uri.fsPath; - const startLine = editor.selection.start.line; - const endLine = editor.selection.end.line; + async streamEdit(input: string) { + const editor = vscode.window.activeTextEditor; + if (!editor) { + return; + } - const existingHandler = - verticalPerLineDiffManager.getHandlerForFile(filepath); - existingHandler?.clear(false); - await new Promise((resolve) => { - setTimeout(resolve, 200); - }); - const diffHandler = - verticalPerLineDiffManager.createVerticalPerLineDiffHandler( + const filepath = editor.document.uri.fsPath; + const startLine = editor.selection.start.line; + const endLine = editor.selection.end.line; + + const existingHandler = this.getHandlerForFile(filepath); + existingHandler?.clear(false); + await new Promise((resolve) => { + setTimeout(resolve, 200); + }); + const diffHandler = this.createVerticalPerLineDiffHandler( filepath, existingHandler?.range.start.line ?? startLine, existingHandler?.range.end.line ?? endLine, input ); - if (!diffHandler) { - return; - } - - const selectedRange = - existingHandler?.range ?? - new vscode.Range( - editor.selection.start.with(undefined, 0), - editor.selection.end.with(undefined, Number.MAX_SAFE_INTEGER) - ); - const rangeContent = editor.document.getText(selectedRange); - const llm = await llmFromTitle(); - - // Unselect the range - editor.selection = new vscode.Selection( - editor.selection.active, - editor.selection.active - ); - - vscode.commands.executeCommand("setContext", "continue.streamingDiff", true); - - if (existingHandler?.input) { - if (existingHandler.input.startsWith("Original request: ")) { - existingHandler.input = existingHandler.input.substring( - "Original request: ".length - ); + if (!diffHandler) { + return; } - input = `Original request: ${existingHandler.input}\nUpdated request: ${input}`; - } - try { - await diffHandler.run( - streamDiffLines( - rangeContent, - llm, - input, - getMarkdownLanguageTagForFile(filepath) - ) + + const selectedRange = + existingHandler?.range ?? + new vscode.Range( + editor.selection.start.with(undefined, 0), + editor.selection.end.with(undefined, Number.MAX_SAFE_INTEGER) + ); + const rangeContent = editor.document.getText(selectedRange); + const llm = await this.configHandler.llmFromTitle(); + + // Unselect the range + editor.selection = new vscode.Selection( + editor.selection.active, + editor.selection.active ); - } finally { + vscode.commands.executeCommand( "setContext", "continue.streamingDiff", - false + true ); + + if (existingHandler?.input) { + if (existingHandler.input.startsWith("Original request: ")) { + existingHandler.input = existingHandler.input.substring( + "Original request: ".length + ); + } + input = `Original request: ${existingHandler.input}\nUpdated request: ${input}`; + } + try { + await diffHandler.run( + streamDiffLines( + rangeContent, + llm, + input, + getMarkdownLanguageTagForFile(filepath) + ) + ); + } finally { + vscode.commands.executeCommand( + "setContext", + "continue.streamingDiff", + false + ); + } } } - -export interface VerticalDiffCodeLens { - start: number; - numRed: number; - numGreen: number; -} - -export const editorToVerticalDiffCodeLens: Map = - new Map(); diff --git a/extensions/vscode/src/extension/autocomplete.ts b/extensions/vscode/src/extension/autocomplete.ts new file mode 100644 index 000000000..e69de29bb diff --git a/extensions/vscode/src/extension/indexing.ts b/extensions/vscode/src/extension/indexing.ts new file mode 100644 index 000000000..e69de29bb diff --git a/extensions/vscode/src/extension/vscodeExtension.ts b/extensions/vscode/src/extension/vscodeExtension.ts new file mode 100644 index 000000000..ec429f945 --- /dev/null +++ b/extensions/vscode/src/extension/vscodeExtension.ts @@ -0,0 +1,183 @@ +import { ConfigHandler } from "core/config/handler"; +import { CodebaseIndexer } from "core/indexing/indexCodebase"; +import { v4 as uuidv4 } from "uuid"; +import * as vscode from "vscode"; +import { registerAllCommands } from "../commands"; +import { ContinueGUIWebviewViewProvider } from "../debugPanel"; +import { DiffManager } from "../diff/horizontal"; +import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager"; +import { VsCodeIde } from "../ideProtocol"; +import { registerAllCodeLensProviders } from "../lang-server/codeLens"; +import { + ContinueCompletionProvider, + setupStatusBar, +} from "../lang-server/completionProvider"; +import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; + +export class VsCodeExtension { + private configHandler: ConfigHandler; + private extensionContext: vscode.ExtensionContext; + private ide: VsCodeIde; + private tabAutocompleteModel: TabAutocompleteModel; + private sidebar: ContinueGUIWebviewViewProvider; + private windowId: string; + private indexer: CodebaseIndexer; + private diffManager: DiffManager; + private verticalDiffManager: VerticalPerLineDiffManager; + + constructor(context: vscode.ExtensionContext) { + this.diffManager = new DiffManager(undefined, context); + this.ide = new VsCodeIde(this.diffManager); + this.configHandler = new ConfigHandler(this.ide); + this.verticalDiffManager = new VerticalPerLineDiffManager( + this.configHandler + ); + this.extensionContext = context; + this.tabAutocompleteModel = new TabAutocompleteModel(this.configHandler); + this.windowId = uuidv4(); + this.sidebar = new ContinueGUIWebviewViewProvider( + this.configHandler, + this.ide, + this.windowId, + this.extensionContext, + this.verticalDiffManager + ); + this.diffManager.webview = this.sidebar.webview; + this.indexer = new CodebaseIndexer(this.configHandler, this.ide); + + // CodeLens + registerAllCodeLensProviders( + context, + this.diffManager, + this.verticalDiffManager.editorToVerticalDiffCodeLens + ); + + // Tab autocomplete + const config = vscode.workspace.getConfiguration("continue"); + const enabled = config.get("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 + ) + ) + ); + } + + // Sidebar + context.subscriptions.push( + vscode.window.registerWebviewViewProvider( + "continue.continueGUIView", + this.sidebar, + { + webviewOptions: { retainContextWhenHidden: true }, + } + ) + ); + + // Commands + registerAllCommands( + context, + this.ide, + context, + this.sidebar, + this.configHandler, + this.diffManager, + this.verticalDiffManager + ); + + // Indexing + this.ide.getWorkspaceDirs().then((dirs) => this.refreshCodebaseIndex(dirs)); + + // Listen for file saving + vscode.workspace.onDidSaveTextDocument((event) => { + const filepath = event.uri.fsPath; + + if ( + filepath.endsWith(".continue/config.json") || + filepath.endsWith(".continue\\config.json") || + filepath.endsWith(".continue/config.ts") || + filepath.endsWith(".continue\\config.ts") || + filepath.endsWith(".continuerc.json") + ) { + this.configHandler.reloadConfig(); + this.tabAutocompleteModel.clearLlm(); + } else if ( + filepath.endsWith(".continueignore") || + filepath.endsWith(".gitignore") + ) { + this.sidebar.webview?.postMessage({ + type: "updateEmbeddings", + }); + } + }); + + // Refresh index when branch is changed + this.ide.getWorkspaceDirs().then((dirs) => + dirs.forEach(async (dir) => { + const repo = await this.ide.getRepo(vscode.Uri.file(dir)); + if (repo) { + repo.state.onDidChange(() => { + // args passed to this callback are always undefined, so keep track of previous branch + const currentBranch = repo?.state?.HEAD?.name; + if (currentBranch) { + if (this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir]) { + if ( + currentBranch !== this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] + ) { + // Trigger refresh of index only in this directory + this.refreshCodebaseIndex([dir]); + } + } + + this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] = currentBranch; + } + }); + } + }) + ); + + // Register a content provider for the readonly virtual documents + const documentContentProvider = new (class + implements vscode.TextDocumentContentProvider + { + // emitter and its event + onDidChangeEmitter = new vscode.EventEmitter(); + onDidChange = this.onDidChangeEmitter.event; + + provideTextDocumentContent(uri: vscode.Uri): string { + return uri.query; + } + })(); + context.subscriptions.push( + vscode.workspace.registerTextDocumentContentProvider( + VsCodeExtension.continueVirtualDocumentScheme, + documentContentProvider + ) + ); + } + + static continueVirtualDocumentScheme = "continue"; + + private PREVIOUS_BRANCH_FOR_WORKSPACE_DIR: { [dir: string]: string } = {}; + + private async refreshCodebaseIndex(dirs: string[]) { + for await (const { progress, desc } of this.indexer.refresh(dirs)) { + this.sidebar.webview?.postMessage({ + type: "indexProgress", + progress, + desc, + }); + } + } +} diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/ideProtocol.ts index e7855934a..469b38261 100644 --- a/extensions/vscode/src/ideProtocol.ts +++ b/extensions/vscode/src/ideProtocol.ts @@ -2,48 +2,97 @@ import { exec } from "child_process"; import { getContinueGlobalPath } from "core/util/paths"; import * as path from "path"; import * as vscode from "vscode"; -import { ideProtocolClient } from "./activation/activate"; import * as child_process from "child_process"; -import { Chunk, DiffLine, IDE, Problem } from "core"; -import { - BrowserSerializedContinueConfig, - finalToBrowserConfig, -} from "core/config/load"; -import { LanceDbIndex } from "core/indexing/LanceDbIndex"; -import { IndexTag } from "core/indexing/types"; -import { verticalPerLineDiffManager } from "./diff/verticalPerLine/manager"; -import { configHandler } from "./loadConfig"; +import { ContinueRcJson, IDE, Problem, Range } from "core"; +import { DiffManager } from "./diff/horizontal"; +import { VsCodeIdeUtils } from "./util/ideUtils"; import { traverseDirectory } from "./util/traverseDirectory"; import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode"; class VsCodeIde implements IDE { - async getSerializedConfig(): Promise { - const config = await configHandler.loadConfig(); - return finalToBrowserConfig(config); + ideUtils: VsCodeIdeUtils; + + constructor(private readonly diffManager: DiffManager) { + this.ideUtils = new VsCodeIdeUtils(); + } + readRangeInFile(filepath: string, range: Range): Promise { + return this.ideUtils.readRangeInFile( + filepath, + new vscode.Range( + new vscode.Position(range.start.line, range.start.character), + new vscode.Position(range.end.line, range.end.character) + ) + ); + } + + async getStats(directory: string): Promise<{ [path: string]: number }> { + const files = await this.listWorkspaceContents(directory); + const pathToLastModified: { [path: string]: number } = {}; + await Promise.all( + files.map(async (file) => { + let stat = await vscode.workspace.fs.stat(vscode.Uri.file(file)); + pathToLastModified[file] = stat.mtime; + }) + ); + + return pathToLastModified; + } + + async getRepo(dir: vscode.Uri): Promise { + return this.ideUtils.getRepo(dir); + } + + async isTelemetryEnabled(): Promise { + return ( + (await vscode.workspace + .getConfiguration("continue") + .get("telemetryEnabled")) ?? true + ); + } + getUniqueId(): Promise { + return Promise.resolve(vscode.env.machineId); } async getDiff(): Promise { - return await ideProtocolClient.getDiff(); + return await this.ideUtils.getDiff(); } async getTerminalContents(): Promise { - return await ideProtocolClient.getTerminalContents(1); + return await this.ideUtils.getTerminalContents(1); } async listWorkspaceContents(directory?: string): Promise { if (directory) { - return await ideProtocolClient.getDirectoryContents(directory, true); + return await this.ideUtils.getDirectoryContents(directory, true); } else { const contents = await Promise.all( - ideProtocolClient + this.ideUtils .getWorkspaceDirectories() - .map((dir) => ideProtocolClient.getDirectoryContents(dir, true)) + .map((dir) => this.ideUtils.getDirectoryContents(dir, true)) ); return contents.flat(); } } + async getWorkspaceConfigs() { + const workspaceDirs = + vscode.workspace.workspaceFolders?.map((folder) => folder.uri) || []; + const configs: ContinueRcJson[] = []; + for (const workspaceDir of workspaceDirs) { + const files = await vscode.workspace.fs.readDirectory(workspaceDir); + for (const [filename, type] of files) { + if (type === vscode.FileType.File && filename === ".continuerc.json") { + const contents = await this.ideUtils.readFile( + vscode.Uri.joinPath(workspaceDir, filename).fsPath + ); + configs.push(JSON.parse(contents)); + } + } + } + return configs; + } + async listFolders(): Promise { const allDirs: string[] = []; @@ -63,7 +112,7 @@ class VsCodeIde implements IDE { } async getWorkspaceDirs(): Promise { - return ideProtocolClient.getWorkspaceDirectories(); + return this.ideUtils.getWorkspaceDirectories(); } async getContinueDir(): Promise { @@ -78,11 +127,11 @@ class VsCodeIde implements IDE { } async showVirtualFile(title: string, contents: string): Promise { - ideProtocolClient.showVirtualFile(title, contents); + this.ideUtils.showVirtualFile(title, contents); } async openFile(path: string): Promise { - ideProtocolClient.openFile(path); + this.ideUtils.openFile(path); } async showLines( @@ -95,53 +144,44 @@ class VsCodeIde implements IDE { new vscode.Position(endLine, 0) ); openEditorAndRevealRange(filepath, range).then(() => { - ideProtocolClient.highlightCode( - { - filepath, - range, - }, - "#fff1" - ); + // TODO: Highlight lines + // this.ideUtils.highlightCode( + // { + // filepath, + // range, + // }, + // "#fff1" + // ); }); } async runCommand(command: string): Promise { - await ideProtocolClient.runCommand(command); + if (vscode.window.terminals.length) { + vscode.window.terminals[0].show(); + vscode.window.terminals[0].sendText(command, false); + } else { + const terminal = vscode.window.createTerminal(); + terminal.show(); + terminal.sendText(command, false); + } } async saveFile(filepath: string): Promise { - await ideProtocolClient.saveFile(filepath); + await this.ideUtils.saveFile(filepath); } async readFile(filepath: string): Promise { - return await ideProtocolClient.readFile(filepath); + return await this.ideUtils.readFile(filepath); } async showDiff( filepath: string, newContents: string, stepIndex: number ): Promise { - await ideProtocolClient.showDiff(filepath, newContents, stepIndex); - } - - async verticalDiffUpdate( - filepath: string, - startLine: number, - endLine: number, - diffLine: DiffLine - ) { - const diffHandler = - verticalPerLineDiffManager.getOrCreateVerticalPerLineDiffHandler( - filepath, - startLine, - endLine - ); - if (diffHandler) { - await diffHandler.handleDiffLine(diffLine); - } + await this.diffManager.writeDiff(filepath, newContents, stepIndex); } async getOpenFiles(): Promise { - return await ideProtocolClient.getOpenFiles(); + return await this.ideUtils.getOpenFiles(); } async getPinnedFiles(): Promise { @@ -227,48 +267,7 @@ class VsCodeIde implements IDE { } async getBranch(dir: string): Promise { - return ideProtocolClient.getBranch(vscode.Uri.file(dir)); - } - - async getFilesToEmbed( - providerId: string - ): Promise<[string, string, string][]> { - return []; - } - - async sendEmbeddingForChunk( - chunk: Chunk, - embedding: number[], - tags: string[] - ) {} - - async retrieveChunks( - text: string, - n: number, - directory: string | undefined - ): Promise { - const embeddingsProvider = (await configHandler.loadConfig()) - .embeddingsProvider; - if (!embeddingsProvider) { - return []; - } - const lanceDbIndex = new LanceDbIndex(embeddingsProvider, (path) => - ideProtocolClient.readFile(path) - ); - - const tags = await Promise.all( - (await this.getWorkspaceDirs()).map(async (dir) => { - let branch = await ideProtocolClient.getBranch(vscode.Uri.file(dir)); - let tag: IndexTag = { - directory: dir, - branch, - artifactId: lanceDbIndex.artifactId, - }; - return tag; - }) - ); - let chunks = await lanceDbIndex.retrieve(tags, text, n, directory); - return chunks as any[]; + return this.ideUtils.getBranch(vscode.Uri.file(dir)); } } diff --git a/extensions/vscode/src/lang-server/autocompletePromptBuilder.ts b/extensions/vscode/src/lang-server/autocompletePromptBuilder.ts new file mode 100644 index 000000000..eab90c80e --- /dev/null +++ b/extensions/vscode/src/lang-server/autocompletePromptBuilder.ts @@ -0,0 +1,31 @@ +import { IDE } from "core"; +import { AutocompleteSnippet } from "core/autocomplete/constructPrompt"; +import * as vscode from "vscode"; + +export class AutocompletePromptBuilder { + constructor(private readonly ide: IDE) {} + + async getDefinition( + uri: string, + line: number, + character: number + ): Promise { + const definitions = (await vscode.commands.executeCommand( + "vscode.executeDefinitionProvider", + vscode.Uri.parse(uri), + new vscode.Position(line, character) + )) as any; + + if (definitions[0]?.targetRange) { + return { + filepath: uri, + content: await this.ide.readRangeInFile( + definitions[0].targetUri.fsPath, + definitions[0].targetRange + ), + }; + } + + return undefined; + } +} diff --git a/extensions/vscode/src/lang-server/codeLens.ts b/extensions/vscode/src/lang-server/codeLens.ts index 04915b777..1b28e6280 100644 --- a/extensions/vscode/src/lang-server/codeLens.ts +++ b/extensions/vscode/src/lang-server/codeLens.ts @@ -1,19 +1,26 @@ import * as os from "os"; import * as path from "path"; import * as vscode from "vscode"; -import { DIFF_DIRECTORY, diffManager } from "../diff/horizontal"; -import { editorToVerticalDiffCodeLens } from "../diff/verticalPerLine/manager"; +import { DIFF_DIRECTORY, DiffManager } from "../diff/horizontal"; +import { VerticalDiffCodeLens } from "../diff/verticalPerLine/manager"; import { editorSuggestionsLocked, editorToSuggestions } from "../suggestions"; import { getMetaKeyLabel } from "../util/util"; import { getExtensionUri } from "../util/vscode"; class VerticalPerLineCodeLensProvider implements vscode.CodeLensProvider { + constructor( + private readonly editorToVerticalDiffCodeLens: Map< + string, + VerticalDiffCodeLens[] + > + ) {} + public provideCodeLenses( document: vscode.TextDocument, _: vscode.CancellationToken ): vscode.CodeLens[] | Thenable { const filepath = document.uri.fsPath; - const blocks = editorToVerticalDiffCodeLens.get(filepath); + const blocks = this.editorToVerticalDiffCodeLens.get(filepath); if (!blocks) { return []; } @@ -96,6 +103,12 @@ class SuggestionsCodeLensProvider implements vscode.CodeLensProvider { } class DiffViewerCodeLensProvider implements vscode.CodeLensProvider { + diffManager: DiffManager; + + constructor(diffManager: DiffManager) { + this.diffManager = diffManager; + } + public provideCodeLenses( document: vscode.TextDocument, _: vscode.CancellationToken @@ -103,7 +116,7 @@ class DiffViewerCodeLensProvider implements vscode.CodeLensProvider { if (path.dirname(document.uri.fsPath) === DIFF_DIRECTORY) { const codeLenses: vscode.CodeLens[] = []; let range = new vscode.Range(0, 0, 1, 0); - const diffInfo = diffManager.diffAtNewFilepath(document.uri.fsPath); + const diffInfo = this.diffManager.diffAtNewFilepath(document.uri.fsPath); if (diffInfo) { range = diffInfo.range; } @@ -334,7 +347,11 @@ let suggestionsCodeLensDisposable: vscode.Disposable | undefined = undefined; let configPyCodeLensDisposable: vscode.Disposable | undefined = undefined; let tutorialCodeLensDisposable: vscode.Disposable | undefined = undefined; -export function registerAllCodeLensProviders(context: vscode.ExtensionContext) { +export function registerAllCodeLensProviders( + context: vscode.ExtensionContext, + diffManager: DiffManager, + editorToVerticalDiffCodeLens: Map +) { if (verticalPerLineCodeLensProvider) { verticalPerLineCodeLensProvider.dispose(); } @@ -353,7 +370,7 @@ export function registerAllCodeLensProviders(context: vscode.ExtensionContext) { verticalPerLineCodeLensProvider = vscode.languages.registerCodeLensProvider( "*", - new VerticalPerLineCodeLensProvider() + new VerticalPerLineCodeLensProvider(editorToVerticalDiffCodeLens) ); suggestionsCodeLensDisposable = vscode.languages.registerCodeLensProvider( "*", @@ -361,7 +378,7 @@ export function registerAllCodeLensProviders(context: vscode.ExtensionContext) { ); diffsCodeLensDisposable = vscode.languages.registerCodeLensProvider( "*", - new DiffViewerCodeLensProvider() + new DiffViewerCodeLensProvider(diffManager) ); configPyCodeLensDisposable = vscode.languages.registerCodeLensProvider( "*", diff --git a/extensions/vscode/src/lang-server/completionProvider.ts b/extensions/vscode/src/lang-server/completionProvider.ts index 515bbb9f2..c2af7f2c4 100644 --- a/extensions/vscode/src/lang-server/completionProvider.ts +++ b/extensions/vscode/src/lang-server/completionProvider.ts @@ -1,8 +1,7 @@ -import { TabAutocompleteOptions } from "core"; +import { IDE, TabAutocompleteOptions } from "core"; import { AutocompleteLruCache } from "core/autocomplete/cache"; import { onlyWhitespaceAfterEndOfLine } from "core/autocomplete/charStream"; import { - AutocompleteSnippet, constructAutocompletePrompt, languageForFilepath, } from "core/autocomplete/constructPrompt"; @@ -12,13 +11,14 @@ import { } from "core/autocomplete/lineStream"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "core/autocomplete/parameters"; import { getTemplateForModel } from "core/autocomplete/templates"; +import { ConfigHandler } from "core/config/handler"; import { streamLines } from "core/diff/util"; import OpenAI from "core/llm/llms/OpenAI"; -import Handlebars from "handlebars"; +import { logDevData } from "core/util/devdata"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; -import { ideProtocolClient } from "../activation/activate"; -import { TabAutocompleteModel, configHandler } from "../loadConfig"; +import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; +import { AutocompletePromptBuilder } from "./autocompletePromptBuilder"; const statusBarItemText = (enabled: boolean | undefined) => enabled ? "$(check) Continue" : "$(circle-slash) Continue"; @@ -70,30 +70,6 @@ export function setupStatusBar( }); } -async function getDefinition( - uri: string, - line: number, - character: number -): Promise { - const definitions = (await vscode.commands.executeCommand( - "vscode.executeDefinitionProvider", - vscode.Uri.parse(uri), - new vscode.Position(line, character) - )) as any; - - if (definitions[0]?.targetRange) { - return { - filepath: uri, - content: await ideProtocolClient.readRangeInFile( - definitions[0].targetUri.fsPath, - definitions[0].targetRange - ), - }; - } - - return undefined; -} - export interface AutocompleteOutcome { accepted?: boolean; time: number; @@ -234,157 +210,6 @@ class GeneratorReuseManager { } } -async function getTabCompletion( - document: vscode.TextDocument, - pos: vscode.Position, - token: vscode.CancellationToken, - options: TabAutocompleteOptions -): Promise { - const startTime = Date.now(); - - // Filter - const lang = languageForFilepath(document.fileName); - const line = document.lineAt(pos).text; - for (const endOfLine of lang.endOfLine) { - if (line.endsWith(endOfLine) && pos.character >= endOfLine.length) { - return undefined; - } - } - - try { - // Model - const llm = await TabAutocompleteModel.get(); - if (llm instanceof OpenAI) { - llm.useLegacyCompletionsEndpoint = true; - } - if (!llm) return; - - // Prompt - const fullPrefix = document.getText( - new vscode.Range(new vscode.Position(0, 0), pos) - ); - const fullSuffix = document.getText( - new vscode.Range( - pos, - new vscode.Position(document.lineCount, Number.MAX_SAFE_INTEGER) - ) - ); - const lineBelowCursor = document.lineAt( - Math.min(pos.line + 1, document.lineCount - 1) - ).text; - const clipboardText = await vscode.env.clipboard.readText(); - const { prefix, suffix } = await constructAutocompletePrompt( - document.uri.toString(), - fullPrefix, - fullSuffix, - clipboardText, - lang, - getDefinition, - options - ); - - const { template, completionOptions } = options.template - ? { template: options.template, completionOptions: {} } - : getTemplateForModel(llm.model); - - const compiledTemplate = Handlebars.compile(template); - const prompt = compiledTemplate({ prefix, suffix }); - - // Completion - let completion = ""; - - const cache = await autocompleteCache; - const cachedCompletion = await cache.get(prompt); - let cacheHit = false; - if (cachedCompletion) { - // Cache - cacheHit = true; - completion = cachedCompletion; - } else { - setupStatusBar(true, true); - - // Try to reuse pending requests if what the user typed matches start of completion - let stop = [ - ...(completionOptions?.stop || []), - "\n\n", - "```", - ...lang.stopWords, - ]; - if (options.disableMultiLineCompletions) { - stop.unshift("\n"); - } - let generator = GeneratorReuseManager.getGenerator(prefix, () => - llm.streamComplete(prompt, { - ...completionOptions, - temperature: 0, - raw: true, - stop, - }) - ); - - // LLM - let cancelled = false; - const generatorWithCancellation = async function* () { - for await (const update of generator) { - if (token.isCancellationRequested) { - stopStatusBarLoading(); - cancelled = true; - return undefined; - } - yield update; - } - }; - const gen2 = onlyWhitespaceAfterEndOfLine( - generatorWithCancellation(), - lang.endOfLine - ); - const lineGenerator = streamWithNewLines(streamLines(gen2)); - const finalGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor); - for await (const update of finalGenerator) { - completion += update; - } - - if (cancelled) { - return undefined; - } - - // Don't return empty - if (completion.trim().length <= 0) { - return undefined; - } - - // Post-processing - completion = completion.trimEnd(); - } - - const time = Date.now() - startTime; - return { - time, - completion, - prompt, - modelProvider: llm.providerName, - modelName: llm.model, - completionOptions, - cacheHit, - }; - } catch (e: any) { - console.warn("Error generating autocompletion: ", e); - if (!ContinueCompletionProvider.errorsShown.has(e.message)) { - ContinueCompletionProvider.errorsShown.add(e.message); - vscode.window.showErrorMessage(e.message, "Documentation").then((val) => { - if (val === "Documentation") { - vscode.env.openExternal( - vscode.Uri.parse( - "https://continue.dev/docs/walkthroughs/tab-autocomplete" - ) - ); - } - }); - } - return undefined; - } -} - export class ContinueCompletionProvider implements vscode.InlineCompletionItemProvider { @@ -394,6 +219,172 @@ export class ContinueCompletionProvider public static errorsShown: Set = new Set(); + private readonly promptBuilder: AutocompletePromptBuilder; + + constructor( + private readonly configHandler: ConfigHandler, + private readonly ide: IDE, + private readonly tabAutocompleteModel: TabAutocompleteModel + ) { + this.promptBuilder = new AutocompletePromptBuilder(ide); + } + + async getTabCompletion( + document: vscode.TextDocument, + pos: vscode.Position, + token: vscode.CancellationToken, + options: TabAutocompleteOptions + ): Promise { + const startTime = Date.now(); + + // Filter + const lang = languageForFilepath(document.fileName); + const line = document.lineAt(pos).text; + for (const endOfLine of lang.endOfLine) { + if (line.endsWith(endOfLine) && pos.character >= endOfLine.length) { + return undefined; + } + } + + try { + // Model + const llm = await this.tabAutocompleteModel.get(); + if (llm instanceof OpenAI) { + llm.useLegacyCompletionsEndpoint = true; + } + if (!llm) return; + + // Prompt + const fullPrefix = document.getText( + new vscode.Range(new vscode.Position(0, 0), pos) + ); + const fullSuffix = document.getText( + new vscode.Range( + pos, + new vscode.Position(document.lineCount, Number.MAX_SAFE_INTEGER) + ) + ); + const lineBelowCursor = document.lineAt( + Math.min(pos.line + 1, document.lineCount - 1) + ).text; + const clipboardText = await vscode.env.clipboard.readText(); + const { prefix, suffix } = await constructAutocompletePrompt( + document.uri.toString(), + fullPrefix, + fullSuffix, + clipboardText, + lang, + this.promptBuilder.getDefinition, + options + ); + + const { template, completionOptions } = options.template + ? { template: options.template, completionOptions: {} } + : getTemplateForModel(llm.model); + + const compiledTemplate = Handlebars.compile(template); + const prompt = compiledTemplate({ prefix, suffix }); + + // Completion + let completion = ""; + + const cache = await autocompleteCache; + const cachedCompletion = await cache.get(prompt); + let cacheHit = false; + if (cachedCompletion) { + // Cache + cacheHit = true; + completion = cachedCompletion; + } else { + setupStatusBar(true, true); + + // Try to reuse pending requests if what the user typed matches start of completion + let stop = [ + ...(completionOptions?.stop || []), + "\n\n", + "```", + ...lang.stopWords, + ]; + if (options.disableMultiLineCompletions) { + stop.unshift("\n"); + } + let generator = GeneratorReuseManager.getGenerator(prefix, () => + llm.streamComplete(prompt, { + ...completionOptions, + temperature: 0, + raw: true, + stop, + }) + ); + + // LLM + let cancelled = false; + const generatorWithCancellation = async function* () { + for await (const update of generator) { + if (token.isCancellationRequested) { + stopStatusBarLoading(); + cancelled = true; + return undefined; + } + yield update; + } + }; + const gen2 = onlyWhitespaceAfterEndOfLine( + generatorWithCancellation(), + lang.endOfLine + ); + const lineGenerator = streamWithNewLines(streamLines(gen2)); + const finalGenerator = stopAtSimilarLine( + lineGenerator, + lineBelowCursor + ); + for await (const update of finalGenerator) { + completion += update; + } + + if (cancelled) { + return undefined; + } + + // Don't return empty + if (completion.trim().length <= 0) { + return undefined; + } + + // Post-processing + completion = completion.trimEnd(); + } + + const time = Date.now() - startTime; + return { + time, + completion, + prompt, + modelProvider: llm.providerName, + modelName: llm.model, + completionOptions, + cacheHit, + }; + } catch (e: any) { + console.warn("Error generating autocompletion: ", e); + if (!ContinueCompletionProvider.errorsShown.has(e.message)) { + ContinueCompletionProvider.errorsShown.add(e.message); + vscode.window + .showErrorMessage(e.message, "Documentation") + .then((val) => { + if (val === "Documentation") { + vscode.env.openExternal( + vscode.Uri.parse( + "https://continue.dev/docs/walkthroughs/tab-autocomplete" + ) + ); + } + }); + } + return undefined; + } + } + public async provideInlineCompletionItems( document: vscode.TextDocument, position: vscode.Position, @@ -405,7 +396,7 @@ export class ContinueCompletionProvider const uuid = uuidv4(); ContinueCompletionProvider.lastUUID = uuid; - const config = await configHandler.loadConfig(); + const config = await this.configHandler.loadConfig(); const options = { ...config.tabAutocompleteOptions, ...DEFAULT_AUTOCOMPLETE_OPTS, @@ -437,7 +428,7 @@ export class ContinueCompletionProvider } try { - const outcome = await getTabCompletion( + const outcome = await this.getTabCompletion( document, position, token, @@ -459,7 +450,7 @@ export class ContinueCompletionProvider const logRejectionTimeout = setTimeout(() => { // Wait 10 seconds, then assume it wasn't accepted outcome.accepted = false; - ideProtocolClient.logDevData("autocomplete", outcome); + logDevData("autocomplete", outcome); }, 10_000); return [ diff --git a/extensions/vscode/src/loadConfig.ts b/extensions/vscode/src/loadConfig.ts deleted file mode 100644 index 4f2ddc502..000000000 --- a/extensions/vscode/src/loadConfig.ts +++ /dev/null @@ -1,300 +0,0 @@ -import { ContinueConfig, ContinueRcJson, ILLM } from "core"; -import defaultConfig from "core/config/default"; -import { - finalToBrowserConfig, - intermediateToFinalConfig, - loadFullConfigNode, - serializedToIntermediateConfig, -} from "core/config/load"; -import Ollama from "core/llm/llms/Ollama"; -import { getConfigJsonPath } from "core/util/paths"; -import { Telemetry } from "core/util/posthog"; -import { http, https } from "follow-redirects"; -import * as fs from "fs"; -import { HttpProxyAgent } from "http-proxy-agent"; -import { HttpsProxyAgent } from "https-proxy-agent"; -import fetch from "node-fetch"; -import * as vscode from "vscode"; -import { ideProtocolClient } from "./activation/activate"; -import { debugPanelWebview, webviewRequest } from "./debugPanel"; -import { getUniqueId } from "./util/vscode"; -const tls = require("tls"); - -const outputChannel = vscode.window.createOutputChannel( - "Continue - LLM Prompt/Completion" -); - -class VsCodeConfigHandler { - savedConfig: ContinueConfig | undefined; - - reloadConfig() { - this.savedConfig = undefined; - this.loadConfig(); - } - - private async _getWorkspaceConfigs() { - const workspaceDirs = - vscode.workspace.workspaceFolders?.map((folder) => folder.uri) || []; - const configs: ContinueRcJson[] = []; - for (const workspaceDir of workspaceDirs) { - const files = await vscode.workspace.fs.readDirectory(workspaceDir); - for (const [filename, type] of files) { - if (type === vscode.FileType.File && filename === ".continuerc.json") { - const contents = await ideProtocolClient.readFile( - vscode.Uri.joinPath(workspaceDir, filename).fsPath - ); - configs.push(JSON.parse(contents)); - } - } - } - return configs; - } - - async loadConfig(): Promise { - try { - if (this.savedConfig) { - return this.savedConfig; - } - let workspaceConfigs: ContinueRcJson[] = []; - try { - workspaceConfigs = await this._getWorkspaceConfigs(); - } catch (e) { - console.warn("Failed to load workspace configs"); - } - this.savedConfig = await loadFullConfigNode( - ideProtocolClient.readFile, - workspaceConfigs - ); - this.savedConfig.allowAnonymousTelemetry = - this.savedConfig.allowAnonymousTelemetry && - vscode.workspace.getConfiguration("continue").get("telemetryEnabled"); - - // Update the sidebar panel - const browserConfig = finalToBrowserConfig(this.savedConfig); - debugPanelWebview?.postMessage({ type: "configUpdate", browserConfig }); - - // Setup telemetry only after (and if) we know it is enabled - await Telemetry.setup( - this.savedConfig.allowAnonymousTelemetry ?? true, - getUniqueId() - ); - - return this.savedConfig; - } catch (e) { - vscode.window - .showErrorMessage( - "Error loading config.json. Please check your config.json file: " + e, - "Open config.json" - ) - .then((selection) => { - if (selection === "Open config.json") { - vscode.workspace - .openTextDocument(getConfigJsonPath()) - .then((doc) => { - vscode.window.showTextDocument(doc); - }); - } - }); - return intermediateToFinalConfig( - serializedToIntermediateConfig(defaultConfig), - ideProtocolClient.readFile - ); - } - } -} - -export const configHandler = new VsCodeConfigHandler(); - -const TIMEOUT = 7200; // 7200 seconds = 2 hours - -function setupLlm(llm: ILLM): ILLM { - // Since we know this is happening in Node.js, we can add requestOptions through a custom agent - const ca = [...tls.rootCertificates]; - const customCerts = - typeof llm.requestOptions?.caBundlePath === "string" - ? [llm.requestOptions?.caBundlePath] - : llm.requestOptions?.caBundlePath; - if (customCerts) { - ca.push( - ...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8")) - ); - } - - let timeout = (llm.requestOptions?.timeout || TIMEOUT) * 1000; // measured in ms - - const agentOptions = { - ca, - rejectUnauthorized: llm.requestOptions?.verifySsl, - timeout, - sessionTimeout: timeout, - keepAlive: true, - keepAliveMsecs: timeout, - }; - - const proxy = llm.requestOptions?.proxy; - - llm._fetch = async (input, init) => { - // Create agent - const protocol = new URL(input).protocol === "https:" ? https : http; - const agent = proxy - ? new URL(input).protocol === "https:" - ? new HttpsProxyAgent(proxy, agentOptions) - : new HttpProxyAgent(proxy, agentOptions) - : new protocol.Agent(agentOptions); - - const headers: { [key: string]: string } = - llm!.requestOptions?.headers || {}; - for (const [key, value] of Object.entries(init?.headers || {})) { - headers[key] = value as string; - } - - const resp = await fetch(input, { - ...init, - headers, - agent, - }); - - if (!resp.ok) { - let text = await resp.text(); - if (resp.status === 404 && !resp.url.includes("/v1")) { - if (text.includes("try pulling it first")) { - const model = JSON.parse(text).error.split(" ")[1].slice(1, -1); - text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`; - } else if (text.includes("/api/chat")) { - text = - "The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue."; - } else { - text = - "This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json."; - } - } - throw new Error( - `HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}` - ); - } - - return resp; - }; - - llm.writeLog = async (log: string) => { - outputChannel.appendLine( - "==========================================================================" - ); - outputChannel.appendLine( - "==========================================================================" - ); - - outputChannel.append(log); - }; - return llm; -} - -export async function llmFromTitle(title?: string): Promise { - let config = await configHandler.loadConfig(); - - if (title === undefined) { - const resp = await webviewRequest("getDefaultModelTitle"); - if (resp?.defaultModelTitle) { - title = resp.defaultModelTitle; - } - } - - let llm = title - ? config.models.find((llm) => llm.title === title) - : config.models[0]; - if (!llm) { - // Try to reload config - configHandler.reloadConfig(); - config = await configHandler.loadConfig(); - llm = config.models.find((llm) => llm.title === title); - if (!llm) { - throw new Error(`Unknown model ${title}`); - } - } - - return setupLlm(llm); -} - -export class TabAutocompleteModel { - private static _llm: ILLM | undefined; - private static defaultTag: string = "deepseek-coder:1.3b-base"; - - private static shownOllamaWarning: boolean = false; - private static shownDeepseekWarning: boolean = false; - - static clearLlm() { - TabAutocompleteModel._llm = undefined; - } - - static async getDefaultTabAutocompleteModel() { - const llm = new Ollama({ - model: TabAutocompleteModel.defaultTag, - }); - - // Check that deepseek is already downloaded - try { - const models = await llm.listModels(); - if (!models.includes(TabAutocompleteModel.defaultTag)) { - // Raise warning and explain how to download - if (!TabAutocompleteModel.shownDeepseekWarning) { - vscode.window - .showWarningMessage( - `Your local Ollama instance doesn't yet have DeepSeek Coder. To download this model, run \`ollama run deepseek-coder:1.3b-base\` (recommended). If you'd like to use a custom model for tab autocomplete, learn more in the docs`, - "Documentation", - "Copy Command" - ) - .then((value) => { - if (value === "Documentation") { - vscode.env.openExternal( - vscode.Uri.parse( - "https://continue.dev/docs/walkthroughs/tab-autocomplete" - ) - ); - } else if (value === "Copy Command") { - vscode.env.clipboard.writeText( - "ollama run deepseek-coder:1.3b-base" - ); - } - }); - TabAutocompleteModel.shownDeepseekWarning = true; - } - return undefined; - } - } catch (e) { - if (!TabAutocompleteModel.shownOllamaWarning) { - vscode.window - .showWarningMessage( - "Continue failed to connect to Ollama, which is used by default for tab-autocomplete. If you haven't downloaded it yet, you can do so at https://ollama.ai (recommended). If you'd like to use a custom model for tab autocomplete, learn more in the docs", - "Documentation" - ) - .then((value) => { - if (value === "Documentation") { - vscode.env.openExternal( - vscode.Uri.parse( - "https://continue.dev/docs/walkthroughs/tab-autocomplete" - ) - ); - } - }); - TabAutocompleteModel.shownOllamaWarning = true; - } - return undefined; - } - - return llm; - } - - static async get() { - if (!TabAutocompleteModel._llm) { - const config = await configHandler.loadConfig(); - if (config.tabAutocompleteModel) { - TabAutocompleteModel._llm = setupLlm(config.tabAutocompleteModel); - } else { - TabAutocompleteModel._llm = - await TabAutocompleteModel.getDefaultTabAutocompleteModel(); - } - } - - return TabAutocompleteModel._llm; - } -} diff --git a/extensions/vscode/src/suggestions.ts b/extensions/vscode/src/suggestions.ts index b5be341dd..e13cb42b4 100644 --- a/extensions/vscode/src/suggestions.ts +++ b/extensions/vscode/src/suggestions.ts @@ -1,8 +1,5 @@ import * as vscode from "vscode"; -import { openEditorAndRevealRange } from "./util/vscode"; -import { translate } from "./util/vscode"; -import { registerAllCodeLensProviders } from "./lang-server/codeLens"; -import { extensionContext, ideProtocolClient } from "./activation/activate"; +import { openEditorAndRevealRange, translate } from "./util/vscode"; export interface SuggestionRanges { oldRange: vscode.Range; @@ -125,9 +122,9 @@ export function rerenderDecorations(editorUri: string) { vscode.TextEditorRevealType.Default ); - if (extensionContext) { - registerAllCodeLensProviders(extensionContext); - } + // if (extensionContext) { + // registerAllCodeLensProviders(extensionContext); + // } } export function suggestionDownCommand() { diff --git a/extensions/vscode/src/continueIdeClient.ts b/extensions/vscode/src/util/ideUtils.ts similarity index 74% rename from extensions/vscode/src/continueIdeClient.ts rename to extensions/vscode/src/util/ideUtils.ts index dda054467..15f51fb7c 100644 --- a/extensions/vscode/src/continueIdeClient.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -1,104 +1,24 @@ import { FileEdit, RangeInFile } from "core"; -import { getDevDataFilePath } from "core/util/paths"; -import { writeFileSync } from "fs"; -import * as path from "path"; +import path from "path"; import * as vscode from "vscode"; -import { extensionContext } from "./activation/activate"; -import { debugPanelWebview, getSidebarContent } from "./debugPanel"; -import { diffManager } from "./diff/horizontal"; -import { TabAutocompleteModel, configHandler } from "./loadConfig"; +import { VsCodeExtension } from "../extension/vscodeExtension"; import { SuggestionRanges, acceptSuggestionCommand, editorSuggestionsLocked, rejectSuggestionCommand, showSuggestion as showSuggestionInEditor, -} from "./suggestions"; -import { vsCodeIndexCodebase } from "./util/indexCodebase"; -import { defaultIgnoreFile, traverseDirectory } from "./util/traverseDirectory"; +} from "../suggestions"; +import { defaultIgnoreFile, traverseDirectory } from "./traverseDirectory"; import { getUniqueId, openEditorAndRevealRange, uriFromFilePath, -} from "./util/vscode"; +} from "./vscode"; const util = require("util"); -const exec = util.promisify(require("child_process").exec); - -const continueVirtualDocumentScheme = "continue"; - -class IdeProtocolClient { - private static PREVIOUS_BRANCH_FOR_WORKSPACE_DIR: { [dir: string]: string } = - {}; - - constructor(context: vscode.ExtensionContext) { - // Listen for file saving - vscode.workspace.onDidSaveTextDocument((event) => { - const filepath = event.uri.fsPath; - - if ( - filepath.endsWith(".continue/config.json") || - filepath.endsWith(".continue\\config.json") || - filepath.endsWith(".continue/config.ts") || - filepath.endsWith(".continue\\config.ts") || - filepath.endsWith(".continuerc.json") - ) { - configHandler.reloadConfig(); - TabAutocompleteModel.clearLlm(); - } else if ( - filepath.endsWith(".continueignore") || - filepath.endsWith(".gitignore") - ) { - debugPanelWebview?.postMessage({ - type: "updateEmbeddings", - }); - } - }); - - // Refresh index when branch is changed - this.getWorkspaceDirectories().forEach(async (dir) => { - const repo = await this.getRepo(vscode.Uri.file(dir)); - if (repo) { - repo.state.onDidChange(() => { - // args passed to this callback are always undefined, so keep track of previous branch - const currentBranch = repo?.state?.HEAD?.name; - if (currentBranch) { - if (IdeProtocolClient.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir]) { - if ( - currentBranch !== - IdeProtocolClient.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] - ) { - // Trigger refresh of index only in this directory - vsCodeIndexCodebase([dir]); - } - } - - IdeProtocolClient.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] = - currentBranch; - } - }); - } - }); - - // Register a content provider for the readonly virtual documents - const documentContentProvider = new (class - implements vscode.TextDocumentContentProvider - { - // emitter and its event - onDidChangeEmitter = new vscode.EventEmitter(); - onDidChange = this.onDidChangeEmitter.event; - - provideTextDocumentContent(uri: vscode.Uri): string { - return uri.query; - } - })(); - context.subscriptions.push( - vscode.workspace.registerTextDocumentContentProvider( - continueVirtualDocumentScheme, - documentContentProvider - ) - ); - } +const asyncExec = util.promisify(require("child_process").exec); +export class VsCodeIdeUtils { visibleMessages: Set = new Set(); async gotoDefinition( @@ -207,10 +127,6 @@ class IdeProtocolClient { ); } - async showDiff(filepath: string, replacement: string, step_index: number) { - await diffManager.writeDiff(filepath, replacement, step_index); - } - showMultiFileEdit(edits: FileEdit[]) { vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar"); const panel = vscode.window.createWebviewPanel( @@ -218,12 +134,13 @@ class IdeProtocolClient { "Continue", vscode.ViewColumn.One ); - panel.webview.html = getSidebarContent( - extensionContext, - panel, - "/monaco", - edits - ); + // panel.webview.html = this.sidebar.getSidebarContent( + // extensionContext, + // panel, + // this.ide, + // "/monaco", + // edits + // ); } openFile(filepath: string, range?: vscode.Range) { @@ -244,9 +161,9 @@ class IdeProtocolClient { vscode.workspace .openTextDocument( vscode.Uri.parse( - `${continueVirtualDocumentScheme}:${encodeURIComponent( - name - )}?${encodeURIComponent(contents)}` + `${ + VsCodeExtension.continueVirtualDocumentScheme + }:${encodeURIComponent(name)}?${encodeURIComponent(contents)}` ) ) .then((doc) => { @@ -485,7 +402,7 @@ class IdeProtocolClient { let repo = await this.getRepo(forDirectory); if (repo?.state?.HEAD?.name === undefined) { try { - const { stdout } = await exec("git rev-parse --abbrev-ref HEAD", { + const { stdout } = await asyncExec("git rev-parse --abbrev-ref HEAD", { cwd: forDirectory.fsPath, }); return stdout?.trim() || "NONE"; @@ -538,30 +455,4 @@ class IdeProtocolClient { }); return rangeInFiles; } - - async runCommand(command: string) { - if (vscode.window.terminals.length) { - vscode.window.terminals[0].show(); - vscode.window.terminals[0].sendText(command, false); - } else { - const terminal = vscode.window.createTerminal(); - terminal.show(); - terminal.sendText(command, false); - } - } - - sendMainUserInput(input: string) { - debugPanelWebview?.postMessage({ - type: "userInput", - input, - }); - } - - logDevData(tableName: string, data: any) { - const filepath: string = getDevDataFilePath(tableName); - const jsonLine = JSON.stringify(data); - writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" }); - } } - -export default IdeProtocolClient; diff --git a/extensions/vscode/src/util/indexCodebase.ts b/extensions/vscode/src/util/indexCodebase.ts deleted file mode 100644 index 50d541c1f..000000000 --- a/extensions/vscode/src/util/indexCodebase.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { FullTextSearchCodebaseIndex } from "core/indexing/FullTextSearch"; -import { LanceDbIndex } from "core/indexing/LanceDbIndex"; -import { ChunkCodebaseIndex } from "core/indexing/chunk/ChunkCodebaseIndex"; -import { getComputeDeleteAddRemove } from "core/indexing/refreshIndex"; -import { CodebaseIndex, IndexTag, LastModifiedMap } from "core/indexing/types"; -import * as vscode from "vscode"; -import { ideProtocolClient } from "../activation/activate"; -import { debugPanelWebview } from "../debugPanel"; -import { VsCodeIde } from "../ideProtocol"; -import { configHandler } from "../loadConfig"; - -const vscodeGetStats = async ( - directory: string | undefined -): Promise => { - const files = await new VsCodeIde().listWorkspaceContents(directory); - const pathToLastModified: { [path: string]: number } = {}; - await Promise.all( - files.map(async (file) => { - let stat = await vscode.workspace.fs.stat(vscode.Uri.file(file)); - pathToLastModified[file] = stat.mtime; - }) - ); - - return pathToLastModified; -}; - -async function getIndexesToBuild(): Promise { - const ide = new VsCodeIde(); - const config = await configHandler.loadConfig(); - - const indexes = [ - new ChunkCodebaseIndex(ide.readFile), // Chunking must come first - new LanceDbIndex(config.embeddingsProvider, ide.readFile), - new FullTextSearchCodebaseIndex(), - ]; - - return indexes; -} - -export async function vsCodeIndexCodebase(workspaceDirs: string[]) { - const update = (progress: number, desc: string) => { - debugPanelWebview?.postMessage({ type: "indexProgress", progress, desc }); - }; - - const config = await configHandler.loadConfig(); - if (config.disableIndexing) { - return; - } - - const indexesToBuild = await getIndexesToBuild(); - - let completedDirs = 0; - - for (let directory of workspaceDirs) { - const stats = await vscodeGetStats(directory); - const branch = await ideProtocolClient.getBranch( - vscode.Uri.file(directory) - ); - let completedIndexes = 0; - - try { - for (let codebaseIndex of indexesToBuild) { - const tag: IndexTag = { - directory, - branch, - artifactId: codebaseIndex.artifactId, - }; - const [results, markComplete] = await getComputeDeleteAddRemove( - tag, - { ...stats }, - (filepath) => ideProtocolClient.readFile(filepath) - ); - - for await (let { progress, desc } of codebaseIndex.update( - tag, - results, - markComplete - )) { - update( - (completedDirs + - (completedIndexes + progress) / indexesToBuild.length) / - workspaceDirs.length, - desc - ); - } - completedIndexes++; - update( - (completedDirs + completedIndexes / indexesToBuild.length) / - workspaceDirs.length, - "Completed indexing " + codebaseIndex.artifactId - ); - } - } catch (e) { - console.warn("Error refreshing index: ", e); - } - - completedDirs++; - update(completedDirs / workspaceDirs.length, "Indexing Complete"); - } -} diff --git a/extensions/vscode/src/util/loadAutocompleteModel.ts b/extensions/vscode/src/util/loadAutocompleteModel.ts new file mode 100644 index 000000000..a720cad51 --- /dev/null +++ b/extensions/vscode/src/util/loadAutocompleteModel.ts @@ -0,0 +1,90 @@ +import { ILLM } from "core"; +import { ConfigHandler } from "core/config/handler"; +import Ollama from "core/llm/llms/Ollama"; +import * as vscode from "vscode"; + +export class TabAutocompleteModel { + private _llm: ILLM | undefined; + private defaultTag: string = "starcoder:3b"; + private defaultTagName: string = "Starcoder 3b"; + + private shownOllamaWarning: boolean = false; + private shownDeepseekWarning: boolean = false; + + private configHandler: ConfigHandler; + + constructor(configHandler: ConfigHandler) { + this.configHandler = configHandler; + } + + clearLlm() { + this._llm = undefined; + } + + async getDefaultTabAutocompleteModel() { + const llm = new Ollama({ + model: this.defaultTag, + }); + + try { + const models = await llm.listModels(); + if (!models.includes(this.defaultTag)) { + if (!this.shownDeepseekWarning) { + vscode.window + .showWarningMessage( + `Your local Ollama instance doesn't yet have ${this.defaultTagName}. To download this model, run \`ollama run ${this.defaultTag}\` (recommended). If you'd like to use a custom model for tab autocomplete, learn more in the docs`, + "Documentation", + "Copy Command" + ) + .then((value) => { + if (value === "Documentation") { + vscode.env.openExternal( + vscode.Uri.parse( + "https://continue.dev/docs/walkthroughs/tab-autocomplete" + ) + ); + } else if (value === "Copy Command") { + vscode.env.clipboard.writeText(`ollama run ${this.defaultTag}`); + } + }); + this.shownDeepseekWarning = true; + } + return undefined; + } + } catch (e) { + if (!this.shownOllamaWarning) { + vscode.window + .showWarningMessage( + "Continue failed to connect to Ollama, which is used by default for tab-autocomplete. If you haven't downloaded it yet, you can do so at https://ollama.ai (recommended). If you'd like to use a custom model for tab autocomplete, learn more in the docs", + "Documentation" + ) + .then((value) => { + if (value === "Documentation") { + vscode.env.openExternal( + vscode.Uri.parse( + "https://continue.dev/docs/walkthroughs/tab-autocomplete" + ) + ); + } + }); + this.shownOllamaWarning = true; + } + return undefined; + } + + return llm; + } + + async get() { + if (!this._llm) { + const config = await this.configHandler.loadConfig(); + if (config.tabAutocompleteModel) { + this._llm = this.configHandler.setupLlm(config.tabAutocompleteModel); + } else { + this._llm = await this.getDefaultTabAutocompleteModel(); + } + } + + return this._llm; + } +} diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts new file mode 100644 index 000000000..1ff475435 --- /dev/null +++ b/extensions/vscode/src/webviewProtocol.ts @@ -0,0 +1,490 @@ +import { ContextItemId, IDE } from "core"; +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 { logDevData } from "core/util/devdata"; +import historyManager from "core/util/history"; +import { Message } from "core/util/messenger"; +import { getConfigJsonPath } from "core/util/paths"; +import { WebviewProtocol } from "core/web/webviewProtocol"; +import { v4 as uuidv4 } from "uuid"; +import * as vscode from "vscode"; +import { Webview } from "vscode"; +import { showTutorial } from "./activation/activate"; +import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager"; + +export class VsCodeWebviewProtocol { + listeners = new Map any)[]>(); + abortedMessageIds: Set = new Set(); + + private send(messageType: string, message: any, messageId?: string): string { + const id = messageId || uuidv4(); + this.webview.postMessage({ + type: messageType, + message, + messageId: messageId || id, + }); + return id; + } + + private on( + messageType: T, + handler: (message: Message) => WebviewProtocol[T][1] + ): void { + if (!this.listeners.has(messageType)) { + this.listeners.set(messageType, []); + } + this.listeners.get(messageType)?.push(handler); + } + + constructor( + private readonly webview: Webview, + private readonly ide: IDE, + private readonly configHandler: ConfigHandler, + private readonly verticalDiffManager: VerticalPerLineDiffManager + ) { + webview.onDidReceiveMessage(async (msg) => { + if (!msg.messageType || !msg.messageId) { + throw new Error("Invalid webview protocol msg: " + JSON.stringify(msg)); + } + + const respond = (message: any) => + this.send(msg.messageType, message, msg.messageId); + + const handlers = this.listeners.get(msg.messageType) || []; + for (const handler of handlers) { + try { + const response = await handler(msg); + respond(response || {}); + } catch (e: any) { + console.error( + "Error handling webview message: " + + JSON.stringify({ msg }, null, 2) + ); + + let message = `Continue error: ${e.message}`; + if (e.cause) { + if (e.cause.name === "ConnectTimeoutError") { + message = `Connection timed out. If you expect it to take a long time to connect, you can increase the timeout in config.json by setting "requestOptions": { "timeout": 10000 }. You can find the full config reference here: https://continue.dev/docs/reference/config`; + } else if (e.cause.code === "ECONNREFUSED") { + message = `Connection was refused. This likely means that there is no server running at the specified URL. If you are running your own server you may need to set the "apiBase" parameter in config.json. For example, you can set up an OpenAI-compatible server like here: https://continue.dev/docs/reference/Model%20Providers/openai#openai-compatible-servers--apis`; + } else { + message = `The request failed with "${e.cause.name}": ${e.cause.message}. If you're having trouble setting up Continue, please see the troubleshooting guide for help.`; + } + } + + vscode.window + .showErrorMessage(message, "Show Logs", "Troubleshooting") + .then((selection) => { + if (selection === "Show Logs") { + vscode.commands.executeCommand( + "workbench.action.toggleDevTools" + ); + } else if (selection === "Troubleshooting") { + vscode.env.openExternal( + vscode.Uri.parse("https://continue.dev/docs/troubleshooting") + ); + } + }); + } + } + respond({ done: true, data: {} }); + }); + + this.on("abort", (msg) => { + this.abortedMessageIds.add(msg.messageId); + }); + this.on("showFile", (msg) => { + this.ide.openFile(msg.data.filepath); + }); + this.on("openConfigJson", (msg) => { + this.ide.openFile(getConfigJsonPath()); + }); + this.on("readRangeInFile", (msg) => { + vscode.workspace.openTextDocument(msg.data.filepath).then((document) => { + let start = new vscode.Position(0, 0); + let end = new vscode.Position(5, 0); + let range = new vscode.Range(start, end); + + let contents = document.getText(range); + return contents; + }); + }); + this.on("toggleDevTools", (msg) => { + vscode.commands.executeCommand("workbench.action.toggleDevTools"); + vscode.commands.executeCommand("continue.viewLogs"); + }); + this.on("reloadWindow", (msg) => { + vscode.commands.executeCommand("workbench.action.reloadWindow"); + }); + this.on("focusEditor", (msg) => { + vscode.commands.executeCommand("workbench.action.focusActiveEditorGroup"); + }); + this.on("toggleFullScreen", (msg) => { + vscode.commands.executeCommand("continue.toggleFullScreen"); + }); + + // IDE + this.on("getDiff", async (msg) => { + return await ide.getDiff(); + }); + this.on("getSerializedConfig", async (msg) => { + return await configHandler.getSerializedConfig(); + }); + this.on("getTerminalContents", async (msg) => { + return await ide.getTerminalContents(); + }); + this.on("listWorkspaceContents", async (msg) => { + return await ide.listWorkspaceContents(); + }); + this.on("getWorkspaceDirs", async (msg) => { + return await ide.getWorkspaceDirs(); + }); + this.on("listFolders", async (msg) => { + return await ide.listFolders(); + }); + this.on("writeFile", async (msg) => { + return await ide.writeFile(msg.data.path, msg.data.contents); + }); + this.on("showVirtualFile", async (msg) => { + return await ide.showVirtualFile(msg.data.name, msg.data.content); + }); + this.on("getContinueDir", async (msg) => { + return await ide.getContinueDir(); + }); + this.on("openFile", async (msg) => { + return await ide.openFile(msg.data.path); + }); + this.on("runCommand", async (msg) => { + await ide.runCommand(msg.data.command); + }); + this.on("getSearchResults", async (msg) => { + return await ide.getSearchResults(msg.data.query); + }); + this.on("subprocess", async (msg) => { + return await ide.subprocess(msg.data.command); + }); + // History + this.on("history", (msg) => { + return historyManager.list(); + }); + this.on("saveSession", (msg) => { + historyManager.save(msg.data); + return {}; + }); + this.on("deleteSession", (msg) => { + historyManager.delete(msg.data); + return {}; + }); + this.on("loadSession", (msg) => { + return historyManager.load(msg.data); + }); + this.on("saveFile", async (msg) => { + return await ide.saveFile(msg.data.filepath); + }); + this.on("readFile", async (msg) => { + return await ide.readFile(msg.data.filepath); + }); + this.on("showDiff", async (msg) => { + return await ide.showDiff( + msg.data.filepath, + msg.data.newContents, + msg.data.stepIndex + ); + }); + + this.on("getProblems", async (msg) => { + return await ide.getProblems(msg.data.filepath); + }); + this.on("getBranch", async (msg) => { + const { dir } = msg.data; + return await ide.getBranch(dir); + }); + this.on("getOpenFiles", async (msg) => { + return await ide.getOpenFiles(); + }); + this.on("getPinnedFiles", async (msg) => { + return await ide.getPinnedFiles(); + }); + this.on("showLines", async (msg) => { + const { filepath, startLine, endLine } = msg.data; + return await ide.showLines(filepath, startLine, endLine); + }); + // Other + this.on("errorPopup", (msg) => { + vscode.window + .showErrorMessage(msg.data.message, "Show Logs") + .then((selection) => { + if (selection === "Show Logs") { + vscode.commands.executeCommand("workbench.action.toggleDevTools"); + } + }); + }); + this.on("logDevData", (msg) => { + logDevData(msg.data.tableName, msg.data.data); + }); + this.on("addModel", (msg) => { + const model = msg.data; + const newConfigString = addModel(model); + this.configHandler.reloadConfig(); + this.ide.openFile(getConfigJsonPath()); + + // Find the range where it was added and highlight + let lines = newConfigString.split("\n"); + let startLine; + let endLine; + for (let i = 0; i < lines.length; i++) { + let line = lines[i]; + + if (!startLine) { + if (line.trim() === `"title": "${model.title}",`) { + startLine = i - 1; + } + } else { + if (line.startsWith(" }")) { + endLine = i; + break; + } + } + } + + if (startLine && endLine) { + this.ide.showLines( + getConfigJsonPath(), + startLine, + endLine + // "#fff1" + ); + } + vscode.window.showInformationMessage( + "🎉 Your model has been successfully added to config.json. You can use this file to further edit its configuration." + ); + }); + this.on("deleteModel", (msg) => { + deleteModel(msg.data.title); + this.configHandler.reloadConfig(); + }); + this.on("addOpenAIKey", async (msg) => { + addOpenAIKey(msg.data.key); + this.configHandler.reloadConfig(); + }); + + async function* llmStreamComplete( + protocol: VsCodeWebviewProtocol, + msg: Message + ) { + const model = await protocol.configHandler.llmFromTitle(msg.data.title); + const gen = model.streamComplete( + msg.data.prompt, + msg.data.completionOptions + ); + let next = await gen.next(); + while (!next.done) { + if (protocol.abortedMessageIds.has(msg.messageId)) { + protocol.abortedMessageIds.delete(msg.messageId); + next = await gen.return({ completion: "", prompt: "" }); + break; + } + yield { content: next.value }; + next = await gen.next(); + } + + return { done: true, content: next.value }; + } + this.on("llmStreamComplete", (msg) => llmStreamComplete(this, msg)); + + async function* llmStreamChat( + protocol: VsCodeWebviewProtocol, + msg: Message + ) { + const model = await protocol.configHandler.llmFromTitle(msg.data.title); + const gen = model.streamChat( + msg.data.messages, + msg.data.completionOptions + ); + let next = await gen.next(); + while (!next.done) { + if (protocol.abortedMessageIds.has(msg.messageId)) { + protocol.abortedMessageIds.delete(msg.messageId); + next = await gen.return({ completion: "", prompt: "" }); + break; + } + yield { content: next.value.content }; + next = await gen.next(); + } + + return { done: true, content: next.value }; + } + this.on("llmStreamChat", (msg) => llmStreamChat(this, msg)); + this.on("llmComplete", async (msg) => { + const model = await this.configHandler.llmFromTitle(msg.data.title); + const completion = await model.complete( + msg.data.prompt, + msg.data.completionOptions + ); + return { content: completion }; + }); + + async function* runNodeJsSlashCommand( + protocol: VsCodeWebviewProtocol, + msg: Message + ) { + const { + input, + history, + modelTitle, + slashCommandName, + contextItems, + params, + historyIndex, + } = msg.data; + + const config = await protocol.configHandler.loadConfig(); + const llm = await protocol.configHandler.llmFromTitle(modelTitle); + const slashCommand = config.slashCommands?.find( + (sc) => sc.name === slashCommandName + ); + if (!slashCommand) { + throw new Error(`Unknown slash command ${slashCommandName}`); + } + + for await (const content of slashCommand.run({ + input, + history, + llm, + contextItems, + params, + ide, + addContextItem: (item) => { + protocol.webview?.postMessage({ + type: "addContextItem", + message: { item, historyIndex }, + }); + }, + })) { + if (content) { + yield { content }; + } + } + yield { done: true, content: "" }; + } + this.on("runNodeJsSlashCommand", (msg) => runNodeJsSlashCommand(this, msg)); + + this.on("loadSubmenuItems", async (msg) => { + const { title } = msg.data; + const config = await this.configHandler.loadConfig(); + const provider = config.contextProviders?.find( + (p) => p.description.title === title + ); + if (!provider) { + vscode.window.showErrorMessage( + `Unknown provider ${title}. Existing providers: ${config.contextProviders + ?.map((p) => p.description.title) + .join(", ")}` + ); + return []; + } + + try { + const items = await provider.loadSubmenuItems({ ide }); + return items; + } catch (e) { + vscode.window.showErrorMessage( + `Error loading submenu items from ${title}: ${e}` + ); + return []; + } + }); + + this.on("getContextItems", async (msg) => { + const { name, query, fullInput, selectedCode } = msg.data; + const config = await this.configHandler.loadConfig(); + const llm = await this.configHandler.llmFromTitle(); + const provider = config.contextProviders?.find( + (p) => p.description.title === name + ); + if (!provider) { + vscode.window.showErrorMessage( + `Unknown provider ${name}. Existing providers: ${config.contextProviders + ?.map((p) => p.description.title) + .join(", ")}` + ); + return []; + } + + try { + const id: ContextItemId = { + providerTitle: provider.description.title, + itemId: uuidv4(), + }; + const items = await provider.getContextItems(query, { + llm, + embeddingsProvider: config.embeddingsProvider, + fullInput, + ide, + selectedCode, + }); + return items.map((item) => ({ ...item, id })); + } catch (e) { + vscode.window.showErrorMessage( + `Error getting context items from ${name}: ${e}` + ); + return []; + } + }); + this.on("addDocs", (msg) => { + const { url, title } = msg.data; + const embeddingsProvider = new TransformersJsEmbeddingsProvider(); + vscode.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + title: `Indexing ${title}`, + cancellable: false, + }, + async (progress) => { + for await (const update of indexDocs( + title, + new URL(url), + embeddingsProvider + )) { + progress.report({ + increment: update.progress, + message: update.desc, + }); + } + + vscode.window.showInformationMessage( + `🎉 Successfully indexed ${title}` + ); + + this.webview?.postMessage({ + type: "refreshSubmenuItems", + }); + } + ); + }); + this.on("applyToCurrentFile", (msg) => { + // Select the entire current file + const editor = vscode.window.activeTextEditor; + if (!editor) { + vscode.window.showErrorMessage("No active editor to apply edits to"); + return; + } + const document = editor.document; + const start = new vscode.Position(0, 0); + const end = new vscode.Position( + document.lineCount - 1, + document.lineAt(document.lineCount - 1).text.length + ); + editor.selection = new vscode.Selection(start, end); + + this.verticalDiffManager.streamEdit( + `The following code was suggested as an edit:\n\`\`\`\n${msg.data.text}\n\`\`\`\nPlease apply it to the previous code.` + ); + }); + this.on("showTutorial", (msg) => { + showTutorial(); + }); + } +} diff --git a/extensions/vscode/yarn.lock b/extensions/vscode/yarn.lock index 91fe0f08c..5c9af9f54 100644 --- a/extensions/vscode/yarn.lock +++ b/extensions/vscode/yarn.lock @@ -696,7 +696,12 @@ resolved "https://registry.npmjs.org/@jsdevtools/ono/-/ono-7.1.3.tgz" integrity sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg== -"@lancedb/vectordb-darwin-arm64@*", "@lancedb/vectordb-darwin-arm64@0.4.8": +"@lancedb/vectordb-darwin-arm64@*": + version "0.4.9" + resolved "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.9.tgz" + integrity sha512-u56TXU0hvdLbknGwC7Ebza3/CUFeCTkoCy/sC6h0FtOGya+NV7jraAeXEwDzoZbfW08VYYxnp3TsCcpNU9lpTA== + +"@lancedb/vectordb-darwin-arm64@0.4.8": version "0.4.8" resolved "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.8.tgz" integrity sha512-FpnJaw7KmNdD/FtOw9AcmPL5P+L04AcnfPj9ZyEjN8iCwB/qaOGYgdfBv+EbEtfHIsqA12q/1BRduu9KdB6BIA== @@ -2315,9 +2320,13 @@ core-util-is@1.0.2: "@types/node-fetch" "^2.6.11" "@xenova/transformers" "^2.14.0" cheerio "^1.0.0-rc.12" + commander "^12.0.0" dotenv "^16.3.1" fastest-levenshtein "^1.0.16" + follow-redirects "^1.15.5" handlebars "^4.7.8" + http-proxy-agent "^7.0.1" + https-proxy-agent "^7.0.3" js-tiktoken "^1.0.8" llm-code-highlighter "^0.0.5" node-fetch "^3.3.2" diff --git a/gui/package-lock.json b/gui/package-lock.json index 2f544738a..84788575a 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -77,9 +77,13 @@ "@types/node-fetch": "^2.6.11", "@xenova/transformers": "^2.14.0", "cheerio": "^1.0.0-rc.12", + "commander": "^12.0.0", "dotenv": "^16.3.1", "fastest-levenshtein": "^1.0.16", + "follow-redirects": "^1.15.5", "handlebars": "^4.7.8", + "http-proxy-agent": "^7.0.1", + "https-proxy-agent": "^7.0.3", "js-tiktoken": "^1.0.8", "llm-code-highlighter": "^0.0.5", "node-fetch": "^3.3.2", @@ -97,6 +101,7 @@ "web-tree-sitter": "^0.20.8" }, "devDependencies": { + "@types/follow-redirects": "^1.14.4", "@types/handlebars": "^4.1.0", "@types/jest": "^29.5.11", "@types/jquery": "^3.5.29", diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index b91a9bf4a..da972b54c 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -3,7 +3,7 @@ import { useEffect } from "react"; import { setServerStatusMessage } from "../redux/slices/miscSlice"; import { isJetBrains, postToIde } from "../util/ide"; -import { ExtensionIde } from "core/ide/index"; +import { ideRequest } from "core/ide/messaging"; import { useSelector } from "react-redux"; import { VSC_THEME_COLOR_VARS } from "../components"; import { setVscMachineId } from "../redux/slices/configSlice"; @@ -17,7 +17,8 @@ import useChatHandler from "./useChatHandler"; function useSetup(dispatch: Dispatch) { const loadConfig = async () => { - dispatch(setConfig(await new ExtensionIde().getSerializedConfig())); + const config = await ideRequest("getSerializedConfig", {}); + dispatch(setConfig(config)); }; // Load config from the IDE diff --git a/gui/src/util/ide.ts b/gui/src/util/ide.ts index 5f8fd4393..4bbca782a 100644 --- a/gui/src/util/ide.ts +++ b/gui/src/util/ide.ts @@ -55,13 +55,6 @@ export async function ideRequest(type: string, data: any): Promise { }); } -export async function withProgress(title: string, fn: () => Promise) { - postToIde("withProgress", { title, done: false }); - return fn().finally(() => { - postToIde("withProgress", { title, done: true }); - }); -} - export function errorPopup(message: string) { postToIde("errorPopup", { message }); } From 7e314df38035eff20110f596baef6b68eb8baee9 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 14 Feb 2024 16:49:00 -0800 Subject: [PATCH 06/59] =?UTF-8?q?=F0=9F=9A=A7=20reverse=20webview=20protoc?= =?UTF-8?q?ol?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/indexing/indexCodebase.ts | 5 +- core/ipc/messenger.ts | 3 +- core/util/history.ts | 2 +- core/web/message.ts | 137 -------------- core/web/webviewProtocol.ts | 102 ++++++++--- extensions/vscode/src/commands.ts | 55 +++--- extensions/vscode/src/debugPanel.ts | 5 +- extensions/vscode/src/diff/horizontal.ts | 14 +- .../vscode/src/extension/vscodeExtension.ts | 42 +++-- extensions/vscode/src/webviewProtocol.ts | 64 ++++--- gui/src/components/Layout.tsx | 56 +++--- gui/src/components/dialogs/AddDocsDialog.tsx | 2 +- .../components/mainInput/ContextItemsPeek.tsx | 8 +- .../components/mainInput/ContinueInputBox.tsx | 20 +-- gui/src/components/mainInput/TipTapEditor.tsx | 170 +++++++++++------- gui/src/components/mainInput/resolveInput.ts | 11 +- .../components/markdown/CodeBlockToolbar.tsx | 2 +- .../markdown/CodeSnippetPreview.tsx | 4 +- gui/src/hooks/useChatHandler.ts | 3 +- gui/src/hooks/useHistory.tsx | 40 ++--- gui/src/hooks/useNavigationListener.tsx | 60 ++++--- gui/src/hooks/useSetup.ts | 85 ++++----- gui/src/hooks/useSubmenuContextProviders.tsx | 24 +-- gui/src/hooks/useVscTheme.ts | 19 +- gui/src/hooks/useWebviewListener.ts | 25 +++ gui/src/pages/gui.tsx | 21 +-- gui/src/pages/help.tsx | 6 +- gui/src/pages/history.tsx | 4 +- gui/src/pages/modelconfig.tsx | 9 +- gui/src/pages/models.tsx | 18 +- gui/src/pages/monaco.tsx | 5 +- gui/src/util/ide.ts | 141 +++++++++++++-- {core/web => gui/src/util}/webviewIde.ts | 38 ++-- 33 files changed, 627 insertions(+), 573 deletions(-) delete mode 100644 core/web/message.ts create mode 100644 gui/src/hooks/useWebviewListener.ts rename {core/web => gui/src/util}/webviewIde.ts (72%) diff --git a/core/indexing/indexCodebase.ts b/core/indexing/indexCodebase.ts index f4797b0b8..32c85f2b9 100644 --- a/core/indexing/indexCodebase.ts +++ b/core/indexing/indexCodebase.ts @@ -19,7 +19,10 @@ export class CodebaseIndexer { const indexes = [ new ChunkCodebaseIndex(this.ide.readFile.bind(this.ide)), // Chunking must come first - new LanceDbIndex(config.embeddingsProvider, this.ide.readFile), + new LanceDbIndex( + config.embeddingsProvider, + this.ide.readFile.bind(this.ide) + ), new FullTextSearchCodebaseIndex(), ]; diff --git a/core/ipc/messenger.ts b/core/ipc/messenger.ts index 54819140a..b2b851cdb 100644 --- a/core/ipc/messenger.ts +++ b/core/ipc/messenger.ts @@ -7,6 +7,7 @@ import { PersistedSessionInfo, RangeInFile, SerializedContinueConfig, + SessionInfo, } from ".."; import { Message } from "../util/messenger"; @@ -29,7 +30,7 @@ export type Protocol = { abort: [undefined, void]; // History - "history/list": [undefined, PersistedSessionInfo[]]; + "history/list": [undefined, SessionInfo[]]; "history/delete": [{ id: string }, void]; "history/load": [{ id: string }, PersistedSessionInfo]; "history/save": [PersistedSessionInfo, void]; diff --git a/core/util/history.ts b/core/util/history.ts index 777af8805..bab04c4f8 100644 --- a/core/util/history.ts +++ b/core/util/history.ts @@ -3,7 +3,7 @@ import { PersistedSessionInfo, SessionInfo } from ".."; import { getSessionFilePath, getSessionsListPath } from "./paths"; class HistoryManager { - list(): PersistedSessionInfo[] { + list(): SessionInfo[] { const filepath = getSessionsListPath(); if (!fs.existsSync(filepath)) { return []; diff --git a/core/web/message.ts b/core/web/message.ts deleted file mode 100644 index f0e9416cd..000000000 --- a/core/web/message.ts +++ /dev/null @@ -1,137 +0,0 @@ -import { v4 as uuidv4 } from "uuid"; -import { ChatMessage, LLMFullCompletionOptions, LLMReturnValue } from ".."; -interface vscode { - postMessage(message: any): vscode; -} - -declare const vscode: any; - -function _postToIde(type: string, data: any) { - if (typeof vscode === "undefined") { - if (localStorage.getItem("ide") === "jetbrains") { - if ((window as any).postIntellijMessage === undefined) { - console.log( - "Unable to send message: postIntellijMessage is undefined. ", - type, - data - ); - throw new Error("postIntellijMessage is undefined"); - } - (window as any).postIntellijMessage?.(type, data); - return; - } else { - console.log("Unable to send message: vscode is undefined. ", type, data); - return; - } - } - vscode.postMessage({ - type, - ...data, - }); -} - -export function postToIde(type: string, data: any, attempt: number = 0) { - try { - _postToIde(type, data); - } catch (error) { - if (attempt < 5) { - console.log(`Attempt ${attempt} failed. Retrying...`); - setTimeout( - () => postToIde(type, data, attempt + 1), - Math.pow(2, attempt) * 1000 - ); - } else { - console.error("Max attempts reached. Message could not be sent.", error); - } - } -} - -export async function ideRequest(type: string, message: any): Promise { - // message, messageId, and type are passed back and forth - const messageId = uuidv4(); - - return new Promise((resolve) => { - const handler = (event: any) => { - if (event.data.messageId === messageId) { - window.removeEventListener("message", handler); - resolve(event.data.message); - } - }; - window.addEventListener("message", handler); - - postToIde(type, { message, messageId }); - }); -} - -export async function* ideStreamRequest( - type: string, - message: any, - cancelToken?: AbortSignal -): AsyncGenerator { - const messageId = uuidv4(); - - postToIde(type, { message, messageId }); - - let buffer = ""; - let index = 0; - let done = false; - let returnVal = undefined; - - const handler = (event: any) => { - if (event.data.messageId === messageId) { - if (event.data.message.done) { - window.removeEventListener("message", handler); - done = true; - returnVal = event.data.message.data; - } else { - buffer += event.data.message.content; - } - } - }; - window.addEventListener("message", handler); - - cancelToken?.addEventListener("abort", () => { - postToIde("abort", { messageId }); - }); - - while (!done) { - if (buffer.length > index) { - const chunk = buffer.slice(index); - index = buffer.length; - yield chunk; - } - await new Promise((resolve) => setTimeout(resolve, 50)); - } - - if (buffer.length > index) { - const chunk = buffer.slice(index); - index = buffer.length; - yield chunk; - } - - return returnVal; -} - -export async function* llmStreamChat( - modelTitle: string, - cancelToken: AbortSignal | undefined, - messages: ChatMessage[], - options: LLMFullCompletionOptions = {} -): AsyncGenerator { - const gen = ideStreamRequest( - "llmStreamChat", - { - messages, - title: modelTitle, - completionOptions: options, - }, - cancelToken - ); - - let next = await gen.next(); - while (!next.done) { - yield { role: "user", content: next.value }; - next = await gen.next(); - } - return { prompt: next.value?.prompt, completion: next.value?.completion }; -} diff --git a/core/web/webviewProtocol.ts b/core/web/webviewProtocol.ts index c0bf50deb..cc005b7ef 100644 --- a/core/web/webviewProtocol.ts +++ b/core/web/webviewProtocol.ts @@ -1,36 +1,49 @@ import { ChatMessage, - CompletionOptions, - ContextItem, ContextItemWithId, ContextSubmenuItem, + ContinueRcJson, DiffLine, + LLMFullCompletionOptions, MessageContent, ModelDescription, PersistedSessionInfo, Problem, + Range, RangeInFile, + SessionInfo, } from ".."; +import { RangeInFileWithContents } from "../commands/util"; import { BrowserSerializedContinueConfig } from "../config/load"; export type WebviewProtocol = { - abort: [undefined, void]; - listWorkspaceContents: [undefined, Promise]; - getWorkspaceDirs: [undefined, Promise]; - listFolders: [undefined, Promise]; + abort: [string, void]; + onLoad: [ + undefined, + { + windowId: string; + serverUrl: string; + workspacePaths: string[]; + vscMachineId: string; + vscMediaUrl: string; + }, + ]; + listWorkspaceContents: [undefined, string[]]; + getWorkspaceDirs: [undefined, string[]]; + listFolders: [undefined, string[]]; writeFile: [{ path: string; contents: string }, void]; showVirtualFile: [{ name: string; content: string }, void]; - getContinueDir: [undefined, Promise]; + getContinueDir: [undefined, string]; openFile: [{ path: string }, void]; runCommand: [{ command: string }, void]; - getSearchResults: [{ query: string }, Promise]; - subprocess: [{ command: string }, Promise<[string, string]>]; - history: [undefined, PersistedSessionInfo[]]; + getSearchResults: [{ query: string }, string]; + subprocess: [{ command: string }, [string, string]]; + history: [undefined, SessionInfo[]]; saveSession: [PersistedSessionInfo, void]; deleteSession: [string, void]; loadSession: [string, PersistedSessionInfo]; saveFile: [{ filepath: string }, void]; - readFile: [{ filepath: string }, Promise]; + readFile: [{ filepath: string }, string]; showDiff: [ { filepath: string; newContents: string; stepIndex: number }, void, @@ -44,10 +57,10 @@ export type WebviewProtocol = { }, void, ]; - getProblems: [{ filepath: string }, Promise]; - getBranch: [{ dir: string }, Promise]; - getOpenFiles: [undefined, Promise]; - getPinnedFiles: [undefined, Promise]; + getProblems: [{ filepath: string }, Problem[]]; + getBranch: [{ dir: string }, string]; + getOpenFiles: [undefined, string[]]; + getPinnedFiles: [undefined, string[]]; showLines: [{ filepath: string; startLine: number; endLine: number }, void]; errorPopup: [{ message: string }, void]; logDevData: [{ tableName: string; data: any }, void]; @@ -55,20 +68,28 @@ export type WebviewProtocol = { deleteModel: [{ title: string }, void]; addOpenAIKey: [{ key: string }, void]; llmStreamComplete: [ - { title: string; prompt: string; completionOptions: CompletionOptions }, + { + title: string; + prompt: string; + completionOptions: LLMFullCompletionOptions; + }, AsyncGenerator<{ content: string; done?: boolean }>, ]; llmStreamChat: [ { title: string; messages: ChatMessage[]; - completionOptions: CompletionOptions; + completionOptions: LLMFullCompletionOptions; }, AsyncGenerator<{ content: MessageContent; done?: boolean }>, ]; llmComplete: [ - { title: string; prompt: string; completionOptions: CompletionOptions }, - Promise<{ content: string }>, + { + title: string; + prompt: string; + completionOptions: LLMFullCompletionOptions; + }, + { content: string }, ]; runNodeJsSlashCommand: [ { @@ -82,7 +103,7 @@ export type WebviewProtocol = { }, AsyncGenerator<{ content: string; done?: boolean }>, ]; - loadSubmenuItems: [{ title: string }, Promise]; + loadSubmenuItems: [{ title: string }, ContextSubmenuItem[]]; getContextItems: [ { name: string; @@ -90,19 +111,50 @@ export type WebviewProtocol = { fullInput: string; selectedCode: RangeInFile[]; }, - Promise, + ContextItemWithId[], ]; addDocs: [{ url: string; title: string }, void]; applyToCurrentFile: [{ text: string }, void]; showTutorial: [undefined, void]; showFile: [{ filepath: string }, void]; openConfigJson: [undefined, void]; - readRangeInFile: [{ filepath: string }, void]; + readRangeInFile: [{ filepath: string; range: Range }, string]; toggleDevTools: [undefined, void]; reloadWindow: [undefined, void]; focusEditor: [undefined, void]; toggleFullScreen: [undefined, void]; - getDiff: [undefined, Promise]; - getSerializedConfig: [undefined, Promise]; - getTerminalContents: [undefined, Promise]; + getDiff: [undefined, string]; + getSerializedConfig: [undefined, BrowserSerializedContinueConfig]; + getTerminalContents: [undefined, string]; + isTelemetryEnabled: [undefined, boolean]; + getUniqueId: [undefined, string]; + getWorkspaceConfigs: [undefined, ContinueRcJson[]]; + getDefaultModelTitle: [{ defaultModelTitle: string }, void]; +}; + +export type ReverseWebviewProtocol = { + setInactive: [undefined, void]; + configUpdate: [undefined, void]; + submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap + addContextItem: [ + { + historyIndex: number; + item: ContextItemWithId; + }, + void, + ]; + getDefaultModelTitle: [undefined, string]; + newSessionWithPrompt: [{ prompt: string }, void]; + userInput: [{ input: string }, void]; + focusContinueInput: [undefined, void]; + focusContinueInputWithoutClear: [undefined, void]; + focusContinueInputWithNewSession: [undefined, void]; + highlightedCode: [{ rangeInFileWithContents: RangeInFileWithContents }, void]; + addModel: [undefined, void]; + openSettings: [undefined, void]; + viewHistory: [undefined, void]; + indexProgress: [{ progress: number; desc: string }, void]; + newSession: [undefined, void]; + refreshSubmenuItems: [undefined, void]; + setTheme: [{ theme: any }, void]; }; diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index ab1f83e28..307d35dfb 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -10,10 +10,11 @@ import { ContinueGUIWebviewViewProvider } from "./debugPanel"; import { DiffManager } from "./diff/horizontal"; import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager"; import { AutocompleteOutcome } from "./lang-server/completionProvider"; +import { VsCodeWebviewProtocol } from "./webviewProtocol"; function addHighlightedCodeToContext( edit: boolean, - webview: vscode.Webview | undefined + webviewProtocol: VsCodeWebviewProtocol | undefined ) { const editor = vscode.window.activeTextEditor; if (editor) { @@ -36,10 +37,8 @@ function addHighlightedCodeToContext( }, }; - webview?.postMessage({ - type: "highlightedCode", + webviewProtocol?.request("highlightedCode", { rangeInFileWithContents, - edit, }); } } @@ -47,7 +46,7 @@ function addHighlightedCodeToContext( async function addEntireFileToContext( filepath: vscode.Uri, edit: boolean, - debugPanelWebview: vscode.Webview | undefined + webviewProtocol: VsCodeWebviewProtocol | undefined ) { // If a directory, add all files in the directory const stat = await vscode.workspace.fs.stat(filepath); @@ -58,7 +57,7 @@ async function addEntireFileToContext( addEntireFileToContext( vscode.Uri.joinPath(filepath, filename), edit, - debugPanelWebview + webviewProtocol ); } } @@ -82,10 +81,8 @@ async function addEntireFileToContext( }, }; - debugPanelWebview?.postMessage({ - type: "highlightedCode", + webviewProtocol?.request("highlightedCode", { rangeInFileWithContents, - edit, }); } @@ -126,29 +123,28 @@ const commandsMap: ( verticalDiffManager.acceptRejectVerticalDiffBlock(false, filepath, index); }, "continue.quickFix": async (message: string, code: string, edit: boolean) => { - sidebar.webview?.postMessage({ - type: "newSessionWithPrompt", + sidebar.webviewProtocol?.request("newSessionWithPrompt", { prompt: `${ edit ? "/edit " : "" }${code}\n\nHow do I fix this problem in the above code?: ${message}`, }); + if (!edit) { vscode.commands.executeCommand("continue.continueGUIView.focus"); } }, "continue.focusContinueInput": async () => { vscode.commands.executeCommand("continue.continueGUIView.focus"); - sidebar.webview?.postMessage({ - type: "focusContinueInput", - }); - addHighlightedCodeToContext(false, sidebar.webview); + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + addHighlightedCodeToContext(false, sidebar.webviewProtocol); }, "continue.focusContinueInputWithoutClear": async () => { vscode.commands.executeCommand("continue.continueGUIView.focus"); - sidebar.webview?.postMessage({ - type: "focusContinueInputWithoutClear", - }); - addHighlightedCodeToContext(true, sidebar.webview); + sidebar.webviewProtocol?.request( + "focusContinueInputWithoutClear", + undefined + ); + addHighlightedCodeToContext(true, sidebar.webviewProtocol); }, "continue.toggleAuxiliaryBar": () => { vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar"); @@ -267,8 +263,7 @@ const commandsMap: ( "continue.debugTerminal": async () => { const terminalContents = await ide.getTerminalContents(); vscode.commands.executeCommand("continue.continueGUIView.focus"); - sidebar.webview?.postMessage({ - type: "userInput", + sidebar.webviewProtocol?.request("userInput", { input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents}`, }); }, @@ -281,15 +276,11 @@ const commandsMap: ( // Commands without keyboard shortcuts "continue.addModel": () => { vscode.commands.executeCommand("continue.continueGUIView.focus"); - sidebar.webview?.postMessage({ - type: "addModel", - }); + sidebar.webviewProtocol?.request("addModel", undefined); }, "continue.openSettingsUI": () => { vscode.commands.executeCommand("continue.continueGUIView.focus"); - sidebar.webview?.postMessage({ - type: "openSettings", - }); + sidebar.webviewProtocol?.request("openSettings", undefined); }, "continue.sendMainUserInput": (text: string) => { sidebar.sendMainUserInput(text); @@ -323,14 +314,10 @@ const commandsMap: ( ide.runCommand(text); }, "continue.newSession": () => { - sidebar.webview?.postMessage({ - type: "newSession", - }); + sidebar.webviewProtocol?.request("newSession", undefined); }, "continue.viewHistory": () => { - sidebar.webview?.postMessage({ - type: "viewHistory", - }); + sidebar.webviewProtocol?.request("viewHistory", undefined); }, "continue.toggleFullScreen": () => { // Check if full screen is already open by checking open tabs @@ -392,7 +379,7 @@ const commandsMap: ( vscode.commands.executeCommand("continue.continueGUIView.focus"); for (const uri of uris) { - addEntireFileToContext(uri, false, sidebar.webview); + addEntireFileToContext(uri, false, sidebar.webviewProtocol); } }, "continue.updateAllReferences": (filepath: vscode.Uri) => { diff --git a/extensions/vscode/src/debugPanel.ts b/extensions/vscode/src/debugPanel.ts index 15e2c6cbe..16927c040 100644 --- a/extensions/vscode/src/debugPanel.ts +++ b/extensions/vscode/src/debugPanel.ts @@ -10,6 +10,7 @@ export class ContinueGUIWebviewViewProvider implements vscode.WebviewViewProvider { public static readonly viewType = "continue.continueGUIView"; + public webviewProtocol?: VsCodeWebviewProtocol; resolveWebviewView( webviewView: vscode.WebviewView, @@ -121,11 +122,11 @@ export class ContinueGUIWebviewViewProvider vscode.workspace.onDidChangeConfiguration((e) => { if (e.affectsConfiguration("workbench.colorTheme")) { // Send new theme to GUI to update embedded Monaco themes - this._webview?.postMessage({ type: "setTheme", theme: getTheme() }); + this.webviewProtocol?.request("setTheme", { theme: getTheme() }); } }); - const webviewProtocol = new VsCodeWebviewProtocol( + this.webviewProtocol = new VsCodeWebviewProtocol( panel.webview, ide, configHandler, diff --git a/extensions/vscode/src/diff/horizontal.ts b/extensions/vscode/src/diff/horizontal.ts index f07dec3e8..c268f58b1 100644 --- a/extensions/vscode/src/diff/horizontal.ts +++ b/extensions/vscode/src/diff/horizontal.ts @@ -5,6 +5,7 @@ import * as path from "path"; import * as vscode from "vscode"; import { getMetaKeyLabel, getPlatform } from "../util/util"; import { uriFromFilePath } from "../util/vscode"; +import { VsCodeWebviewProtocol } from "../webviewProtocol"; interface DiffInfo { originalFilepath: string; @@ -47,16 +48,9 @@ export class DiffManager { } } - webview: vscode.Webview | undefined; - private readonly extensionContext: vscode.ExtensionContext; - - constructor( - webview: vscode.Webview | undefined, - extensionContext: vscode.ExtensionContext - ) { - this.webview = webview; - this.extensionContext = extensionContext; + webviewProtocol: VsCodeWebviewProtocol | undefined; + constructor(private readonly extensionContext: vscode.ExtensionContext) { this.setupDirectory(); // Listen for file closes, and if it's a diff file, clean up @@ -303,7 +297,7 @@ export class DiffManager { } // Stop the step at step_index in case it is still streaming - this.webview?.postMessage({ type: "setInactive" }); + this.webviewProtocol?.request("setInactive", undefined); vscode.workspace.textDocuments .find((doc) => doc.uri.fsPath === newFilepath) diff --git a/extensions/vscode/src/extension/vscodeExtension.ts b/extensions/vscode/src/extension/vscodeExtension.ts index ec429f945..43197d90b 100644 --- a/extensions/vscode/src/extension/vscodeExtension.ts +++ b/extensions/vscode/src/extension/vscodeExtension.ts @@ -13,6 +13,7 @@ import { setupStatusBar, } from "../lang-server/completionProvider"; import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; +import { VsCodeWebviewProtocol } from "../webviewProtocol"; export class VsCodeExtension { private configHandler: ConfigHandler; @@ -24,9 +25,10 @@ export class VsCodeExtension { private indexer: CodebaseIndexer; private diffManager: DiffManager; private verticalDiffManager: VerticalPerLineDiffManager; + private webviewProtocol: VsCodeWebviewProtocol; constructor(context: vscode.ExtensionContext) { - this.diffManager = new DiffManager(undefined, context); + this.diffManager = new DiffManager(context); this.ide = new VsCodeIde(this.diffManager); this.configHandler = new ConfigHandler(this.ide); this.verticalDiffManager = new VerticalPerLineDiffManager( @@ -42,7 +44,20 @@ export class VsCodeExtension { this.extensionContext, this.verticalDiffManager ); - this.diffManager.webview = this.sidebar.webview; + + // Sidebar + context.subscriptions.push( + vscode.window.registerWebviewViewProvider( + "continue.continueGUIView", + this.sidebar, + { + webviewOptions: { retainContextWhenHidden: true }, + } + ) + ); + this.webviewProtocol = this.sidebar.webviewProtocol!; + + this.diffManager.webviewProtocol = this.webviewProtocol; this.indexer = new CodebaseIndexer(this.configHandler, this.ide); // CodeLens @@ -74,17 +89,6 @@ export class VsCodeExtension { ); } - // Sidebar - context.subscriptions.push( - vscode.window.registerWebviewViewProvider( - "continue.continueGUIView", - this.sidebar, - { - webviewOptions: { retainContextWhenHidden: true }, - } - ) - ); - // Commands registerAllCommands( context, @@ -116,9 +120,7 @@ export class VsCodeExtension { filepath.endsWith(".continueignore") || filepath.endsWith(".gitignore") ) { - this.sidebar.webview?.postMessage({ - type: "updateEmbeddings", - }); + // Update embeddings! (TODO) } }); @@ -172,12 +174,8 @@ export class VsCodeExtension { private PREVIOUS_BRANCH_FOR_WORKSPACE_DIR: { [dir: string]: string } = {}; private async refreshCodebaseIndex(dirs: string[]) { - for await (const { progress, desc } of this.indexer.refresh(dirs)) { - this.sidebar.webview?.postMessage({ - type: "indexProgress", - progress, - desc, - }); + for await (const update of this.indexer.refresh(dirs)) { + this.webviewProtocol.request("indexProgress", update); } } } diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 1ff475435..44c93282d 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -7,10 +7,12 @@ import { logDevData } from "core/util/devdata"; import historyManager from "core/util/history"; import { Message } from "core/util/messenger"; import { getConfigJsonPath } from "core/util/paths"; -import { WebviewProtocol } from "core/web/webviewProtocol"; +import { + ReverseWebviewProtocol, + WebviewProtocol, +} from "core/web/webviewProtocol"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; -import { Webview } from "vscode"; import { showTutorial } from "./activation/activate"; import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager"; @@ -18,19 +20,21 @@ export class VsCodeWebviewProtocol { listeners = new Map any)[]>(); abortedMessageIds: Set = new Set(); - private send(messageType: string, message: any, messageId?: string): string { + private send(messageType: string, data: any, messageId?: string): string { const id = messageId || uuidv4(); this.webview.postMessage({ - type: messageType, - message, - messageId: messageId || id, + messageType, + data, + messageId: id, }); return id; } private on( messageType: T, - handler: (message: Message) => WebviewProtocol[T][1] + handler: ( + message: Message + ) => Promise | WebviewProtocol[T][1] ): void { if (!this.listeners.has(messageType)) { this.listeners.set(messageType, []); @@ -39,7 +43,7 @@ export class VsCodeWebviewProtocol { } constructor( - private readonly webview: Webview, + readonly webview: vscode.Webview, private readonly ide: IDE, private readonly configHandler: ConfigHandler, private readonly verticalDiffManager: VerticalPerLineDiffManager @@ -101,15 +105,17 @@ export class VsCodeWebviewProtocol { this.on("openConfigJson", (msg) => { this.ide.openFile(getConfigJsonPath()); }); - this.on("readRangeInFile", (msg) => { - vscode.workspace.openTextDocument(msg.data.filepath).then((document) => { - let start = new vscode.Position(0, 0); - let end = new vscode.Position(5, 0); - let range = new vscode.Range(start, end); + this.on("readRangeInFile", async (msg) => { + return await vscode.workspace + .openTextDocument(msg.data.filepath) + .then((document) => { + let start = new vscode.Position(0, 0); + let end = new vscode.Position(5, 0); + let range = new vscode.Range(start, end); - let contents = document.getText(range); - return contents; - }); + let contents = document.getText(range); + return contents; + }); }); this.on("toggleDevTools", (msg) => { vscode.commands.executeCommand("workbench.action.toggleDevTools"); @@ -171,11 +177,9 @@ export class VsCodeWebviewProtocol { }); this.on("saveSession", (msg) => { historyManager.save(msg.data); - return {}; }); this.on("deleteSession", (msg) => { historyManager.delete(msg.data); - return {}; }); this.on("loadSession", (msg) => { return historyManager.load(msg.data); @@ -357,9 +361,9 @@ export class VsCodeWebviewProtocol { params, ide, addContextItem: (item) => { - protocol.webview?.postMessage({ - type: "addContextItem", - message: { item, historyIndex }, + protocol.request("addContextItem", { + item, + historyIndex, }); }, })) { @@ -458,9 +462,7 @@ export class VsCodeWebviewProtocol { `🎉 Successfully indexed ${title}` ); - this.webview?.postMessage({ - type: "refreshSubmenuItems", - }); + this.request("refreshSubmenuItems", undefined); } ); }); @@ -487,4 +489,18 @@ export class VsCodeWebviewProtocol { showTutorial(); }); } + + public request( + messageType: T, + data: ReverseWebviewProtocol[T][0] + ): Promise { + const messageId = uuidv4(); + return new Promise((resolve) => { + this.send(messageType, data, messageId); + const disposable = this.webview.onDidReceiveMessage((msg) => { + resolve(msg); + disposable.dispose(); + }); + }); + } } diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index a8fb8de28..a8237e46d 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -2,7 +2,6 @@ import { Cog6ToothIcon, QuestionMarkCircleIcon, } from "@heroicons/react/24/outline"; -import { postToIde } from "core/ide/messaging"; import { useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { Outlet, useLocation, useNavigate } from "react-router-dom"; @@ -13,6 +12,7 @@ import { vscForeground, vscInputBackground, } from "."; +import { useWebviewListener } from "../hooks/useWebviewListener"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { setBottomMessage, @@ -21,6 +21,7 @@ import { } from "../redux/slices/uiStateSlice"; import { RootStore } from "../redux/store"; import { getFontSize, isMetaEquivalentKeyPressed } from "../util"; +import { postToIde } from "../util/ide"; import HeaderButtonWithText from "./HeaderButtonWithText"; import TextDialog from "./dialogs"; import IndexingProgressBar from "./loaders/IndexingProgressBar"; @@ -146,30 +147,35 @@ const Layout = () => { }; }, [timeline]); - useEffect(() => { - const handler = (event: any) => { - if (event.data.type === "addModel") { - navigate("/models"); - } else if (event.data.type === "openSettings") { - // navigate("/settings"); - postToIde("openConfigJson", {}); - } else if (event.data.type === "viewHistory") { - // Toggle the history page / main page - if (location.pathname === "/history") { - navigate("/"); - } else { - navigate("/history"); - } - } else if (event.data.type === "indexProgress") { - setIndexingProgress(event.data.progress); - setIndexingTask(event.data.desc); + useWebviewListener( + "addModel", + async () => { + navigate("/models"); + }, + [navigate] + ); + + useWebviewListener("openSettings", async () => { + postToIde("openConfigJson", undefined); + }); + + useWebviewListener( + "viewHistory", + async () => { + // Toggle the history page / main page + if (location.pathname === "/history") { + navigate("/"); + } else { + navigate("/history"); } - }; - window.addEventListener("message", handler); - return () => { - window.removeEventListener("message", handler); - }; - }, [location, navigate]); + }, + [location, navigate] + ); + + useWebviewListener("indexProgress", async (data) => { + setIndexingProgress(data.progress); + setIndexingTask(data.desc); + }); const [indexingProgress, setIndexingProgress] = useState(1); const [indexingTask, setIndexingTask] = useState("Indexing Codebase"); @@ -259,7 +265,7 @@ const Layout = () => { { // navigate("/settings"); - postToIde("openConfigJson", {}); + postToIde("openConfigJson", undefined); }} text="Config" > diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index 54a158078..76cf0953f 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -1,4 +1,3 @@ -import { postToIde } from "core/ide/messaging"; import { usePostHog } from "posthog-js/react"; import React, { useContext, useLayoutEffect } from "react"; import { useDispatch } from "react-redux"; @@ -6,6 +5,7 @@ import styled from "styled-components"; import { Button, Input } from ".."; import { SubmenuContextProvidersContext } from "../../App"; import { setShowDialog } from "../../redux/slices/uiStateSlice"; +import { postToIde } from "../../util/ide"; const GridDiv = styled.div` display: grid; diff --git a/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/ContextItemsPeek.tsx index 877da274b..51c2a7c5f 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -1,7 +1,6 @@ import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/outline"; import { ContextItemWithId } from "core"; import { contextItemToRangeInFileWithContents } from "core/commands/util"; -import { ExtensionIde } from "core/ide"; import React from "react"; import styled from "styled-components"; import { @@ -10,6 +9,7 @@ import { vscBackground, vscForeground, } from ".."; +import { WebviewIde } from "../../util/webviewIde"; import FileIcon from "../FileIcon"; const ContextItemDiv = styled.div` @@ -49,16 +49,16 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => { ) { if (contextItem.name.includes(" (") && contextItem.name.endsWith(")")) { const rif = contextItemToRangeInFileWithContents(contextItem); - new ExtensionIde().showLines( + new WebviewIde().showLines( rif.filepath, rif.range.start.line, rif.range.end.line ); } else { - new ExtensionIde().openFile(contextItem.description); + new WebviewIde().openFile(contextItem.description); } } else { - new ExtensionIde().showVirtualFile(contextItem.name, contextItem.content); + new WebviewIde().showVirtualFile(contextItem.name, contextItem.content); } } diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 15c31a564..836e9aa3b 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -1,9 +1,10 @@ import { JSONContent } from "@tiptap/react"; import { ContextItemWithId } from "core"; -import { useEffect, useState } from "react"; +import { useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import styled, { keyframes } from "styled-components"; import { defaultBorderRadius, vscBackground } from ".."; +import { useWebviewListener } from "../../hooks/useWebviewListener"; import { selectSlashCommands } from "../../redux/selectors"; import { newSession } from "../../redux/slices/stateSlice"; import { RootStore } from "../../redux/store"; @@ -70,19 +71,10 @@ function ContinueInputBox(props: ContinueInputBoxProps) { const [editorState, setEditorState] = useState(props.editorState); - useEffect(() => { - const listener = (e) => { - if (e.data.type === "newSessionWithPrompt") { - dispatch(newSession()); - setEditorState(e.data.prompt); - } - }; - - window.addEventListener("message", listener); - return () => { - window.removeEventListener("message", listener); - }; - }, []); + useWebviewListener("newSessionWithPrompt", async (data) => { + dispatch(newSession()); + setEditorState(data.prompt as any); // any -> JSONContent + }); return (
{ + if (!props.isMainInput) { + return; + } + editor?.commands.insertContent(data.input); + onEnterRef.current(editor.getJSON()); + }, + [editor, onEnterRef.current, props.isMainInput] + ); + + useWebviewListener( + "focusContinueInput", + async (data) => { + if (!props.isMainInput) { + return; + } + if (historyLength > 0) { + saveSession(); + } + editor?.commands.focus("end"); + }, + [historyLength, saveSession, editor, props.isMainInput] + ); + + useWebviewListener( + "focusContinueInputWithoutClear", + async () => { + if (!props.isMainInput) { + return; + } + editor?.commands.focus("end"); + }, + [editor, props.isMainInput] + ); + + useWebviewListener( + "focusContinueInputWithNewSession", + async () => { + if (!props.isMainInput) { + return; + } + saveSession(); + editor?.commands.focus("end"); + }, + [editor, props.isMainInput] + ); + + useWebviewListener( + "highlightedCode", + async (data) => { + if (!props.isMainInput || !editor) { + return; + } + if (!ignoreHighlightedCode) { + const rif: RangeInFile & { contents: string } = + data.rangeInFileWithContents; + const basename = getBasename(rif.filepath); + const item: ContextItemWithId = { + content: rif.contents, + name: `${basename} (${rif.range.start.line + 1}-${ + rif.range.end.line + 1 + })`, + description: rif.filepath, + id: { + providerTitle: "code", + itemId: rif.filepath, + }, + }; + + let index = 0; + for (const el of editor.getJSON().content) { + if (el.type === "codeBlock") { + index += 2; + } else { + break; + } + } + editor + .chain() + .insertContentAt(index, { + type: "codeBlock", + attrs: { + item, + }, + }) + .run(); + setTimeout(() => { + editor.commands.focus("end"); + }, 100); + } + setIgnoreHighlightedCode(false); + }, + [ + editor, + props.isMainInput, + historyLength, + ignoreHighlightedCode, + props.isMainInput, + ] + ); + useEffect(() => { if (!props.isMainInput) { return; @@ -377,68 +481,6 @@ function TipTapEditor(props: TipTapEditorProps) { if (editor && document.hasFocus()) { editor.commands.focus(); } - const handler = async (event: any) => { - if (!editor) return; - - if (event.data.type === "userInput") { - const input = event.data.input; - editor.commands.insertContent(input); - onEnterRef.current(editor.getJSON()); - } else if (event.data.type === "focusContinueInput") { - if (historyLength > 0) { - saveSession(); - } - editor.commands.focus("end"); - } else if (event.data.type === "focusContinueInputWithoutClear") { - editor.commands.focus("end"); - } else if (event.data.type === "focusContinueInputWithNewSession") { - saveSession(); - editor.commands.focus("end"); - } else if (event.data.type === "highlightedCode") { - if (!ignoreHighlightedCode) { - const rif: RangeInFile & { contents: string } = - event.data.rangeInFileWithContents; - const basename = getBasename(rif.filepath); - const item: ContextItemWithId = { - content: rif.contents, - name: `${basename} (${rif.range.start.line + 1}-${ - rif.range.end.line + 1 - })`, - description: rif.filepath, - id: { - providerTitle: "code", - itemId: rif.filepath, - }, - }; - - let index = 0; - for (const el of editor.getJSON().content) { - if (el.type === "codeBlock") { - index += 2; - } else { - break; - } - } - editor - .chain() - .insertContentAt(index, { - type: "codeBlock", - attrs: { - item, - }, - }) - .run(); - setTimeout(() => { - editor.commands.focus("end"); - }, 100); - } - setIgnoreHighlightedCode(false); - } - }; - window.addEventListener("message", handler); - return () => { - window.removeEventListener("message", handler); - }; }, [editor, props.isMainInput, historyLength, ignoreHighlightedCode]); const [showDragOverMsg, setShowDragOverMsg] = useState(false); diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index d9ee02ea2..79830852a 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -5,10 +5,10 @@ import { MessagePart, RangeInFile, } from "core"; -import { ExtensionIde } from "core/ide"; -import { ideRequest } from "core/ide/messaging"; import { stripImages } from "core/llm/countTokens"; import { getBasename } from "core/util"; +import { ideRequest } from "../../util/ide"; +import { WebviewIde } from "../../util/webviewIde"; interface MentionAttrs { label: string; @@ -87,7 +87,7 @@ async function resolveEditorContent( let contextItemsText = ""; let contextItems: ContextItemWithId[] = []; - const ide = new ExtensionIde(); + const ide = new WebviewIde(); for (const item of contextItemAttrs) { if (item.itemType === "file") { // This is a quick way to resolve @file references @@ -110,10 +110,7 @@ async function resolveEditorContent( fullInput: stripImages(parts), selectedCode, }; - const { items: resolvedItems } = await ideRequest( - "getContextItems", - data - ); + const resolvedItems = await ideRequest("getContextItems", data); contextItems.push(...resolvedItems); for (const resolvedItem of resolvedItems) { contextItemsText += resolvedItem.content + "\n\n"; diff --git a/gui/src/components/markdown/CodeBlockToolbar.tsx b/gui/src/components/markdown/CodeBlockToolbar.tsx index 97aa7ede0..30556dbad 100644 --- a/gui/src/components/markdown/CodeBlockToolbar.tsx +++ b/gui/src/components/markdown/CodeBlockToolbar.tsx @@ -3,10 +3,10 @@ import { ClipboardIcon, PlayIcon, } from "@heroicons/react/24/outline"; -import { postToIde } from "core/ide/messaging"; import { useState } from "react"; import styled from "styled-components"; import { vscEditorBackground } from ".."; +import { postToIde } from "../../util/ide"; import HeaderButtonWithText from "../HeaderButtonWithText"; const TopDiv = styled.div` diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx index 5116cc9b0..0ce562239 100644 --- a/gui/src/components/markdown/CodeSnippetPreview.tsx +++ b/gui/src/components/markdown/CodeSnippetPreview.tsx @@ -5,13 +5,13 @@ import { XMarkIcon, } from "@heroicons/react/24/outline"; import { ContextItemWithId } from "core"; -import { ExtensionIde } from "core/ide"; import { getMarkdownLanguageTagForFile } from "core/util"; import React from "react"; import styled from "styled-components"; import { defaultBorderRadius, lightGray, vscEditorBackground } from ".."; import { getFontSize } from "../../util"; import { postToIde } from "../../util/ide"; +import { WebviewIde } from "../../util/webviewIde"; import FileIcon from "../FileIcon"; import HeaderButtonWithText from "../HeaderButtonWithText"; import StyledMarkdownPreview from "./StyledMarkdownPreview"; @@ -90,7 +90,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { .split("(")[1] .split(")")[0] .split("-"); - new ExtensionIde().showLines( + new WebviewIde().showLines( props.item.description, parseInt(lines[0]) - 1, parseInt(lines[1]) - 1 diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 7f1191ceb..9c0190a28 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -9,7 +9,6 @@ import { MessageContent, SlashCommandDescription, } from "core"; -import { ideStreamRequest, llmStreamChat } from "core/ide/messaging"; import { constructMessages } from "core/llm/constructMessages"; import { stripImages } from "core/llm/countTokens"; import { usePostHog } from "posthog-js/react"; @@ -26,7 +25,7 @@ import { streamUpdate, } from "../redux/slices/stateSlice"; import { RootStore } from "../redux/store"; -import { errorPopup } from "../util/ide"; +import { errorPopup, ideStreamRequest, llmStreamChat } from "../util/ide"; function useChatHandler(dispatch: Dispatch) { const posthog = usePostHog(); diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 486070bf0..ce54059d8 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -1,12 +1,13 @@ import { Dispatch } from "@reduxjs/toolkit"; import { PersistedSessionInfo, SessionInfo } from "core"; -import { ideRequest, llmStreamChat } from "core/ide/messaging"; + import { llmCanGenerateInParallel } from "core/llm/autodetect"; import { stripImages } from "core/llm/countTokens"; import { useSelector } from "react-redux"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { newSession } from "../redux/slices/stateSlice"; import { RootStore } from "../redux/store"; +import { ideRequest } from "../util/ide"; function truncateText(text: string, maxLength: number) { if (text.length > maxLength) { @@ -23,7 +24,7 @@ function useHistory(dispatch: Dispatch) { ); async function getHistory(): Promise { - return await ideRequest("history", {}); + return await ideRequest("history", undefined); } async function saveSession() { @@ -46,24 +47,23 @@ function useHistory(dispatch: Dispatch) { !disableSessionTitles && llmCanGenerateInParallel(defaultModel.provider, defaultModel.model) ) { - let fullContent = ""; - for await (const { content } of llmStreamChat( - defaultModel.title, - undefined, - [ - ...stateCopy.history.map((item) => item.message), - { - role: "user", - content: - "Give a maximum 40 character title to describe this conversation so far. The title should help me recall the conversation if I look for it later. DO NOT PUT QUOTES AROUND THE TITLE", - }, - ], - { maxTokens: 20 } - )) { - fullContent += content; - } - - title = stripImages(fullContent); + // let fullContent = ""; + // for await (const { content } of llmStreamChat( + // defaultModel.title, + // undefined, + // [ + // ...stateCopy.history.map((item) => item.message), + // { + // role: "user", + // content: + // "Give a maximum 40 character title to describe this conversation so far. The title should help me recall the conversation if I look for it later. DO NOT PUT QUOTES AROUND THE TITLE", + // }, + // ], + // { maxTokens: 20 } + // )) { + // fullContent += content; + // } + // title = stripImages(fullContent); } const sessionInfo: PersistedSessionInfo = { diff --git a/gui/src/hooks/useNavigationListener.tsx b/gui/src/hooks/useNavigationListener.tsx index cd5e1ffb1..c7e3cb6e6 100644 --- a/gui/src/hooks/useNavigationListener.tsx +++ b/gui/src/hooks/useNavigationListener.tsx @@ -1,7 +1,9 @@ -import { useEffect } from 'react'; -import { useNavigate, useLocation } from 'react-router-dom'; +import { ReverseWebviewProtocol } from "core/web/webviewProtocol"; +import { useLocation, useNavigate } from "react-router-dom"; +import { v4 as uuidv4 } from "uuid"; +import { useWebviewListener } from "./useWebviewListener"; -const openGUITypes = [ +const openGUITypes: (keyof ReverseWebviewProtocol)[] = [ "highlightedCode", "newSessionWithPrompt", "focusContinueInput", @@ -13,30 +15,36 @@ export const useNavigationListener = () => { const navigate = useNavigate(); const location = useLocation(); - useEffect(() => { - const listener = (e) => { - if(openGUITypes.includes(e.data.type)) { - + for (const messageType of openGUITypes) { + useWebviewListener( + messageType, + async (data) => { navigate("/"); setTimeout(() => { - window.postMessage(e.data, "*"); + window.postMessage( + { + messageType, + data, + messageId: uuidv4(), + }, + "*" + ); }, 200); + }, + [navigate] + ); + } + + useWebviewListener( + "viewHistory", + async () => { + // Toggle the history page / main page + if (location.pathname === "/history") { + navigate("/"); + } else { + navigate("/history"); } - - if(e.data.type === "viewHistory") { - // Toggle the history page / main page - if (location.pathname === "/history") { - navigate("/"); - } else { - navigate("/history"); - } - } - }; - - window.addEventListener("message", listener); - - return () => { - window.removeEventListener("message", listener); - }; - }, [navigate]); -} + }, + [location, navigate] + ); +}; diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index da972b54c..ffe408d7e 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -1,9 +1,5 @@ import { Dispatch } from "@reduxjs/toolkit"; import { useEffect } from "react"; -import { setServerStatusMessage } from "../redux/slices/miscSlice"; -import { isJetBrains, postToIde } from "../util/ide"; - -import { ideRequest } from "core/ide/messaging"; import { useSelector } from "react-redux"; import { VSC_THEME_COLOR_VARS } from "../components"; import { setVscMachineId } from "../redux/slices/configSlice"; @@ -13,11 +9,13 @@ import { setInactive, } from "../redux/slices/stateSlice"; import { RootStore } from "../redux/store"; +import { ideRequest, isJetBrains } from "../util/ide"; import useChatHandler from "./useChatHandler"; +import { useWebviewListener } from "./useWebviewListener"; function useSetup(dispatch: Dispatch) { const loadConfig = async () => { - const config = await ideRequest("getSerializedConfig", {}); + const config = await ideRequest("getSerializedConfig", undefined); dispatch(setConfig(config)); }; @@ -31,7 +29,15 @@ function useSetup(dispatch: Dispatch) { dispatch(setInactive()); // Tell JetBrains the webview is ready - postToIde("onLoad", {}); + ideRequest("onLoad", undefined).then((msg) => { + (window as any).windowId = msg.windowId; + (window as any).serverUrl = msg.serverUrl; + (window as any).workspacePaths = msg.workspacePaths; + (window as any).vscMachineId = msg.vscMachineId; + (window as any).vscMediaUrl = msg.vscMediaUrl; + dispatch(setVscMachineId(msg.vscMachineId)); + // dispatch(setVscMediaUrl(msg.vscMediaUrl)); + }); }, []); const { streamResponse } = useChatHandler(dispatch); @@ -41,47 +47,34 @@ function useSetup(dispatch: Dispatch) { ); // IDE event listeners - useEffect(() => { - const eventListener = (event: any) => { - switch (event.data.type) { - case "onLoad": - (window as any).windowId = event.data.windowId; - (window as any).serverUrl = event.data.serverUrl; - (window as any).workspacePaths = event.data.workspacePaths; - (window as any).vscMachineId = event.data.vscMachineId; - (window as any).vscMediaUrl = event.data.vscMediaUrl; - dispatch(setVscMachineId(event.data.vscMachineId)); - // dispatch(setVscMediaUrl(event.data.vscMediaUrl)); + useWebviewListener("setInactive", async () => { + dispatch(setInactive()); + }); - break; - case "serverStatus": - dispatch(setServerStatusMessage(event.data.message)); - break; - case "setInactive": - dispatch(setInactive()); - break; - case "configUpdate": - loadConfig(); - break; - case "submitMessage": - streamResponse(event.data.message); - break; - case "addContextItem": - dispatch( - addContextItemsAtIndex({ - index: event.data.message.historyIndex, - contextItems: [event.data.message.item], - }) - ); - break; - case "getDefaultModelTitle": - postToIde("getDefaultModelTitle", { defaultModelTitle }); - break; - } - }; - window.addEventListener("message", eventListener); - return () => window.removeEventListener("message", eventListener); - }, [defaultModelTitle]); + useWebviewListener("configUpdate", async () => { + loadConfig(); + }); + + useWebviewListener("submitMessage", async (data) => { + streamResponse(data.message); + }); + + useWebviewListener("addContextItem", async (data) => { + dispatch( + addContextItemsAtIndex({ + index: data.historyIndex, + contextItems: [data.item], + }) + ); + }); + + useWebviewListener( + "getDefaultModelTitle", + async () => { + return defaultModelTitle; + }, + [defaultModelTitle] + ); // Save theme colors to local storage for immediate loading in JetBrains useEffect(() => { diff --git a/gui/src/hooks/useSubmenuContextProviders.tsx b/gui/src/hooks/useSubmenuContextProviders.tsx index baf7b39f7..6cf22efa4 100644 --- a/gui/src/hooks/useSubmenuContextProviders.tsx +++ b/gui/src/hooks/useSubmenuContextProviders.tsx @@ -1,11 +1,12 @@ import { ContextSubmenuItem } from "core"; -import { ExtensionIde } from "core/ide"; -import { ideRequest } from "core/ide/messaging"; import { getBasename, getLastNPathParts } from "core/util"; import MiniSearch, { SearchResult } from "minisearch"; import { useEffect, useState } from "react"; import { useSelector } from "react-redux"; import { selectContextProviderDescriptions } from "../redux/selectors"; +import { ideRequest } from "../util/ide"; +import { WebviewIde } from "../util/webviewIde"; +import { useWebviewListener } from "./useWebviewListener"; const MINISEARCH_OPTIONS = { prefix: true, @@ -29,7 +30,7 @@ function useSubmenuContextProviders() { const [loaded, setLoaded] = useState(false); async function getOpenFileItems() { - const openFiles = await new ExtensionIde().getOpenFiles(); + const openFiles = await new WebviewIde().getOpenFiles(); return openFiles.map((file) => { return { id: file, @@ -40,18 +41,9 @@ function useSubmenuContextProviders() { }); } - useEffect(() => { - const handler = (e) => { - if (e.data.type !== "refreshSubmenuItems") { - return; - } - setLoaded(false); - }; - window.addEventListener("message", handler); - return () => { - window.removeEventListener("message", handler); - }; - }, []); + useWebviewListener("refreshSubmenuItems", async (data) => { + setLoaded(true); + }); function addItem(providerTitle: string, item: ContextSubmenuItem) { if (!minisearches[providerTitle]) { @@ -82,7 +74,7 @@ function useSubmenuContextProviders() { fields: ["title"], storeFields: ["id", "title", "description"], }); - const { items } = await ideRequest("loadSubmenuItems", { + const items = await ideRequest("loadSubmenuItems", { title: description.title, }); minisearch.addAll(items); diff --git a/gui/src/hooks/useVscTheme.ts b/gui/src/hooks/useVscTheme.ts index 6b1e86ea0..1eb268308 100644 --- a/gui/src/hooks/useVscTheme.ts +++ b/gui/src/hooks/useVscTheme.ts @@ -1,4 +1,5 @@ -import { useEffect, useState } from "react"; +import { useState } from "react"; +import { useWebviewListener } from "./useWebviewListener"; const hljsToTextMate = { ".hljs-comment": ["comment"], @@ -81,18 +82,10 @@ export function useVscTheme() { constructTheme((window as any).fullColorTheme || {}) ); - useEffect(() => { - const listener = (e) => { - if (e.data.type === "setTheme") { - (window as any).fullColorTheme = e.data.theme; - setTheme(constructTheme(e.data.theme)); - } - }; - window.addEventListener("message", listener); - return () => { - window.removeEventListener("message", listener); - }; - }, []); + useWebviewListener("setTheme", async (data) => { + (window as any).fullColorTheme = data.theme; + setTheme(constructTheme(data.theme)); + }); return theme; } diff --git a/gui/src/hooks/useWebviewListener.ts b/gui/src/hooks/useWebviewListener.ts new file mode 100644 index 000000000..ab56b1ffb --- /dev/null +++ b/gui/src/hooks/useWebviewListener.ts @@ -0,0 +1,25 @@ +import { Message } from "core/util/messenger"; +import { ReverseWebviewProtocol } from "core/web/webviewProtocol"; +import { useEffect } from "react"; +import { respondToIde } from "../util/ide"; + +export function useWebviewListener( + messageType: T, + handler: ( + data: ReverseWebviewProtocol[T][0] + ) => Promise, + dependencies?: any[] +) { + useEffect(() => { + const listener = async (event: { data: Message }) => { + if (event.data.messageType === messageType) { + const result = await handler(event.data.data); + respondToIde(messageType, result, event.data.messageId); + } + }; + window.addEventListener("message", listener); + return () => { + window.removeEventListener("message", listener); + }; + }, dependencies ?? []); +} diff --git a/gui/src/pages/gui.tsx b/gui/src/pages/gui.tsx index 490c17bfb..e2d535e48 100644 --- a/gui/src/pages/gui.tsx +++ b/gui/src/pages/gui.tsx @@ -30,6 +30,7 @@ import TimelineItem from "../components/gui/TimelineItem"; import ContinueInputBox from "../components/mainInput/ContinueInputBox"; import useChatHandler from "../hooks/useChatHandler"; import useHistory from "../hooks/useHistory"; +import { useWebviewListener } from "../hooks/useWebviewListener"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { newSession, setInactive } from "../redux/slices/stateSlice"; import { @@ -348,18 +349,14 @@ function GUI(props: GUIProps) { const { saveSession } = useHistory(dispatch); - useEffect(() => { - const handler = (event: any) => { - if (event.data.type === "newSession") { - saveSession(); - mainTextInputRef.current?.focus?.(); - } - }; - window.addEventListener("message", handler); - return () => { - window.removeEventListener("message", handler); - }; - }, [saveSession]); + useWebviewListener( + "newSession", + async () => { + saveSession(); + mainTextInputRef.current?.focus?.(); + }, + [saveSession] + ); const isLastUserInput = useCallback( (index: number): boolean => { diff --git a/gui/src/pages/help.tsx b/gui/src/pages/help.tsx index 0c8dfe845..a4b4cf0ec 100644 --- a/gui/src/pages/help.tsx +++ b/gui/src/pages/help.tsx @@ -1,12 +1,10 @@ import { ArrowLeftIcon } from "@heroicons/react/24/outline"; -import { postToIde } from "core/ide/messaging"; import { useNavigate } from "react-router-dom"; import styled from "styled-components"; import { Button, lightGray, vscBackground, vscForeground } from "../components"; import KeyboardShortcutsDialog from "../components/dialogs/KeyboardShortcuts"; import { useNavigationListener } from "../hooks/useNavigationListener"; - - +import { postToIde } from "../util/ide"; const IconDiv = styled.div<{ backgroundColor?: string }>` display: flex; @@ -56,7 +54,7 @@ function HelpPage() {

Help Center

{ - postToIde("showTutorial", {}); + postToIde("showTutorial", undefined); }} > Open tutorial diff --git a/gui/src/pages/history.tsx b/gui/src/pages/history.tsx index 57ed49bda..a97ab462b 100644 --- a/gui/src/pages/history.tsx +++ b/gui/src/pages/history.tsx @@ -7,9 +7,9 @@ import styled from "styled-components"; import { lightGray, vscBackground, vscInputBackground } from "../components"; import HeaderButtonWithText from "../components/HeaderButtonWithText"; import useHistory from "../hooks/useHistory"; +import { useNavigationListener } from "../hooks/useNavigationListener"; import { newSession } from "../redux/slices/stateSlice"; import { getFontSize } from "../util"; -import { useNavigationListener } from "../hooks/useNavigationListener"; const Tr = styled.tr` &:hover { @@ -128,7 +128,7 @@ function lastPartOfPath(path: string): string { function History() { useNavigationListener(); const navigate = useNavigate(); - + const [sessions, setSessions] = useState([]); const [filteredAndSortedSessions, setFilteredAndSortedSessions] = useState< SessionInfo[] diff --git a/gui/src/pages/modelconfig.tsx b/gui/src/pages/modelconfig.tsx index af44a4aa1..949c037c4 100644 --- a/gui/src/pages/modelconfig.tsx +++ b/gui/src/pages/modelconfig.tsx @@ -1,5 +1,4 @@ import { ArrowLeftIcon } from "@heroicons/react/24/outline"; -import { postToIde } from "core/ide/messaging"; import _ from "lodash"; import { useCallback, useEffect, useState } from "react"; import { FormProvider, useForm } from "react-hook-form"; @@ -14,15 +13,15 @@ import { } from "../components"; import StyledMarkdownPreview from "../components/markdown/StyledMarkdownPreview"; import ModelCard from "../components/modelSelection/ModelCard"; +import { useNavigationListener } from "../hooks/useNavigationListener"; import { setDefaultModel } from "../redux/slices/stateSlice"; -import { addModel } from "../util/ide"; +import { postToIde } from "../util/ide"; import { MODEL_PROVIDER_TAG_COLORS, ModelInfo, PROVIDER_INFO, updatedObj, } from "../util/modelData"; -import { useNavigationListener } from "../hooks/useNavigationListener"; const GridDiv = styled.div` display: grid; @@ -247,7 +246,7 @@ function ModelConfig() { ...formParams, provider: modelInfo.provider, }; - addModel(model); + postToIde("addModel", model); dispatch(setDefaultModel(model.title)); navigate("/"); }} @@ -265,7 +264,7 @@ function ModelConfig() { { - postToIde("openConfigJson", {}); + postToIde("openConfigJson", undefined); }} >

Open config.json

diff --git a/gui/src/pages/models.tsx b/gui/src/pages/models.tsx index 782a42984..097f67389 100644 --- a/gui/src/pages/models.tsx +++ b/gui/src/pages/models.tsx @@ -1,19 +1,17 @@ import { ArrowLeftIcon } from "@heroicons/react/24/outline"; import _ from "lodash"; import React from "react"; +import { useDispatch } from "react-redux"; import { useNavigate } from "react-router-dom"; import styled from "styled-components"; import { defaultBorderRadius, lightGray, vscBackground } from "../components"; import ModelCard from "../components/modelSelection/ModelCard"; - -import { postToIde } from "core/ide/messaging"; -import { useDispatch } from "react-redux"; import Toggle from "../components/modelSelection/Toggle"; +import { useNavigationListener } from "../hooks/useNavigationListener"; import { setDefaultModel } from "../redux/slices/stateSlice"; -import { addModel } from "../util/ide"; +import { postToIde } from "../util/ide"; import { MODEL_INFO, PROVIDER_INFO } from "../util/modelData"; import { CustomModelButton } from "./modelconfig"; -import { useNavigationListener } from "../hooks/useNavigationListener"; const IntroDiv = styled.div` padding: 8px 12px; @@ -75,10 +73,8 @@ function Models() {
  • a model (the LLM being run, e.g. GPT-4, CodeLlama).
  • To read more about the options, check out our{" "} - - overview - {" "} - in the docs. + overview in + the docs. {providersSelected ? ( @@ -121,7 +117,7 @@ function Models() { ), provider: PROVIDER_INFO[selectedProvider].provider, }; - addModel(model); + postToIde("addModel", model); dispatch(setDefaultModel(model.title)); navigate("/"); }} @@ -138,7 +134,7 @@ function Models() { { - postToIde("openConfigJson", {}); + postToIde("openConfigJson", undefined); }} >

    Open config.json

    diff --git a/gui/src/pages/monaco.tsx b/gui/src/pages/monaco.tsx index 1bddac4ec..b49b5b1b5 100644 --- a/gui/src/pages/monaco.tsx +++ b/gui/src/pages/monaco.tsx @@ -27,10 +27,7 @@ function EditorFrame(props: EditorFrameProps) { }; window.addEventListener("message", eventListener); - postToIde("readRangeInFile", { - filepath: props.filename, - messageId: messageId, - }); + postToIde("readFile", { filepath: props.filename }); return () => window.removeEventListener("message", eventListener); }, []); diff --git a/gui/src/util/ide.ts b/gui/src/util/ide.ts index 4bbca782a..90af1d856 100644 --- a/gui/src/util/ide.ts +++ b/gui/src/util/ide.ts @@ -1,39 +1,59 @@ +import { ChatMessage, LLMFullCompletionOptions, LLMReturnValue } from "core"; +import { Message } from "core/util/messenger"; +import { + ReverseWebviewProtocol, + WebviewProtocol, +} from "core/web/webviewProtocol"; +import { v4 as uuidv4 } from "uuid"; import "vscode-webview"; +interface vscode { + postMessage(message: any): vscode; +} declare const vscode: any; -function _postToIde(type: string, data: any) { +function _postToIde(messageType: string, data: any, messageId?: string) { if (typeof vscode === "undefined") { if (localStorage.getItem("ide") === "jetbrains") { if ((window as any).postIntellijMessage === undefined) { console.log( "Unable to send message: postIntellijMessage is undefined. ", - type, + messageType, data ); throw new Error("postIntellijMessage is undefined"); } - (window as any).postIntellijMessage?.(type, data); + (window as any).postIntellijMessage?.(messageType, data); return; } else { - console.log("Unable to send message: vscode is undefined. ", type, data); + console.log( + "Unable to send message: vscode is undefined. ", + messageType, + data + ); return; } } - vscode.postMessage({ - type, - ...data, - }); + const msg: Message = { + messageId: messageId ?? uuidv4(), + messageType, + data, + }; + vscode.postMessage(msg); } -export function postToIde(type: string, data: any, attempt: number = 0) { +export function postToIde( + messageType: T, + data: WebviewProtocol[T][0], + attempt: number = 0 +) { try { - _postToIde(type, data); + _postToIde(messageType, data); } catch (error) { if (attempt < 5) { console.log(`Attempt ${attempt} failed. Retrying...`); setTimeout( - () => postToIde(type, data, attempt + 1), + () => postToIde(messageType, data, attempt + 1), Math.pow(2, attempt) * 1000 ); } else { @@ -42,17 +62,104 @@ export function postToIde(type: string, data: any, attempt: number = 0) { } } -export async function ideRequest(type: string, data: any): Promise { +export function respondToIde( + messageType: T, + data: ReverseWebviewProtocol[T][1], + messageId: string +) { + _postToIde(messageType, data, messageId); +} + +export async function ideRequest( + messageType: T, + data: WebviewProtocol[T][0] +): Promise { + const messageId = uuidv4(); + return new Promise((resolve) => { const handler = (event: any) => { - if (event.data.type === type) { + if (event.data.messageId === messageId) { window.removeEventListener("message", handler); - resolve(event.data); + resolve(event.data.data); } }; window.addEventListener("message", handler); - postToIde(type, data); + + postToIde(messageType, data); + }) as any; +} + +export async function* ideStreamRequest( + messageType: T, + data: WebviewProtocol[T][0], + cancelToken?: AbortSignal +): WebviewProtocol[T][1] { + const messageId = uuidv4(); + + postToIde(messageType, data); + + let buffer = ""; + let index = 0; + let done = false; + let returnVal = undefined; + + const handler = (event: { data: Message }) => { + if (event.data.messageId === messageId) { + if (event.data.data.done) { + window.removeEventListener("message", handler); + done = true; + returnVal = event.data.data; + } else { + buffer += event.data.data.content; + } + } + }; + window.addEventListener("message", handler); + + cancelToken?.addEventListener("abort", () => { + postToIde("abort", messageId); }); + + while (!done) { + if (buffer.length > index) { + const chunk = buffer.slice(index); + index = buffer.length; + yield chunk; + } + await new Promise((resolve) => setTimeout(resolve, 50)); + } + + if (buffer.length > index) { + const chunk = buffer.slice(index); + index = buffer.length; + yield chunk; + } + + return returnVal; +} + +export async function* llmStreamChat( + modelTitle: string, + cancelToken: AbortSignal | undefined, + messages: ChatMessage[], + options: LLMFullCompletionOptions = {} +): AsyncGenerator { + const gen = ideStreamRequest( + "llmStreamChat", + { + messages, + title: modelTitle, + completionOptions: options, + }, + cancelToken + ); + + let next = await gen.next(); + while (!next.done) { + yield { role: "user", content: next.value }; + next = await gen.next(); + } + return { prompt: next.value?.prompt, completion: next.value?.completion }; } export function errorPopup(message: string) { @@ -63,10 +170,6 @@ export function logDevData(tableName: string, data: any) { postToIde("logDevData", { tableName, data }); } -export function addModel(model: any) { - postToIde("addModel", { model }); -} - export function deleteModel(title: any) { postToIde("deleteModel", { title }); } diff --git a/core/web/webviewIde.ts b/gui/src/util/webviewIde.ts similarity index 72% rename from core/web/webviewIde.ts rename to gui/src/util/webviewIde.ts index b7b5584da..6f993703e 100644 --- a/core/web/webviewIde.ts +++ b/gui/src/util/webviewIde.ts @@ -1,43 +1,45 @@ -import { ContinueRcJson, Problem, Range } from ".."; -import { IDE } from "../index"; - -import { ideRequest } from "./message"; -async function r(messageType: string, options: any = {}) { - return await ideRequest(messageType, options); +import { ContinueRcJson, IDE, Problem, Range } from "core"; +import { WebviewProtocol } from "core/web/webviewProtocol"; +import { ideRequest } from "./ide"; +function r( + messageType: T, + data: WebviewProtocol[T][0] +): Promise { + return ideRequest(messageType, data); } export class WebviewIde implements IDE { readRangeInFile(filepath: string, range: Range): Promise { return r("readRangeInFile", { filepath, range }); } getStats(directory: string): Promise<{ [path: string]: number }> { - return r("getStats", { directory }); + throw new Error("Method not implemented."); } isTelemetryEnabled(): Promise { - return r("isTelemetryEnabled"); + return r("isTelemetryEnabled", undefined); } getUniqueId(): Promise { - return r("getUniqueId"); + return r("getUniqueId", undefined); } getWorkspaceConfigs(): Promise { - return r("getWorkspaceConfigs"); + return r("getWorkspaceConfigs", undefined); } async getDiff() { - return await r("getDiff"); + return await r("getDiff", undefined); } async getTerminalContents() { - return await r("getTerminalContents"); + return await r("getTerminalContents", undefined); } async listWorkspaceContents(directory?: string): Promise { - return await r("listWorkspaceContents"); + return await r("listWorkspaceContents", undefined); } async getWorkspaceDirs(): Promise { - return await r("getWorkspaceDirs"); + return await r("getWorkspaceDirs", undefined); } async showLines( @@ -49,7 +51,7 @@ export class WebviewIde implements IDE { } async listFolders(): Promise { - return await r("listFolders"); + return await r("listFolders", undefined); } _continueDir: string | null = null; @@ -58,7 +60,7 @@ export class WebviewIde implements IDE { if (this._continueDir) { return this._continueDir; } - const dir = await r("getContinueDir"); + const dir = await r("getContinueDir", undefined); this._continueDir = dir; return dir; } @@ -94,11 +96,11 @@ export class WebviewIde implements IDE { } getOpenFiles(): Promise { - return r("getOpenFiles"); + return r("getOpenFiles", undefined); } getPinnedFiles(): Promise { - return r("getPinnedFiles"); + return r("getPinnedFiles", undefined); } getSearchResults(query: string): Promise { From fa106c569b542a1c6710c50a857f47d59948628d Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 14 Feb 2024 17:59:18 -0800 Subject: [PATCH 07/59] =?UTF-8?q?=F0=9F=9A=A7=20fixing=20webview=20messagi?= =?UTF-8?q?ng?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/package-lock.json | 186 ++++--- core/yarn.lock | 34 +- extensions/vscode/package-lock.json | 47 +- extensions/vscode/src/debugPanel.ts | 37 +- .../vscode/src/extension/vscodeExtension.ts | 3 +- extensions/vscode/src/webviewProtocol.ts | 34 +- extensions/vscode/yarn.lock | 26 +- gui/package-lock.json | 472 ++++++++++-------- gui/src/util/ide.ts | 11 +- 9 files changed, 455 insertions(+), 395 deletions(-) diff --git a/core/package-lock.json b/core/package-lock.json index 88ae15d27..46f57ceda 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -2044,15 +2044,14 @@ } }, "node_modules/agent-base": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", - "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", - "optional": true, + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.0.tgz", + "integrity": "sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg==", "dependencies": { - "debug": "4" + "debug": "^4.3.4" }, "engines": { - "node": ">= 6.0.0" + "node": ">= 14" } }, "node_modules/agentkeepalive": { @@ -2179,6 +2178,20 @@ "node": "^12.13.0 || ^14.15.0 || >=16.0.0" } }, + "node_modules/are-we-there-yet/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "optional": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/argparse": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", @@ -2376,6 +2389,42 @@ "readable-stream": "^3.4.0" } }, + "node_modules/bl/node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/bl/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/boolbase": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", @@ -2457,9 +2506,9 @@ } }, "node_modules/buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", "funding": [ { "type": "github", @@ -2474,9 +2523,10 @@ "url": "https://feross.org/support" } ], + "optional": true, "dependencies": { "base64-js": "^1.3.1", - "ieee754": "^1.1.13" + "ieee754": "^1.2.1" } }, "node_modules/buffer-from": { @@ -3811,17 +3861,6 @@ "node": ">= 14" } }, - "node_modules/http-proxy-agent/node_modules/agent-base": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.0.tgz", - "integrity": "sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg==", - "dependencies": { - "debug": "^4.3.4" - }, - "engines": { - "node": ">= 14" - } - }, "node_modules/https-proxy-agent": { "version": "7.0.3", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.3.tgz", @@ -3834,17 +3873,6 @@ "node": ">= 14" } }, - "node_modules/https-proxy-agent/node_modules/agent-base": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.0.tgz", - "integrity": "sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg==", - "dependencies": { - "debug": "^4.3.4" - }, - "engines": { - "node": ">= 14" - } - }, "node_modules/human-signals": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", @@ -4952,6 +4980,18 @@ "node": ">= 10" } }, + "node_modules/make-fetch-happen/node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "optional": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, "node_modules/make-fetch-happen/node_modules/http-proxy-agent": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-4.0.1.tgz", @@ -5837,6 +5877,19 @@ "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==" }, + "node_modules/prebuild-install/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/prebuild-install/node_modules/tar-fs": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz", @@ -6019,16 +6072,19 @@ "dev": true }, "node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "version": "4.5.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.5.2.tgz", + "integrity": "sha512-yjavECdqeZ3GLXNgRXgeQEdz9fvDDkNKyHnbHRFtOr7/LcfgBcmct7t/ET+HaCTqfh06OzoAxrkN/IfjJBVe+g==", + "optional": true, "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" + "abort-controller": "^3.0.0", + "buffer": "^6.0.3", + "events": "^3.3.0", + "process": "^0.11.10", + "string_decoder": "^1.3.0" }, "engines": { - "node": ">= 6" + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, "node_modules/repeat-string": { @@ -6053,46 +6109,6 @@ "readable-stream": ">=4.0.0" } }, - "node_modules/replicate/node_modules/buffer": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", - "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "optional": true, - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.2.1" - } - }, - "node_modules/replicate/node_modules/readable-stream": { - "version": "4.5.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.5.2.tgz", - "integrity": "sha512-yjavECdqeZ3GLXNgRXgeQEdz9fvDDkNKyHnbHRFtOr7/LcfgBcmct7t/ET+HaCTqfh06OzoAxrkN/IfjJBVe+g==", - "optional": true, - "dependencies": { - "abort-controller": "^3.0.0", - "buffer": "^6.0.3", - "events": "^3.3.0", - "process": "^0.11.10", - "string_decoder": "^1.3.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - } - }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", @@ -6432,6 +6448,18 @@ "node": ">= 10" } }, + "node_modules/socks-proxy-agent/node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "optional": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, "node_modules/source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", diff --git a/core/yarn.lock b/core/yarn.lock index 25c0f5df8..6f9f7285c 100644 --- a/core/yarn.lock +++ b/core/yarn.lock @@ -974,26 +974,26 @@ abort-controller@^3.0.0: dependencies: event-target-shim "^5.0.0" -agent-base@^6.0.2, agent-base@6: +agent-base@^6.0.2: version "6.0.2" resolved "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz" integrity sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ== dependencies: debug "4" -agent-base@^7.0.2: +agent-base@^7.0.2, agent-base@^7.1.0: version "7.1.0" resolved "https://registry.npmjs.org/agent-base/-/agent-base-7.1.0.tgz" integrity sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg== dependencies: debug "^4.3.4" -agent-base@^7.1.0: - version "7.1.0" - resolved "https://registry.npmjs.org/agent-base/-/agent-base-7.1.0.tgz" - integrity sha512-o/zjMZRhJxny7OyEF+Op8X+efiELC7k7yOjMzgfzVqOzXqkBkWI79YoTdOtsuWd5BWhAGAuOY/Xa6xpiaWXiNg== +agent-base@6: + version "6.0.2" + resolved "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz" + integrity sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ== dependencies: - debug "^4.3.4" + debug "4" agentkeepalive@^4.1.3, agentkeepalive@^4.2.1: version "4.5.0" @@ -3417,7 +3417,25 @@ react-is@^18.0.0: resolved "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz" integrity sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w== -readable-stream@^3.1.1, readable-stream@^3.4.0, readable-stream@^3.6.0: +readable-stream@^3.1.1: + version "3.6.2" + resolved "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz" + integrity sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA== + dependencies: + inherits "^2.0.3" + string_decoder "^1.1.1" + util-deprecate "^1.0.1" + +readable-stream@^3.4.0: + version "3.6.2" + resolved "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz" + integrity sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA== + dependencies: + inherits "^2.0.3" + string_decoder "^1.1.1" + util-deprecate "^1.0.1" + +readable-stream@^3.6.0: version "3.6.2" resolved "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz" integrity sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA== diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 8ff6a2c00..170597b3a 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -4591,15 +4591,6 @@ "node": ">=10" } }, - "node_modules/concurrently/node_modules/yargs-parser": { - "version": "20.2.9", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", - "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", - "dev": true, - "engines": { - "node": ">=10" - } - }, "node_modules/consola": { "version": "2.15.3", "resolved": "https://registry.npmjs.org/consola/-/consola-2.15.3.tgz", @@ -4996,9 +4987,9 @@ "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==" }, "node_modules/diff": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/diff/-/diff-5.1.0.tgz", - "integrity": "sha512-D+mk+qE8VC/PAUrlAU34N+VfXev0ghe5ywmpqrawphmVZc1bEfn56uo9qpyGp1p4xpzOHkSW4ztBd6L7Xx4ACw==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-5.0.0.tgz", + "integrity": "sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w==", "engines": { "node": ">=0.3.1" } @@ -9105,14 +9096,6 @@ "wrap-ansi": "^7.0.0" } }, - "node_modules/mocha/node_modules/diff": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/diff/-/diff-5.0.0.tgz", - "integrity": "sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w==", - "engines": { - "node": ">=0.3.1" - } - }, "node_modules/mocha/node_modules/minimatch": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.0.1.tgz", @@ -9187,14 +9170,6 @@ "node": ">=10" } }, - "node_modules/mocha/node_modules/yargs-parser": { - "version": "20.2.4", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.4.tgz", - "integrity": "sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA==", - "engines": { - "node": ">=10" - } - }, "node_modules/monaco-editor": { "version": "0.45.0", "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.45.0.tgz", @@ -13604,11 +13579,11 @@ } }, "node_modules/yargs-parser": { - "version": "21.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", - "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "version": "20.2.4", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.4.tgz", + "integrity": "sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA==", "engines": { - "node": ">=12" + "node": ">=10" } }, "node_modules/yargs-unparser": { @@ -13644,6 +13619,14 @@ "node": ">=8" } }, + "node_modules/yargs/node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "engines": { + "node": ">=12" + } + }, "node_modules/yarn": { "version": "1.22.21", "resolved": "https://registry.npmjs.org/yarn/-/yarn-1.22.21.tgz", diff --git a/extensions/vscode/src/debugPanel.ts b/extensions/vscode/src/debugPanel.ts index 16927c040..4be5a05c0 100644 --- a/extensions/vscode/src/debugPanel.ts +++ b/extensions/vscode/src/debugPanel.ts @@ -10,7 +10,7 @@ export class ContinueGUIWebviewViewProvider implements vscode.WebviewViewProvider { public static readonly viewType = "continue.continueGUIView"; - public webviewProtocol?: VsCodeWebviewProtocol; + public webviewProtocol: VsCodeWebviewProtocol; resolveWebviewView( webviewView: vscode.WebviewView, @@ -46,28 +46,12 @@ export class ContinueGUIWebviewViewProvider private readonly windowId: string, private readonly extensionContext: vscode.ExtensionContext, private readonly verticalDiffManager: VerticalPerLineDiffManager - ) {} - - async webviewRequest(messageType: string, data: any = {}): Promise { - return new Promise((resolve, reject) => { - if (!this._webview) { - resolve(undefined); - } - - const listener = this._webview?.onDidReceiveMessage((data) => { - if (data.type === messageType) { - resolve(data); - listener?.dispose(); - } - }); - - this._webview?.postMessage({ type: messageType, data }); - - setTimeout(() => { - reject("Error communciating with Continue side panel: timed out"); - listener?.dispose(); - }, 500); - }); + ) { + this.webviewProtocol = new VsCodeWebviewProtocol( + ide, + configHandler, + verticalDiffManager + ); } getSidebarContent( @@ -126,12 +110,7 @@ export class ContinueGUIWebviewViewProvider } }); - this.webviewProtocol = new VsCodeWebviewProtocol( - panel.webview, - ide, - configHandler, - verticalDiffManager - ); + this.webviewProtocol.webview = panel.webview; return ` diff --git a/extensions/vscode/src/extension/vscodeExtension.ts b/extensions/vscode/src/extension/vscodeExtension.ts index 43197d90b..a83b7838b 100644 --- a/extensions/vscode/src/extension/vscodeExtension.ts +++ b/extensions/vscode/src/extension/vscodeExtension.ts @@ -31,6 +31,7 @@ export class VsCodeExtension { this.diffManager = new DiffManager(context); this.ide = new VsCodeIde(this.diffManager); this.configHandler = new ConfigHandler(this.ide); + this.configHandler.reloadConfig(); this.verticalDiffManager = new VerticalPerLineDiffManager( this.configHandler ); @@ -55,7 +56,7 @@ export class VsCodeExtension { } ) ); - this.webviewProtocol = this.sidebar.webviewProtocol!; + this.webviewProtocol = this.sidebar.webviewProtocol; this.diffManager.webviewProtocol = this.webviewProtocol; this.indexer = new CodebaseIndexer(this.configHandler, this.ide); diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 44c93282d..2f83e8cb0 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -22,7 +22,7 @@ export class VsCodeWebviewProtocol { private send(messageType: string, data: any, messageId?: string): string { const id = messageId || uuidv4(); - this.webview.postMessage({ + this.webview?.postMessage({ messageType, data, messageId: id, @@ -42,13 +42,18 @@ export class VsCodeWebviewProtocol { this.listeners.get(messageType)?.push(handler); } - constructor( - readonly webview: vscode.Webview, - private readonly ide: IDE, - private readonly configHandler: ConfigHandler, - private readonly verticalDiffManager: VerticalPerLineDiffManager - ) { - webview.onDidReceiveMessage(async (msg) => { + _webview?: vscode.Webview; + _webviewListener?: vscode.Disposable; + + get webview(): vscode.Webview | undefined { + return this._webview; + } + + set webview(webView: vscode.Webview) { + this._webview = webView; + this._webviewListener?.dispose(); + + this._webviewListener = this._webview.onDidReceiveMessage(async (msg) => { if (!msg.messageType || !msg.messageId) { throw new Error("Invalid webview protocol msg: " + JSON.stringify(msg)); } @@ -95,7 +100,13 @@ export class VsCodeWebviewProtocol { } respond({ done: true, data: {} }); }); + } + constructor( + private readonly ide: IDE, + private readonly configHandler: ConfigHandler, + private readonly verticalDiffManager: VerticalPerLineDiffManager + ) { this.on("abort", (msg) => { this.abortedMessageIds.add(msg.messageId); }); @@ -496,10 +507,15 @@ export class VsCodeWebviewProtocol { ): Promise { const messageId = uuidv4(); return new Promise((resolve) => { + if (!this.webview) { + resolve(undefined); + return; + } + this.send(messageType, data, messageId); const disposable = this.webview.onDidReceiveMessage((msg) => { resolve(msg); - disposable.dispose(); + disposable?.dispose(); }); }); } diff --git a/extensions/vscode/yarn.lock b/extensions/vscode/yarn.lock index 5c9af9f54..be8c6d1c0 100644 --- a/extensions/vscode/yarn.lock +++ b/extensions/vscode/yarn.lock @@ -697,9 +697,9 @@ integrity sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg== "@lancedb/vectordb-darwin-arm64@*": - version "0.4.9" - resolved "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.9.tgz" - integrity sha512-u56TXU0hvdLbknGwC7Ebza3/CUFeCTkoCy/sC6h0FtOGya+NV7jraAeXEwDzoZbfW08VYYxnp3TsCcpNU9lpTA== + version "0.4.10" + resolved "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.10.tgz" + integrity sha512-y/uHOGb0g15pvqv5tdTyZ6oN+0QVpBmZDzKFWW6pPbuSZjB2uPqcs+ti0RB+AUdmS21kavVQqaNsw/HLKEGrHA== "@lancedb/vectordb-darwin-arm64@0.4.8": version "0.4.8" @@ -2546,12 +2546,7 @@ diff-sequences@^29.6.3: resolved "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz" integrity sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q== -diff@^5.0.0: - version "5.1.0" - resolved "https://registry.npmjs.org/diff/-/diff-5.1.0.tgz" - integrity sha512-D+mk+qE8VC/PAUrlAU34N+VfXev0ghe5ywmpqrawphmVZc1bEfn56uo9qpyGp1p4xpzOHkSW4ztBd6L7Xx4ACw== - -diff@5.0.0: +diff@^5.0.0, diff@5.0.0: version "5.0.0" resolved "https://registry.npmjs.org/diff/-/diff-5.0.0.tgz" integrity sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w== @@ -7588,21 +7583,16 @@ yaml@^2.3.4: resolved "https://registry.npmjs.org/yaml/-/yaml-2.3.4.tgz" integrity sha512-8aAvwVUSHpfEqTQ4w/KMlf3HcRdt50E5ODIQJBw1fQ5RL34xabzxtUlzTXVqc4rkZsPbvrXKWnABCD7kWSmocA== -yargs-parser@^20.2.2: - version "20.2.9" - resolved "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz" - integrity sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w== +yargs-parser@^20.2.2, yargs-parser@20.2.4: + version "20.2.4" + resolved "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.4.tgz" + integrity sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA== yargs-parser@^21.1.1: version "21.1.1" resolved "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz" integrity sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw== -yargs-parser@20.2.4: - version "20.2.4" - resolved "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.4.tgz" - integrity sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA== - yargs-unparser@2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/yargs-unparser/-/yargs-unparser-2.0.0.tgz" diff --git a/gui/package-lock.json b/gui/package-lock.json index 84788575a..632e8f618 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -839,12 +839,12 @@ } }, "node_modules/@floating-ui/dom": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.6.1.tgz", - "integrity": "sha512-iA8qE43/H5iGozC3W0YSnVSW42Vh522yyM1gj+BqRwVsTNOyr231PsXDaV04yT39PsO0QL2QpbI/M0ZaLUQgRQ==", + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.6.3.tgz", + "integrity": "sha512-RnDthu3mzPlQ31Ss/BTwQ1zjzIhr3lk1gZB1OC56h/1vEtaXkESrOqL5fQVMfXpwGtRwX+YsZBdyHtJMQnkArw==", "dependencies": { - "@floating-ui/core": "^1.6.0", - "@floating-ui/utils": "^0.2.1" + "@floating-ui/core": "^1.0.0", + "@floating-ui/utils": "^0.2.0" } }, "node_modules/@floating-ui/utils": { @@ -907,9 +907,9 @@ } }, "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz", - "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==", + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", "engines": { "node": ">=6.0.0" } @@ -1116,13 +1116,13 @@ "integrity": "sha512-+9jVqKhRSpsc591z5vX+X5Yyw+he/HCB4iQ/RYxw35CEPaY1gnsNE43nf9n9AaYjAQrTiI/mOwKUKdUs9vf7Xg==" }, "node_modules/@swc/core": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core/-/core-1.4.0.tgz", - "integrity": "sha512-wc5DMI5BJftnK0Fyx9SNJKkA0+BZSJQx8430yutWmsILkHMBD3Yd9GhlMaxasab9RhgKqZp7Ht30hUYO5ZDvQg==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core/-/core-1.4.1.tgz", + "integrity": "sha512-3y+Y8js+e7BbM16iND+6Rcs3jdiL28q3iVtYsCviYSSpP2uUVKkp5sJnCY4pg8AaVvyN7CGQHO7gLEZQ5ByozQ==", "dev": true, "hasInstallScript": true, "dependencies": { - "@swc/counter": "^0.1.1", + "@swc/counter": "^0.1.2", "@swc/types": "^0.1.5" }, "engines": { @@ -1133,16 +1133,16 @@ "url": "https://opencollective.com/swc" }, "optionalDependencies": { - "@swc/core-darwin-arm64": "1.4.0", - "@swc/core-darwin-x64": "1.4.0", - "@swc/core-linux-arm-gnueabihf": "1.4.0", - "@swc/core-linux-arm64-gnu": "1.4.0", - "@swc/core-linux-arm64-musl": "1.4.0", - "@swc/core-linux-x64-gnu": "1.4.0", - "@swc/core-linux-x64-musl": "1.4.0", - "@swc/core-win32-arm64-msvc": "1.4.0", - "@swc/core-win32-ia32-msvc": "1.4.0", - "@swc/core-win32-x64-msvc": "1.4.0" + "@swc/core-darwin-arm64": "1.4.1", + "@swc/core-darwin-x64": "1.4.1", + "@swc/core-linux-arm-gnueabihf": "1.4.1", + "@swc/core-linux-arm64-gnu": "1.4.1", + "@swc/core-linux-arm64-musl": "1.4.1", + "@swc/core-linux-x64-gnu": "1.4.1", + "@swc/core-linux-x64-musl": "1.4.1", + "@swc/core-win32-arm64-msvc": "1.4.1", + "@swc/core-win32-ia32-msvc": "1.4.1", + "@swc/core-win32-x64-msvc": "1.4.1" }, "peerDependencies": { "@swc/helpers": "^0.5.0" @@ -1154,9 +1154,9 @@ } }, "node_modules/@swc/core-darwin-arm64": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-darwin-arm64/-/core-darwin-arm64-1.4.0.tgz", - "integrity": "sha512-UTJ/Vz+s7Pagef6HmufWt6Rs0aUu+EJF4Pzuwvr7JQQ5b1DZeAAUeUtkUTFx/PvCbM8Xfw4XdKBUZfrIKCfW8A==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-darwin-arm64/-/core-darwin-arm64-1.4.1.tgz", + "integrity": "sha512-ePyfx0348UbR4DOAW24TedeJbafnzha8liXFGuQ4bdXtEVXhLfPngprrxKrAddCuv42F9aTxydlF6+adD3FBhA==", "cpu": [ "arm64" ], @@ -1170,9 +1170,9 @@ } }, "node_modules/@swc/core-darwin-x64": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-darwin-x64/-/core-darwin-x64-1.4.0.tgz", - "integrity": "sha512-f8v58u2GsGak8EtZFN9guXqE0Ep10Suny6xriaW2d8FGqESPyNrnBzli3aqkSeQk5gGqu2zJ7WiiKp3XoUOidA==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-darwin-x64/-/core-darwin-x64-1.4.1.tgz", + "integrity": "sha512-eLf4JSe6VkCMdDowjM8XNC5rO+BrgfbluEzAVtKR8L2HacNYukieumN7EzpYCi0uF1BYwu1ku6tLyG2r0VcGxA==", "cpu": [ "x64" ], @@ -1186,9 +1186,9 @@ } }, "node_modules/@swc/core-linux-arm-gnueabihf": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-linux-arm-gnueabihf/-/core-linux-arm-gnueabihf-1.4.0.tgz", - "integrity": "sha512-q2KAkBzmPcTnRij/Y1fgHCKAGevUX/H4uUESrw1J5gmUg9Qip6onKV80lTumA1/aooGJ18LOsB31qdbwmZk9OA==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-linux-arm-gnueabihf/-/core-linux-arm-gnueabihf-1.4.1.tgz", + "integrity": "sha512-K8VtTLWMw+rkN/jDC9o/Q9SMmzdiHwYo2CfgkwVT29NsGccwmNhCQx6XoYiPKyKGIFKt4tdQnJHKUFzxUqQVtQ==", "cpu": [ "arm" ], @@ -1202,9 +1202,9 @@ } }, "node_modules/@swc/core-linux-arm64-gnu": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-gnu/-/core-linux-arm64-gnu-1.4.0.tgz", - "integrity": "sha512-SknGu96W0mzHtLHWm+62fk5+Omp9fMPFO7AWyGFmz2tr8EgRRXtTSrBUnWhAbgcalnhen48GsvtMdxf1KNputg==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-gnu/-/core-linux-arm64-gnu-1.4.1.tgz", + "integrity": "sha512-0e8p4g0Bfkt8lkiWgcdiENH3RzkcqKtpRXIVNGOmVc0OBkvc2tpm2WTx/eoCnes2HpTT4CTtR3Zljj4knQ4Fvw==", "cpu": [ "arm64" ], @@ -1218,9 +1218,9 @@ } }, "node_modules/@swc/core-linux-arm64-musl": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-musl/-/core-linux-arm64-musl-1.4.0.tgz", - "integrity": "sha512-/k3TDvpBRMDNskHooNN1KqwUhcwkfBlIYxRTnJvsfT2C7My4pffR+4KXmt0IKynlTTbCdlU/4jgX4801FSuliw==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-musl/-/core-linux-arm64-musl-1.4.1.tgz", + "integrity": "sha512-b/vWGQo2n7lZVUnSQ7NBq3Qrj85GrAPPiRbpqaIGwOytiFSk8VULFihbEUwDe0rXgY4LDm8z8wkgADZcLnmdUA==", "cpu": [ "arm64" ], @@ -1234,9 +1234,9 @@ } }, "node_modules/@swc/core-linux-x64-gnu": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-linux-x64-gnu/-/core-linux-x64-gnu-1.4.0.tgz", - "integrity": "sha512-GYsTMvNt5+WTVlwwQzOOWsPMw6P/F41u5PGHWmfev8Nd4QJ1h3rWPySKk4mV42IJwH9MgQCVSl3ygwNqwl6kFg==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-linux-x64-gnu/-/core-linux-x64-gnu-1.4.1.tgz", + "integrity": "sha512-AFMQlvkKEdNi1Vk2GFTxxJzbICttBsOQaXa98kFTeWTnFFIyiIj2w7Sk8XRTEJ/AjF8ia8JPKb1zddBWr9+bEQ==", "cpu": [ "x64" ], @@ -1250,9 +1250,9 @@ } }, "node_modules/@swc/core-linux-x64-musl": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-linux-x64-musl/-/core-linux-x64-musl-1.4.0.tgz", - "integrity": "sha512-jGVPdM/VwF7kK/uYRW5N6FwzKf/FnDjGIR3RPvQokjYJy7Auk+3Oj21C0Jev7sIT9RYnO/TrFEoEozKeD/z2Qw==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-linux-x64-musl/-/core-linux-x64-musl-1.4.1.tgz", + "integrity": "sha512-QX2MxIECX1gfvUVZY+jk528/oFkS9MAl76e3ZRvG2KC/aKlCQL0KSzcTSm13mOxkDKS30EaGRDRQWNukGpMeRg==", "cpu": [ "x64" ], @@ -1266,9 +1266,9 @@ } }, "node_modules/@swc/core-win32-arm64-msvc": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.4.0.tgz", - "integrity": "sha512-biHYm1AronEKlt47O/H8sSOBM2BKXMmWT+ApvlxUw50m1RGNnVnE0bgY7tylFuuSiWyXsQPJbmUV708JqORXVg==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.4.1.tgz", + "integrity": "sha512-OklkJYXXI/tntD2zaY8i3iZldpyDw5q+NAP3k9OlQ7wXXf37djRsHLV0NW4+ZNHBjE9xp2RsXJ0jlOJhfgGoFA==", "cpu": [ "arm64" ], @@ -1282,9 +1282,9 @@ } }, "node_modules/@swc/core-win32-ia32-msvc": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.4.0.tgz", - "integrity": "sha512-TL5L2tFQb19kJwv6+elToGBj74QXCn9j+hZfwQatvZEJRA5rDK16eH6oAE751dGUArhnWlW3Vj65hViPvTuycw==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.4.1.tgz", + "integrity": "sha512-MBuc3/QfKX9FnLOU7iGN+6yHRTQaPQ9WskiC8s8JFiKQ+7I2p25tay2RplR9dIEEGgVAu6L7auv96LbNTh+FaA==", "cpu": [ "ia32" ], @@ -1298,9 +1298,9 @@ } }, "node_modules/@swc/core-win32-x64-msvc": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@swc/core-win32-x64-msvc/-/core-win32-x64-msvc-1.4.0.tgz", - "integrity": "sha512-e2xVezU7XZ2Stzn4i7TOQe2Kn84oYdG0M3A7XI7oTdcpsKCcKwgiMoroiAhqCv+iN20KNqhnWwJiUiTj/qN5AA==", + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/@swc/core-win32-x64-msvc/-/core-win32-x64-msvc-1.4.1.tgz", + "integrity": "sha512-lu4h4wFBb/bOK6N2MuZwg7TrEpwYXgpQf5R7ObNSXL65BwZ9BG8XRzD+dLJmALu8l5N08rP/TrpoKRoGT4WSxw==", "cpu": [ "x64" ], @@ -1808,9 +1808,9 @@ "integrity": "sha512-nG96G3Wp6acyAgJqGasjODb+acrI7KltPiRxzHPXnP3NgI28bpQDRv53olbqGXbfcgF5aiiHmO3xpwEpS5Ld9g==" }, "node_modules/@types/node": { - "version": "20.11.16", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.16.tgz", - "integrity": "sha512-gKb0enTmRCzXSSUJDq6/sPcqrfCv2mkkG6Jt/clpn5eiCbKTY+SgZUxo+p8ZKMof5dCp9vHQUAB7wOUTod22wQ==", + "version": "20.11.17", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.17.tgz", + "integrity": "sha512-QmgQZGWu1Yw9TDyAP9ZzpFJKynYNeOvwMJmaxABfieQoVoiVOS6MN1WSpqpRcbeA5+RW82kraAVxCCJg+780Qw==", "dev": true, "dependencies": { "undici-types": "~5.26.4" @@ -2069,6 +2069,15 @@ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "dev": true }, + "node_modules/bcp-47-match": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-1.0.3.tgz", + "integrity": "sha512-LggQ4YTdjWQSKELZF5JwchnBa1u0pIQSZf5lSdOHEdbVP55h0qICA/FUp3+W99q0xqxYa1ZQizTUH87gecII5w==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/binary-extensions": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", @@ -2105,9 +2114,9 @@ } }, "node_modules/browserslist": { - "version": "4.22.3", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.22.3.tgz", - "integrity": "sha512-UAp55yfwNv0klWNapjs/ktHoguxuQNGnOzxYmfnXIS+8AsRDZkSDxg7R1AX3GKzn078SBI5dzwzj/Yx0Or0e3A==", + "version": "4.23.0", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.23.0.tgz", + "integrity": "sha512-QW8HiM1shhT2GuzkvklfjcKDiWFXHOeFCIA/huJPwHsslwcydgk7X+z2zXpEijP98UCY7HbubZt5J2Zgvf0CaQ==", "funding": [ { "type": "opencollective", @@ -2123,8 +2132,8 @@ } ], "dependencies": { - "caniuse-lite": "^1.0.30001580", - "electron-to-chromium": "^1.4.648", + "caniuse-lite": "^1.0.30001587", + "electron-to-chromium": "^1.4.668", "node-releases": "^2.0.14", "update-browserslist-db": "^1.0.13" }, @@ -2153,9 +2162,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001585", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001585.tgz", - "integrity": "sha512-yr2BWR1yLXQ8fMpdS/4ZZXpseBgE7o4g41x3a6AJOqZuOi+iE/WdJYAuZ6Y95i4Ohd2Y+9MzIWRR+uGABH4s3Q==", + "version": "1.0.30001587", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001587.tgz", + "integrity": "sha512-HMFNotUmLXn71BQxg8cijvqxnIAofforZOwGsxyXJ0qugTdspUF4sPSJ2vhgprHCB996tIDzEq1ubumPDV8ULA==", "funding": [ { "type": "opencollective", @@ -2378,6 +2387,11 @@ "node": ">=4" } }, + "node_modules/css-selector-parser": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/css-selector-parser/-/css-selector-parser-1.4.1.tgz", + "integrity": "sha512-HYPSb7y/Z7BNDCOrakL4raGO2zltZkbeXyAd6Tg9obzix6QhzxCotdBl6VT0Dv4vZfJGVz3WL/xaEI9Ly3ul0g==" + }, "node_modules/css-to-react-native": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/css-to-react-native/-/css-to-react-native-3.2.0.tgz", @@ -2481,6 +2495,18 @@ "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==", "dev": true }, + "node_modules/direction": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/direction/-/direction-1.0.4.tgz", + "integrity": "sha512-GYqKi1aH7PJXxdhTeZBFrg8vUBeKXi+cNprXsC1kpJcbcVnV9wBsrOu1cQEdG0WeQwlfHiy3XvnKfIrJ2R0NzQ==", + "bin": { + "direction": "cli.js" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/dlv": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz", @@ -2519,9 +2545,9 @@ "dev": true }, "node_modules/electron-to-chromium": { - "version": "1.4.661", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.661.tgz", - "integrity": "sha512-AFg4wDHSOk5F+zA8aR+SVIOabu7m0e7BiJnigCvPXzIGy731XENw/lmNxTySpVFtkFEy+eyt4oHhh5FF3NjQNw==" + "version": "1.4.669", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.669.tgz", + "integrity": "sha512-E2SmpffFPrZhBSgf8ibqanRS2mpuk3FIRDzLDwt7WFpfgJMKDHJs0hmacyP0PS1cWsq0dVkwIIzlscNaterkPg==" }, "node_modules/emoji-regex": { "version": "9.2.2", @@ -2853,9 +2879,9 @@ } }, "node_modules/hasown": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.0.tgz", - "integrity": "sha512-vUptKVTpIJhcczKBbgnS+RtcuYMB8+oNzPK2/Hp3hanz8JmpATdmmgLgSaadVREkDm+e2giHwY3ZRkyjSIDDFA==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.1.tgz", + "integrity": "sha512-1/th4MHjnwncwXsIW6QMzlvYL9kG5e/CpVvLRZe4XPa8TOUNbCELqmvhDmnkNsAjwaG4+I8gJJL0JBvTTLO9qA==", "dev": true, "dependencies": { "function-bind": "^1.1.2" @@ -3069,6 +3095,15 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/hast-util-has-property": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/hast-util-has-property/-/hast-util-has-property-1.0.4.tgz", + "integrity": "sha512-ghHup2voGfgFoHMGnaLHOjbYFACKrRh9KFttdCzMCbFoBMJXiNi2+XTrPP8+q6cDJM/RSqlCfVWrjp1H201rZg==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/hast-util-is-element": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/hast-util-is-element/-/hast-util-is-element-3.0.0.tgz", @@ -3090,6 +3125,129 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/hast-util-select": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/hast-util-select/-/hast-util-select-4.0.2.tgz", + "integrity": "sha512-8EEG2//bN5rrzboPWD2HdS3ugLijNioS1pqOTIolXNf67xxShYw4SQEmVXd3imiBG+U2bC2nVTySr/iRAA7Cjg==", + "dependencies": { + "bcp-47-match": "^1.0.0", + "comma-separated-tokens": "^1.0.0", + "css-selector-parser": "^1.0.0", + "direction": "^1.0.0", + "hast-util-has-property": "^1.0.0", + "hast-util-is-element": "^1.0.0", + "hast-util-to-string": "^1.0.0", + "hast-util-whitespace": "^1.0.0", + "not": "^0.1.0", + "nth-check": "^2.0.0", + "property-information": "^5.0.0", + "space-separated-tokens": "^1.0.0", + "unist-util-visit": "^2.0.0", + "zwitch": "^1.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-select/node_modules/@types/unist": { + "version": "2.0.10", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.10.tgz", + "integrity": "sha512-IfYcSBWE3hLpBg8+X2SEa8LVkJdJEkT2Ese2aaLs3ptGdVtABxndrMaxuFlQ1qdFf9Q5rDvDpxI3WwgvKFAsQA==" + }, + "node_modules/hast-util-select/node_modules/comma-separated-tokens": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-1.0.8.tgz", + "integrity": "sha512-GHuDRO12Sypu2cV70d1dkA2EUmXHgntrzbpvOB+Qy+49ypNfGgFQIC2fhhXbnyrJRynDCAARsT7Ou0M6hirpfw==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/hast-util-select/node_modules/hast-util-is-element": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/hast-util-is-element/-/hast-util-is-element-1.1.0.tgz", + "integrity": "sha512-oUmNua0bFbdrD/ELDSSEadRVtWZOf3iF6Lbv81naqsIV99RnSCieTbWuWCY8BAeEfKJTKl0gRdokv+dELutHGQ==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-select/node_modules/hast-util-whitespace": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-1.0.4.tgz", + "integrity": "sha512-I5GTdSfhYfAPNztx2xJRQpG8cuDSNt599/7YUn7Gx/WxNMsG+a835k97TDkFgk123cwjfwINaZknkKkphx/f2A==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-select/node_modules/property-information": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/property-information/-/property-information-5.6.0.tgz", + "integrity": "sha512-YUHSPk+A30YPv+0Qf8i9Mbfe/C0hdPXk1s1jPVToV8pk8BQtpw10ct89Eo7OWkutrwqvT0eicAxlOg3dOAu8JA==", + "dependencies": { + "xtend": "^4.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/hast-util-select/node_modules/space-separated-tokens": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-1.1.5.tgz", + "integrity": "sha512-q/JSVd1Lptzhf5bkYm4ob4iWPjx0KiRe3sRFBNrVqbJkFaBm5vbbowy1mymoPNLRa52+oadOhJ+K49wsSeSjTA==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/hast-util-select/node_modules/unist-util-is": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-4.1.0.tgz", + "integrity": "sha512-ZOQSsnce92GrxSqlnEEseX0gi7GH9zTJZ0p9dtu87WRb/37mMPO2Ilx1s/t9vBHrFhbgweUwb+t7cIn5dxPhZg==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-select/node_modules/unist-util-visit": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-2.0.3.tgz", + "integrity": "sha512-iJ4/RczbJMkD0712mGktuGpm/U4By4FfDonL7N/9tATGIF4imikjOuagyMY53tnZq3NP6BcmlrHhEKAfGWjh7Q==", + "dependencies": { + "@types/unist": "^2.0.0", + "unist-util-is": "^4.0.0", + "unist-util-visit-parents": "^3.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-select/node_modules/unist-util-visit-parents": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-3.1.1.tgz", + "integrity": "sha512-1KROIZWo6bcMrZEwiH2UrXDyalAa0uqzWCxCJj6lPOvTve2WkfgCytoDTPaMnodXh1WrXOq0haVYHj99ynJlsg==", + "dependencies": { + "@types/unist": "^2.0.0", + "unist-util-is": "^4.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/hast-util-select/node_modules/zwitch": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-1.0.5.tgz", + "integrity": "sha512-V50KMwwzqJV0NpZIZFwfOD5/lyny3WlSzRiXgA0G7VUnRlqttta1L6UQIHzd6EuBY/cHGfwTIck7w1yH6Q5zUw==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/hast-util-to-jsx-runtime": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.0.tgz", @@ -3116,6 +3274,15 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/hast-util-to-string": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/hast-util-to-string/-/hast-util-to-string-1.0.4.tgz", + "integrity": "sha512-eK0MxRX47AV2eZ+Lyr18DCpQgodvaS3fAQO2+b9Two9F5HEoRPhiUMNzoXArMJfZi2yieFzUBMRl3HNJ3Jus3w==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, "node_modules/hast-util-to-text": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/hast-util-to-text/-/hast-util-to-text-4.0.0.tgz", @@ -3701,9 +3868,9 @@ } }, "node_modules/mdast-util-mdx-jsx": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.0.0.tgz", - "integrity": "sha512-XZuPPzQNBPAlaqsTTgRrcJnyFbSOBovSadFgbFu8SnuNgm+6Bdx1K+IWoitsmj6Lq6MNtI+ytOqwN70n//NaBA==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mdast-util-mdx-jsx/-/mdast-util-mdx-jsx-3.1.0.tgz", + "integrity": "sha512-A8AJHlR7/wPQ3+Jre1+1rq040fX9A4Q1jG8JxmSNp/PLPHg80A6475wxTp3KzHpApFH6yWxFotHrJQA3dXP6/w==", "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", @@ -4322,9 +4489,9 @@ "integrity": "sha512-ihFnidEeU8iXzcVHy74dhkxh/dn8Dc08ERl0xwoMMGqp4+LvRSCgicb+zGqWthVokQKvCSxITlh3P08OzdTYCQ==" }, "node_modules/monaco-editor": { - "version": "0.45.0", - "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.45.0.tgz", - "integrity": "sha512-mjv1G1ZzfEE3k9HZN0dQ2olMdwIfaeAAjFiwNprLfYNRSz7ctv9XuCT7gPtBGrMUeV1/iZzYKj17Khu1hxoHOA==", + "version": "0.46.0", + "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.46.0.tgz", + "integrity": "sha512-ADwtLIIww+9FKybWscd7OCfm9odsFYHImBRI1v9AviGce55QY8raT+9ihH8jX/E/e6QVSGM+pKj4jSUSRmALNQ==", "peer": true }, "node_modules/ms": { @@ -4661,12 +4828,15 @@ } }, "node_modules/postcss-load-config/node_modules/lilconfig": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.0.0.tgz", - "integrity": "sha512-K2U4W2Ff5ibV7j7ydLr+zLAkIg5JJ4lPn1Ltsdt+Tz/IjQ8buJ55pZAxoP34lqIiwtF9iAvtLv3JGv7CAyAg+g==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.0.tgz", + "integrity": "sha512-p3cz0JV5vw/XeouBU3Ldnp+ZkBjE+n8ydJ4mcwBrOiXXPqNlrzGBqWs9X4MWF7f+iKUBu794Y8Hh8yawiJbCjw==", "dev": true, "engines": { "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" } }, "node_modules/postcss-nested": { @@ -4707,18 +4877,18 @@ "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==" }, "node_modules/posthog-js": { - "version": "1.105.4", - "resolved": "https://registry.npmjs.org/posthog-js/-/posthog-js-1.105.4.tgz", - "integrity": "sha512-hazxQYi4nxSqktu0Hh1xCV+sJCpN8mp5E5Ei/cfEa2nsb13xQbzn81Lf3VIDA0xMU1mXxNRStntlY267eQVC/w==", + "version": "1.105.9", + "resolved": "https://registry.npmjs.org/posthog-js/-/posthog-js-1.105.9.tgz", + "integrity": "sha512-i9DnfyXDktugF5E9x0ejihQ8Xdh1kdVnVh7GdL7+PvFtULGMoN/b4pDmWBCwmH+ciubmqTCImVuNrZYy8+eTbw==", "dependencies": { "fflate": "^0.4.8", "preact": "^10.19.3" } }, "node_modules/preact": { - "version": "10.19.3", - "resolved": "https://registry.npmjs.org/preact/-/preact-10.19.3.tgz", - "integrity": "sha512-nHHTeFVBTHRGxJXKkKu5hT8C/YWBkPso4/Gad6xuj5dbptt9iF9NZr9pHbPhBrnT2klheu7mHTxTZ/LjwJiEiQ==", + "version": "10.19.4", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.19.4.tgz", + "integrity": "sha512-dwaX5jAh0Ga8uENBX1hSOujmKWgx9RtL80KaKUFLc6jb4vCEAc3EeZ0rnQO/FO4VgjfPMfoLFWnNG8bHuZ9VLw==", "funding": { "type": "opencollective", "url": "https://opencollective.com/preact" @@ -5474,11 +5644,11 @@ } }, "node_modules/react-tooltip": { - "version": "5.26.0", - "resolved": "https://registry.npmjs.org/react-tooltip/-/react-tooltip-5.26.0.tgz", - "integrity": "sha512-UBbwy3fo1KYDwRCOWwM6AEfQsk9shgVfNkXFqgwS33QHplzg7xao/7mX/6wd+lE6KSZzhUNTkB5TNk9SMaBV/A==", + "version": "5.26.2", + "resolved": "https://registry.npmjs.org/react-tooltip/-/react-tooltip-5.26.2.tgz", + "integrity": "sha512-C1qHiqWYn6l5c98kL/NKFyJSw5G11vUVJkgOPcKgn306c5iL5317LxMNn5Qg1GSSM7Qvtsd6KA5MvwfgxFF7Dg==", "dependencies": { - "@floating-ui/dom": "^1.0.0", + "@floating-ui/dom": "^1.6.1", "classnames": "^2.3.0" }, "peerDependencies": { @@ -5741,123 +5911,6 @@ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.10.tgz", "integrity": "sha512-IfYcSBWE3hLpBg8+X2SEa8LVkJdJEkT2Ese2aaLs3ptGdVtABxndrMaxuFlQ1qdFf9Q5rDvDpxI3WwgvKFAsQA==" }, - "node_modules/rehype-wrap-all/node_modules/bcp-47-match": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-1.0.3.tgz", - "integrity": "sha512-LggQ4YTdjWQSKELZF5JwchnBa1u0pIQSZf5lSdOHEdbVP55h0qICA/FUp3+W99q0xqxYa1ZQizTUH87gecII5w==", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/rehype-wrap-all/node_modules/comma-separated-tokens": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-1.0.8.tgz", - "integrity": "sha512-GHuDRO12Sypu2cV70d1dkA2EUmXHgntrzbpvOB+Qy+49ypNfGgFQIC2fhhXbnyrJRynDCAARsT7Ou0M6hirpfw==", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/rehype-wrap-all/node_modules/css-selector-parser": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/css-selector-parser/-/css-selector-parser-1.4.1.tgz", - "integrity": "sha512-HYPSb7y/Z7BNDCOrakL4raGO2zltZkbeXyAd6Tg9obzix6QhzxCotdBl6VT0Dv4vZfJGVz3WL/xaEI9Ly3ul0g==" - }, - "node_modules/rehype-wrap-all/node_modules/direction": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/direction/-/direction-1.0.4.tgz", - "integrity": "sha512-GYqKi1aH7PJXxdhTeZBFrg8vUBeKXi+cNprXsC1kpJcbcVnV9wBsrOu1cQEdG0WeQwlfHiy3XvnKfIrJ2R0NzQ==", - "bin": { - "direction": "cli.js" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/rehype-wrap-all/node_modules/hast-util-has-property": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/hast-util-has-property/-/hast-util-has-property-1.0.4.tgz", - "integrity": "sha512-ghHup2voGfgFoHMGnaLHOjbYFACKrRh9KFttdCzMCbFoBMJXiNi2+XTrPP8+q6cDJM/RSqlCfVWrjp1H201rZg==", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/rehype-wrap-all/node_modules/hast-util-is-element": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/hast-util-is-element/-/hast-util-is-element-1.1.0.tgz", - "integrity": "sha512-oUmNua0bFbdrD/ELDSSEadRVtWZOf3iF6Lbv81naqsIV99RnSCieTbWuWCY8BAeEfKJTKl0gRdokv+dELutHGQ==", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/rehype-wrap-all/node_modules/hast-util-select": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/hast-util-select/-/hast-util-select-4.0.2.tgz", - "integrity": "sha512-8EEG2//bN5rrzboPWD2HdS3ugLijNioS1pqOTIolXNf67xxShYw4SQEmVXd3imiBG+U2bC2nVTySr/iRAA7Cjg==", - "dependencies": { - "bcp-47-match": "^1.0.0", - "comma-separated-tokens": "^1.0.0", - "css-selector-parser": "^1.0.0", - "direction": "^1.0.0", - "hast-util-has-property": "^1.0.0", - "hast-util-is-element": "^1.0.0", - "hast-util-to-string": "^1.0.0", - "hast-util-whitespace": "^1.0.0", - "not": "^0.1.0", - "nth-check": "^2.0.0", - "property-information": "^5.0.0", - "space-separated-tokens": "^1.0.0", - "unist-util-visit": "^2.0.0", - "zwitch": "^1.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/rehype-wrap-all/node_modules/hast-util-to-string": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/hast-util-to-string/-/hast-util-to-string-1.0.4.tgz", - "integrity": "sha512-eK0MxRX47AV2eZ+Lyr18DCpQgodvaS3fAQO2+b9Two9F5HEoRPhiUMNzoXArMJfZi2yieFzUBMRl3HNJ3Jus3w==", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/rehype-wrap-all/node_modules/hast-util-whitespace": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-1.0.4.tgz", - "integrity": "sha512-I5GTdSfhYfAPNztx2xJRQpG8cuDSNt599/7YUn7Gx/WxNMsG+a835k97TDkFgk123cwjfwINaZknkKkphx/f2A==", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/rehype-wrap-all/node_modules/property-information": { - "version": "5.6.0", - "resolved": "https://registry.npmjs.org/property-information/-/property-information-5.6.0.tgz", - "integrity": "sha512-YUHSPk+A30YPv+0Qf8i9Mbfe/C0hdPXk1s1jPVToV8pk8BQtpw10ct89Eo7OWkutrwqvT0eicAxlOg3dOAu8JA==", - "dependencies": { - "xtend": "^4.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/rehype-wrap-all/node_modules/space-separated-tokens": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-1.1.5.tgz", - "integrity": "sha512-q/JSVd1Lptzhf5bkYm4ob4iWPjx0KiRe3sRFBNrVqbJkFaBm5vbbowy1mymoPNLRa52+oadOhJ+K49wsSeSjTA==", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, "node_modules/rehype-wrap-all/node_modules/unist-util-is": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-4.1.0.tgz", @@ -5894,15 +5947,6 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/rehype-wrap-all/node_modules/zwitch": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-1.0.5.tgz", - "integrity": "sha512-V50KMwwzqJV0NpZIZFwfOD5/lyny3WlSzRiXgA0G7VUnRlqttta1L6UQIHzd6EuBY/cHGfwTIck7w1yH6Q5zUw==", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, "node_modules/remark-math": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/remark-math/-/remark-math-6.0.0.tgz", diff --git a/gui/src/util/ide.ts b/gui/src/util/ide.ts index 90af1d856..1cd49adb9 100644 --- a/gui/src/util/ide.ts +++ b/gui/src/util/ide.ts @@ -45,15 +45,16 @@ function _postToIde(messageType: string, data: any, messageId?: string) { export function postToIde( messageType: T, data: WebviewProtocol[T][0], + messageId?: string, attempt: number = 0 ) { try { - _postToIde(messageType, data); + _postToIde(messageType, data, messageId); } catch (error) { if (attempt < 5) { console.log(`Attempt ${attempt} failed. Retrying...`); setTimeout( - () => postToIde(messageType, data, attempt + 1), + () => postToIde(messageType, data, messageId, attempt + 1), Math.pow(2, attempt) * 1000 ); } else { @@ -85,7 +86,7 @@ export async function ideRequest( }; window.addEventListener("message", handler); - postToIde(messageType, data); + postToIde(messageType, data, messageId); }) as any; } @@ -96,7 +97,7 @@ export async function* ideStreamRequest( ): WebviewProtocol[T][1] { const messageId = uuidv4(); - postToIde(messageType, data); + postToIde(messageType, data, messageId); let buffer = ""; let index = 0; @@ -117,7 +118,7 @@ export async function* ideStreamRequest( window.addEventListener("message", handler); cancelToken?.addEventListener("abort", () => { - postToIde("abort", messageId); + postToIde("abort", undefined, messageId); }); while (!done) { From cc9f057454c73770c09e1bdbf32af55f7b95cfbc Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 14 Feb 2024 18:31:00 -0800 Subject: [PATCH 08/59] =?UTF-8?q?=F0=9F=90=9B=20stop=20infinite=20loop=20o?= =?UTF-8?q?f=20messages=20between=20webview=20and=20ide?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extensions/vscode/src/lang-server/completionProvider.ts | 1 + extensions/vscode/src/webviewProtocol.ts | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/src/lang-server/completionProvider.ts b/extensions/vscode/src/lang-server/completionProvider.ts index c2af7f2c4..626899754 100644 --- a/extensions/vscode/src/lang-server/completionProvider.ts +++ b/extensions/vscode/src/lang-server/completionProvider.ts @@ -15,6 +15,7 @@ import { ConfigHandler } from "core/config/handler"; import { streamLines } from "core/diff/util"; import OpenAI from "core/llm/llms/OpenAI"; import { logDevData } from "core/util/devdata"; +import Handlebars from "handlebars"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 2f83e8cb0..bbdf3d66b 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -98,7 +98,6 @@ export class VsCodeWebviewProtocol { }); } } - respond({ done: true, data: {} }); }); } From 3a39b4b28c50e86398fc3610a8fd8eb63a6e6bac Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 14 Feb 2024 18:47:29 -0800 Subject: [PATCH 09/59] =?UTF-8?q?=E2=9C=A8=20streaming?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extensions/vscode/src/webviewProtocol.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index bbdf3d66b..88d2d8039 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -65,7 +65,17 @@ export class VsCodeWebviewProtocol { for (const handler of handlers) { try { const response = await handler(msg); - respond(response || {}); + if ( + response && + typeof response[Symbol.asyncIterator] === "function" + ) { + for await (const update of response) { + respond(update); + } + respond({ done: true }); + } else { + respond(response || {}); + } } catch (e: any) { console.error( "Error handling webview message: " + From c54e2ce288d72dd45e21fefd7b73da8bbc3f5a3e Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 14 Feb 2024 20:21:04 -0800 Subject: [PATCH 10/59] =?UTF-8?q?=F0=9F=90=9B=20load=20onigasm.wasm=20in?= =?UTF-8?q?=20jetbrains?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extensions/vscode/scripts/prepackage.js | 8 ++++++++ gui/src/main.tsx | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index 4db78c7cb..756661d15 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -77,11 +77,19 @@ if (args[2] === "--target") { }); }); + // Put back index.html if (fs.existsSync(indexHtmlPath)) { fs.rmSync(indexHtmlPath, {}); } fs.copyFileSync("tmp_index.html", indexHtmlPath); fs.unlinkSync("tmp_index.html"); + + // Copy over other misc. files + fs.copyFileSync( + "../extensions/vscode/gui/onigasm.wasm", + path.join(intellijExtensionWebviewPath, "onigasm.wasm") + ); + console.log("[info] Copied gui build to Intellij extension"); // Then copy over the dist folder to the VSCode extension // diff --git a/gui/src/main.tsx b/gui/src/main.tsx index 9e46b8109..fe9196049 100644 --- a/gui/src/main.tsx +++ b/gui/src/main.tsx @@ -9,7 +9,7 @@ import "./index.css"; import { persistor, store } from "./redux/store"; (async () => { - const onigPath = (window as any).vscMediaUrl + "/onigasm.wasm"; + const onigPath = ((window as any).vscMediaUrl ?? "") + "/onigasm.wasm"; const resp = await fetch(onigPath); const onigWasm = await resp.arrayBuffer(); await loadWASM(onigWasm); From fb1d38436a8e49922984c7fbf67d903cb43a060d Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 14 Feb 2024 21:38:06 -0800 Subject: [PATCH 11/59] =?UTF-8?q?=F0=9F=9A=A7=20update=20jetbrains=20messa?= =?UTF-8?q?ging=20format?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../continue/IdeProtocolClient.kt | 26 ++----------------- .../factories/CustomhandlerFactory.kt | 2 +- .../ContinuePluginToolWindowFactory.kt | 22 +++++++++++----- gui/src/main.tsx | 1 + 4 files changed, 20 insertions(+), 31 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 8a6f64ae4..b52384052 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -1,28 +1,19 @@ package com.github.continuedev.continueintellijextension.`continue` -import com.github.continuedev.continueintellijextension.* import com.github.continuedev.continueintellijextension.constants.* import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.google.gson.Gson import com.google.gson.GsonBuilder -import com.google.gson.JsonObject import com.google.gson.reflect.TypeToken -import com.intellij.execution.ExecutionManager -import com.intellij.execution.process.ProcessAdapter -import com.intellij.execution.process.ProcessEvent -import com.intellij.execution.ui.RunContentDescriptor import com.intellij.openapi.Disposable -import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.editor.SelectionModel import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project -import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.ui.MessageType import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory @@ -32,15 +23,10 @@ import com.intellij.openapi.wm.WindowManager import com.intellij.testFramework.LightVirtualFile import com.intellij.ui.awt.RelativePoint import kotlinx.coroutines.* -import net.minidev.json.JSONObject -import org.jetbrains.annotations.NotNull import java.io.* import java.net.NetworkInterface import java.nio.charset.Charset -import java.nio.file.Files -import java.nio.file.Paths import java.util.* -import kotlin.coroutines.ContinuationInterceptor fun uuid(): String { @@ -146,27 +132,19 @@ class IdeProtocolClient ( continuePluginService.dispatchCustomEvent(json) } - fun handleWebsocketMessage(text: String) { + fun handleMessage(text: String, respond: (Any?) -> Unit) { coroutineScope.launch(Dispatchers.IO) { val parsedMessage: Map = Gson().fromJson( text, object : TypeToken>() {}.type ) - val messageType = parsedMessage["type"] as? String + val messageType = parsedMessage["messageType"] as? String if (messageType == null) { println("Recieved message without type: $text") return@launch } val data = parsedMessage["data"] as Map<*, *> - fun respond(responseData: Any?) { - if (data["messageId"] == null) { - println("Recieved message without messageId: $text") - return - } - send(messageType, responseData ?: emptyMap(), data["messageId"] as String); - } - val historyManager = HistoryManager() try { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/factories/CustomhandlerFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/factories/CustomhandlerFactory.kt index 0bc9d70e6..4b3c3cdcd 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/factories/CustomhandlerFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/factories/CustomhandlerFactory.kt @@ -35,7 +35,7 @@ class CustomResourceHandler : CefResourceHandler, DumbAware { ): Boolean { val url = cefRequest.url return if (url != null) { - val pathToResource = url.replace("http://continue", "webview/") + val pathToResource = url.replace("http://continue", "webview/").replace("http://localhost:5173", "webview/") val newUrl = javaClass.classLoader.getResource(pathToResource) state = OpenedConnection(newUrl?.openConnection()) currentUrl = url diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt index 8f83decf7..50451b02f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt @@ -68,6 +68,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { registerAppSchemeHandler() browser.loadURL("http://continue/index.html") +// browser.loadURL("http://localhost:5173/index.html") Disposer.register(project, browser) val continuePluginService = ServiceManager.getService( @@ -81,12 +82,23 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { myJSQueryOpenInBrowser.addHandler { msg: String? -> val parser = JsonParser() val json: JsonObject = parser.parse(msg).asJsonObject - val type = json.get("type").asString + val messageType = json.get("messageType").asString val data = json.get("data").asJsonObject + val messageId = json.get("messageId").asString val ide = continuePluginService.ideProtocolClient; - when (type) { + val respond = fun(data: Any?) { + val jsonData = mutableMapOf( + "messageId" to messageId, + "data" to data, + "messageType" to messageType + ) + val jsonString = Gson().toJson(jsonData) + browser.executeJavaScriptAsync("""window.postMessage($jsonString, "*");""") + } + + when (messageType) { "onLoad" -> { GlobalScope.launch { // Set the colors to match Intellij theme @@ -121,14 +133,12 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-editor-background\", \"$defaultBackgroundHex\");") val jsonData = mutableMapOf( - "type" to "onLoad", "windowId" to continuePluginService.windowId, "workspacePaths" to continuePluginService.worksapcePaths, "vscMachineId" to getMachineUniqueID(), "vscMediaUrl" to "http://continue", ) - val jsonString = Gson().toJson(jsonData) - browser.executeJavaScriptAsync("""window.postMessage($jsonString, "*");""") + respond(jsonData) } } @@ -172,7 +182,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { // IDE // else -> { if (msg != null) { - ide?.handleWebsocketMessage(msg) + ide?.handleMessage(msg, respond) } } } diff --git a/gui/src/main.tsx b/gui/src/main.tsx index fe9196049..be4348f20 100644 --- a/gui/src/main.tsx +++ b/gui/src/main.tsx @@ -9,6 +9,7 @@ import "./index.css"; import { persistor, store } from "./redux/store"; (async () => { + // "" lets it pass through to the correct path for JetBrains const onigPath = ((window as any).vscMediaUrl ?? "") + "/onigasm.wasm"; const resp = await fetch(onigPath); const onigWasm = await resp.arrayBuffer(); From 756cb7fead383fe649a5d70692b52109c6da01be Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 14 Feb 2024 23:14:29 -0800 Subject: [PATCH 12/59] =?UTF-8?q?=F0=9F=91=B7=20build=20with=20pkg?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/.continueignore | 1 + pkg/.gitignore | 4 + pkg/build.js | 34 + pkg/importMetaUrl.js | 2 + pkg/package-lock.json | 2480 +++++++++++++++++++++++++++ pkg/package.json | 41 + {core/ipc => pkg/src}/IpcIde.ts | 2 +- {core/ipc => pkg/src}/core.ts | 16 +- core/ipc/cli.ts => pkg/src/index.ts | 0 {core/ipc => pkg/src}/messenger.ts | 4 +- pkg/tsconfig.json | 19 + 11 files changed, 2592 insertions(+), 11 deletions(-) create mode 100644 pkg/.continueignore create mode 100644 pkg/.gitignore create mode 100644 pkg/build.js create mode 100644 pkg/importMetaUrl.js create mode 100644 pkg/package-lock.json create mode 100644 pkg/package.json rename {core/ipc => pkg/src}/IpcIde.ts (97%) rename {core/ipc => pkg/src}/core.ts (87%) rename core/ipc/cli.ts => pkg/src/index.ts (100%) rename {core/ipc => pkg/src}/messenger.ts (98%) create mode 100644 pkg/tsconfig.json diff --git a/pkg/.continueignore b/pkg/.continueignore new file mode 100644 index 000000000..01b7e33fd --- /dev/null +++ b/pkg/.continueignore @@ -0,0 +1 @@ +**/* \ No newline at end of file diff --git a/pkg/.gitignore b/pkg/.gitignore new file mode 100644 index 000000000..49383d4fc --- /dev/null +++ b/pkg/.gitignore @@ -0,0 +1,4 @@ +node_modules +bin +data +out \ No newline at end of file diff --git a/pkg/build.js b/pkg/build.js new file mode 100644 index 000000000..b55bfbf72 --- /dev/null +++ b/pkg/build.js @@ -0,0 +1,34 @@ +const esbuild = require("esbuild"); +const { execSync } = require("child_process"); + +const esbuildOutputFile = "out/index.js"; + +(async () => { + // console.log("[info] Building with ncc..."); + // execSync(`npx ncc build src/index.ts -o out`); + + console.log("[info] Building with esbuild..."); + // Bundles the extension into one file + await esbuild.build({ + entryPoints: ["src/index.ts"], + bundle: true, + outfile: esbuildOutputFile, + external: ["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" }, + }); + + console.log("[info] Building binary with pkg..."); + execSync("npx pkg ."); + console.log("[info] Done!"); +})(); diff --git a/pkg/importMetaUrl.js b/pkg/importMetaUrl.js new file mode 100644 index 000000000..0508c8d33 --- /dev/null +++ b/pkg/importMetaUrl.js @@ -0,0 +1,2 @@ +// https://github.com/evanw/esbuild/issues/1492#issuecomment-893144483 +export var importMetaUrl = require("url").pathToFileURL(__filename); diff --git a/pkg/package-lock.json b/pkg/package-lock.json new file mode 100644 index 000000000..973d4c0a7 --- /dev/null +++ b/pkg/package-lock.json @@ -0,0 +1,2480 @@ +{ + "name": "pkg", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "pkg", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "commander": "^12.0.0", + "core": "file:../core", + "uuid": "^9.0.1", + "vectordb": "^0.4.10" + }, + "bin": { + "pkg": "out/index.js" + }, + "devDependencies": { + "@types/uuid": "^9.0.8", + "@vercel/ncc": "^0.38.1", + "esbuild": "^0.19.11", + "pkg": "^5.8.1", + "typescript": "^5.3.3" + } + }, + "../core": { + "version": "1.0.0", + "license": "Apache-2.0", + "dependencies": { + "@octokit/rest": "^20.0.2", + "@types/node-fetch": "^2.6.11", + "@xenova/transformers": "^2.14.0", + "cheerio": "^1.0.0-rc.12", + "commander": "^12.0.0", + "dotenv": "^16.3.1", + "fastest-levenshtein": "^1.0.16", + "follow-redirects": "^1.15.5", + "handlebars": "^4.7.8", + "http-proxy-agent": "^7.0.1", + "https-proxy-agent": "^7.0.3", + "js-tiktoken": "^1.0.8", + "llm-code-highlighter": "^0.0.5", + "node-fetch": "^3.3.2", + "node-html-markdown": "^1.3.0", + "ollama": "^0.4.6", + "openai": "^4.20.1", + "posthog-node": "^3.6.2", + "replicate": "^0.26.0", + "socket.io-client": "^4.7.3", + "sqlite": "^5.1.1", + "sqlite3": "^5.1.7", + "tree-sitter-wasms": "^0.1.6", + "uuid": "^9.0.1", + "vectordb": "^0.4.3", + "web-tree-sitter": "^0.20.8" + }, + "devDependencies": { + "@types/follow-redirects": "^1.14.4", + "@types/handlebars": "^4.1.0", + "@types/jest": "^29.5.11", + "@types/jquery": "^3.5.29", + "@types/mustache": "^4.2.5", + "@types/uuid": "^9.0.7", + "esbuild": "^0.19.11", + "jest": "^29.7.0", + "ts-jest": "^29.1.1" + } + }, + "node_modules/@75lb/deep-merge": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.1.tgz", + "integrity": "sha512-xvgv6pkMGBA6GwdyJbNAnDmfAIR/DfWhrj9jgWh3TY7gRm3KO46x/GPjRg6wJ0nOepwqrNxFfojebh0Df4h4Tw==", + "dependencies": { + "lodash.assignwith": "^4.2.0", + "typical": "^7.1.1" + }, + "engines": { + "node": ">=12.17" + } + }, + "node_modules/@75lb/deep-merge/node_modules/typical": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-7.1.1.tgz", + "integrity": "sha512-T+tKVNs6Wu7IWiAce5BgMd7OZfNYUndHwc5MknN+UHOudi7sGZzuHdCadllRuqJ3fPtgFtIH9+lt9qRv6lmpfA==", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/@apache-arrow/ts": { + "version": "14.0.2", + "resolved": "https://registry.npmjs.org/@apache-arrow/ts/-/ts-14.0.2.tgz", + "integrity": "sha512-CtwAvLkK0CZv7xsYeCo91ml6PvlfzAmAJZkRYuz2GNBwfYufj5SVi0iuSMwIMkcU/szVwvLdzORSLa5PlF/2ug==", + "dependencies": { + "@types/command-line-args": "5.2.0", + "@types/command-line-usage": "5.0.2", + "@types/node": "20.3.0", + "@types/pad-left": "2.1.1", + "command-line-args": "5.2.1", + "command-line-usage": "7.0.1", + "flatbuffers": "23.5.26", + "json-bignum": "^0.0.3", + "pad-left": "^2.1.0", + "tslib": "^2.5.3" + } + }, + "node_modules/@babel/generator": { + "version": "7.18.2", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.18.2.tgz", + "integrity": "sha512-W1lG5vUwFvfMd8HVXqdfbuG7RuaSrTCCD8cl8fP8wOivdbtbIg2Db3IWUcgvfxKbbn6ZBGYRW/Zk1MIwK49mgw==", + "dev": true, + "dependencies": { + "@babel/types": "^7.18.2", + "@jridgewell/gen-mapping": "^0.3.0", + "jsesc": "^2.5.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.23.4.tgz", + "integrity": "sha512-803gmbQdqwdf4olxrX4AJyFBV/RTr3rSmOj0rKwesmzlfhYNDEs+/iOcznzpNWlJlIlTJC2QfPFcHB6DlzdVLQ==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", + "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.18.4", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.18.4.tgz", + "integrity": "sha512-FDge0dFazETFcxGw/EXzOkN8uJp0PC7Qbm+Pe9T+av2zlBpOgunFHkQPPn+eRuClU73JF+98D531UgayY89tow==", + "dev": true, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.19.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.19.0.tgz", + "integrity": "sha512-YuGopBq3ke25BVSiS6fgF49Ul9gH1x70Bcr6bqRLjWCkcX8Hre1/5+z+IiWOIerRMSSEfGZVB9z9kyq7wVs9YA==", + "dev": true, + "dependencies": { + "@babel/helper-string-parser": "^7.18.10", + "@babel/helper-validator-identifier": "^7.18.6", + "to-fast-properties": "^2.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.19.11.tgz", + "integrity": "sha512-FnzU0LyE3ySQk7UntJO4+qIiQgI7KoODnZg5xzXIrFJlKd2P2gwHsHY4927xj9y5PJmJSzULiUCWmv7iWnNa7g==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.11.tgz", + "integrity": "sha512-5OVapq0ClabvKvQ58Bws8+wkLCV+Rxg7tUVbo9xu034Nm536QTII4YzhaFriQ7rMrorfnFKUsArD2lqKbFY4vw==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.11.tgz", + "integrity": "sha512-aiu7K/5JnLj//KOnOfEZ0D90obUkRzDMyqd/wNAUQ34m4YUPVhRZpnqKV9uqDGxT7cToSDnIHsGooyIczu9T+Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.11.tgz", + "integrity": "sha512-eccxjlfGw43WYoY9QgB82SgGgDbibcqyDTlk3l3C0jOVHKxrjdc9CTwDUQd0vkvYg5um0OH+GpxYvp39r+IPOg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.11.tgz", + "integrity": "sha512-ETp87DRWuSt9KdDVkqSoKoLFHYTrkyz2+65fj9nfXsaV3bMhTCjtQfw3y+um88vGRKRiF7erPrh/ZuIdLUIVxQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.11.tgz", + "integrity": "sha512-fkFUiS6IUK9WYUO/+22omwetaSNl5/A8giXvQlcinLIjVkxwTLSktbF5f/kJMftM2MJp9+fXqZ5ezS7+SALp4g==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.11.tgz", + "integrity": "sha512-lhoSp5K6bxKRNdXUtHoNc5HhbXVCS8V0iZmDvyWvYq9S5WSfTIHU2UGjcGt7UeS6iEYp9eeymIl5mJBn0yiuxA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.11.tgz", + "integrity": "sha512-JkUqn44AffGXitVI6/AbQdoYAq0TEullFdqcMY/PCUZ36xJ9ZJRtQabzMA+Vi7r78+25ZIBosLTOKnUXBSi1Kw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.11.tgz", + "integrity": "sha512-3CRkr9+vCV2XJbjwgzjPtO8T0SZUmRZla+UL1jw+XqHZPkPgZiyWvbDvl9rqAN8Zl7qJF0O/9ycMtjU67HN9/Q==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.11.tgz", + "integrity": "sha512-LneLg3ypEeveBSMuoa0kwMpCGmpu8XQUh+mL8XXwoYZ6Be2qBnVtcDI5azSvh7vioMDhoJFZzp9GWp9IWpYoUg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.11.tgz", + "integrity": "sha512-caHy++CsD8Bgq2V5CodbJjFPEiDPq8JJmBdeyZ8GWVQMjRD0sU548nNdwPNvKjVpamYYVL40AORekgfIubwHoA==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.11.tgz", + "integrity": "sha512-ppZSSLVpPrwHccvC6nQVZaSHlFsvCQyjnvirnVjbKSHuE5N24Yl8F3UwYUUR1UEPaFObGD2tSvVKbvR+uT1Nrg==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.11.tgz", + "integrity": "sha512-B5x9j0OgjG+v1dF2DkH34lr+7Gmv0kzX6/V0afF41FkPMMqaQ77pH7CrhWeR22aEeHKaeZVtZ6yFwlxOKPVFyg==", + "cpu": [ + "mips64el" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.11.tgz", + "integrity": "sha512-MHrZYLeCG8vXblMetWyttkdVRjQlQUb/oMgBNurVEnhj4YWOr4G5lmBfZjHYQHHN0g6yDmCAQRR8MUHldvvRDA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.11.tgz", + "integrity": "sha512-f3DY++t94uVg141dozDu4CCUkYW+09rWtaWfnb3bqe4w5NqmZd6nPVBm+qbz7WaHZCoqXqHz5p6CM6qv3qnSSQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.11.tgz", + "integrity": "sha512-A5xdUoyWJHMMlcSMcPGVLzYzpcY8QP1RtYzX5/bS4dvjBGVxdhuiYyFwp7z74ocV7WDc0n1harxmpq2ePOjI0Q==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.11.tgz", + "integrity": "sha512-grbyMlVCvJSfxFQUndw5mCtWs5LO1gUlwP4CDi4iJBbVpZcqLVT29FxgGuBJGSzyOxotFG4LoO5X+M1350zmPA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.11.tgz", + "integrity": "sha512-13jvrQZJc3P230OhU8xgwUnDeuC/9egsjTkXN49b3GcS5BKvJqZn86aGM8W9pd14Kd+u7HuFBMVtrNGhh6fHEQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.11.tgz", + "integrity": "sha512-ysyOGZuTp6SNKPE11INDUeFVVQFrhcNDVUgSQVDzqsqX38DjhPEPATpid04LCoUr2WXhQTEZ8ct/EgJCUDpyNw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.11.tgz", + "integrity": "sha512-Hf+Sad9nVwvtxy4DXCZQqLpgmRTQqyFyhT3bZ4F2XlJCjxGmRFF0Shwn9rzhOYRB61w9VMXUkxlBy56dk9JJiQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.11.tgz", + "integrity": "sha512-0P58Sbi0LctOMOQbpEOvOL44Ne0sqbS0XWHMvvrg6NE5jQ1xguCSSw9jQeUk2lfrXYsKDdOe6K+oZiwKPilYPQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.11.tgz", + "integrity": "sha512-6YOrWS+sDJDmshdBIQU+Uoyh7pQKrdykdefC1avn76ss5c+RN6gut3LZA4E2cH5xUEp5/cA0+YxRaVtRAb0xBg==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.11.tgz", + "integrity": "sha512-vfkhltrjCAb603XaFhqhAF4LGDi2M4OrCRrFusyQ+iTLQ/o60QQXxc9cZC/FFpihBI9N1Grn6SMKVJ4KP7Fuiw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz", + "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==", + "dev": true, + "dependencies": { + "@jridgewell/set-array": "^1.0.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz", + "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz", + "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", + "dev": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.21", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.21.tgz", + "integrity": "sha512-SRfKmRe1KvYnxjEMtxEr+J4HIeMX5YBg/qhRHpxEIGjhX1rshcHlnFUE9K0GazhVKWM7B+nARSkV8LuvJdJ5/g==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@lancedb/vectordb-darwin-arm64": { + "version": "0.4.10", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.10.tgz", + "integrity": "sha512-y/uHOGb0g15pvqv5tdTyZ6oN+0QVpBmZDzKFWW6pPbuSZjB2uPqcs+ti0RB+AUdmS21kavVQqaNsw/HLKEGrHA==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@lancedb/vectordb-darwin-x64": { + "version": "0.4.10", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-x64/-/vectordb-darwin-x64-0.4.10.tgz", + "integrity": "sha512-XbfR58OkQpAe0xMSTrwJh9ZjGSzG9EZ7zwO6HfYem8PxcLYAcC6eWRWoSG/T0uObyrPTcYYyvHsp0eNQWYBFAQ==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@lancedb/vectordb-linux-arm64-gnu": { + "version": "0.4.10", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-arm64-gnu/-/vectordb-linux-arm64-gnu-0.4.10.tgz", + "integrity": "sha512-x40WKH9b+KxorRmKr9G7fv8p5mMj8QJQvRMA0v6v+nbZHr2FLlAZV+9mvhHOnm4AGIkPP5335cUgv6Qz6hgwkQ==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@lancedb/vectordb-linux-x64-gnu": { + "version": "0.4.10", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-x64-gnu/-/vectordb-linux-x64-gnu-0.4.10.tgz", + "integrity": "sha512-CTGPpuzlqq2nVjUxI9gAJOT1oBANIovtIaFsOmBSnEAHgX7oeAxKy2b6L/kJzsgqSzvR5vfLwYcWFrr6ZmBxSA==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@lancedb/vectordb-win32-x64-msvc": { + "version": "0.4.10", + "resolved": "https://registry.npmjs.org/@lancedb/vectordb-win32-x64-msvc/-/vectordb-win32-x64-msvc-0.4.10.tgz", + "integrity": "sha512-Fd7r74coZyrKzkfXg4WthqOL+uKyJyPTia6imcrMNqKOlTGdKmHf02Qi2QxWZrFaabkRYo4Tpn5FeRJ3yYX8CA==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@neon-rs/load": { + "version": "0.0.74", + "resolved": "https://registry.npmjs.org/@neon-rs/load/-/load-0.0.74.tgz", + "integrity": "sha512-/cPZD907UNz55yrc/ud4wDgQKtU1TvkD9jeqZWG6J4IMmZkp6zgjkQcKA8UvpkZlcpPHvc8J17sGzLFbP/LUYg==" + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@types/command-line-args": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@types/command-line-args/-/command-line-args-5.2.0.tgz", + "integrity": "sha512-UuKzKpJJ/Ief6ufIaIzr3A/0XnluX7RvFgwkV89Yzvm77wCh1kFaFmqN8XEnGcN62EuHdedQjEMb8mYxFLGPyA==" + }, + "node_modules/@types/command-line-usage": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@types/command-line-usage/-/command-line-usage-5.0.2.tgz", + "integrity": "sha512-n7RlEEJ+4x4TS7ZQddTmNSxP+zziEG0TNsMfiRIxcIVXt71ENJ9ojeXmGO3wPoTdn7pJcU2xc3CJYMktNT6DPg==" + }, + "node_modules/@types/node": { + "version": "20.3.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.3.0.tgz", + "integrity": "sha512-cumHmIAf6On83X7yP+LrsEyUOf/YlociZelmpRYaGFydoaPdxdt80MAbu6vWerQT2COCp2nPvHdsbD7tHn/YlQ==" + }, + "node_modules/@types/pad-left": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@types/pad-left/-/pad-left-2.1.1.tgz", + "integrity": "sha512-Xd22WCRBydkGSApl5Bw0PhAOHKSVjNL3E3AwzKaps96IMraPqy5BvZIsBVK6JLwdybUzjHnuWVwpDd0JjTfHXA==" + }, + "node_modules/@types/uuid": { + "version": "9.0.8", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.8.tgz", + "integrity": "sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA==", + "dev": true + }, + "node_modules/@vercel/ncc": { + "version": "0.38.1", + "resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.38.1.tgz", + "integrity": "sha512-IBBb+iI2NLu4VQn3Vwldyi2QwaXt5+hTyh58ggAMoCGE6DJmPvwL3KPBWcJl1m9LYPChBLE980Jw+CS4Wokqxw==", + "dev": true, + "bin": { + "ncc": "dist/ncc/cli.js" + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "dev": true, + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/apache-arrow": { + "version": "14.0.2", + "resolved": "https://registry.npmjs.org/apache-arrow/-/apache-arrow-14.0.2.tgz", + "integrity": "sha512-EBO2xJN36/XoY81nhLcwCJgFwkboDZeyNQ+OPsG7bCoQjc2BT0aTyH/MR6SrL+LirSNz+cYqjGRlupMMlP1aEg==", + "dependencies": { + "@types/command-line-args": "5.2.0", + "@types/command-line-usage": "5.0.2", + "@types/node": "20.3.0", + "@types/pad-left": "2.1.1", + "command-line-args": "5.2.1", + "command-line-usage": "7.0.1", + "flatbuffers": "23.5.26", + "json-bignum": "^0.0.3", + "pad-left": "^2.1.0", + "tslib": "^2.5.3" + }, + "bin": { + "arrow2csv": "bin/arrow2csv.js" + } + }, + "node_modules/array-back": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-3.1.0.tgz", + "integrity": "sha512-TkuxA4UCOvxuDK6NZYXCalszEzj+TLszyASooky+i742l9TqsOdYCMJJupxRic61hwquNtppB3hgcuq9SVSH1Q==", + "engines": { + "node": ">=6" + } + }, + "node_modules/array-union": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", + "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/at-least-node": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/at-least-node/-/at-least-node-1.0.0.tgz", + "integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==", + "dev": true, + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/axios": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.7.tgz", + "integrity": "sha512-/hDJGff6/c7u0hDkvkGxR/oy6CbCs8ziCsC7SqmhjfozqiJGc8Z11wrv9z9lYfY4K8l+H9TpjcMDX0xOZmx+RA==", + "dependencies": { + "follow-redirects": "^1.15.4", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "dev": true, + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/bl/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dev": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk-template": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/chalk-template/-/chalk-template-0.4.0.tgz", + "integrity": "sha512-/ghrgmhfY8RaSdeo43hNXxpoHAtxdbskUHjPpfqUWGttFgycUhYPGx3YZBCnUCvOa7Doivn1IZec3DEGFoMgLg==", + "dependencies": { + "chalk": "^4.1.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/chalk-template?sponsor=1" + } + }, + "node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "dev": true + }, + "node_modules/cliui": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", + "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", + "dev": true, + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^7.0.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/command-line-args": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.2.1.tgz", + "integrity": "sha512-H4UfQhZyakIjC74I9d34fGYDwk3XpSr17QhEd0Q3I9Xq1CETHo4Hcuo87WyWHpAF1aSLjLRf5lD9ZGX2qStUvg==", + "dependencies": { + "array-back": "^3.1.0", + "find-replace": "^3.0.0", + "lodash.camelcase": "^4.3.0", + "typical": "^4.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/command-line-usage": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-7.0.1.tgz", + "integrity": "sha512-NCyznE//MuTjwi3y84QVUGEOT+P5oto1e1Pk/jFPVdPPfsG03qpTIl3yw6etR+v73d0lXsoojRpvbru2sqePxQ==", + "dependencies": { + "array-back": "^6.2.2", + "chalk-template": "^0.4.0", + "table-layout": "^3.0.0", + "typical": "^7.1.1" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/command-line-usage/node_modules/array-back": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-6.2.2.tgz", + "integrity": "sha512-gUAZ7HPyb4SJczXAMUXMGAvI976JoK3qEx9v1FTmeYuJj0IBiaKttG1ydtGKdkfqWkIkouke7nG8ufGy77+Cvw==", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/command-line-usage/node_modules/typical": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-7.1.1.tgz", + "integrity": "sha512-T+tKVNs6Wu7IWiAce5BgMd7OZfNYUndHwc5MknN+UHOudi7sGZzuHdCadllRuqJ3fPtgFtIH9+lt9qRv6lmpfA==", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/commander": { + "version": "12.0.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.0.0.tgz", + "integrity": "sha512-MwVNWlYjDTtOjX5PiD7o5pK0UrFU/OYgcJfjjK4RaHZETNtjJqrZa9Y9ds88+A+f+d5lv+561eZ+yCKoS3gbAA==", + "engines": { + "node": ">=18" + } + }, + "node_modules/core": { + "resolved": "../core", + "link": true + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "dev": true + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dev": true, + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", + "dev": true, + "dependencies": { + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-extend": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", + "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", + "dev": true, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/detect-libc": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.2.tgz", + "integrity": "sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/dir-glob": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", + "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", + "dev": true, + "dependencies": { + "path-type": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true + }, + "node_modules/encoding": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz", + "integrity": "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==", + "dev": true, + "optional": true, + "peer": true, + "dependencies": { + "iconv-lite": "^0.6.2" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", + "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", + "dev": true, + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/esbuild": { + "version": "0.19.11", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.11.tgz", + "integrity": "sha512-HJ96Hev2hX/6i5cDVwcqiJBBtuo9+FeIJOtZ9W1kA5M6AMJRHUZlpYZ1/SbEwtO0ioNAW8rUooVpC/WehY2SfA==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.19.11", + "@esbuild/android-arm": "0.19.11", + "@esbuild/android-arm64": "0.19.11", + "@esbuild/android-x64": "0.19.11", + "@esbuild/darwin-arm64": "0.19.11", + "@esbuild/darwin-x64": "0.19.11", + "@esbuild/freebsd-arm64": "0.19.11", + "@esbuild/freebsd-x64": "0.19.11", + "@esbuild/linux-arm": "0.19.11", + "@esbuild/linux-arm64": "0.19.11", + "@esbuild/linux-ia32": "0.19.11", + "@esbuild/linux-loong64": "0.19.11", + "@esbuild/linux-mips64el": "0.19.11", + "@esbuild/linux-ppc64": "0.19.11", + "@esbuild/linux-riscv64": "0.19.11", + "@esbuild/linux-s390x": "0.19.11", + "@esbuild/linux-x64": "0.19.11", + "@esbuild/netbsd-x64": "0.19.11", + "@esbuild/openbsd-x64": "0.19.11", + "@esbuild/sunos-x64": "0.19.11", + "@esbuild/win32-arm64": "0.19.11", + "@esbuild/win32-ia32": "0.19.11", + "@esbuild/win32-x64": "0.19.11" + } + }, + "node_modules/escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/expand-template": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", + "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/fast-glob": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz", + "integrity": "sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==", + "dev": true, + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.4" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fastq": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.16.0.tgz", + "integrity": "sha512-ifCoaXsDrsdkWTtiNJX5uzHDsrck5TzfKKDcuFFTIrrc/BS076qgEIfoIy1VeZqViznfKiysPYTh/QeHtnIsYA==", + "dev": true, + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dev": true, + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-replace": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-3.0.0.tgz", + "integrity": "sha512-6Tb2myMioCAgv5kfvP5/PkZZ/ntTpVK39fHY7WkWBgvbeE+VHd/tZuZ4mrC+bxh4cfOZeYKVPaJIZtZXV7GNCQ==", + "dependencies": { + "array-back": "^3.0.1" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/flatbuffers": { + "version": "23.5.26", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-23.5.26.tgz", + "integrity": "sha512-vE+SI9vrJDwi1oETtTIFldC/o9GsVKRM+s6EL0nQgxXlYV1Vc4Tk30hj4xGICftInKQKj1F3up2n8UbIVobISQ==" + }, + "node_modules/follow-redirects": { + "version": "1.15.5", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz", + "integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/from2": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/from2/-/from2-2.3.0.tgz", + "integrity": "sha512-OMcX/4IC/uqEPVgGeyfN22LJk6AZrMkRZHxcHBMBvHScDGgwTm2GT2Wkgtocyd3JfZffjj2kYUDXXII0Fk9W0g==", + "dev": true, + "dependencies": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.0" + } + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "dev": true + }, + "node_modules/fs-extra": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz", + "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==", + "dev": true, + "dependencies": { + "at-least-node": "^1.0.0", + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "dev": true, + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/github-from-package": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", + "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", + "dev": true + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/globby": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", + "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", + "dev": true, + "dependencies": { + "array-union": "^2.1.0", + "dir-glob": "^3.0.1", + "fast-glob": "^3.2.9", + "ignore": "^5.2.0", + "merge2": "^1.4.1", + "slash": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true + }, + "node_modules/has": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.4.tgz", + "integrity": "sha512-qdSAmqLF6209RFj4VVItywPMbm3vWylknmB3nvNiUIs72xAimcM8nVYxYr7ncvZq5qzk9MKIZR8ijqD/1QuYjQ==", + "dev": true, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/hasown": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.0.tgz", + "integrity": "sha512-vUptKVTpIJhcczKBbgnS+RtcuYMB8+oNzPK2/Hp3hanz8JmpATdmmgLgSaadVREkDm+e2giHwY3ZRkyjSIDDFA==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "dev": true, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dev": true, + "optional": true, + "peer": true, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/ignore": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.0.tgz", + "integrity": "sha512-g7dmpshy+gD7mh88OC9NwSGTKoc3kyLAZQRU1mt53Aw/vnvfXnbC+F/7F7QoYVKbV+KNvJx8wArewKy1vXMtlg==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", + "dev": true + }, + "node_modules/into-stream": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/into-stream/-/into-stream-6.0.0.tgz", + "integrity": "sha512-XHbaOAvP+uFKUFsOgoNPRjLkwB+I22JFPFe5OjTkQ0nwgj6+pSjb4NmB6VMxaPshLiOf+zcpOCBQuLwC1KHhZA==", + "dev": true, + "dependencies": { + "from2": "^2.3.0", + "p-is-promise": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-core-module": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.9.0.tgz", + "integrity": "sha512-+5FPy5PnwmO3lvfMb0AsoPaBG+5KHUI0wYFXOtYPnVVVspTFUuMZNfNaNVRt3FZadstu2c8x23vykRW/NBoU6A==", + "dev": true, + "dependencies": { + "has": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "dev": true + }, + "node_modules/jsesc": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "dev": true, + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/json-bignum": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/json-bignum/-/json-bignum-0.0.3.tgz", + "integrity": "sha512-2WHyXj3OfHSgNyuzDbSxI1w2jgw5gkWSWhS7Qg4bWXx1nLk3jnbwfUeS0PSba3IzpTUWdHxBieELUzXRjQB2zg==", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/jsonfile": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", + "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", + "dev": true, + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/lodash.assignwith": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/lodash.assignwith/-/lodash.assignwith-4.2.0.tgz", + "integrity": "sha512-ZznplvbvtjK2gMvnQ1BR/zqPFZmS6jbK4p+6Up4xcRYA7yMIwxHCfbTcrYxXKzzqLsQ05eJPVznEW3tuwV7k1g==" + }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==" + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "dev": true, + "dependencies": { + "braces": "^3.0.2", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "dev": true + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "node_modules/multistream": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/multistream/-/multistream-4.1.0.tgz", + "integrity": "sha512-J1XDiAmmNpRCBfIWJv+n0ymC4ABcf/Pl+5YvC5B/D2f/2+8PtHvCNxMPKiQcZyi922Hq69J2YOpb1pTywfifyw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "once": "^1.4.0", + "readable-stream": "^3.6.0" + } + }, + "node_modules/multistream/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dev": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/napi-build-utils": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-1.0.2.tgz", + "integrity": "sha512-ONmRUqK7zj7DWX0D9ADe03wbwOBZxNAfF20PlGfCWQcD3+/MakShIHrMqx9YwPTfxDdF1zLeL+RGZiR9kGMLdg==", + "dev": true + }, + "node_modules/node-abi": { + "version": "3.54.0", + "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.54.0.tgz", + "integrity": "sha512-p7eGEiQil0YUV3ItH4/tBb781L5impVmmx2E9FRKF7d18XXzp4PGT2tdYMFY6wQqgxD0IwNZOiSJ0/K0fSi/OA==", + "dev": true, + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dev": true, + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/p-is-promise": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-is-promise/-/p-is-promise-3.0.0.tgz", + "integrity": "sha512-Wo8VsW4IRQSKVXsJCn7TomUaVtyfjVDn3nUP7kE967BQk0CwFpdbZs0X0uk5sW9mkBa9eNM7hCMaG93WUAwxYQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/pad-left": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/pad-left/-/pad-left-2.1.0.tgz", + "integrity": "sha512-HJxs9K9AztdIQIAIa/OIazRAUW/L6B9hbQDxO4X07roW3eo9XqZc2ur9bn1StH9CnbbI9EgvejHQX7CBpCF1QA==", + "dependencies": { + "repeat-string": "^1.5.4" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "node_modules/path-type": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", + "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pkg": { + "version": "5.8.1", + "resolved": "https://registry.npmjs.org/pkg/-/pkg-5.8.1.tgz", + "integrity": "sha512-CjBWtFStCfIiT4Bde9QpJy0KeH19jCfwZRJqHFDFXfhUklCx8JoFmMj3wgnEYIwGmZVNkhsStPHEOnrtrQhEXA==", + "dev": true, + "dependencies": { + "@babel/generator": "7.18.2", + "@babel/parser": "7.18.4", + "@babel/types": "7.19.0", + "chalk": "^4.1.2", + "fs-extra": "^9.1.0", + "globby": "^11.1.0", + "into-stream": "^6.0.0", + "is-core-module": "2.9.0", + "minimist": "^1.2.6", + "multistream": "^4.1.0", + "pkg-fetch": "3.4.2", + "prebuild-install": "7.1.1", + "resolve": "^1.22.0", + "stream-meter": "^1.0.4" + }, + "bin": { + "pkg": "lib-es5/bin.js" + }, + "peerDependencies": { + "node-notifier": ">=9.0.1" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/pkg-fetch": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/pkg-fetch/-/pkg-fetch-3.4.2.tgz", + "integrity": "sha512-0+uijmzYcnhC0hStDjm/cl2VYdrmVVBpe7Q8k9YBojxmR5tG8mvR9/nooQq3QSXiQqORDVOTY3XqMEqJVIzkHA==", + "dev": true, + "dependencies": { + "chalk": "^4.1.2", + "fs-extra": "^9.1.0", + "https-proxy-agent": "^5.0.0", + "node-fetch": "^2.6.6", + "progress": "^2.0.3", + "semver": "^7.3.5", + "tar-fs": "^2.1.1", + "yargs": "^16.2.0" + }, + "bin": { + "pkg-fetch": "lib-es5/bin.js" + } + }, + "node_modules/prebuild-install": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.1.tgz", + "integrity": "sha512-jAXscXWMcCK8GgCoHOfIr0ODh5ai8mj63L2nWrjuAgXE6tDyYGnx4/8o/rCgU+B4JSyZBKbeZqzhtwtC3ovxjw==", + "dev": true, + "dependencies": { + "detect-libc": "^2.0.0", + "expand-template": "^2.0.3", + "github-from-package": "0.0.0", + "minimist": "^1.2.3", + "mkdirp-classic": "^0.5.3", + "napi-build-utils": "^1.0.1", + "node-abi": "^3.3.0", + "pump": "^3.0.0", + "rc": "^1.2.7", + "simple-get": "^4.0.0", + "tar-fs": "^2.0.0", + "tunnel-agent": "^0.6.0" + }, + "bin": { + "prebuild-install": "bin.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "dev": true + }, + "node_modules/progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, + "node_modules/pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "dev": true, + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/rc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", + "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", + "dev": true, + "dependencies": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "bin": { + "rc": "cli.js" + } + }, + "node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "dev": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/repeat-string": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha512-PV0dzCYDNfRi1jCDbJzpW7jNNDRuCOG/jI5ctQcGKt/clZD+YcPS3yIlWuTJMmESC8aevCFmWJy5wjAFgNqN6w==", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve": { + "version": "1.22.8", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", + "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", + "dev": true, + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve/node_modules/is-core-module": { + "version": "2.13.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.13.1.tgz", + "integrity": "sha512-hHrIjvZsftOsvKSn2TRYl63zvxsgE0K+0mYMoH6gD4omR5IWB2KynivBQczo3+wF1cCkjzvptnI9Q0sPU66ilw==", + "dev": true, + "dependencies": { + "hasown": "^2.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/reusify": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", + "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", + "dev": true, + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "optional": true, + "peer": true + }, + "node_modules/semver": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", + "dev": true, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + } + }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/stream-meter": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/stream-meter/-/stream-meter-1.0.4.tgz", + "integrity": "sha512-4sOEtrbgFotXwnEuzzsQBYEV1elAeFSO8rSGeTwabuX1RRn/kEq9JVH7I0MRBhKVRR0sJkr0M0QCH7yOLf9fhQ==", + "dev": true, + "dependencies": { + "readable-stream": "^2.1.4" + } + }, + "node_modules/stream-read-all": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/stream-read-all/-/stream-read-all-3.0.1.tgz", + "integrity": "sha512-EWZT9XOceBPlVJRrYcykW8jyRSZYbkb/0ZK36uLEmoWVO5gxBOnntNTseNzfREsqxqdfEGQrD8SXQ3QWbBmq8A==", + "engines": { + "node": ">=10" + } + }, + "node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-json-comments": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", + "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/table-layout": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-3.0.2.tgz", + "integrity": "sha512-rpyNZYRw+/C+dYkcQ3Pr+rLxW4CfHpXjPDnG7lYhdRoUcZTUt+KEsX+94RGp/aVp/MQU35JCITv2T/beY4m+hw==", + "dependencies": { + "@75lb/deep-merge": "^1.1.1", + "array-back": "^6.2.2", + "command-line-args": "^5.2.1", + "command-line-usage": "^7.0.0", + "stream-read-all": "^3.0.1", + "typical": "^7.1.1", + "wordwrapjs": "^5.1.0" + }, + "bin": { + "table-layout": "bin/cli.js" + }, + "engines": { + "node": ">=12.17" + } + }, + "node_modules/table-layout/node_modules/array-back": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-6.2.2.tgz", + "integrity": "sha512-gUAZ7HPyb4SJczXAMUXMGAvI976JoK3qEx9v1FTmeYuJj0IBiaKttG1ydtGKdkfqWkIkouke7nG8ufGy77+Cvw==", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/table-layout/node_modules/typical": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-7.1.1.tgz", + "integrity": "sha512-T+tKVNs6Wu7IWiAce5BgMd7OZfNYUndHwc5MknN+UHOudi7sGZzuHdCadllRuqJ3fPtgFtIH9+lt9qRv6lmpfA==", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/tar-fs": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz", + "integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==", + "dev": true, + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "dev": true, + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tar-stream/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dev": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "dev": true + }, + "node_modules/tslib": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz", + "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==" + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "dev": true, + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/typescript": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.3.3.tgz", + "integrity": "sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==", + "dev": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/typical": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/typical/-/typical-4.0.0.tgz", + "integrity": "sha512-VAH4IvQ7BDFYglMd7BPRDfLgxZZX4O4TFcRDA6EN5X7erNJJq+McIEp8np9aVtxrCJ6qx4GTYVfOWNjcqwZgRw==", + "engines": { + "node": ">=8" + } + }, + "node_modules/universalify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", + "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", + "dev": true, + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true + }, + "node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/vectordb": { + "version": "0.4.10", + "resolved": "https://registry.npmjs.org/vectordb/-/vectordb-0.4.10.tgz", + "integrity": "sha512-O6WR65CvpbIbTDs4awKV9smfymVuW1AqYOcdJf8PI0THr1b+h/LyDlAQBf3xBV5Ns8XeaIzWfSHoDspg+WJgKg==", + "cpu": [ + "x64", + "arm64" + ], + "os": [ + "darwin", + "linux", + "win32" + ], + "dependencies": { + "@apache-arrow/ts": "^14.0.2", + "@neon-rs/load": "^0.0.74", + "apache-arrow": "^14.0.2", + "axios": "^1.4.0" + }, + "optionalDependencies": { + "@lancedb/vectordb-darwin-arm64": "0.4.10", + "@lancedb/vectordb-darwin-x64": "0.4.10", + "@lancedb/vectordb-linux-arm64-gnu": "0.4.10", + "@lancedb/vectordb-linux-x64-gnu": "0.4.10", + "@lancedb/vectordb-win32-x64-msvc": "0.4.10" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "dev": true + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dev": true, + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/wordwrapjs": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-5.1.0.tgz", + "integrity": "sha512-JNjcULU2e4KJwUNv6CHgI46UvDGitb6dGryHajXTDiLgg1/RiGoPSDw4kZfYnwGtEXf2ZMeIewDQgFGzkCB2Sg==", + "engines": { + "node": ">=12.17" + } + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "dev": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true + }, + "node_modules/yargs": { + "version": "16.2.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", + "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", + "dev": true, + "dependencies": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^20.2.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs-parser": { + "version": "20.2.9", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", + "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", + "dev": true, + "engines": { + "node": ">=10" + } + } + } +} diff --git a/pkg/package.json b/pkg/package.json new file mode 100644 index 000000000..0c77fa7ed --- /dev/null +++ b/pkg/package.json @@ -0,0 +1,41 @@ +{ + "name": "pkg", + "version": "1.0.0", + "description": "", + "main": "out/index.js", + "bin": "out/index.js", + "pkg": { + "scripts": [ + "node_modules/axios/**/*" + ], + "assets": [ + "../core/node_modules/sqlite3/**/*", + "node_modules/@lancedb/**/*" + ], + "targets": [ + "node18-darwin-arm64" + ], + "outputPath": "bin" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "build": "node build.js", + "build:old": "ncc build src/index.ts -o out && pkg .", + "build:dev": "tsc" + }, + "author": "", + "license": "ISC", + "devDependencies": { + "@types/uuid": "^9.0.8", + "@vercel/ncc": "^0.38.1", + "esbuild": "^0.19.11", + "pkg": "^5.8.1", + "typescript": "^5.3.3" + }, + "dependencies": { + "commander": "^12.0.0", + "core": "file:../core", + "uuid": "^9.0.1", + "vectordb": "^0.4.10" + } +} diff --git a/core/ipc/IpcIde.ts b/pkg/src/IpcIde.ts similarity index 97% rename from core/ipc/IpcIde.ts rename to pkg/src/IpcIde.ts index 38f0e08b8..06b5d6cc8 100644 --- a/core/ipc/IpcIde.ts +++ b/pkg/src/IpcIde.ts @@ -1,4 +1,4 @@ -import { Chunk, ContinueRcJson, IDE, Problem, Range } from ".."; +import { Chunk, ContinueRcJson, IDE, Problem, Range } from "../../core"; import { IpcMessenger } from "./messenger"; export class IpcIde implements IDE { diff --git a/core/ipc/core.ts b/pkg/src/core.ts similarity index 87% rename from core/ipc/core.ts rename to pkg/src/core.ts index 63a666dbc..3c0473905 100644 --- a/core/ipc/core.ts +++ b/pkg/src/core.ts @@ -1,12 +1,12 @@ +import { ContextItemId, IDE } from "core"; +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 { logDevData } from "core/util/devdata"; +import historyManager from "core/util/history"; import { v4 as uuidv4 } from "uuid"; -import { ContextItemId, IDE } from ".."; -import { ConfigHandler } from "../config/handler"; -import { addModel, addOpenAIKey, deleteModel } from "../config/util"; -import { indexDocs } from "../indexing/docs"; -import TransformersJsEmbeddingsProvider from "../indexing/embeddings/TransformersJsEmbeddingsProvider"; -import { CodebaseIndexer } from "../indexing/indexCodebase"; -import { logDevData } from "../util/devdata"; -import historyManager from "../util/history"; import { Messenger, Protocol } from "./messenger"; export class Core { diff --git a/core/ipc/cli.ts b/pkg/src/index.ts similarity index 100% rename from core/ipc/cli.ts rename to pkg/src/index.ts diff --git a/core/ipc/messenger.ts b/pkg/src/messenger.ts similarity index 98% rename from core/ipc/messenger.ts rename to pkg/src/messenger.ts index b2b851cdb..797240c08 100644 --- a/core/ipc/messenger.ts +++ b/pkg/src/messenger.ts @@ -8,8 +8,8 @@ import { RangeInFile, SerializedContinueConfig, SessionInfo, -} from ".."; -import { Message } from "../util/messenger"; +} from "../../core"; +import { Message } from "../../core/util/messenger"; export abstract class Messenger { abstract send(messageType: string, message: any, messageId?: string): string; diff --git a/pkg/tsconfig.json b/pkg/tsconfig.json new file mode 100644 index 000000000..94fbda91f --- /dev/null +++ b/pkg/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "ES2020", + "outDir": "out", + "lib": ["ES2020", "dom", "es6", "es5", "dom.iterable", "scripthost"], + "sourceMap": true, + "rootDirs": ["src", "../core"], + "allowJs": true, + "strict": true /* enable all strict type-checking options */, + /* Additional Checks */ + // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + // "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 */ + }, + "include": ["src/**/*"] +} From 6113e802d5863fe87f0ade9e6889e4b688b61693 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 14 Feb 2024 23:54:15 -0800 Subject: [PATCH 13/59] =?UTF-8?q?=F0=9F=9A=A7=20IpcIde=20in=20fewer=20line?= =?UTF-8?q?s=20of=20code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/util/messageIde.ts | 118 ++++++++++++++++++++++++++++++++ gui/src/util/webviewIde.ts | 114 ++---------------------------- pkg/package.json | 4 +- pkg/src/IpcIde.ts | 112 +----------------------------- pkg/src/core.ts | 9 +-- pkg/src/messenger.ts | 137 +++++++------------------------------ pkg/src/protocol.ts | 85 +++++++++++++++++++++++ 7 files changed, 244 insertions(+), 335 deletions(-) create mode 100644 core/util/messageIde.ts create mode 100644 pkg/src/protocol.ts diff --git a/core/util/messageIde.ts b/core/util/messageIde.ts new file mode 100644 index 000000000..d6bd21ca6 --- /dev/null +++ b/core/util/messageIde.ts @@ -0,0 +1,118 @@ +import { ContinueRcJson, IDE, Problem, Range } from ".."; + +export class MessageIde implements IDE { + constructor( + private readonly request: (messageType: string, data: any) => Promise + ) {} + + readRangeInFile(filepath: string, range: Range): Promise { + return this.request("readRangeInFile", { filepath, range }); + } + getStats(directory: string): Promise<{ [path: string]: number }> { + throw new Error("Method not implemented."); + } + isTelemetryEnabled(): Promise { + return this.request("isTelemetryEnabled", undefined); + } + + getUniqueId(): Promise { + return this.request("getUniqueId", undefined); + } + + getWorkspaceConfigs(): Promise { + return this.request("getWorkspaceConfigs", undefined); + } + + async getDiff() { + return await this.request("getDiff", undefined); + } + + async getTerminalContents() { + return await this.request("getTerminalContents", undefined); + } + + async listWorkspaceContents(directory?: string): Promise { + return await this.request("listWorkspaceContents", undefined); + } + + async getWorkspaceDirs(): Promise { + return await this.request("getWorkspaceDirs", undefined); + } + + async showLines( + filepath: string, + startLine: number, + endLine: number + ): Promise { + return await this.request("showLines", { filepath, startLine, endLine }); + } + + async listFolders(): Promise { + return await this.request("listFolders", undefined); + } + + _continueDir: string | null = null; + + async getContinueDir(): Promise { + if (this._continueDir) { + return this._continueDir; + } + const dir = await this.request("getContinueDir", undefined); + this._continueDir = dir; + return dir; + } + + async writeFile(path: string, contents: string): Promise { + await this.request("writeFile", { path, contents }); + } + + async showVirtualFile(title: string, contents: string): Promise { + await this.request("showVirtualFile", { name: title, content: contents }); + } + + async openFile(path: string): Promise { + await this.request("openFile", { path }); + } + + async runCommand(command: string): Promise { + await this.request("runCommand", { command }); + } + + async saveFile(filepath: string): Promise { + await this.request("saveFile", { filepath }); + } + async readFile(filepath: string): Promise { + return await this.request("readFile", { filepath }); + } + async showDiff( + filepath: string, + newContents: string, + stepIndex: number + ): Promise { + await this.request("showDiff", { filepath, newContents, stepIndex }); + } + + getOpenFiles(): Promise { + return this.request("getOpenFiles", undefined); + } + + getPinnedFiles(): Promise { + return this.request("getPinnedFiles", undefined); + } + + getSearchResults(query: string): Promise { + return this.request("getSearchResults", { query }); + } + + getProblems(filepath?: string | undefined): Promise { + return this.request("getProblems", { filepath }); + } + + subprocess(command: string): Promise<[string, string]> { + return this.request("subprocess", { command }); + } + + async getBranch(dir: string): Promise { + return this.request("getBranch", { dir }); + } +} diff --git a/gui/src/util/webviewIde.ts b/gui/src/util/webviewIde.ts index 6f993703e..236555b4a 100644 --- a/gui/src/util/webviewIde.ts +++ b/gui/src/util/webviewIde.ts @@ -1,4 +1,4 @@ -import { ContinueRcJson, IDE, Problem, Range } from "core"; +import { MessageIde } from "core/util/messageIde"; import { WebviewProtocol } from "core/web/webviewProtocol"; import { ideRequest } from "./ide"; function r( @@ -7,115 +7,9 @@ function r( ): Promise { return ideRequest(messageType, data); } -export class WebviewIde implements IDE { - readRangeInFile(filepath: string, range: Range): Promise { - return r("readRangeInFile", { filepath, range }); - } - getStats(directory: string): Promise<{ [path: string]: number }> { - throw new Error("Method not implemented."); - } - isTelemetryEnabled(): Promise { - return r("isTelemetryEnabled", undefined); - } - getUniqueId(): Promise { - return r("getUniqueId", undefined); - } - - getWorkspaceConfigs(): Promise { - return r("getWorkspaceConfigs", undefined); - } - - async getDiff() { - return await r("getDiff", undefined); - } - - async getTerminalContents() { - return await r("getTerminalContents", undefined); - } - - async listWorkspaceContents(directory?: string): Promise { - return await r("listWorkspaceContents", undefined); - } - - async getWorkspaceDirs(): Promise { - return await r("getWorkspaceDirs", undefined); - } - - async showLines( - filepath: string, - startLine: number, - endLine: number - ): Promise { - return await r("showLines", { filepath, startLine, endLine }); - } - - async listFolders(): Promise { - return await r("listFolders", undefined); - } - - _continueDir: string | null = null; - - async getContinueDir(): Promise { - if (this._continueDir) { - return this._continueDir; - } - const dir = await r("getContinueDir", undefined); - this._continueDir = dir; - return dir; - } - - async writeFile(path: string, contents: string): Promise { - await r("writeFile", { path, contents }); - } - - async showVirtualFile(title: string, contents: string): Promise { - await r("showVirtualFile", { name: title, content: contents }); - } - - async openFile(path: string): Promise { - await r("openFile", { path }); - } - - async runCommand(command: string): Promise { - await r("runCommand", { command }); - } - - async saveFile(filepath: string): Promise { - await r("saveFile", { filepath }); - } - async readFile(filepath: string): Promise { - return await r("readFile", { filepath }); - } - async showDiff( - filepath: string, - newContents: string, - stepIndex: number - ): Promise { - await r("showDiff", { filepath, newContents, stepIndex }); - } - - getOpenFiles(): Promise { - return r("getOpenFiles", undefined); - } - - getPinnedFiles(): Promise { - return r("getPinnedFiles", undefined); - } - - getSearchResults(query: string): Promise { - return r("getSearchResults", { query }); - } - - getProblems(filepath?: string | undefined): Promise { - return r("getProblems", { filepath }); - } - - subprocess(command: string): Promise<[string, string]> { - return r("subprocess", { command }); - } - - async getBranch(dir: string): Promise { - return r("getBranch", { dir }); +export class WebviewIde extends MessageIde { + constructor() { + super(r); } } diff --git a/pkg/package.json b/pkg/package.json index 0c77fa7ed..8f0f726d9 100644 --- a/pkg/package.json +++ b/pkg/package.json @@ -10,7 +10,9 @@ ], "assets": [ "../core/node_modules/sqlite3/**/*", - "node_modules/@lancedb/**/*" + "node_modules/@lancedb/**/*", + "out/tree-sitter.wasm", + "out/tree-sitter-wasms/*" ], "targets": [ "node18-darwin-arm64" diff --git a/pkg/src/IpcIde.ts b/pkg/src/IpcIde.ts index 06b5d6cc8..ff4c5fed1 100644 --- a/pkg/src/IpcIde.ts +++ b/pkg/src/IpcIde.ts @@ -1,114 +1,8 @@ -import { Chunk, ContinueRcJson, IDE, Problem, Range } from "../../core"; +import { MessageIde } from "core/util/messageIde"; import { IpcMessenger } from "./messenger"; -export class IpcIde implements IDE { - private messenger: IpcMessenger; - +export class IpcIde extends MessageIde { constructor(messenger: IpcMessenger) { - this.messenger = messenger; - } - readRangeInFile(filepath: string, range: Range): Promise { - throw new Error("Method not implemented."); - } - - getStats(directory: string): Promise<{ [path: string]: number }> { - throw new Error("Method not implemented."); - } - - isTelemetryEnabled(): Promise { - throw new Error("Method not implemented."); - } - - getUniqueId(): Promise { - throw new Error("Method not implemented."); - } - - getWorkspaceConfigs(): Promise { - throw new Error("Method not implemented."); - } - getDiff(): Promise { - throw new Error("Method not implemented."); - } - getTerminalContents(): Promise { - throw new Error("Method not implemented."); - } - listWorkspaceContents(directory?: string | undefined): Promise { - throw new Error("Method not implemented."); - } - listFolders(): Promise { - throw new Error("Method not implemented."); - } - getWorkspaceDirs(): Promise { - throw new Error("Method not implemented."); - } - writeFile(path: string, contents: string): Promise { - throw new Error("Method not implemented."); - } - showVirtualFile(title: string, contents: string): Promise { - throw new Error("Method not implemented."); - } - getContinueDir(): Promise { - throw new Error("Method not implemented."); - } - openFile(path: string): Promise { - throw new Error("Method not implemented."); - } - runCommand(command: string): Promise { - throw new Error("Method not implemented."); - } - saveFile(filepath: string): Promise { - throw new Error("Method not implemented."); - } - readFile(filepath: string): Promise { - throw new Error("Method not implemented."); - } - showLines( - filepath: string, - startLine: number, - endLine: number - ): Promise { - throw new Error("Method not implemented."); - } - showDiff( - filepath: string, - newContents: string, - stepIndex: number - ): Promise { - throw new Error("Method not implemented."); - } - getOpenFiles(): Promise { - throw new Error("Method not implemented."); - } - getPinnedFiles(): Promise { - throw new Error("Method not implemented."); - } - getSearchResults(query: string): Promise { - throw new Error("Method not implemented."); - } - subprocess(command: string): Promise<[string, string]> { - throw new Error("Method not implemented."); - } - getProblems(filepath?: string | undefined): Promise { - throw new Error("Method not implemented."); - } - getBranch(dir: string): Promise { - throw new Error("Method not implemented."); - } - getFilesToEmbed(providerId: string): Promise<[string, string, string][]> { - throw new Error("Method not implemented."); - } - sendEmbeddingForChunk( - chunk: Chunk, - embedding: number[], - tags: string[] - ): void { - throw new Error("Method not implemented."); - } - retrieveChunks( - text: string, - n: number, - directory: string | undefined - ): Promise { - throw new Error("Method not implemented."); + super(messenger.request); } } diff --git a/pkg/src/core.ts b/pkg/src/core.ts index 3c0473905..2e0f020e3 100644 --- a/pkg/src/core.ts +++ b/pkg/src/core.ts @@ -7,10 +7,11 @@ import { CodebaseIndexer } from "core/indexing/indexCodebase"; import { logDevData } from "core/util/devdata"; import historyManager from "core/util/history"; import { v4 as uuidv4 } from "uuid"; -import { Messenger, Protocol } from "./messenger"; +import { IpcMessenger } from "./messenger"; +import { Protocol } from "./protocol"; export class Core { - private messenger: Messenger; + private messenger: IpcMessenger; private readonly ide: IDE; private readonly configHandler: ConfigHandler; private readonly codebaseIndexer: CodebaseIndexer; @@ -25,13 +26,13 @@ export class Core { return await this.configHandler.llmFromTitle(this.selectedModelTitle); } - constructor(messenger: Messenger, ide: IDE) { + 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); - const on = this.messenger.on; + const on = this.messenger.on.bind(this.messenger); // New on("update/modelChange", (msg) => { diff --git a/pkg/src/messenger.ts b/pkg/src/messenger.ts index 797240c08..ba0138025 100644 --- a/pkg/src/messenger.ts +++ b/pkg/src/messenger.ts @@ -1,114 +1,13 @@ import { v4 as uuidv4 } from "uuid"; -import { - ChatMessage, - CompletionOptions, - ContextItem, - ContextSubmenuItem, - PersistedSessionInfo, - RangeInFile, - SerializedContinueConfig, - SessionInfo, -} from "../../core"; + import { Message } from "../../core/util/messenger"; +import { Protocol } from "./protocol"; -export abstract class Messenger { - abstract send(messageType: string, message: any, messageId?: string): string; - abstract on( - messageType: T, - handler: (message: Message) => Protocol[T][1] - ): void; - abstract invoke( - messageType: T, - data: Protocol[T][0] - ): Protocol[T][1]; -} - -export type Protocol = { - // New - "update/modelChange": [string, void]; - // Special - abort: [undefined, void]; - - // History - "history/list": [undefined, SessionInfo[]]; - "history/delete": [{ id: string }, void]; - "history/load": [{ id: string }, PersistedSessionInfo]; - "history/save": [PersistedSessionInfo, void]; - "devdata/log": [{ tableName: string; data: any }, void]; - "config/addOpenAiKey": [string, void]; - "config/addModel": [ - { model: SerializedContinueConfig["models"][number] }, - void, - ]; - "config/deleteModel": [{ title: string }, void]; - "config/reload": [undefined, void]; - "context/getContextItems": [ - { - name: string; - query: string; - fullInput: string; - selectedCode: RangeInFile[]; - }, - Promise, - ]; - "context/loadSubmenuItems": [ - { title: string }, - Promise, - ]; - "context/addDocs": [{ title: string; url: string }, void]; - "autocomplete/complete": [ - { filepath: string; line: number; column: number }, - string[], - ]; - "command/run": [ - { - input: string; - history: ChatMessage[]; - modelTitle: string; - slashCommandName: string; - contextItems: ContextItem[]; - params: any; - historyIndex: number; - }, - AsyncGenerator, - ]; - "llm/complete": [ - { - prompt: string; - completionOptions: CompletionOptions; - title: string; - }, - AsyncGenerator, - ]; - "llm/streamComplete": [ - { - prompt: string; - completionOptions: CompletionOptions; - title: string; - }, - AsyncGenerator, - ]; - "llm/streamChat": [ - { - messages: ChatMessage[]; - completionOptions: CompletionOptions; - title: string; - }, - AsyncGenerator, - ]; -}; -type ProtocolKeys = keyof Protocol; - -type ProtocolCallbacks = { - [K in ProtocolKeys]: (msg: Protocol[K][0]) => Protocol[K][1]; -}; - -export class IpcMessenger extends Messenger { - listeners = new Map any)[]>(); +export class IpcMessenger { + typeListeners = new Map any)[]>(); + idListeners = new Map any>(); constructor() { - super(); - console.log = console.error; process.stdin.on("data", (data) => { @@ -123,10 +22,14 @@ export class IpcMessenger extends Messenger { throw new Error("Invalid message sent: " + JSON.stringify(msg)); } - this.listeners.get(msg.messageType)?.forEach(async (handler) => { + // Call handler and respond with return value + this.typeListeners.get(msg.messageType)?.forEach(async (handler) => { const response = await handler(msg); this.send(msg.messageType, response, msg.messageId); }); + + // Call handler which is waiting for the response, nothing to return + this.idListeners.get(msg.messageId)?.(msg); } catch (e) { console.error("Invalid JSON:", d); return; @@ -150,20 +53,32 @@ export class IpcMessenger extends Messenger { messageType: T, handler: (message: Message) => Protocol[T][1] ): void { - if (!this.listeners.has(messageType)) { - this.listeners.set(messageType, []); + if (!this.typeListeners.has(messageType)) { + this.typeListeners.set(messageType, []); } - this.listeners.get(messageType)?.push(handler); + this.typeListeners.get(messageType)?.push(handler); } invoke( messageType: T, data: Protocol[T][0] ): Protocol[T][1] { - return this.listeners.get(messageType)?.[0]?.({ + return this.typeListeners.get(messageType)?.[0]?.({ messageId: uuidv4(), messageType, data, }); } + + request(messageType: string, data: any): Promise { + const messageId = uuidv4(); + return new Promise((resolve) => { + const handler = (msg: Message) => { + resolve(msg.data); + this.idListeners.delete(messageId); + }; + this.idListeners.set(messageId, handler); + this.send(messageType, data, messageId); + }); + } } diff --git a/pkg/src/protocol.ts b/pkg/src/protocol.ts new file mode 100644 index 000000000..ab5e4af8a --- /dev/null +++ b/pkg/src/protocol.ts @@ -0,0 +1,85 @@ +import { + ChatMessage, + CompletionOptions, + ContextItem, + ContextSubmenuItem, + PersistedSessionInfo, + RangeInFile, + SerializedContinueConfig, + SessionInfo, +} from "../../core"; + +export type Protocol = { + // New + "update/modelChange": [string, void]; + // Special + abort: [undefined, void]; + + // History + "history/list": [undefined, SessionInfo[]]; + "history/delete": [{ id: string }, void]; + "history/load": [{ id: string }, PersistedSessionInfo]; + "history/save": [PersistedSessionInfo, void]; + "devdata/log": [{ tableName: string; data: any }, void]; + "config/addOpenAiKey": [string, void]; + "config/addModel": [ + { model: SerializedContinueConfig["models"][number] }, + void, + ]; + "config/deleteModel": [{ title: string }, void]; + "config/reload": [undefined, void]; + "context/getContextItems": [ + { + name: string; + query: string; + fullInput: string; + selectedCode: RangeInFile[]; + }, + Promise, + ]; + "context/loadSubmenuItems": [ + { title: string }, + Promise, + ]; + "context/addDocs": [{ title: string; url: string }, void]; + "autocomplete/complete": [ + { filepath: string; line: number; column: number }, + string[], + ]; + "command/run": [ + { + input: string; + history: ChatMessage[]; + modelTitle: string; + slashCommandName: string; + contextItems: ContextItem[]; + params: any; + historyIndex: number; + }, + AsyncGenerator, + ]; + "llm/complete": [ + { + prompt: string; + completionOptions: CompletionOptions; + title: string; + }, + AsyncGenerator, + ]; + "llm/streamComplete": [ + { + prompt: string; + completionOptions: CompletionOptions; + title: string; + }, + AsyncGenerator, + ]; + "llm/streamChat": [ + { + messages: ChatMessage[]; + completionOptions: CompletionOptions; + title: string; + }, + AsyncGenerator, + ]; +}; From 5bb270fa97ef9edc66fc198e9f43e76a7b2c61eb Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Thu, 15 Feb 2024 19:56:40 -0800 Subject: [PATCH 14/59] =?UTF-8?q?=F0=9F=9A=A7=20communication=20between=20?= =?UTF-8?q?core=20and=20jetbrains?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vscode/launch.json | 12 ++ .vscode/tasks.json | 12 ++ core/config/handler.ts | 6 +- core/util/paths.ts | 4 + extensions/intellij/.gitignore | 3 +- extensions/intellij/build.gradle.kts | 6 + .../ContinuePluginStartupActivity.kt | 25 +++- .../continue/CoreMessenger.kt | 139 ++++++++++++++++++ pkg/build.js | 12 ++ pkg/package-lock.json | 11 ++ pkg/package.json | 5 +- pkg/src/IpcIde.ts | 2 +- pkg/src/core.ts | 12 ++ pkg/src/messenger.ts | 36 +++-- pkg/src/protocol.ts | 1 + 15 files changed, 264 insertions(+), 22 deletions(-) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt diff --git a/.vscode/launch.json b/.vscode/launch.json index ad855a194..c00f3a766 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -5,6 +5,18 @@ "version": "0.2.0", "compounds": [], "configurations": [ + { + "type": "node", + "request": "launch", + "name": "Core Binary", + "skipFiles": ["/**"], + "program": "${workspaceFolder}/pkg/out/index.js", + "preLaunchTask": "pkg:esbuild", + "outFiles": ["${workspaceFolder}/pkg/out/**/*.js"], + "sourceMaps": true, + "smartStep": true, + "internalConsoleOptions": "openOnSessionStart" + }, { "type": "node", "request": "launch", diff --git a/.vscode/tasks.json b/.vscode/tasks.json index c46520247..16c7f8614 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -136,6 +136,18 @@ } } ] + }, + // + // esbuild for the core binary + { + "label": "pkg:esbuild", + "type": "shell", + "command": "npm", + "args": ["run", "esbuild"], + "problemMatcher": [], + "options": { + "cwd": "pkg" + } } ] } diff --git a/core/config/handler.ts b/core/config/handler.ts index f83ff8638..8f134a8e1 100644 --- a/core/config/handler.ts +++ b/core/config/handler.ts @@ -18,7 +18,11 @@ export class ConfigHandler { private readonly ide: IDE; constructor(ide: IDE) { this.ide = ide; - this.loadConfig(); + try { + this.loadConfig(); + } catch (e) { + console.error("Failed to load config: ", e); + } } reloadConfig() { diff --git a/core/util/paths.ts b/core/util/paths.ts index 46c545102..ddf9c93da 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -183,3 +183,7 @@ export function getTabAutocompleteCacheSqlitePath(): string { export function getDocsSqlitePath(): string { return path.join(getIndexFolderPath(), "docs.sqlite"); } + +export function getCoreLogsPath(): string { + return path.join(getContinueGlobalPath(), "core.log"); +} diff --git a/extensions/intellij/.gitignore b/extensions/intellij/.gitignore index 73ab23c38..9873b602d 100644 --- a/extensions/intellij/.gitignore +++ b/extensions/intellij/.gitignore @@ -1 +1,2 @@ -src/main/resources/webview \ No newline at end of file +src/main/resources/webview +src/main/resources/bin \ No newline at end of file diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index 5c1ee1e69..034edeef4 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -79,6 +79,12 @@ koverReport { } tasks { + prepareSandbox { + from("../../pkg/bin") { + into("${intellij.pluginName.get()}/core/") + } + } + wrapper { gradleVersion = properties("gradleVersion").get() } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 1230ee60e..fe93bc637 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -1,6 +1,7 @@ package com.github.continuedev.continueintellijextension.activities import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath +import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger import com.github.continuedev.continueintellijextension.`continue`.startProxyServer import com.github.continuedev.continueintellijextension.`continue`.DefaultTextSelectionStrategy import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient @@ -30,7 +31,9 @@ import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Paths import javax.swing.* - +import com.intellij.openapi.application.PathManager; +import com.intellij.ide.plugins.PluginManager +import com.intellij.openapi.extensions.PluginId class WelcomeDialogWrapper(val project: Project) : DialogWrapper(true) { private var panel: JPanel? = null @@ -156,17 +159,17 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { // settings.continueState.shownWelcomeDialog = true } - GlobalScope.async(Dispatchers.IO) { - val ideProtocolClient = IdeProtocolClient( + val ideProtocolClient = IdeProtocolClient( continuePluginService, defaultStrategy, coroutineScope, project.basePath, project - ) + ) - continuePluginService.ideProtocolClient = ideProtocolClient + continuePluginService.ideProtocolClient = ideProtocolClient + GlobalScope.async(Dispatchers.IO) { val listener = ContinuePluginSelectionListener( ideProtocolClient, @@ -193,6 +196,18 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { } } + GlobalScope.async(Dispatchers.IO) { + val myPluginId = "com.github.continuedev.continueintellijextension" + val pluginDescriptor = PluginManager.getPlugin(PluginId.getId(myPluginId)) + + if (pluginDescriptor == null) { + throw Exception("Plugin not found") + } + val pluginPath = pluginDescriptor.pluginPath + val continueCorePath = Paths.get(pluginPath.toString(), "core", "pkg").toString() + + val coreMessenger = CoreMessenger(continueCorePath, ideProtocolClient); + } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt new file mode 100644 index 000000000..e1e505eb6 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -0,0 +1,139 @@ +package com.github.continuedev.continueintellijextension.`continue` +import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import java.io.BufferedReader +import java.io.InputStreamReader +import java.io.OutputStreamWriter + +import java.io.* + +import com.google.gson.Gson +import com.intellij.openapi.components.ServiceManager +import java.io.* + +class CoreMessenger(continueCorePath: String, ideProtocolClient: IdeProtocolClient) { + private val writer: OutputStreamWriter + private val reader: BufferedReader + private val process: Process + private val gson = Gson() + private val responseListeners = mutableMapOf Unit>() + private val ideProtocolClient = ideProtocolClient + + private fun write(message: String) { + writer.write(message + "\n") + writer.flush() + } + + private fun close() { + writer.close() + reader.close() + val exitCode = process.waitFor() + println("Subprocess exited with code: $exitCode") + } + + fun request(messageType: String, data: Any, onResponse: (String) -> Unit) { + val messageId = uuid(); + val message = gson.toJson(mapOf( + "messageId" to messageId, + "messageType" to messageType, + "data" to data + )) + responseListeners[messageId] = onResponse + write(message) + } + + private fun handleResponse(json: String) { + val responseMap = gson.fromJson(json, Map::class.java) + val messageId = responseMap["messageId"].toString() + val messageType = responseMap["messageType"].toString() + val responseData = gson.toJson(responseMap["data"]) + + // IDE listeners + if (ideMessageTypes.contains(responseMap["messageType"])) { + ideProtocolClient.handleMessage(json) { data -> + val message = gson.toJson(mapOf( + "messageId" to messageId, + "messageType" to messageType, + "data" to data + )) + write(message) + }; + } + + // Responses for messageId + responseListeners[messageId]?.let { listener -> + listener(responseData) + responseListeners.remove(messageId) + } + } + + private val ideMessageTypes = listOf( + "readRangeInFile", + "isTelemetryEnabled", + "getUniqueId", + "getWorkspaceConfigs", + "getDiff", + "getTerminalContents", + "listWorkspaceContents", + "getWorkspaceDirs", + "showLines", + "listFolders", + "getContinueDir", + "writeFile", + "showVirtualFile", + "openFile", + "runCommand", + "saveFile", + "readFile", + "showDiff", + "getOpenFiles", + "getPinnedFiles", + "getSearchResults", + "getProblems", + "subprocess", + "getBranch" + ) + + init { + // Start the subprocess + val processBuilder = ProcessBuilder(continueCorePath) + process = processBuilder.start() + + val outputStream = process.outputStream + val inputStream = process.inputStream + + writer = OutputStreamWriter(outputStream) + reader = BufferedReader(InputStreamReader(inputStream)) + + var sentPing = false + + Thread { + try { + while (true) { + if (!sentPing) { + sentPing = true + request("ping", "ping") { response -> + println("Response!: $response") + } + } + val line = reader.readLine() + println("Core: $line") + if (line != null && line.isNotEmpty()) { + handleResponse(line) + } + } + } catch (e: IOException) { + e.printStackTrace() + } finally { + try { + reader.close() + writer.close() + outputStream.close() + inputStream.close() + process.destroy() + } catch (e: IOException) { + e.printStackTrace() + } + } + }.start() + } +} diff --git a/pkg/build.js b/pkg/build.js index b55bfbf72..5ac8d0661 100644 --- a/pkg/build.js +++ b/pkg/build.js @@ -3,6 +3,14 @@ const { execSync } = require("child_process"); const esbuildOutputFile = "out/index.js"; +let esbuildOnly = false; +for (let i = 2; i < process.argv.length; i++) { + if (process.argv[i] === "--esbuild-only") { + esbuildOnly = true; + break; // Exit the loop once the flag is found + } +} + (async () => { // console.log("[info] Building with ncc..."); // execSync(`npx ncc build src/index.ts -o out`); @@ -28,6 +36,10 @@ const esbuildOutputFile = "out/index.js"; define: { "import.meta.url": "importMetaUrl" }, }); + if (esbuildOnly) { + return; + } + console.log("[info] Building binary with pkg..."); execSync("npx pkg ."); console.log("[info] Done!"); diff --git a/pkg/package-lock.json b/pkg/package-lock.json index 973d4c0a7..000992333 100644 --- a/pkg/package-lock.json +++ b/pkg/package-lock.json @@ -11,6 +11,7 @@ "dependencies": { "commander": "^12.0.0", "core": "file:../core", + "follow-redirects": "^1.15.5", "uuid": "^9.0.1", "vectordb": "^0.4.10" }, @@ -18,6 +19,7 @@ "pkg": "out/index.js" }, "devDependencies": { + "@types/follow-redirects": "^1.14.4", "@types/uuid": "^9.0.8", "@vercel/ncc": "^0.38.1", "esbuild": "^0.19.11", @@ -689,6 +691,15 @@ "resolved": "https://registry.npmjs.org/@types/command-line-usage/-/command-line-usage-5.0.2.tgz", "integrity": "sha512-n7RlEEJ+4x4TS7ZQddTmNSxP+zziEG0TNsMfiRIxcIVXt71ENJ9ojeXmGO3wPoTdn7pJcU2xc3CJYMktNT6DPg==" }, + "node_modules/@types/follow-redirects": { + "version": "1.14.4", + "resolved": "https://registry.npmjs.org/@types/follow-redirects/-/follow-redirects-1.14.4.tgz", + "integrity": "sha512-GWXfsD0Jc1RWiFmMuMFCpXMzi9L7oPDVwxUnZdg89kDNnqsRfUKXEtUYtA98A6lig1WXH/CYY/fvPW9HuN5fTA==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/node": { "version": "20.3.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.3.0.tgz", diff --git a/pkg/package.json b/pkg/package.json index 8f0f726d9..df62ee291 100644 --- a/pkg/package.json +++ b/pkg/package.json @@ -23,11 +23,13 @@ "test": "echo \"Error: no test specified\" && exit 1", "build": "node build.js", "build:old": "ncc build src/index.ts -o out && pkg .", - "build:dev": "tsc" + "build:dev": "tsc", + "esbuild": "node build.js --esbuild-only" }, "author": "", "license": "ISC", "devDependencies": { + "@types/follow-redirects": "^1.14.4", "@types/uuid": "^9.0.8", "@vercel/ncc": "^0.38.1", "esbuild": "^0.19.11", @@ -37,6 +39,7 @@ "dependencies": { "commander": "^12.0.0", "core": "file:../core", + "follow-redirects": "^1.15.5", "uuid": "^9.0.1", "vectordb": "^0.4.10" } diff --git a/pkg/src/IpcIde.ts b/pkg/src/IpcIde.ts index ff4c5fed1..5343a2430 100644 --- a/pkg/src/IpcIde.ts +++ b/pkg/src/IpcIde.ts @@ -3,6 +3,6 @@ import { IpcMessenger } from "./messenger"; export class IpcIde extends MessageIde { constructor(messenger: IpcMessenger) { - super(messenger.request); + super(messenger.request.bind(messenger)); } } diff --git a/pkg/src/core.ts b/pkg/src/core.ts index 2e0f020e3..453055377 100644 --- a/pkg/src/core.ts +++ b/pkg/src/core.ts @@ -39,6 +39,18 @@ export class Core { this.selectedModelTitle = msg.data; }); + // Special + on("abort", (msg) => { + // TODO + }); + + on("ping", (msg) => { + if (msg.data !== "ping") { + throw new Error("ping message incorrect"); + } + return "pong"; + }); + // History on("history/list", (msg) => { return historyManager.list(); diff --git a/pkg/src/messenger.ts b/pkg/src/messenger.ts index ba0138025..e396a8650 100644 --- a/pkg/src/messenger.ts +++ b/pkg/src/messenger.ts @@ -1,5 +1,7 @@ import { v4 as uuidv4 } from "uuid"; +import { getCoreLogsPath } from "core/util/paths"; +import * as fs from "fs"; import { Message } from "../../core/util/messenger"; import { Protocol } from "./protocol"; @@ -8,30 +10,37 @@ export class IpcMessenger { idListeners = new Map any>(); constructor() { - console.log = console.error; + const logger = (message: any, ...optionalParams: any[]) => { + const logFilePath = getCoreLogsPath(); + const logMessage = `${message} ${optionalParams.join(" ")}\n`; + fs.appendFileSync(logFilePath, logMessage); + }; + console.log = logger; + console.error = logger; + console.warn = logger; + console.log("[info] Starting Continue core..."); process.stdin.on("data", (data) => { - const d = data.toString(); + console.log("Receieved data: ", data); try { + const d = data.toString(); const msg: Message = JSON.parse(d); - if ( - msg.data !== undefined || - msg.messageType !== undefined || - msg.messageId !== undefined - ) { + if (msg.messageType === undefined || msg.messageId === undefined) { throw new Error("Invalid message sent: " + JSON.stringify(msg)); } // Call handler and respond with return value - this.typeListeners.get(msg.messageType)?.forEach(async (handler) => { - const response = await handler(msg); - this.send(msg.messageType, response, msg.messageId); - }); + this.typeListeners + .get(msg.messageType as any) + ?.forEach(async (handler) => { + const response = await handler(msg); + this.send(msg.messageType, response, msg.messageId); + }); // Call handler which is waiting for the response, nothing to return this.idListeners.get(msg.messageId)?.(msg); } catch (e) { - console.error("Invalid JSON:", d); + console.error("Invalid JSON:", data); return; } }); @@ -45,7 +54,8 @@ export class IpcMessenger { messageId, }; // process.send?.(data); - process.stdout?.write(JSON.stringify(data)); + process.stdout?.write(JSON.stringify(data) + "\n"); + console.log("Sent: ", JSON.stringify(data)); return messageId; } diff --git a/pkg/src/protocol.ts b/pkg/src/protocol.ts index ab5e4af8a..f30586fae 100644 --- a/pkg/src/protocol.ts +++ b/pkg/src/protocol.ts @@ -13,6 +13,7 @@ export type Protocol = { // New "update/modelChange": [string, void]; // Special + ping: [string, string]; abort: [undefined, void]; // History From 05b8776bd3e5646e9f51d23ea704cae1973bef33 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Thu, 15 Feb 2024 21:42:54 -0800 Subject: [PATCH 15/59] =?UTF-8?q?=F0=9F=9A=A7=20jetbrains=20webview=20mess?= =?UTF-8?q?enging?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../actions/ContinuePluginActions.kt | 12 +- .../continue/CoreMessenger.kt | 13 +- .../continue/IdeProtocolClient.kt | 116 +++++++++++++----- .../services/ContinuePluginService.kt | 16 ++- pkg/src/messenger.ts | 2 +- 5 files changed, 106 insertions(+), 53 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt index 0fca2a3e8..3e1aaa1d5 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/actions/ContinuePluginActions.kt @@ -4,13 +4,11 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS import com.google.gson.Gson import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent -import com.intellij.openapi.actionSystem.impl.SimpleDataContext import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.wm.ToolWindowManager import java.awt.Dimension -import java.awt.GridLayout import javax.swing.* import javax.swing.event.DocumentEvent import javax.swing.event.DocumentListener @@ -130,7 +128,7 @@ class QuickTextEntryAction : AnAction() { } continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus() - continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInput"))) + continuePluginService.sendToWebview("focusContinueInput", null) } } @@ -179,7 +177,7 @@ class FocusContinueInputWithoutClearAction : AnAction() { val continuePluginService = pluginServiceFromActionEvent(e) ?: return continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus() - continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInputWithoutClear"))) + continuePluginService.sendToWebview("focusContinueInputWithoutClear", null) continuePluginService.ideProtocolClient?.sendHighlightedCode() } @@ -202,7 +200,7 @@ class FocusContinueInputAction : AnAction() { val continuePluginService = pluginServiceFromActionEvent(e) ?: return continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus() - continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInput"))) + continuePluginService.sendToWebview("focusContinueInput", null) continuePluginService.ideProtocolClient?.sendHighlightedCode() } @@ -225,7 +223,7 @@ class NewContinueSessionAction : AnAction() { val continuePluginService = pluginServiceFromActionEvent(e) ?: return continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus() - continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInputWithNewSession"))) + continuePluginService.sendToWebview("focusContinueInputWithNewSession", null) } } @@ -239,6 +237,6 @@ class ViewHistoryAction : AnAction() { val continuePluginService = pluginServiceFromActionEvent(e) ?: return - continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "viewHistory"))) + continuePluginService.sendToWebview("viewHistory", null) } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index e1e505eb6..ca6d94c20 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -1,5 +1,4 @@ package com.github.continuedev.continueintellijextension.`continue` -import com.github.continuedev.continueintellijextension.services.ContinuePluginService import java.io.BufferedReader import java.io.InputStreamReader import java.io.OutputStreamWriter @@ -7,8 +6,6 @@ import java.io.OutputStreamWriter import java.io.* import com.google.gson.Gson -import com.intellij.openapi.components.ServiceManager -import java.io.* class CoreMessenger(continueCorePath: String, ideProtocolClient: IdeProtocolClient) { private val writer: OutputStreamWriter @@ -41,14 +38,14 @@ class CoreMessenger(continueCorePath: String, ideProtocolClient: IdeProtocolClie write(message) } - private fun handleResponse(json: String) { + private fun handleMessage(json: String) { val responseMap = gson.fromJson(json, Map::class.java) val messageId = responseMap["messageId"].toString() val messageType = responseMap["messageType"].toString() - val responseData = gson.toJson(responseMap["data"]) + val data = gson.toJson(responseMap["data"]) // IDE listeners - if (ideMessageTypes.contains(responseMap["messageType"])) { + if (ideMessageTypes.contains(messageType)) { ideProtocolClient.handleMessage(json) { data -> val message = gson.toJson(mapOf( "messageId" to messageId, @@ -61,7 +58,7 @@ class CoreMessenger(continueCorePath: String, ideProtocolClient: IdeProtocolClie // Responses for messageId responseListeners[messageId]?.let { listener -> - listener(responseData) + listener(data) responseListeners.remove(messageId) } } @@ -118,7 +115,7 @@ class CoreMessenger(continueCorePath: String, ideProtocolClient: IdeProtocolClie val line = reader.readLine() println("Core: $line") if (line != null && line.isNotEmpty()) { - handleResponse(line) + handleMessage(line) } } } catch (e: IOException) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index b52384052..4da8e70dc 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -123,13 +123,7 @@ class IdeProtocolClient ( private fun send(messageType: String, data: Any?, messageId: String? = null) { val id = messageId ?: uuid() - val message = IdeMessage( - messageType, - id, - data - ) - val json = Gson().toJson(message) - continuePluginService.dispatchCustomEvent(json) + continuePluginService.sendToWebview(messageType, data, id) } fun handleMessage(text: String, respond: (Any?) -> Unit) { @@ -143,7 +137,7 @@ class IdeProtocolClient ( println("Recieved message without type: $text") return@launch } - val data = parsedMessage["data"] as Map<*, *> + val data = parsedMessage["data"] val historyManager = HistoryManager() @@ -171,8 +165,12 @@ class IdeProtocolClient ( )) } + "getUniqueId" -> { + respond(uniqueId()) + } + "showDiff" -> { - val data = data["message"] as Map + val data = data as Map diffManager.showDiff( data["filepath"] as String, data["newContents"] as String, @@ -182,10 +180,31 @@ class IdeProtocolClient ( } "readFile" -> { - val msg = readFile((data["message"] as Map)["filepath"] as String) + val msg = readFile((data as Map)["filepath"] as String) respond(msg) } + "isTelemetryEnabled" -> { + respond(true) + } + + "readRangeInFile" -> { + val fullContents = readFile((data as Map)["filepath"] as String) + val range = data["range"] as Map + val start = range["start"] as Map + val end = range["end"] as Map + val startLine = start["line"] as Int + val startCharacter = start["character"] as Int + val endLine = end["line"] as Int + val endCharacter = end["character"] as Int + + val firstLine = fullContents.split("\n")[startLine].slice(startCharacter until fullContents.split("\n")[startLine].length) + val lastLine = fullContents.split("\n")[endLine].slice(0 until endCharacter) + val between = fullContents.split("\n").slice(startLine + 1 until endLine).joinToString("\n") + + respond(firstLine + "\n" + between + "\n" + lastLine) + } + "listWorkspaceContents" -> { respond(listDirectoryContents(null)) } @@ -194,6 +213,10 @@ class IdeProtocolClient ( respond(workspaceDirectories()) } + "getWorkspaceConfigs" -> { + respond(emptyList()) + } + "getTerminalContents" -> { respond( mapOf("contents" to "Terminal cannot be accessed in JetBrains IDE") @@ -207,10 +230,11 @@ class IdeProtocolClient ( } "saveFile" -> { - saveFile((data["message"] as Map)["filepath"] ?: throw Exception("No filepath provided")) + saveFile((data as Map)["filepath"] ?: throw Exception("No filepath provided")) respond(null) } "showVirtualFile" -> { + val data = data as Map showVirtualFile( data["name"] as String, data["contents"] as String @@ -220,10 +244,11 @@ class IdeProtocolClient ( "connected" -> {} "showMessage" -> { - showMessage(data["message"] as String) + showMessage(data as String) respond(null) } "setFileOpen" -> { + val data = data as Map setFileOpen( data["filepath"] as String, data["open"] as Boolean @@ -231,8 +256,27 @@ class IdeProtocolClient ( respond(null) } + "showLines" -> { + val data = data as Map + val filepath = data["filepath"] as String + val startLine = data["startLine"] as Int + val endLine = data["endLine"] as Int + highlightCode( + RangeInFile( + filepath, + Range( + Position(startLine, 0), + Position(endLine, 0) + ) + ), + data["color"] as String + ) + respond(null) + } + "highlightCode" -> { val gson = Gson() + val data = data as Map val json = gson.toJson(data["rangeInFile"]) val type = object : TypeToken() {}.type val rangeInFile = @@ -304,7 +348,7 @@ class IdeProtocolClient ( respond(configJsDataUrl) } "writeFile" -> { - val msg = data["message"] as Map; + val msg = data as Map; val file = File(msg["path"]) file.writeText(msg["contents"] as String) respond(null); @@ -313,7 +357,7 @@ class IdeProtocolClient ( respond(getContinueGlobalPath()) } "openFile" -> { - setFileOpen((data["message"] as Map)["path"] as String) + setFileOpen((data as Map)["path"] as String) respond(null) } "runCommand" -> { @@ -321,7 +365,12 @@ class IdeProtocolClient ( // Running commands not yet supported in JetBrains } "errorPopup" -> { - showMessage(data["message"] as String) + showMessage(data as String) + respond(null) + } + + "listFolders" -> { + respond(null) } // History @@ -329,15 +378,15 @@ class IdeProtocolClient ( respond(historyManager.list()); } "saveSession" -> { - historyManager.save(data["message"] as PersistedSessionInfo); + historyManager.save(data as PersistedSessionInfo); respond(null); } "deleteSession" -> { - historyManager.delete(data["message"] as String); + historyManager.delete(data as String); respond(null); } "loadSession" -> { - val session = historyManager.load(data["message"] as String) + val session = historyManager.load(data as String) respond(session) } "getSearchResults" -> { @@ -349,7 +398,12 @@ class IdeProtocolClient ( val openFiles = visibleFiles() respond(openFiles) } + "getPinnedFiles" -> { + val openFiles = visibleFiles() + respond(openFiles) + } "logDevData" -> { + val data = data as Map val filename = data["tableName"] as String val jsonLine = data["data"] val filepath = getDevDataFilepath(filename) @@ -357,6 +411,7 @@ class IdeProtocolClient ( File(filepath).appendText(contents) } "addModel" -> { + val data = data as Map val model = data["model"] as Map val updatedConfig = editConfigJson { val models = it["models"] as MutableList> @@ -370,7 +425,7 @@ class IdeProtocolClient ( "deleteModel" -> { val configJson = editConfigJson { config -> var models: MutableList> = config["models"] as MutableList> - + val data = data as Map val model = data["title"] as String models = models.filter { it["title"] != model }.toMutableList() config["models"] = models @@ -380,6 +435,7 @@ class IdeProtocolClient ( } "addOpenAIKey" -> { val updatedConfig = editConfigJson { config -> + val data = data as Map val key = data["key"] as String var models = config["models"] as MutableList> models = models.map { @@ -410,12 +466,7 @@ class IdeProtocolClient ( } fun configUpdate(config: Map) { - val data = mapOf( - "type" to "configUpdate", - "config" to config - ) - val json = Gson().toJson(data) - continuePluginService.dispatchCustomEvent(json) + continuePluginService.sendToWebview("configUpdate", config) } private fun editConfigJson(callback: (config: MutableMap) -> Map): Map { @@ -559,20 +610,17 @@ class IdeProtocolClient ( // edit // )) - continuePluginService.dispatchCustomEvent( - Gson().toJson(mapOf( - "type" to "highlightedCode", + continuePluginService.sendToWebview( +"highlightedCode", + mapOf( "rangeInFileWithContents" to rif, "edit" to edit - ))) + ) + ) } fun sendMainUserInput(input: String) { - val data = mapOf( - "type" to "userInput", - "input" to input, - ) - continuePluginService.dispatchCustomEvent(Gson().toJson(data)) + continuePluginService.sendToWebview("userInput", mapOf("input" to input)) } fun sendAcceptRejectDiff(accepted: Boolean, stepIndex: Int) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt index 7e944a97a..06ec7327a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt @@ -1,6 +1,7 @@ package com.github.continuedev.continueintellijextension.services import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient +import com.github.continuedev.continueintellijextension.`continue`.uuid import com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory import com.google.gson.Gson import com.intellij.openapi.Disposable @@ -33,10 +34,19 @@ class ContinuePluginService(project: Project) : Disposable, DumbAware { } } - fun dispatchCustomEvent( - data: String + fun sendToWebview( + messageType: String, + data: Any?, + messageId: String = uuid() ) { - val jsCode = buildJavaScript(data) + val jsonData = Gson().toJson( + mapOf( + "messageId" to messageId, + "messageType" to messageType, + "data" to data + ) + ) + val jsCode = buildJavaScript(jsonData) try { continuePluginWindow?.webView?.executeJavaScriptAsync(jsCode) diff --git a/pkg/src/messenger.ts b/pkg/src/messenger.ts index e396a8650..4fdeb1078 100644 --- a/pkg/src/messenger.ts +++ b/pkg/src/messenger.ts @@ -54,7 +54,7 @@ export class IpcMessenger { messageId, }; // process.send?.(data); - process.stdout?.write(JSON.stringify(data) + "\n"); + process.stdout?.write(JSON.stringify(data) + "\r\n"); console.log("Sent: ", JSON.stringify(data)); return messageId; } From a4b8b1c4e779b86d3a76fd481174d866d976e2ff Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 16 Feb 2024 08:59:33 -0800 Subject: [PATCH 16/59] =?UTF-8?q?=F0=9F=9A=A7=20pass=20messages=20through?= =?UTF-8?q?=20to=20core?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ContinuePluginStartupActivity.kt | 1 + .../continue/CoreMessenger.kt | 2 +- .../services/ContinuePluginService.kt | 2 ++ .../ContinuePluginToolWindowFactory.kt | 21 +++++++++++++++---- gui/src/util/ide.ts | 6 +++++- 5 files changed, 26 insertions(+), 6 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index fe93bc637..817f3902f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -207,6 +207,7 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { val continueCorePath = Paths.get(pluginPath.toString(), "core", "pkg").toString() val coreMessenger = CoreMessenger(continueCorePath, ideProtocolClient); + continuePluginService.coreMessenger = coreMessenger } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index ca6d94c20..0c5e0f86f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -27,7 +27,7 @@ class CoreMessenger(continueCorePath: String, ideProtocolClient: IdeProtocolClie println("Subprocess exited with code: $exitCode") } - fun request(messageType: String, data: Any, onResponse: (String) -> Unit) { + fun request(messageType: String, data: Any?, onResponse: (String) -> Unit) { val messageId = uuid(); val message = gson.toJson(mapOf( "messageId" to messageId, diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt index 06ec7327a..bac9d3096 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt @@ -1,5 +1,6 @@ package com.github.continuedev.continueintellijextension.services +import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient import com.github.continuedev.continueintellijextension.`continue`.uuid import com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory @@ -21,6 +22,7 @@ class ContinuePluginService(project: Project) : Disposable, DumbAware { var continuePluginWindow: ContinuePluginToolWindowFactory.ContinuePluginWindow? = null var ideProtocolClient: IdeProtocolClient? = null + var coreMessenger: CoreMessenger? = null var worksapcePaths: Array? = null var windowId: String = UUID.randomUUID().toString() diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt index 50451b02f..289170d1b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt @@ -55,6 +55,10 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { class ContinuePluginWindow(toolWindow: ToolWindow, project: Project) { + val PASS_THROUGH_TO_CORE = listOf( + "getSerializedConfig" + ) + init { System.setProperty("ide.browser.jcef.jsQueryPoolSize", JS_QUERY_POOL_SIZE) } @@ -83,8 +87,8 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { val parser = JsonParser() val json: JsonObject = parser.parse(msg).asJsonObject val messageType = json.get("messageType").asString - val data = json.get("data").asJsonObject - val messageId = json.get("messageId").asString + val data = json.get("data") + val messageId = json.get("messageId")?.asString val ide = continuePluginService.ideProtocolClient; @@ -98,6 +102,11 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { browser.executeJavaScriptAsync("""window.postMessage($jsonString, "*");""") } + if (PASS_THROUGH_TO_CORE.contains(messageType)) { + continuePluginService.coreMessenger?.request(messageType, data, respond) + return@addHandler null + } + when (messageType) { "onLoad" -> { GlobalScope.launch { @@ -143,6 +152,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { } "showLines" -> { + val data = data.asJsonObject ide?.highlightCode(RangeInFile( data.get("filepath").asString, Range(Position( @@ -156,9 +166,11 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { ),"#00ff0022") } "showVirtualFile" -> { + val data = data.asJsonObject ide?.showVirtualFile(data.get("name").asString, data.get("content").asString) } "showFile" -> { + val data = data.asJsonObject ide?.setFileOpen(data.get("filepath").asString) } "reloadWindow" -> {} @@ -166,6 +178,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { ide?.setFileOpen(getConfigJsonPath()) } "readRangeInFile" -> { + val data = data.asJsonObject ide?.readRangeInFile(RangeInFile( data.get("filepath").asString, Range(Position( @@ -211,8 +224,8 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { fun executeJavaScript(browser: CefBrowser?, myJSQueryOpenInBrowser: JBCefJSQuery) { // Execute JavaScript - you might want to handle potential exceptions here - val script = """window.postIntellijMessage = function(type, data) { - const msg = JSON.stringify({type, data}); + val script = """window.postIntellijMessage = function(messageType, data, messageId) { + const msg = JSON.stringify({messageType, data, messageId}); ${myJSQueryOpenInBrowser.inject("msg")} }""".trimIndent() diff --git a/gui/src/util/ide.ts b/gui/src/util/ide.ts index 1cd49adb9..ee61c6253 100644 --- a/gui/src/util/ide.ts +++ b/gui/src/util/ide.ts @@ -23,7 +23,11 @@ function _postToIde(messageType: string, data: any, messageId?: string) { ); throw new Error("postIntellijMessage is undefined"); } - (window as any).postIntellijMessage?.(messageType, data); + (window as any).postIntellijMessage?.( + messageType, + data, + messageId ?? uuidv4() + ); return; } else { console.log( From ce04a7527433bf5aec3f71e8a2120a7514797213 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sat, 17 Feb 2024 11:16:09 -0800 Subject: [PATCH 17/59] =?UTF-8?q?=F0=9F=9A=A7=20messaging?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/config/default.ts | 5 -- core/config/handler.ts | 5 +- core/config/load.ts | 2 +- .../ContinuePluginStartupActivity.kt | 7 +-- .../continue/CoreMessenger.kt | 10 +--- .../continue/GetTheme.kt | 38 ++++++++++++ .../continue/IdeProtocolClient.kt | 23 -------- .../ContinuePluginToolWindowFactory.kt | 7 +-- gui/src/util/ide.ts | 7 +-- pkg/src/core.ts | 5 ++ pkg/src/index.ts | 16 +++-- pkg/src/messenger.ts | 58 ++++++++++++------- pkg/src/protocol.ts | 4 ++ 13 files changed, 107 insertions(+), 80 deletions(-) create mode 100644 extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt diff --git a/core/config/default.ts b/core/config/default.ts index 0d3a7798f..7af901c99 100644 --- a/core/config/default.ts +++ b/core/config/default.ts @@ -2,11 +2,6 @@ import { SerializedContinueConfig } from ".."; const defaultConfig: SerializedContinueConfig = { models: [ - { - title: "GPT-4 (Free Trial)", - provider: "free-trial", - model: "gpt-4", - }, { title: "GPT-4 Vision (Free Trial)", provider: "free-trial", diff --git a/core/config/handler.ts b/core/config/handler.ts index 8f134a8e1..c1b30b563 100644 --- a/core/config/handler.ts +++ b/core/config/handler.ts @@ -67,8 +67,9 @@ export class ConfigHandler { ); return this.savedConfig; - } catch (e) { - throw new Error("Failed to load config"); + } catch (e: any) { + console.error("Failed to load config: ", e.message); + throw new Error("Failed to load config: " + e.message); } } diff --git a/core/config/load.ts b/core/config/load.ts index 34e7150ad..6b059cc75 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -340,7 +340,7 @@ async function buildConfigTs(browser: boolean) { sourcemap: true, }); } catch (e) { - throw new Error( + console.log( "Build error. Please check your ~/.continue/config.ts file: " + e ); return undefined; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 817f3902f..203e05a23 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -1,10 +1,7 @@ package com.github.continuedev.continueintellijextension.activities import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath -import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger -import com.github.continuedev.continueintellijextension.`continue`.startProxyServer -import com.github.continuedev.continueintellijextension.`continue`.DefaultTextSelectionStrategy -import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient +import com.github.continuedev.continueintellijextension.`continue`.* import com.github.continuedev.continueintellijextension.listeners.ContinuePluginSelectionListener import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService @@ -124,6 +121,8 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { ContinuePluginService::class.java ) + val theme = GetTheme().getTheme() + val defaultStrategy = DefaultTextSelectionStrategy() coroutineScope.launch { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index 0c5e0f86f..98ff3d568 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -16,7 +16,7 @@ class CoreMessenger(continueCorePath: String, ideProtocolClient: IdeProtocolClie private val ideProtocolClient = ideProtocolClient private fun write(message: String) { - writer.write(message + "\n") + writer.write(message + "\r\n") writer.flush() } @@ -101,17 +101,9 @@ class CoreMessenger(continueCorePath: String, ideProtocolClient: IdeProtocolClie writer = OutputStreamWriter(outputStream) reader = BufferedReader(InputStreamReader(inputStream)) - var sentPing = false - Thread { try { while (true) { - if (!sentPing) { - sentPing = true - request("ping", "ping") { response -> - println("Response!: $response") - } - } val line = reader.readLine() println("Core: $line") if (line != null && line.isNotEmpty()) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt new file mode 100644 index 000000000..bf9ae4d5f --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt @@ -0,0 +1,38 @@ +package com.github.continuedev.continueintellijextension.`continue` +import com.intellij.openapi.editor.colors.EditorColorsManager +import com.intellij.openapi.editor.colors.EditorColorsScheme +import com.intellij.openapi.editor.colors.TextAttributesKey + +/* +[ + "--vscode-input-background", + "--vscode-sideBar-background", + "--vscode-editor-foreground", + "--vscode-button-background", + "--vscode-editor-background", + "--vscode-list-activeSelectionBackground", + "--vscode-focus-border", + "--vscode-quickInputList-focusForeground", + "--vscode-quickInput-background", + "--vscode-input-border", + "--vscode-focusBorder", + "--vscode-badge-background", + "--vscode-badge-foreground", + "--vscode-sideBar-border" +] + + */ +val vscToJetBrainsColorName = listOf( + arrayOf("--vscode-input-background", "?"), + arrayOf("--vscode-sideBar-background", "?"), + arrayOf("--vscode-editor-foreground", "?"), + +) + +class GetTheme { + fun getTheme(): EditorColorsScheme { + val editorColorsManager: EditorColorsManager = EditorColorsManager.getInstance() + val scheme: EditorColorsScheme = editorColorsManager.globalScheme + return scheme + } +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 4da8e70dc..ffae756b5 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -317,29 +317,6 @@ class IdeProtocolClient ( respond(output.toString()); } - "getSerializedConfig" -> { - val configPath = getConfigJsonPath() - var config = File(configPath).readText() - - migrate("camelCaseConfig") { - if (config.contains("_")) { - config = config - .replace(Regex("(_\\w)")) { it.value[1].uppercase() } - .replace("openai-aiohttp", "openai") - // Rewrite to config.json - File(configPath).writeText(config) - } - } - - migrate("renameFreeTrialProvider") { - config = config.replace("openai-free-trial", "free-trial"); - File(configPath).writeText(config) - } - - val mapType = object : TypeToken>() {}.type - val parsed: Map = Gson().fromJson(config, mapType) - respond(parsed) - } "getConfigJsUrl" -> { // Calculate a data URL for the config.js file val configJsPath = getConfigJsPath() diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt index 289170d1b..8cbf8a499 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt @@ -1,10 +1,7 @@ package com.github.continuedev.continueintellijextension.toolWindow import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath -import com.github.continuedev.continueintellijextension.`continue`.Position -import com.github.continuedev.continueintellijextension.`continue`.Range -import com.github.continuedev.continueintellijextension.`continue`.RangeInFile -import com.github.continuedev.continueintellijextension.`continue`.getMachineUniqueID +import com.github.continuedev.continueintellijextension.`continue`.* import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.google.gson.Gson @@ -99,7 +96,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { "messageType" to messageType ) val jsonString = Gson().toJson(jsonData) - browser.executeJavaScriptAsync("""window.postMessage($jsonString, "*");""") + continuePluginService.sendToWebview(messageType, data, messageId ?: uuid()) } if (PASS_THROUGH_TO_CORE.contains(messageType)) { diff --git a/gui/src/util/ide.ts b/gui/src/util/ide.ts index ee61c6253..4bcca0a5e 100644 --- a/gui/src/util/ide.ts +++ b/gui/src/util/ide.ts @@ -23,11 +23,8 @@ function _postToIde(messageType: string, data: any, messageId?: string) { ); throw new Error("postIntellijMessage is undefined"); } - (window as any).postIntellijMessage?.( - messageType, - data, - messageId ?? uuidv4() - ); + messageId = messageId ?? uuidv4(); + (window as any).postIntellijMessage?.(messageType, data, messageId); return; } else { console.log( diff --git a/pkg/src/core.ts b/pkg/src/core.ts index 453055377..ff848bca3 100644 --- a/pkg/src/core.ts +++ b/pkg/src/core.ts @@ -119,6 +119,11 @@ export class Core { }); return items; }); + + // Pass-through + on("getSerializedConfig", (msg) => { + return this.configHandler.getSerializedConfig(); + }); } public invoke( diff --git a/pkg/src/index.ts b/pkg/src/index.ts index 8122fe2ff..4b5b81288 100644 --- a/pkg/src/index.ts +++ b/pkg/src/index.ts @@ -1,14 +1,22 @@ import { Command } from "commander"; -import { IpcIde } from "./IpcIde"; +import FileSystemIde from "core/util/filesystem"; +import fs from "fs"; import { Core } from "./core"; import { IpcMessenger } from "./messenger"; const program = new Command(); program.action(() => { - const messenger = new IpcMessenger(); - const ide = new IpcIde(messenger); - const core = new Core(messenger, ide); + try { + const messenger = new IpcMessenger(); + // const ide = new IpcIde(messenger); + const ide = new FileSystemIde(); + const core = new Core(messenger, ide); + } catch (e) { + fs.writeFileSync("./error.log", `${new Date().toISOString()} ${e}\n`); + console.log("Error: ", e); + process.exit(1); + } }); program.parse(process.argv); diff --git a/pkg/src/messenger.ts b/pkg/src/messenger.ts index 4fdeb1078..56700de1d 100644 --- a/pkg/src/messenger.ts +++ b/pkg/src/messenger.ts @@ -21,29 +21,43 @@ export class IpcMessenger { console.log("[info] Starting Continue core..."); process.stdin.on("data", (data) => { - console.log("Receieved data: ", data); - try { - const d = data.toString(); - const msg: Message = JSON.parse(d); - if (msg.messageType === undefined || msg.messageId === undefined) { - throw new Error("Invalid message sent: " + JSON.stringify(msg)); - } - - // Call handler and respond with return value - this.typeListeners - .get(msg.messageType as any) - ?.forEach(async (handler) => { - const response = await handler(msg); - this.send(msg.messageType, response, msg.messageId); - }); - - // Call handler which is waiting for the response, nothing to return - this.idListeners.get(msg.messageId)?.(msg); - } catch (e) { - console.error("Invalid JSON:", data); - return; - } + this._handleData(data); }); + process.stdout.on("close", () => { + fs.writeFileSync("./error.log", `${new Date().toISOString()}\n`); + console.log("[info] Exiting Continue core..."); + process.exit(1); + }); + process.stdin.on("close", () => { + fs.writeFileSync("./error.log", `${new Date().toISOString()}\n`); + console.log("[info] Exiting Continue core..."); + process.exit(1); + }); + } + + private _handleData(data: Buffer) { + console.log("Receieved data: ", data); + try { + const d = data.toString(); + const msg: Message = JSON.parse(d); + if (msg.messageType === undefined || msg.messageId === undefined) { + throw new Error("Invalid message sent: " + JSON.stringify(msg)); + } + + // Call handler and respond with return value + this.typeListeners + .get(msg.messageType as any) + ?.forEach(async (handler) => { + const response = await handler(msg); + this.send(msg.messageType, response, msg.messageId); + }); + + // Call handler which is waiting for the response, nothing to return + this.idListeners.get(msg.messageId)?.(msg); + } catch (e) { + console.error("Invalid JSON:", data); + return; + } } send(messageType: string, message: any, messageId?: string): string { diff --git a/pkg/src/protocol.ts b/pkg/src/protocol.ts index f30586fae..2a666c81c 100644 --- a/pkg/src/protocol.ts +++ b/pkg/src/protocol.ts @@ -1,3 +1,4 @@ +import { BrowserSerializedContinueConfig } from "core/config/load"; import { ChatMessage, CompletionOptions, @@ -83,4 +84,7 @@ export type Protocol = { }, AsyncGenerator, ]; + + // Pass-through from webview + getSerializedConfig: [undefined, Promise]; }; From 5ff47248eb30e7b05801a969c4edfd232ae36433 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sat, 17 Feb 2024 13:07:22 -0800 Subject: [PATCH 18/59] =?UTF-8?q?=F0=9F=9A=A7=20json.parse=20incoming=20me?= =?UTF-8?q?ssages=20in=20webview?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gui/src/util/ide.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gui/src/util/ide.ts b/gui/src/util/ide.ts index 4bcca0a5e..73638eba9 100644 --- a/gui/src/util/ide.ts +++ b/gui/src/util/ide.ts @@ -82,7 +82,8 @@ export async function ideRequest( const handler = (event: any) => { if (event.data.messageId === messageId) { window.removeEventListener("message", handler); - resolve(event.data.data); + const responseData = JSON.parse(event.data.data ?? null); + resolve(responseData); } }; window.addEventListener("message", handler); From 998ceec5df12592e7ae9eb404c81feade0c5bc3b Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sat, 17 Feb 2024 15:01:47 -0800 Subject: [PATCH 19/59] =?UTF-8?q?=F0=9F=9A=A7=20messaging?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/llm/llms/Ollama.ts | 76 +++++++++--------- core/web/webviewProtocol.ts | 1 + .../continue/CoreMessenger.kt | 3 +- .../continue/GetTheme.kt | 78 ++++++++++++------- .../ContinuePluginToolWindowFactory.kt | 50 +++++------- .../components/modelSelection/ModelSelect.tsx | 32 +------- gui/src/hooks/useSetup.ts | 6 ++ pkg/src/index.ts | 8 ++ pkg/src/messenger.ts | 5 ++ 9 files changed, 132 insertions(+), 127 deletions(-) diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 1e2fa32aa..3925c02f4 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -26,40 +26,44 @@ class Ollama extends BaseLLM { method: "POST", headers: {}, body: JSON.stringify({ name: this._getModel() }), - }).then(async (response) => { - if (response.status !== 200) { - console.warn( - "Error calling Ollama /api/show endpoint: ", - await response.text() - ); - return; - } - const body = await response.json(); - if (body.parameters) { - const params = []; - for (let line of body.parameters.split("\n")) { - let parts = line.split(" "); - if (parts.length < 2) { - continue; - } - let key = parts[0]; - let value = parts[parts.length - 1]; - switch (key) { - case "num_ctx": - this.contextLength = parseInt(value); - break; - case "stop": - if (!this.completionOptions.stop) { - this.completionOptions.stop = []; - } - this.completionOptions.stop.push(value); - break; - default: - break; + }) + .then(async (response) => { + if (response.status !== 200) { + console.warn( + "Error calling Ollama /api/show endpoint: ", + await response.text() + ); + return; + } + const body = await response.json(); + if (body.parameters) { + const params = []; + for (let line of body.parameters.split("\n")) { + let parts = line.split(" "); + if (parts.length < 2) { + continue; + } + let key = parts[0]; + let value = parts[parts.length - 1]; + switch (key) { + case "num_ctx": + this.contextLength = parseInt(value); + break; + case "stop": + if (!this.completionOptions.stop) { + this.completionOptions.stop = []; + } + this.completionOptions.stop.push(value); + break; + default: + break; + } } } - } - }); + }) + .catch((e) => { + console.warn(`Error calling Ollama /api/show endpoint: ${e}`); + }); } private _getModel() { @@ -178,16 +182,16 @@ class Ollama extends BaseLLM { ): AsyncGenerator { const client = new ollama.Ollama({ host: this.apiBase, - + fetch: (input, config) => { return fetch(input, { ...config, headers: { ...(config?.headers || {}), - ...(this.requestOptions?.headers || {}) - } + ...(this.requestOptions?.headers || {}), + }, }); - } + }, }); const response = await client.chat({ ...this._convertArgs(options, messages), diff --git a/core/web/webviewProtocol.ts b/core/web/webviewProtocol.ts index cc005b7ef..1bd07192e 100644 --- a/core/web/webviewProtocol.ts +++ b/core/web/webviewProtocol.ts @@ -157,4 +157,5 @@ export type ReverseWebviewProtocol = { newSession: [undefined, void]; refreshSubmenuItems: [undefined, void]; setTheme: [{ theme: any }, void]; + setColors: [{ [key: string]: string }, void]; }; diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index 98ff3d568..98039434a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -105,9 +105,10 @@ class CoreMessenger(continueCorePath: String, ideProtocolClient: IdeProtocolClie try { while (true) { val line = reader.readLine() - println("Core: $line") if (line != null && line.isNotEmpty()) { handleMessage(line) + } else { + Thread.sleep(100) } } } catch (e: IOException) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt index bf9ae4d5f..b8cf94e76 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt @@ -1,38 +1,58 @@ package com.github.continuedev.continueintellijextension.`continue` +import com.intellij.codeInsight.template.impl.TemplateColors +import com.intellij.openapi.editor.DefaultLanguageHighlighterColors +import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.EditorColorsScheme import com.intellij.openapi.editor.colors.TextAttributesKey +import kotlin.math.max +import kotlin.math.min -/* -[ - "--vscode-input-background", - "--vscode-sideBar-background", - "--vscode-editor-foreground", - "--vscode-button-background", - "--vscode-editor-background", - "--vscode-list-activeSelectionBackground", - "--vscode-focus-border", - "--vscode-quickInputList-focusForeground", - "--vscode-quickInput-background", - "--vscode-input-border", - "--vscode-focusBorder", - "--vscode-badge-background", - "--vscode-badge-foreground", - "--vscode-sideBar-border" -] - - */ -val vscToJetBrainsColorName = listOf( - arrayOf("--vscode-input-background", "?"), - arrayOf("--vscode-sideBar-background", "?"), - arrayOf("--vscode-editor-foreground", "?"), - -) class GetTheme { - fun getTheme(): EditorColorsScheme { - val editorColorsManager: EditorColorsManager = EditorColorsManager.getInstance() - val scheme: EditorColorsScheme = editorColorsManager.globalScheme - return scheme + fun getTheme(): Map { + val globalScheme = EditorColorsManager.getInstance().globalScheme + val defaultBackground = globalScheme.defaultBackground + val defaultForeground = globalScheme.defaultForeground + val highlight = globalScheme.getColor(EditorColors.MODIFIED_TAB_ICON_COLOR) ?: defaultForeground + val defaultBackgroundHex = String.format("#%02x%02x%02x", defaultBackground.red, defaultBackground.green, defaultBackground.blue) + val defaultForegroundHex = String.format("#%02x%02x%02x", defaultForeground.red, defaultForeground.green, defaultForeground.blue) + val highlightHex = String.format("#%02x%02x%02x", highlight.red, highlight.green, highlight.blue) + + val grayscale = (defaultBackground.red * 0.3 + defaultBackground.green * 0.59 + defaultBackground.blue * 0.11).toInt() + + val adjustedRed: Int + val adjustedGreen: Int + val adjustedBlue: Int + + val tint: Int = 20 + if (grayscale > 128) { // if closer to white + adjustedRed = max(0, defaultBackground.red - tint) + adjustedGreen = max(0, defaultBackground.green - tint) + adjustedBlue = max(0, defaultBackground.blue - tint) + } else { // if closer to black + adjustedRed = min(255, defaultBackground.red + tint) + adjustedGreen = min(255, defaultBackground.green + tint) + adjustedBlue = min(255, defaultBackground.blue + tint) + } + + val secondaryDarkHex = String.format("#%02x%02x%02x", adjustedRed, adjustedGreen, adjustedBlue) + + return mapOf( + "--vscode-editor-foreground" to defaultForegroundHex, + "--vscode-sideBar-background" to defaultBackgroundHex, + "--vscode-input-background" to secondaryDarkHex, + "--vscode-editor-background" to defaultBackgroundHex, + "--vscode-button-background" to defaultBackgroundHex, + "--vscode-list-activeSelectionBackground" to secondaryDarkHex, + "--vscode-focusBorder" to highlightHex, + "--vscode-quickInputList-focusForeground" to defaultForegroundHex, + "--vscode-quickInput-background" to defaultBackgroundHex, + "--vscode-input-border" to "#80808080", + "--vscode-badge-background" to highlightHex, + "--vscode-badge-foreground" to defaultForegroundHex, + "--vscode-sideBar-border" to "#80808080" + ) + } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt index 8cbf8a499..90c1b549b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt @@ -53,7 +53,24 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { class ContinuePluginWindow(toolWindow: ToolWindow, project: Project) { val PASS_THROUGH_TO_CORE = listOf( - "getSerializedConfig" + "abort", + "getContinueDir", + "history", + "saveSession", + "deleteSession", + "loadSession", + "logDevData", + "addModel", + "deleteModel", + "addOpenAIKey", + "llmStreamComplete", + "llmStreamChat", + "llmComplete", + "runNodeJsSlashCommand", + "loadSubmenuItems", + "getContextItems", + "addDocs", + "getSerializedConfig", ) init { @@ -108,35 +125,8 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { "onLoad" -> { GlobalScope.launch { // Set the colors to match Intellij theme - val globalScheme = EditorColorsManager.getInstance().globalScheme - val defaultBackground = globalScheme.defaultBackground - val defaultForeground = globalScheme.defaultForeground - val defaultBackgroundHex = String.format("#%02x%02x%02x", defaultBackground.red, defaultBackground.green, defaultBackground.blue) - val defaultForegroundHex = String.format("#%02x%02x%02x", defaultForeground.red, defaultForeground.green, defaultForeground.blue) - - val grayscale = (defaultBackground.red * 0.3 + defaultBackground.green * 0.59 + defaultBackground.blue * 0.11).toInt() - - val adjustedRed: Int - val adjustedGreen: Int - val adjustedBlue: Int - - val tint: Int = 20 - if (grayscale > 128) { // if closer to white - adjustedRed = max(0, defaultBackground.red - tint) - adjustedGreen = max(0, defaultBackground.green - tint) - adjustedBlue = max(0, defaultBackground.blue - tint) - } else { // if closer to black - adjustedRed = min(255, defaultBackground.red + tint) - adjustedGreen = min(255, defaultBackground.green + tint) - adjustedBlue = min(255, defaultBackground.blue + tint) - } - - val secondaryDarkHex = String.format("#%02x%02x%02x", adjustedRed, adjustedGreen, adjustedBlue) - - browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-editor-foreground\", \"$defaultForegroundHex\");") - browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-sideBar-background\", \"$defaultBackgroundHex\");") - browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-input-background\", \"$secondaryDarkHex\");") - browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-editor-background\", \"$defaultBackgroundHex\");") + val colors = GetTheme().getTheme(); + continuePluginService.sendToWebview("setColors", colors) val jsonData = mutableMapOf( "windowId" to continuePluginService.windowId, diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 25a7adcc7..44fa818dc 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -34,24 +34,6 @@ const GridDiv = styled.div` overflow: hidden; `; -const Select = styled.select` - border: none; - max-width: 50vw; - background-color: ${vscBackground}; - color: ${vscForeground}; - padding: 6px; - max-height: 35vh; - overflow: scroll; - cursor: pointer; - - &:focus { - outline: none; - } - &:hover { - background-color: ${vscInputBackground}; - } -`; - const StyledPlusIcon = styled(PlusIcon)` background-color: ${vscBackground}; cursor: pointer; @@ -66,18 +48,6 @@ const StyledPlusIcon = styled(PlusIcon)` border-left: 0.5px solid ${lightGray}; `; -const NewProviderDiv = styled.div` - cursor: pointer; - padding: 8px; - padding-left: 16px; - padding-right: 16px; - border-top: 0.5px solid ${lightGray}; - - &:hover { - background-color: ${vscInputBackground}; - } -`; - const StyledListbox = styled(Listbox)` background-color: ${vscBackground}; padding: 0; @@ -124,7 +94,7 @@ const StyledListboxOptions = styled(Listbox.Options)` max-height: 80vh; border-radius: ${defaultBorderRadius}; - overflow: scroll; + overflow-y: scroll; `; const StyledListboxOption = styled(Listbox.Option)<{ selected: boolean }>` diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index ffe408d7e..0cdd4ec50 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -51,6 +51,12 @@ function useSetup(dispatch: Dispatch) { dispatch(setInactive()); }); + useWebviewListener("setColors", async (colors) => { + Object.keys(colors).forEach((key) => { + document.body.style.setProperty(key, colors[key]); + }); + }); + useWebviewListener("configUpdate", async () => { loadConfig(); }); diff --git a/pkg/src/index.ts b/pkg/src/index.ts index 4b5b81288..8635b90c7 100644 --- a/pkg/src/index.ts +++ b/pkg/src/index.ts @@ -12,6 +12,14 @@ program.action(() => { // const ide = new IpcIde(messenger); const ide = new FileSystemIde(); const core = new Core(messenger, ide); + + // setTimeout(() => { + // messenger.mock({ + // messageId: "2fe7823c-10bd-4771-abb5-781f520039ec", + // messageType: "loadSubmenuItems", + // data: { title: "issue" }, + // }); + // }, 1000); } catch (e) { fs.writeFileSync("./error.log", `${new Date().toISOString()} ${e}\n`); console.log("Error: ", e); diff --git a/pkg/src/messenger.ts b/pkg/src/messenger.ts index 56700de1d..9a87b40c0 100644 --- a/pkg/src/messenger.ts +++ b/pkg/src/messenger.ts @@ -35,6 +35,11 @@ export class IpcMessenger { }); } + mock(data: any) { + const d = JSON.stringify(data); + this._handleData(Buffer.from(d)); + } + private _handleData(data: Buffer) { console.log("Receieved data: ", data); try { From 251c3281f8ae81bd0084edd2eba6e12a59d42b96 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sat, 17 Feb 2024 16:10:07 -0800 Subject: [PATCH 20/59] =?UTF-8?q?=F0=9F=9A=A7=20clean=20up=20webview=20pro?= =?UTF-8?q?tocol?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- {pkg/src => core}/protocol.ts | 39 +++--- core/web/webviewProtocol.ts | 116 +++++------------- extensions/vscode/src/webviewProtocol.ts | 48 ++++---- gui/src/components/dialogs/AddDocsDialog.tsx | 2 +- gui/src/components/dialogs/FTCDialog.tsx | 4 +- gui/src/components/gui/StepContainer.tsx | 7 +- gui/src/components/mainInput/TipTapEditor.tsx | 9 +- gui/src/components/mainInput/resolveInput.ts | 2 +- .../components/modelSelection/ModelSelect.tsx | 4 +- gui/src/hooks/useChatHandler.ts | 8 +- gui/src/hooks/useHistory.tsx | 12 +- gui/src/hooks/useSetup.ts | 2 +- gui/src/hooks/useSubmenuContextProviders.tsx | 2 +- gui/src/pages/modelconfig.tsx | 2 +- gui/src/pages/models.tsx | 2 +- gui/src/util/ide.ts | 23 +--- pkg/src/core.ts | 7 +- 17 files changed, 116 insertions(+), 173 deletions(-) rename {pkg/src => core}/protocol.ts (70%) diff --git a/pkg/src/protocol.ts b/core/protocol.ts similarity index 70% rename from pkg/src/protocol.ts rename to core/protocol.ts index 2a666c81c..1c27ed6bb 100644 --- a/pkg/src/protocol.ts +++ b/core/protocol.ts @@ -1,14 +1,20 @@ -import { BrowserSerializedContinueConfig } from "core/config/load"; import { ChatMessage, - CompletionOptions, - ContextItem, + ContextItemWithId, ContextSubmenuItem, + LLMFullCompletionOptions, + MessageContent, PersistedSessionInfo, RangeInFile, SerializedContinueConfig, SessionInfo, -} from "../../core"; +} from "."; +import { BrowserSerializedContinueConfig } from "./config/load"; + +export type ProtocolGeneratorType = AsyncGenerator<{ + done?: boolean; + content: T; +}>; export type Protocol = { // New @@ -28,6 +34,10 @@ export type Protocol = { { model: SerializedContinueConfig["models"][number] }, void, ]; + "config/getBrowserSerialized": [ + undefined, + Promise, + ]; "config/deleteModel": [{ title: string }, void]; "config/reload": [undefined, void]; "context/getContextItems": [ @@ -37,7 +47,7 @@ export type Protocol = { fullInput: string; selectedCode: RangeInFile[]; }, - Promise, + Promise, ]; "context/loadSubmenuItems": [ { title: string }, @@ -54,37 +64,34 @@ export type Protocol = { history: ChatMessage[]; modelTitle: string; slashCommandName: string; - contextItems: ContextItem[]; + contextItems: ContextItemWithId[]; params: any; historyIndex: number; }, - AsyncGenerator, + ProtocolGeneratorType, ]; "llm/complete": [ { prompt: string; - completionOptions: CompletionOptions; + completionOptions: LLMFullCompletionOptions; title: string; }, - AsyncGenerator, + string, ]; "llm/streamComplete": [ { prompt: string; - completionOptions: CompletionOptions; + completionOptions: LLMFullCompletionOptions; title: string; }, - AsyncGenerator, + ProtocolGeneratorType, ]; "llm/streamChat": [ { messages: ChatMessage[]; - completionOptions: CompletionOptions; + completionOptions: LLMFullCompletionOptions; title: string; }, - AsyncGenerator, + ProtocolGeneratorType, ]; - - // Pass-through from webview - getSerializedConfig: [undefined, Promise]; }; diff --git a/core/web/webviewProtocol.ts b/core/web/webviewProtocol.ts index 1bd07192e..bc61add77 100644 --- a/core/web/webviewProtocol.ts +++ b/core/web/webviewProtocol.ts @@ -1,33 +1,14 @@ import { - ChatMessage, ContextItemWithId, - ContextSubmenuItem, ContinueRcJson, DiffLine, - LLMFullCompletionOptions, - MessageContent, - ModelDescription, - PersistedSessionInfo, Problem, Range, - RangeInFile, - SessionInfo, } from ".."; import { RangeInFileWithContents } from "../commands/util"; -import { BrowserSerializedContinueConfig } from "../config/load"; +import { Protocol } from "../protocol"; -export type WebviewProtocol = { - abort: [string, void]; - onLoad: [ - undefined, - { - windowId: string; - serverUrl: string; - workspacePaths: string[]; - vscMachineId: string; - vscMediaUrl: string; - }, - ]; +export type IdeProtocol = { listWorkspaceContents: [undefined, string[]]; getWorkspaceDirs: [undefined, string[]]; listFolders: [undefined, string[]]; @@ -38,10 +19,6 @@ export type WebviewProtocol = { runCommand: [{ command: string }, void]; getSearchResults: [{ query: string }, string]; subprocess: [{ command: string }, [string, string]]; - history: [undefined, SessionInfo[]]; - saveSession: [PersistedSessionInfo, void]; - deleteSession: [string, void]; - loadSession: [string, PersistedSessionInfo]; saveFile: [{ filepath: string }, void]; readFile: [{ filepath: string }, string]; showDiff: [ @@ -62,76 +39,39 @@ export type WebviewProtocol = { getOpenFiles: [undefined, string[]]; getPinnedFiles: [undefined, string[]]; showLines: [{ filepath: string; startLine: number; endLine: number }, void]; - errorPopup: [{ message: string }, void]; - logDevData: [{ tableName: string; data: any }, void]; - addModel: [ModelDescription, void]; - deleteModel: [{ title: string }, void]; - addOpenAIKey: [{ key: string }, void]; - llmStreamComplete: [ - { - title: string; - prompt: string; - completionOptions: LLMFullCompletionOptions; - }, - AsyncGenerator<{ content: string; done?: boolean }>, - ]; - llmStreamChat: [ - { - title: string; - messages: ChatMessage[]; - completionOptions: LLMFullCompletionOptions; - }, - AsyncGenerator<{ content: MessageContent; done?: boolean }>, - ]; - llmComplete: [ - { - title: string; - prompt: string; - completionOptions: LLMFullCompletionOptions; - }, - { content: string }, - ]; - runNodeJsSlashCommand: [ - { - input: string; - history: ChatMessage[]; - modelTitle: string; - slashCommandName: string; - contextItems: ContextItemWithId[]; - params: { [key: string]: any } | undefined; - historyIndex: number; - }, - AsyncGenerator<{ content: string; done?: boolean }>, - ]; - loadSubmenuItems: [{ title: string }, ContextSubmenuItem[]]; - getContextItems: [ - { - name: string; - query: string; - fullInput: string; - selectedCode: RangeInFile[]; - }, - ContextItemWithId[], - ]; - addDocs: [{ url: string; title: string }, void]; - applyToCurrentFile: [{ text: string }, void]; - showTutorial: [undefined, void]; - showFile: [{ filepath: string }, void]; - openConfigJson: [undefined, void]; readRangeInFile: [{ filepath: string; range: Range }, string]; - toggleDevTools: [undefined, void]; - reloadWindow: [undefined, void]; - focusEditor: [undefined, void]; - toggleFullScreen: [undefined, void]; getDiff: [undefined, string]; - getSerializedConfig: [undefined, BrowserSerializedContinueConfig]; + getWorkspaceConfigs: [undefined, ContinueRcJson[]]; getTerminalContents: [undefined, string]; isTelemetryEnabled: [undefined, boolean]; getUniqueId: [undefined, string]; - getWorkspaceConfigs: [undefined, ContinueRcJson[]]; - getDefaultModelTitle: [{ defaultModelTitle: string }, void]; }; +export type WebviewProtocol = Protocol & + IdeProtocol & { + onLoad: [ + undefined, + { + windowId: string; + serverUrl: string; + workspacePaths: string[]; + vscMachineId: string; + vscMediaUrl: string; + }, + ]; + + errorPopup: [{ message: string }, void]; + applyToCurrentFile: [{ text: string }, void]; + showTutorial: [undefined, void]; + showFile: [{ filepath: string }, void]; + openConfigJson: [undefined, void]; + + toggleDevTools: [undefined, void]; + reloadWindow: [undefined, void]; + focusEditor: [undefined, void]; + toggleFullScreen: [undefined, void]; + }; + export type ReverseWebviewProtocol = { setInactive: [undefined, void]; configUpdate: [undefined, void]; diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 88d2d8039..5aa2a8e78 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -155,7 +155,7 @@ export class VsCodeWebviewProtocol { this.on("getDiff", async (msg) => { return await ide.getDiff(); }); - this.on("getSerializedConfig", async (msg) => { + this.on("config/getBrowserSerialized", async (msg) => { return await configHandler.getSerializedConfig(); }); this.on("getTerminalContents", async (msg) => { @@ -192,17 +192,17 @@ export class VsCodeWebviewProtocol { return await ide.subprocess(msg.data.command); }); // History - this.on("history", (msg) => { + this.on("history/list", (msg) => { return historyManager.list(); }); - this.on("saveSession", (msg) => { + this.on("history/save", (msg) => { historyManager.save(msg.data); }); - this.on("deleteSession", (msg) => { - historyManager.delete(msg.data); + this.on("history/delete", (msg) => { + historyManager.delete(msg.data.id); }); - this.on("loadSession", (msg) => { - return historyManager.load(msg.data); + this.on("history/load", (msg) => { + return historyManager.load(msg.data.id); }); this.on("saveFile", async (msg) => { return await ide.saveFile(msg.data.filepath); @@ -245,11 +245,11 @@ export class VsCodeWebviewProtocol { } }); }); - this.on("logDevData", (msg) => { + this.on("devdata/log", (msg) => { logDevData(msg.data.tableName, msg.data.data); }); - this.on("addModel", (msg) => { - const model = msg.data; + this.on("config/addModel", (msg) => { + const model = msg.data.model; const newConfigString = addModel(model); this.configHandler.reloadConfig(); this.ide.openFile(getConfigJsonPath()); @@ -285,18 +285,18 @@ export class VsCodeWebviewProtocol { "🎉 Your model has been successfully added to config.json. You can use this file to further edit its configuration." ); }); - this.on("deleteModel", (msg) => { + this.on("config/deleteModel", (msg) => { deleteModel(msg.data.title); this.configHandler.reloadConfig(); }); - this.on("addOpenAIKey", async (msg) => { - addOpenAIKey(msg.data.key); + this.on("config/addOpenAiKey", async (msg) => { + addOpenAIKey(msg.data); this.configHandler.reloadConfig(); }); async function* llmStreamComplete( protocol: VsCodeWebviewProtocol, - msg: Message + msg: Message ) { const model = await protocol.configHandler.llmFromTitle(msg.data.title); const gen = model.streamComplete( @@ -316,11 +316,11 @@ export class VsCodeWebviewProtocol { return { done: true, content: next.value }; } - this.on("llmStreamComplete", (msg) => llmStreamComplete(this, msg)); + this.on("llm/streamComplete", (msg) => llmStreamComplete(this, msg)); async function* llmStreamChat( protocol: VsCodeWebviewProtocol, - msg: Message + msg: Message ) { const model = await protocol.configHandler.llmFromTitle(msg.data.title); const gen = model.streamChat( @@ -340,19 +340,19 @@ export class VsCodeWebviewProtocol { return { done: true, content: next.value }; } - this.on("llmStreamChat", (msg) => llmStreamChat(this, msg)); - this.on("llmComplete", async (msg) => { + this.on("llm/streamChat", (msg) => llmStreamChat(this, msg)); + this.on("llm/complete", async (msg) => { const model = await this.configHandler.llmFromTitle(msg.data.title); const completion = await model.complete( msg.data.prompt, msg.data.completionOptions ); - return { content: completion }; + return completion; }); async function* runNodeJsSlashCommand( protocol: VsCodeWebviewProtocol, - msg: Message + msg: Message ) { const { input, @@ -393,9 +393,9 @@ export class VsCodeWebviewProtocol { } yield { done: true, content: "" }; } - this.on("runNodeJsSlashCommand", (msg) => runNodeJsSlashCommand(this, msg)); + this.on("command/run", (msg) => runNodeJsSlashCommand(this, msg)); - this.on("loadSubmenuItems", async (msg) => { + this.on("context/loadSubmenuItems", async (msg) => { const { title } = msg.data; const config = await this.configHandler.loadConfig(); const provider = config.contextProviders?.find( @@ -421,7 +421,7 @@ export class VsCodeWebviewProtocol { } }); - this.on("getContextItems", async (msg) => { + this.on("context/getContextItems", async (msg) => { const { name, query, fullInput, selectedCode } = msg.data; const config = await this.configHandler.loadConfig(); const llm = await this.configHandler.llmFromTitle(); @@ -457,7 +457,7 @@ export class VsCodeWebviewProtocol { return []; } }); - this.on("addDocs", (msg) => { + this.on("context/addDocs", (msg) => { const { url, title } = msg.data; const embeddingsProvider = new TransformersJsEmbeddingsProvider(); vscode.window.withProgress( diff --git a/gui/src/components/dialogs/AddDocsDialog.tsx b/gui/src/components/dialogs/AddDocsDialog.tsx index 76cf0953f..5c70b19a6 100644 --- a/gui/src/components/dialogs/AddDocsDialog.tsx +++ b/gui/src/components/dialogs/AddDocsDialog.tsx @@ -58,7 +58,7 @@ function AddDocsDialog() { disabled={!docsUrl || !urlValid} className="ml-auto" onClick={() => { - postToIde("addDocs", { url: docsUrl, title: docsTitle }); + postToIde("context/addDocs", { url: docsUrl, title: docsTitle }); setDocsTitle(""); setDocsUrl(""); dispatch(setShowDialog(false)); diff --git a/gui/src/components/dialogs/FTCDialog.tsx b/gui/src/components/dialogs/FTCDialog.tsx index e679dadca..8533905ea 100644 --- a/gui/src/components/dialogs/FTCDialog.tsx +++ b/gui/src/components/dialogs/FTCDialog.tsx @@ -5,7 +5,7 @@ import styled from "styled-components"; import { Button, Input } from ".."; import { setDefaultModel } from "../../redux/slices/stateSlice"; import { setShowDialog } from "../../redux/slices/uiStateSlice"; -import { addOpenAIKey } from "../../util/ide"; +import { postToIde } from "../../util/ide"; const GridDiv = styled.div` display: grid; @@ -55,7 +55,7 @@ function FTCDialog() {
    Date: Sun, 18 Feb 2024 20:43:57 -0800 Subject: [PATCH 36/59] =?UTF-8?q?=F0=9F=9A=A7=20download=20sqlite3=20binar?= =?UTF-8?q?y=20for=20all=20targets?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/build.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/pkg/build.js b/pkg/build.js index 4eef70a5e..00844238c 100644 --- a/pkg/build.js +++ b/pkg/build.js @@ -99,6 +99,22 @@ for (let i = 2; i < process.argv.length; i++) { execSync( `npx pkg --no-bytecode --public-packages "*" --public pkgJson/${target} --out-path bin/${target}` ); + + // Download and unzip prebuilt sqlite3 binary for the target + const downloadUrl = `https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-${ + target === "win32-arm64" ? "win32-ia32" : target + }.tar.gz`; + execSync(`curl -L -o bin/${target}/build.tar.gz ${downloadUrl}`); + execSync(`cd bin/${target} && tar -xvzf build.tar.gz`); + fs.copyFileSync( + `bin/${target}/build/Release/node_sqlite3.node`, + `bin/${target}/node_sqlite3.node` + ); + fs.unlinkSync(`bin/${target}/build.tar.gz`); + fs.rmSync(`bin/${target}/build`, { + recursive: true, + force: true, + }); } // execSync( // `npx pkg out/index.js --target node18-darwin-arm64 --no-bytecode --public-packages "*" --public -o bin/pkg` From ae0f5547e544acd8fc94f7bcce8cbe549d2e9095 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 18 Feb 2024 22:41:20 -0800 Subject: [PATCH 37/59] =?UTF-8?q?=F0=9F=9A=A7=20download=20lancedb=20binar?= =?UTF-8?q?ies=20for=20each=20target?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/build.js | 16 ++++++++++++++++ pkg/pkgJson/darwin-x64/package.json | 2 +- pkg/pkgJson/linux-arm64/package.json | 2 +- pkg/pkgJson/linux-x64/package.json | 2 +- pkg/pkgJson/win32-arm64/package.json | 2 +- pkg/pkgJson/win32-x64/package.json | 2 +- 6 files changed, 21 insertions(+), 5 deletions(-) diff --git a/pkg/build.js b/pkg/build.js index 00844238c..ab0db2c14 100644 --- a/pkg/build.js +++ b/pkg/build.js @@ -20,6 +20,14 @@ for (let i = 2; i < process.argv.length; i++) { } } +const targetToLanceDb = { + "darwin-arm64": "@lancedb/vectordb-darwin-arm64", + "darwin-x64": "@lancedb/vectordb-darwin-x64", + "linux-arm64": "@lancedb/vectordb-linux-arm64-gnu", + "linux-x64": "@lancedb/vectordb-linux-x64-gnu", + "win32-x64": "@lancedb/vectordb-win32-x64-msvc", +}; + (async () => { // console.log("[info] Building with ncc..."); // execSync(`npx ncc build src/index.ts -o out`); @@ -68,6 +76,14 @@ for (let i = 2; i < process.argv.length; i++) { ); console.log(`[info] Copied ${DYNAMIC_IMPORTS.join(", ")}`); + console.log("[info] Downloading prebuilt lancedb..."); + for (const target of targets) { + if (targetToLanceDb[target]) { + console.log(`[info] Downloading ${target}...`); + execSync(`npm install -f ${targetToLanceDb[target]} --no-save`); + } + } + console.log("[info] Building with esbuild..."); // Bundles the extension into one file await esbuild.build({ diff --git a/pkg/pkgJson/darwin-x64/package.json b/pkg/pkgJson/darwin-x64/package.json index aa98b9b17..d064d6c2a 100644 --- a/pkg/pkgJson/darwin-x64/package.json +++ b/pkg/pkgJson/darwin-x64/package.json @@ -9,7 +9,7 @@ ], "assets": [ "../../../core/node_modules/sqlite3/**/*", - "../../node_modules/@lancedb/**/*", + "../../node_modules/@lancedb/vectordb-darwin-x64/index.node", "../../out/tree-sitter.wasm", "../../out/tree-sitter-wasms/*" ], diff --git a/pkg/pkgJson/linux-arm64/package.json b/pkg/pkgJson/linux-arm64/package.json index f1d4c5f67..37a3a5b6d 100644 --- a/pkg/pkgJson/linux-arm64/package.json +++ b/pkg/pkgJson/linux-arm64/package.json @@ -9,7 +9,7 @@ ], "assets": [ "../../../core/node_modules/sqlite3/**/*", - "../../node_modules/@lancedb/**/*", + "../../node_modules/@lancedb/vectordb-linux-arm64-gnu/index.node", "../../out/tree-sitter.wasm", "../../out/tree-sitter-wasms/*" ], diff --git a/pkg/pkgJson/linux-x64/package.json b/pkg/pkgJson/linux-x64/package.json index 62f99ebd0..487886d26 100644 --- a/pkg/pkgJson/linux-x64/package.json +++ b/pkg/pkgJson/linux-x64/package.json @@ -9,7 +9,7 @@ ], "assets": [ "../../../core/node_modules/sqlite3/**/*", - "../../node_modules/@lancedb/**/*", + "../../node_modules/@lancedb/vectordb-linux-x64-gnu/index.node", "../../out/tree-sitter.wasm", "../../out/tree-sitter-wasms/*" ], diff --git a/pkg/pkgJson/win32-arm64/package.json b/pkg/pkgJson/win32-arm64/package.json index c7b16e035..4573ccbca 100644 --- a/pkg/pkgJson/win32-arm64/package.json +++ b/pkg/pkgJson/win32-arm64/package.json @@ -9,7 +9,7 @@ ], "assets": [ "../../../core/node_modules/sqlite3/**/*", - "../../node_modules/@lancedb/**/*", + "../../node_modules/@lancedb/vectordb-win32-x64-msvc/index.node", "../../out/tree-sitter.wasm", "../../out/tree-sitter-wasms/*" ], diff --git a/pkg/pkgJson/win32-x64/package.json b/pkg/pkgJson/win32-x64/package.json index 32ac6e583..c9a4b1a9b 100644 --- a/pkg/pkgJson/win32-x64/package.json +++ b/pkg/pkgJson/win32-x64/package.json @@ -9,7 +9,7 @@ ], "assets": [ "../../../core/node_modules/sqlite3/**/*", - "../../node_modules/@lancedb/**/*", + "../../node_modules/@lancedb/vectordb-win32-x64-msvc/index.node", "../../out/tree-sitter.wasm", "../../out/tree-sitter-wasms/*" ], From 61e78ba9041064f3bcece4d17443d53551b56fea Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Feb 2024 09:03:13 -0800 Subject: [PATCH 38/59] =?UTF-8?q?=F0=9F=90=9B=20fix=20config/addModel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extensions/intellij/gradle.properties | 2 +- gui/src/pages/modelconfig.tsx | 2 +- gui/src/pages/models.tsx | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 627737abd..79e91cc2c 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -4,7 +4,7 @@ pluginGroup = com.github.continuedev.continueintellijextension pluginName = continue-intellij-extension pluginRepositoryUrl = https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion = 0.0.27 +pluginVersion = 0.0.28 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild = 223 diff --git a/gui/src/pages/modelconfig.tsx b/gui/src/pages/modelconfig.tsx index f4971f485..e8192f10a 100644 --- a/gui/src/pages/modelconfig.tsx +++ b/gui/src/pages/modelconfig.tsx @@ -246,7 +246,7 @@ function ModelConfig() { ...formParams, provider: modelInfo.provider, }; - postToIde("config/addModel", model); + postToIde("config/addModel", { model }); dispatch(setDefaultModel(model.title)); navigate("/"); }} diff --git a/gui/src/pages/models.tsx b/gui/src/pages/models.tsx index 405096321..f2636dd39 100644 --- a/gui/src/pages/models.tsx +++ b/gui/src/pages/models.tsx @@ -117,7 +117,7 @@ function Models() { ), provider: PROVIDER_INFO[selectedProvider].provider, }; - postToIde("config/addModel", model); + postToIde("config/addModel", { model }); dispatch(setDefaultModel(model.title)); navigate("/"); }} From 6d65a0a74cd401e3f1d29410e6e7cd42355e3b07 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Feb 2024 09:07:46 -0800 Subject: [PATCH 39/59] =?UTF-8?q?=F0=9F=92=84=20improve=20color=20theme=20?= =?UTF-8?q?in=20jetbrains?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../continueintellijextension/continue/GetTheme.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt index b8cf94e76..20367c33b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/GetTheme.kt @@ -44,10 +44,10 @@ class GetTheme { "--vscode-input-background" to secondaryDarkHex, "--vscode-editor-background" to defaultBackgroundHex, "--vscode-button-background" to defaultBackgroundHex, - "--vscode-list-activeSelectionBackground" to secondaryDarkHex, + "--vscode-list-activeSelectionBackground" to defaultBackgroundHex, "--vscode-focusBorder" to highlightHex, "--vscode-quickInputList-focusForeground" to defaultForegroundHex, - "--vscode-quickInput-background" to defaultBackgroundHex, + "--vscode-quickInput-background" to secondaryDarkHex, "--vscode-input-border" to "#80808080", "--vscode-badge-background" to highlightHex, "--vscode-badge-foreground" to defaultForegroundHex, From 67eeca2647c48a13a4a69a149cfaa7f799358204 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Feb 2024 09:10:16 -0800 Subject: [PATCH 40/59] =?UTF-8?q?=F0=9F=94=96=20bump=20intellij=20version?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extensions/intellij/gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 79e91cc2c..97afe4e9e 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -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.28 +pluginVersion = 0.0.29 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild = 223 From f195270a3ef8c09c4a5b649c2a9a92e81fd3cfd4 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Feb 2024 15:18:00 -0800 Subject: [PATCH 41/59] =?UTF-8?q?=F0=9F=94=80=20extra=20changes=20from=20m?= =?UTF-8?q?erge?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/config/handler.ts | 18 ++++++++++++++++++ core/config/load.ts | 17 +---------------- core/index.d.ts | 6 +++++- 3 files changed, 24 insertions(+), 17 deletions(-) diff --git a/core/config/handler.ts b/core/config/handler.ts index ca4e536b6..341dfaf12 100644 --- a/core/config/handler.ts +++ b/core/config/handler.ts @@ -122,8 +122,26 @@ export class ConfigHandler { if (input.hostname === "localhost") { input.hostname = "127.0.0.1"; } + + let updatedBody: string | undefined = undefined; + try { + if ( + llm.requestOptions?.extraBodyProperties && + typeof init.body === "string" + ) { + const parsedBody = JSON.parse(init.body); + updatedBody = JSON.stringify({ + ...parsedBody, + ...llm.requestOptions.extraBodyProperties, + }); + } + } catch (e) { + console.log("Unable to parse HTTP request body: ", e); + } + const resp = await fetch(input, { ...init, + body: updatedBody ?? init.body, headers, agent, }); diff --git a/core/config/load.ts b/core/config/load.ts index d230916bb..232854333 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -1,8 +1,7 @@ import * as fs from "fs"; import { - BaseCompletionOptions, + BrowserSerializedContinueConfig, Config, - ContextProviderDescription, ContextProviderWithParams, ContinueConfig, ContinueRcJson, @@ -14,7 +13,6 @@ import { ModelDescription, SerializedContinueConfig, SlashCommand, - SlashCommandDescription, } from ".."; import { @@ -277,19 +275,6 @@ async function intermediateToFinalConfig( }; } -interface BrowserSerializedContinueConfig { - allowAnonymousTelemetry?: boolean; - models: ModelDescription[]; - systemMessage?: string; - completionOptions?: BaseCompletionOptions; - slashCommands?: SlashCommandDescription[]; - contextProviders?: ContextProviderDescription[]; - disableIndexing?: boolean; - disableSessionTitles?: boolean; - userToken?: string; - embeddingsProvider?: string; -} - function finalToBrowserConfig( final: ContinueConfig ): BrowserSerializedContinueConfig { diff --git a/core/index.d.ts b/core/index.d.ts index 0fa331e33..a8c1f13de 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -13,7 +13,11 @@ declare global { }; colorThemeName?: string; workspacePaths?: string[]; - postIntellijMessage?: (type: string, data: any) => void; + postIntellijMessage?: ( + messageType: string, + data: any, + messageIde: string + ) => void; } } From 0c58fcfb301c508c41269bfd876a6e729f7a6ec9 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Feb 2024 15:45:28 -0800 Subject: [PATCH 42/59] =?UTF-8?q?=F0=9F=94=A7=20pass=20selectedCode=20and?= =?UTF-8?q?=20config=20to=20custom=20slash=20commands?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/config/types.ts | 39 +++++++++++--------- core/index.d.ts | 2 + core/protocol.ts | 1 + extensions/vscode/src/webviewProtocol.ts | 3 ++ gui/src/components/mainInput/resolveInput.ts | 4 +- gui/src/hooks/useChatHandler.ts | 13 +++++-- pkg/src/core.ts | 3 ++ 7 files changed, 41 insertions(+), 24 deletions(-) diff --git a/core/config/types.ts b/core/config/types.ts index dcfd4a40e..976dc3f89 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -15,7 +15,11 @@ declare global { }; colorThemeName?: string; workspacePaths?: string[]; - postIntellijMessage?: (type: string, data: any) => void; + postIntellijMessage?: ( + messageType: string, + data: any, + messageIde: string + ) => void; } } @@ -313,13 +317,24 @@ declare global { message: string; } + export type IdeType = "vscode" | "jetbrains"; + export interface IdeInfo { + ideType: IdeType; + name: string; + version: string; + remoteName: string; + } + export interface IDE { - getSerializedConfig(): Promise; + getIdeInfo(): Promise; getDiff(): Promise; + isTelemetryEnabled(): Promise; + getUniqueId(): Promise; getTerminalContents(): Promise; listWorkspaceContents(directory?: string): Promise; listFolders(): Promise; getWorkspaceDirs(): Promise; + getWorkspaceConfigs(): Promise; writeFile(path: string, contents: string): Promise; showVirtualFile(title: string, contents: string): Promise; getContinueDir(): Promise; @@ -327,6 +342,7 @@ declare global { runCommand(command: string): Promise; saveFile(filepath: string): Promise; readFile(filepath: string): Promise; + readRangeInFile(filepath: string, range: Range): Promise; showLines( filepath: string, startLine: number, @@ -343,22 +359,7 @@ declare global { subprocess(command: string): Promise<[string, string]>; getProblems(filepath?: string | undefined): Promise; getBranch(dir: string): Promise; - - // Embeddings - /** - * Returns list of [tag, filepath, hash of contents] that need to be embedded - */ - getFilesToEmbed(providerId: string): Promise<[string, string, string][]>; - sendEmbeddingForChunk( - chunk: Chunk, - embedding: number[], - tags: string[] - ): void; - retrieveChunks( - text: string, - n: number, - directory: string | undefined - ): Promise; + getStats(directory: string): Promise<{ [path: string]: number }>; } // Slash Commands @@ -371,6 +372,8 @@ declare global { input: string; params?: { [key: string]: any } | undefined; contextItems: ContextItemWithId[]; + selectedCode: RangeInFile[]; + config: ContinueConfig; } export interface SlashCommand { diff --git a/core/index.d.ts b/core/index.d.ts index 9c118ed72..4f34289f8 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -370,6 +370,8 @@ export interface ContinueSDK { input: string; params?: { [key: string]: any } | undefined; contextItems: ContextItemWithId[]; + selectedCode: RangeInFile[]; + config: ContinueConfig; } export interface SlashCommand { diff --git a/core/protocol.ts b/core/protocol.ts index 237223c58..a0259393d 100644 --- a/core/protocol.ts +++ b/core/protocol.ts @@ -67,6 +67,7 @@ export type Protocol = { contextItems: ContextItemWithId[]; params: any; historyIndex: number; + selectedCode: RangeInFile[]; }, ProtocolGeneratorType, ]; diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 5aa2a8e78..3476e5c0d 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -362,6 +362,7 @@ export class VsCodeWebviewProtocol { contextItems, params, historyIndex, + selectedCode, } = msg.data; const config = await protocol.configHandler.loadConfig(); @@ -386,6 +387,8 @@ export class VsCodeWebviewProtocol { historyIndex, }); }, + selectedCode, + config, })) { if (content) { yield { content }; diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index cc576ff06..603a074fb 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -26,7 +26,7 @@ interface MentionAttrs { async function resolveEditorContent( editorState: JSONContent -): Promise<[ContextItemWithId[], MessageContent]> { +): Promise<[ContextItemWithId[], RangeInFile[], MessageContent]> { let parts: MessagePart[] = []; let contextItemAttrs: MentionAttrs[] = []; const selectedCode: RangeInFile[] = []; @@ -127,7 +127,7 @@ async function resolveEditorContent( parts[lastTextIndex].text = `${slashCommand} ${parts[lastTextIndex].text}`; } - return [contextItems, parts]; + return [contextItems, selectedCode, parts]; } function findLastIndex( diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 088a59d95..2c8eee34c 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -7,6 +7,7 @@ import { ChatMessage, LLMReturnValue, MessageContent, + RangeInFile, SlashCommandDescription, } from "core"; import { constructMessages } from "core/llm/constructMessages"; @@ -97,7 +98,8 @@ function useChatHandler(dispatch: Dispatch) { messages: ChatMessage[], slashCommand: SlashCommandDescription, input: string, - historyIndex: number + historyIndex: number, + selectedCode: RangeInFile[] ) { const abortController = new AbortController(); const cancelToken = abortController.signal; @@ -113,6 +115,7 @@ function useChatHandler(dispatch: Dispatch) { contextItems, params: slashCommand.params, historyIndex, + selectedCode, }, cancelToken )) { @@ -135,8 +138,9 @@ function useChatHandler(dispatch: Dispatch) { } // Resolve context providers and construct new history - const [contextItems, content] = await resolveEditorContent(editorState); - console.log(contextItems, content); + const [contextItems, selectedCode, content] = + await resolveEditorContent(editorState); + const message: ChatMessage = { role: "user", content, @@ -192,7 +196,8 @@ function useChatHandler(dispatch: Dispatch) { messages, slashCommand, commandInput, - historyIndex + historyIndex, + selectedCode ); } } catch (e) { diff --git a/pkg/src/core.ts b/pkg/src/core.ts index c84e99927..4244e09a9 100644 --- a/pkg/src/core.ts +++ b/pkg/src/core.ts @@ -203,6 +203,7 @@ export class Core { contextItems, params, historyIndex, + selectedCode, } = msg.data; const config = await configHandler.loadConfig(); @@ -228,6 +229,8 @@ export class Core { // historyIndex, // }); }, + selectedCode, + config, })) { if (content) { yield { content }; From 9fc4069f53a1b24dc9d8743abdbd5b518cb89d08 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Feb 2024 17:16:12 -0800 Subject: [PATCH 43/59] =?UTF-8?q?=F0=9F=90=9B=20small=20improvements?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/test/edit.test.ts | 2 ++ .../src/main/resources/config_schema.json | 24 +++++++++++++++---- extensions/vscode/src/lang-server/codeLens.ts | 8 +++---- extensions/vscode/src/util/ideUtils.ts | 4 +++- extensions/vscode/yarn.lock | 8 +++---- gui/src/pages/modelconfig.tsx | 1 - 6 files changed, 32 insertions(+), 15 deletions(-) diff --git a/core/test/edit.test.ts b/core/test/edit.test.ts index 48543ce4b..d4186915d 100644 --- a/core/test/edit.test.ts +++ b/core/test/edit.test.ts @@ -62,6 +62,8 @@ describe("/edit slash command", () => { history: [], input: "implement this function", contextItems: [TEST_CONTEXT_ITEM], + selectedCode: [], + config: {} as any, }; let total = ""; diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index ca9a92aa8..b82858588 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -87,6 +87,11 @@ "additionalProperties": { "type": "string" } + }, + "extraBodyProperties": { + "title": "Extra Body Properties", + "description": "This object will be merged with the body when making the HTTP requests", + "type": "object" } } }, @@ -216,7 +221,8 @@ "verifySsl": null, "caBundlePath": null, "proxy": null, - "headers": null + "headers": null, + "extraBodyProperties": null }, "allOf": [ { @@ -336,6 +342,7 @@ "gpt-3.5-turbo-0613", "gpt-4-32k", "gpt-4-0125-preview", + "gpt-4-turbo-preview", "AUTODETECT" ] } @@ -421,7 +428,7 @@ "gpt-4", "gpt-3.5-turbo-0613", "gpt-4-32k", - "gpt-4-0125-preview", + "gpt-4-turbo-preview", "gpt-4-vision-preview", "mistral-7b", "mistral-8x7b", @@ -444,6 +451,9 @@ "stable-code-3b", "starcoder-1b", "starcoder-3b", + "mistral-tiny", + "mistral-small", + "mistral-medium", "AUTODETECT" ] }, @@ -782,7 +792,7 @@ "gpt-4", "gpt-3.5-turbo-0613", "gpt-4-32k", - "gpt-4-0125-preview", + "gpt-4-turbo-preview", "gpt-4-vision-preview", "mistral-7b", "mistral-8x7b", @@ -986,7 +996,9 @@ "folder", "issue", "docs", - "tree" + "tree", + "highlights", + "outline" ], "markdownEnumDescriptions": [ "Reference the contents of the current changes as given by `git diff`", @@ -1002,7 +1014,9 @@ "Retrieve important pages from a documentation website, as determined by similarity search", "Index and retrieve the contents of any documentation site, using embeddings to find important snippets", "Display a file tree of the current workspace", - "Include a repo map showing important code objects" + "Include a repo map showing important code objects", + "Displays important snippets of code from the currently open files", + "Displays definition lines from the currently open files" ], "type": "string" }, diff --git a/extensions/vscode/src/lang-server/codeLens.ts b/extensions/vscode/src/lang-server/codeLens.ts index 1b28e6280..69d2a5613 100644 --- a/extensions/vscode/src/lang-server/codeLens.ts +++ b/extensions/vscode/src/lang-server/codeLens.ts @@ -35,12 +35,12 @@ class VerticalPerLineCodeLensProvider implements vscode.CodeLensProvider { ); codeLenses.push( new vscode.CodeLens(range, { - title: "Accept ✅", + title: "Accept", command: "continue.acceptVerticalDiffBlock", arguments: [filepath, i], }), new vscode.CodeLens(range, { - title: "Reject ❌", + title: "Reject", command: "continue.rejectVerticalDiffBlock", arguments: [filepath, i], }) @@ -78,12 +78,12 @@ class SuggestionsCodeLensProvider implements vscode.CodeLensProvider { ); codeLenses.push( new vscode.CodeLens(range, { - title: "Accept ✅", + title: "Accept", command: "continue.acceptSuggestion", arguments: [suggestion], }), new vscode.CodeLens(range, { - title: "Reject ❌", + title: "Reject", command: "continue.rejectSuggestion", arguments: [suggestion], }) diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 15f51fb7c..a83141831 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -219,7 +219,9 @@ export class VsCodeIdeUtils { !( document.languageId === "plaintext" && document.getText() === "accessible-buffer-accessible-buffer-" - ) && !document.uri.scheme.startsWith("git") + ) && + !document.uri.scheme.startsWith("git") && + document.uri.scheme !== "vscode-scm" ); } diff --git a/extensions/vscode/yarn.lock b/extensions/vscode/yarn.lock index ec6f22821..8514c2ac5 100644 --- a/extensions/vscode/yarn.lock +++ b/extensions/vscode/yarn.lock @@ -701,10 +701,10 @@ resolved "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.10.tgz" integrity sha512-y/uHOGb0g15pvqv5tdTyZ6oN+0QVpBmZDzKFWW6pPbuSZjB2uPqcs+ti0RB+AUdmS21kavVQqaNsw/HLKEGrHA== -"@lancedb/vectordb-darwin-arm64@0.4.8": - version "0.4.8" - resolved "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.8.tgz" - integrity sha512-FpnJaw7KmNdD/FtOw9AcmPL5P+L04AcnfPj9ZyEjN8iCwB/qaOGYgdfBv+EbEtfHIsqA12q/1BRduu9KdB6BIA== +"@lancedb/vectordb-darwin-arm64@0.4.9": + version "0.4.9" + resolved "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.9.tgz" + integrity sha512-u56TXU0hvdLbknGwC7Ebza3/CUFeCTkoCy/sC6h0FtOGya+NV7jraAeXEwDzoZbfW08VYYxnp3TsCcpNU9lpTA== "@lukeed/csprng@^1.0.0": version "1.1.0" diff --git a/gui/src/pages/modelconfig.tsx b/gui/src/pages/modelconfig.tsx index 44a966be7..08a982c2b 100644 --- a/gui/src/pages/modelconfig.tsx +++ b/gui/src/pages/modelconfig.tsx @@ -39,7 +39,6 @@ export const CustomModelButton = styled.div<{ disabled: boolean }>` display: flex; justify-content: center; align-items: center; - width: 100%; transition: all 0.5s; ${(props) => From c067d9b0d006412b33b44c6a22297137054b35d9 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Feb 2024 17:20:42 -0800 Subject: [PATCH 44/59] =?UTF-8?q?=F0=9F=9A=B8=20update=20shortcuts=20for?= =?UTF-8?q?=20vscode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extensions/vscode/continue_tutorial.py | 8 ++++---- extensions/vscode/package.json | 12 ++++++------ extensions/vscode/src/activation/inlineTips.ts | 6 +++--- extensions/vscode/src/lang-server/codeLens.ts | 2 +- gui/src/components/dialogs/KeyboardShortcuts.tsx | 14 +++++++------- gui/src/pages/gui.tsx | 2 +- 6 files changed, 22 insertions(+), 22 deletions(-) diff --git a/extensions/vscode/continue_tutorial.py b/extensions/vscode/continue_tutorial.py index b89fd009a..dff23a718 100644 --- a/extensions/vscode/continue_tutorial.py +++ b/extensions/vscode/continue_tutorial.py @@ -19,7 +19,7 @@ You can either - follow along by clicking the gray CodeLens buttons above the lines, in order, starting with "Begin Section" """ -# region —————————————————————————— Part 1: Ask a question about code [⌘ M] —————————————————————————— +# region —————————————————————————— Part 1: Ask a question about code [⌘ L] —————————————————————————— """Step 1: Highlight the function below""" @@ -34,14 +34,14 @@ def mysterious_function(x): return x -"""Step 2: Use the keyboard shortcut [⌘ M] to +"""Step 2: Use the keyboard shortcut [⌘ L] to select the code and toggle the Continue input box""" """Step 3: Ask a question and press Enter""" # endregion -# region ————————————————————————————————— Part 2: Edit code [⌘ ⇧ L] ————————————————————————————————— +# region ————————————————————————————————— Part 2: Edit code [⌘ I] ————————————————————————————————— """Step 1: Highlight this code""" @@ -60,7 +60,7 @@ def mysterious_function(x): return x -"""Step 2: Use the keyboard shortcut [⌘ ⇧ L] to edit""" +"""Step 2: Use the keyboard shortcut [⌘ I] to edit""" """Step 3: Type "" and press Enter""" diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 977787e74..846ee6145 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -180,13 +180,13 @@ "keybindings": [ { "command": "continue.focusContinueInput", - "mac": "cmd+m", - "key": "ctrl+m" + "mac": "cmd+l", + "key": "ctrl+l" }, { "command": "continue.focusContinueInputWithoutClear", - "mac": "cmd+shift+m", - "key": "ctrl+shift+m" + "mac": "cmd+shift+l", + "key": "ctrl+shift+l" }, { "command": "continue.acceptDiff", @@ -206,8 +206,8 @@ }, { "command": "continue.quickEdit", - "mac": "cmd+shift+l", - "key": "ctrl+shift+l" + "mac": "cmd+i", + "key": "ctrl+i" }, { "command": "continue.toggleAuxiliaryBar", diff --git a/extensions/vscode/src/activation/inlineTips.ts b/extensions/vscode/src/activation/inlineTips.ts index 84039aaa2..001fb6c1a 100644 --- a/extensions/vscode/src/activation/inlineTips.ts +++ b/extensions/vscode/src/activation/inlineTips.ts @@ -3,7 +3,7 @@ import { getMetaKeyLabel } from "../util/util"; const inlineTipDecoration = vscode.window.createTextEditorDecorationType({ after: { - contentText: `${getMetaKeyLabel()} M to select code, ${getMetaKeyLabel()} ⇧ L to edit`, + contentText: `${getMetaKeyLabel()} L to select code, ${getMetaKeyLabel()} I to edit`, color: "#888", margin: "0 0 0 6em", fontWeight: "bold", @@ -31,7 +31,7 @@ function handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) { const line = Math.max(0, selection.start.line - 1); const hoverMarkdown = new vscode.MarkdownString( - `Use ${getMetaKeyLabel()} M to select code, or ${getMetaKeyLabel()} ⇧ L to edit highlighted code. Click [here](command:continue.hideInlineTip) if you don't want to see these inline suggestions.` + `Use ${getMetaKeyLabel()} L to select code, or ${getMetaKeyLabel()} I to edit highlighted code. Click [here](command:continue.hideInlineTip) if you don't want to see these inline suggestions.` ); hoverMarkdown.isTrusted = true; hoverMarkdown.supportHtml = true; @@ -49,7 +49,7 @@ function handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) { const emptyFileTooltipDecoration = vscode.window.createTextEditorDecorationType( { after: { - contentText: `Use ${getMetaKeyLabel()} ⇧ L to generate code`, + contentText: `Use ${getMetaKeyLabel()} I to generate code`, color: "#888", margin: "2em 0 0 0", fontStyle: "italic", diff --git a/extensions/vscode/src/lang-server/codeLens.ts b/extensions/vscode/src/lang-server/codeLens.ts index 69d2a5613..04df50e69 100644 --- a/extensions/vscode/src/lang-server/codeLens.ts +++ b/extensions/vscode/src/lang-server/codeLens.ts @@ -48,7 +48,7 @@ class VerticalPerLineCodeLensProvider implements vscode.CodeLensProvider { if (codeLenses.length === 2) { codeLenses.push( new vscode.CodeLens(range, { - title: `(${getMetaKeyLabel()}⇧↩/${getMetaKeyLabel()}⇧⌫ to accept/reject all, ${getMetaKeyLabel()}⇧L to retry)`, + title: `(${getMetaKeyLabel()}⇧↩/${getMetaKeyLabel()}⇧⌫ to accept/reject all, ${getMetaKeyLabel()}I to retry)`, command: "", }) ); diff --git a/gui/src/components/dialogs/KeyboardShortcuts.tsx b/gui/src/components/dialogs/KeyboardShortcuts.tsx index 271f7078a..55d31da50 100644 --- a/gui/src/components/dialogs/KeyboardShortcuts.tsx +++ b/gui/src/components/dialogs/KeyboardShortcuts.tsx @@ -55,18 +55,18 @@ function KeyboardShortcut(props: KeyboardShortcutProps) { const vscodeShortcuts: KeyboardShortcutProps[] = [ { - mac: "⌘ M", - windows: "⌃ M", + mac: "⌘ L", + windows: "⌃ L", description: "Ask about Highlighted Code", }, + { + mac: "⌘ I", + windows: "⌃ I", + description: "Edit highlighted code", + }, { mac: "⌘ ⇧ L", windows: "⌃ ⇧ L", - description: "Edit highlighted code", - }, - { - mac: "⌘ ⇧ M", - windows: "⌃ ⇧ M", description: "Ask Follow-Up about Highlighted Code", }, { diff --git a/gui/src/pages/gui.tsx b/gui/src/pages/gui.tsx index e2d535e48..953c62745 100644 --- a/gui/src/pages/gui.tsx +++ b/gui/src/pages/gui.tsx @@ -468,7 +468,7 @@ function GUI(props: GUIProps) { }} className="mr-auto" > - New Session ({getMetaKeyLabel()} {isJetBrains() ? "J" : "M"}) + New Session ({getMetaKeyLabel()} {isJetBrains() ? "J" : "L"}) ) : null}
    From f14d2e7b2f955f5995cd85d55e3e28ee897f943e Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Feb 2024 17:42:55 -0800 Subject: [PATCH 45/59] =?UTF-8?q?=E2=9C=A8=20search=20bar=20for=20history?= =?UTF-8?q?=20page?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extensions/vscode/media/welcome.md | 6 +-- gui/src/pages/history.tsx | 61 +++++++++++++++++++++++++++++- 2 files changed, 62 insertions(+), 5 deletions(-) diff --git a/extensions/vscode/media/welcome.md b/extensions/vscode/media/welcome.md index a9e7e381c..618c175ae 100644 --- a/extensions/vscode/media/welcome.md +++ b/extensions/vscode/media/welcome.md @@ -8,10 +8,10 @@ Continue is currently in the left sidebar, but we recommend moving it to the rig ## 🔑 Most important shortcuts -Cmd/Ctrl + M = Select code +Cmd/Ctrl + L = Select code -Cmd/Ctrl + Shift + M = Select code for follow-up +Cmd/Ctrl + Shift + L = Select code for follow-up -Cmd/Ctrl + Shift + L = Quick edit +Cmd/Ctrl + I = Quick edit Cmd/Ctrl + Shift + R = Automatically debug terminal diff --git a/gui/src/pages/history.tsx b/gui/src/pages/history.tsx index 585499fae..b276f1ce9 100644 --- a/gui/src/pages/history.tsx +++ b/gui/src/pages/history.tsx @@ -1,16 +1,41 @@ import { ArrowLeftIcon, TrashIcon } from "@heroicons/react/24/outline"; import { PersistedSessionInfo, SessionInfo } from "core"; +import MiniSearch from "minisearch"; import React, { Fragment, useEffect, useState } from "react"; import { useDispatch } from "react-redux"; import { useNavigate } from "react-router-dom"; import styled from "styled-components"; -import { lightGray, vscBackground, vscInputBackground } from "../components"; +import { + defaultBorderRadius, + lightGray, + vscBackground, + vscBadgeBackground, + vscForeground, + vscInputBackground, +} from "../components"; import HeaderButtonWithText from "../components/HeaderButtonWithText"; import useHistory from "../hooks/useHistory"; import { useNavigationListener } from "../hooks/useNavigationListener"; import { newSession } from "../redux/slices/stateSlice"; import { getFontSize } from "../util"; +const SearchBar = styled.input` + padding: 4px 8px; + border-radius: ${defaultBorderRadius}; + border: 0.5px solid #888; + outline: none; + width: 90vw; + max-width: 500px; + margin: 8px auto; + display: block; + background-color: ${vscInputBackground}; + color: ${vscForeground}; + &:focus { + border: 0.5px solid ${vscBadgeBackground}; + outline: none; + } +`; + const Tr = styled.tr` &:hover { background-color: ${vscInputBackground}; @@ -149,15 +174,38 @@ function History() { const dispatch = useDispatch(); const { getHistory } = useHistory(dispatch); + const [minisearch, setMinisearch] = useState< + MiniSearch<{ title: string; sessionId: string }> + >( + new MiniSearch({ + fields: ["title"], + storeFields: ["title", "sessionId", "id"], + }) + ); + const [searchTerm, setSearchTerm] = useState(""); + useEffect(() => { const fetchSessions = async () => { const sessions = await getHistory(); setSessions(sessions); + minisearch.addAll( + sessions.map((session) => ({ + title: session.title, + sessionId: session.sessionId, + id: session.sessionId, + })) + ); }; fetchSessions(); }, []); useEffect(() => { + const sessionIds = minisearch + .search(searchTerm, { + fuzzy: 0.1, + }) + .map((result) => result.id); + setFilteredAndSortedSessions( sessions .filter((session) => { @@ -170,13 +218,17 @@ function History() { } return workspacePaths.includes(session.workspaceDirectory); }) + // Filter by search term + .filter((session) => { + return searchTerm === "" || sessionIds.includes(session.sessionId); + }) .sort( (a, b) => parseDate(b.dateCreated).getTime() - parseDate(a.dateCreated).getTime() ) ); - }, [filteringByWorkspace, sessions]); + }, [filteringByWorkspace, sessions, searchTerm, minisearch]); useEffect(() => { setHeaderHeight(stickyHistoryHeaderRef.current?.clientHeight || 100); @@ -236,6 +288,11 @@ function History() { )}
    + setSearchTerm(e.target.value)} + /> {filteredAndSortedSessions.map((session, index) => { From 21981156f8eca6a74d0da48b53b6cebafdb8bf48 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Feb 2024 19:10:48 -0800 Subject: [PATCH 46/59] =?UTF-8?q?=F0=9F=92=84=20smaller=20help=20iconds?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gui/src/pages/help.tsx | 41 ++++++++++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/gui/src/pages/help.tsx b/gui/src/pages/help.tsx index a4b4cf0ec..11fb045d8 100644 --- a/gui/src/pages/help.tsx +++ b/gui/src/pages/help.tsx @@ -6,14 +6,28 @@ import KeyboardShortcutsDialog from "../components/dialogs/KeyboardShortcuts"; import { useNavigationListener } from "../hooks/useNavigationListener"; import { postToIde } from "../util/ide"; +const ResourcesDiv = styled.div` + margin: 4px; + border-top: 0.5px solid ${lightGray}; + border-bottom: 0.5px solid ${lightGray}; +`; + const IconDiv = styled.div<{ backgroundColor?: string }>` display: flex; align-items: center; justify-content: center; cursor: pointer; - height: 100%; - padding: 0 4px; + padding: 12px; + + & > a { + color: ${vscForeground}; + text-decoration: none; + display: flex; + align-items: center; + width: 100%; + justify-content: center; + } &:hover { background-color: ${(props) => props.backgroundColor || lightGray}; @@ -37,7 +51,7 @@ function HelpPage() { const navigate = useNavigate(); return ( -
    +
    -
    +

    Resources

    + + Demo Video @@ -83,25 +100,29 @@ function HelpPage() { target="_blank" > + Documentation + Continue Discord @@ -110,16 +131,18 @@ function HelpPage() { target="_blank" > + GitHub Issues -
    +
    From e8bbdc06a192a9d6576b7019a164393c16019306 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Feb 2024 19:50:01 -0800 Subject: [PATCH 47/59] =?UTF-8?q?=F0=9F=90=9B=20use=20llama=20tokenizer=20?= =?UTF-8?q?for=20llama-based=20models?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/autocomplete/constructPrompt.ts | 11 ++-- core/indexing/chunk/basic.ts | 2 +- core/indexing/chunk/chunk.ts | 4 +- core/indexing/chunk/code.ts | 7 +-- core/indexing/chunk/markdown.ts | 5 +- core/llm/countTokens.ts | 53 ++++++++++++++----- core/package-lock.json | 6 +++ core/package.json | 1 + core/yarn.lock | 5 ++ extensions/vscode/package-lock.json | 1 + .../src/lang-server/completionProvider.ts | 5 +- extensions/vscode/yarn.lock | 1 + gui/package-lock.json | 1 + 13 files changed, 70 insertions(+), 32 deletions(-) diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 29e0a38a7..dea714b2f 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -76,7 +76,8 @@ export async function constructAutocompletePrompt( line: number, character: number ) => Promise, - options: TabAutocompleteOptions + options: TabAutocompleteOptions, + modelName: string ): Promise<{ prefix: string; suffix: string; useFim: boolean }> { // Find external snippets const snippets: AutocompleteSnippet[] = []; @@ -121,17 +122,17 @@ export async function constructAutocompletePrompt( .join("\n"); const maxPrefixTokens = options.maxPromptTokens * options.prefixPercentage - - countTokens(formattedSnippets, "gpt-4"); - let prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens); + countTokens(formattedSnippets, modelName); + let prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens, modelName); if (formattedSnippets.length > 0) { prefix = formattedSnippets + "\n" + prefix; } const maxSuffixTokens = Math.min( - options.maxPromptTokens - countTokens(prefix, "gpt-4"), + options.maxPromptTokens - countTokens(prefix, modelName), options.maxSuffixPercentage * options.maxPromptTokens ); - let suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens); + let suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName); return { prefix, suffix, useFim: true }; } diff --git a/core/indexing/chunk/basic.ts b/core/indexing/chunk/basic.ts index 60bda5995..e0e506a90 100644 --- a/core/indexing/chunk/basic.ts +++ b/core/indexing/chunk/basic.ts @@ -11,7 +11,7 @@ export function* basicChunker( let currLine = 0; for (const line of contents.split("\n")) { - const lineTokens = countTokens(line, "gpt-4"); + const lineTokens = countTokens(line); if (chunkTokens + lineTokens > maxChunkSize - 5) { yield { content: chunkContent, startLine, endLine: currLine - 1 }; chunkContent = ""; diff --git a/core/indexing/chunk/chunk.ts b/core/indexing/chunk/chunk.ts index bfb33eb5c..0132bc08d 100644 --- a/core/indexing/chunk/chunk.ts +++ b/core/indexing/chunk/chunk.ts @@ -43,11 +43,11 @@ export async function* chunkDocument( contents, maxChunkSize )) { - if (countTokens(chunkWithoutId.content, "gpt-4") > MAX_CHUNK_SIZE) { + if (countTokens(chunkWithoutId.content) > MAX_CHUNK_SIZE) { console.warn( `Chunk with more than ${maxChunkSize} tokens constructed: `, filepath, - countTokens(chunkWithoutId.content, "gpt-4") + countTokens(chunkWithoutId.content) ); continue; } diff --git a/core/indexing/chunk/code.ts b/core/indexing/chunk/code.ts index b9862c634..b7527d422 100644 --- a/core/indexing/chunk/code.ts +++ b/core/indexing/chunk/code.ts @@ -59,10 +59,7 @@ function collapseChildren( } code = code.slice(node.startIndex); let removedChild = false; - while ( - countTokens(code, "gpt-4") > maxChunkSize && - collapsedChildren.length > 0 - ) { + while (countTokens(code) > maxChunkSize && collapsedChildren.length > 0) { removedChild = true; // Remove children starting at the end - TODO: Add multiple chunks so no children are missing const childCode = collapsedChildren.pop()!; @@ -169,7 +166,7 @@ function* getSmartCollapsedChunks( // Keep entire text if not over size if ( (root || node.type in collapsedNodeConstructors) && - countTokens(node.text, "gpt-4") < maxChunkSize + countTokens(node.text) < maxChunkSize ) { yield { content: node.text, diff --git a/core/indexing/chunk/markdown.ts b/core/indexing/chunk/markdown.ts index 0e0901cf0..252d43f5e 100644 --- a/core/indexing/chunk/markdown.ts +++ b/core/indexing/chunk/markdown.ts @@ -57,7 +57,7 @@ export async function* markdownChunker( maxChunkSize: number, hLevel: number ): AsyncGenerator { - if (countTokens(content, "gpt-4") <= maxChunkSize) { + if (countTokens(content) <= maxChunkSize) { const header = findHeader(content.split("\n")); yield { content, @@ -122,8 +122,7 @@ export async function* markdownChunker( for (const section of sections) { for await (const chunk of markdownChunker( section.content, - maxChunkSize - - (section.header ? countTokens(section.header, "gpt-4") : 0), + maxChunkSize - (section.header ? countTokens(section.header) : 0), hLevel + 1 )) { yield { diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 6283ad782..fddbee08a 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -1,16 +1,29 @@ -import { encodingForModel as _encodingForModel, Tiktoken } from "js-tiktoken"; +import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; +// @ts-expect-error +import llamaTokenizer from "llama-tokenizer-js"; import { ChatMessage, MessageContent, MessagePart } from ".."; +import { autodetectTemplateType } from "./autodetect"; import { TOKEN_BUFFER_FOR_SAFETY } from "./constants"; -let encoding: Tiktoken | null = null; +interface Encoding { + encode: Tiktoken["encode"]; + decode: Tiktoken["decode"]; +} -function encodingForModel(modelName: string): Tiktoken { - if (encoding) { - return encoding; +let gptEncoding: Encoding | null = null; + +function encodingForModel(modelName: string): Encoding { + const modelType = autodetectTemplateType(modelName); + + if (!modelType || modelType === "none") { + if (!gptEncoding) { + gptEncoding = _encodingForModel("gpt-4"); + } + + return gptEncoding; } - encoding = _encodingForModel("gpt-4"); - return encoding; + return llamaTokenizer; } function countImageTokens(content: MessagePart): number { @@ -21,7 +34,11 @@ function countImageTokens(content: MessagePart): number { } } -function countTokens(content: MessageContent, modelName: string): number { +function countTokens( + content: MessageContent, + // defaults to llama2 because the tokenizer tends to produce more tokens + modelName: string = "llama2" +): number { const encoding = encodingForModel(modelName); if (Array.isArray(content)) { return content.reduce((acc, part) => { @@ -72,21 +89,29 @@ function countChatMessageTokens( return countTokens(chatMessage.content, modelName) + TOKENS_PER_MESSAGE; } -function pruneLinesFromTop(prompt: string, maxTokens: number): string { - let totalTokens = countTokens(prompt, "gpt-4"); +function pruneLinesFromTop( + prompt: string, + maxTokens: number, + modelName: string +): string { + let totalTokens = countTokens(prompt, modelName); const lines = prompt.split("\n"); while (totalTokens > maxTokens && lines.length > 0) { - totalTokens -= countTokens(lines.shift()!, "gpt-4"); + totalTokens -= countTokens(lines.shift()!, modelName); } return lines.join("\n"); } -function pruneLinesFromBottom(prompt: string, maxTokens: number): string { - let totalTokens = countTokens(prompt, "gpt-4"); +function pruneLinesFromBottom( + prompt: string, + maxTokens: number, + modelName: string +): string { + let totalTokens = countTokens(prompt, modelName); const lines = prompt.split("\n"); while (totalTokens > maxTokens && lines.length > 0) { - totalTokens -= countTokens(lines.pop()!, "gpt-4"); + totalTokens -= countTokens(lines.pop()!, modelName); } return lines.join("\n"); diff --git a/core/package-lock.json b/core/package-lock.json index 661225ff3..f8bac68aa 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -21,6 +21,7 @@ "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", "js-tiktoken": "^1.0.8", + "llama-tokenizer-js": "^1.1.3", "llm-code-highlighter": "^0.0.9", "node-fetch": "^3.3.2", "node-html-markdown": "^1.3.0", @@ -4840,6 +4841,11 @@ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "dev": true }, + "node_modules/llama-tokenizer-js": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/llama-tokenizer-js/-/llama-tokenizer-js-1.1.3.tgz", + "integrity": "sha512-+BUgsLCXVQJkjiD/t7PdESLn+yXJIRX/BJfwzVVYfKZ9aN3gsP9xoadBZxKnCxGz2Slby+S7x41gUr2TKNaS4Q==" + }, "node_modules/llm-code-highlighter": { "version": "0.0.9", "resolved": "https://registry.npmjs.org/llm-code-highlighter/-/llm-code-highlighter-0.0.9.tgz", diff --git a/core/package.json b/core/package.json index 0de36ab6f..bbee1eec2 100644 --- a/core/package.json +++ b/core/package.json @@ -31,6 +31,7 @@ "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", "js-tiktoken": "^1.0.8", + "llama-tokenizer-js": "^1.1.3", "llm-code-highlighter": "^0.0.9", "node-fetch": "^3.3.2", "node-html-markdown": "^1.3.0", diff --git a/core/yarn.lock b/core/yarn.lock index e62426b85..eeb4d4a45 100644 --- a/core/yarn.lock +++ b/core/yarn.lock @@ -2745,6 +2745,11 @@ lines-and-columns@^1.1.6: resolved "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz" integrity sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg== +llama-tokenizer-js@^1.1.3: + version "1.1.3" + resolved "https://registry.npmjs.org/llama-tokenizer-js/-/llama-tokenizer-js-1.1.3.tgz" + integrity sha512-+BUgsLCXVQJkjiD/t7PdESLn+yXJIRX/BJfwzVVYfKZ9aN3gsP9xoadBZxKnCxGz2Slby+S7x41gUr2TKNaS4Q== + llm-code-highlighter@^0.0.9: version "0.0.9" resolved "https://registry.npmjs.org/llm-code-highlighter/-/llm-code-highlighter-0.0.9.tgz" diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 095f3f786..a859fd72b 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -97,6 +97,7 @@ "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", "js-tiktoken": "^1.0.8", + "llama-tokenizer-js": "^1.1.3", "llm-code-highlighter": "^0.0.9", "node-fetch": "^3.3.2", "node-html-markdown": "^1.3.0", diff --git a/extensions/vscode/src/lang-server/completionProvider.ts b/extensions/vscode/src/lang-server/completionProvider.ts index 626899754..4cde62277 100644 --- a/extensions/vscode/src/lang-server/completionProvider.ts +++ b/extensions/vscode/src/lang-server/completionProvider.ts @@ -275,8 +275,9 @@ export class ContinueCompletionProvider fullSuffix, clipboardText, lang, - this.promptBuilder.getDefinition, - options + this.promptBuilder.getDefinition.bind(this.promptBuilder), + options, + llm.model ); const { template, completionOptions } = options.template diff --git a/extensions/vscode/yarn.lock b/extensions/vscode/yarn.lock index 8514c2ac5..25d57981f 100644 --- a/extensions/vscode/yarn.lock +++ b/extensions/vscode/yarn.lock @@ -2328,6 +2328,7 @@ core-util-is@1.0.2: http-proxy-agent "^7.0.1" https-proxy-agent "^7.0.3" js-tiktoken "^1.0.8" + llama-tokenizer-js "^1.1.3" llm-code-highlighter "^0.0.9" node-fetch "^3.3.2" node-html-markdown "^1.3.0" diff --git a/gui/package-lock.json b/gui/package-lock.json index d323c6c75..08ee5adff 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -85,6 +85,7 @@ "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", "js-tiktoken": "^1.0.8", + "llama-tokenizer-js": "^1.1.3", "llm-code-highlighter": "^0.0.9", "node-fetch": "^3.3.2", "node-html-markdown": "^1.3.0", From 82f6796d7957f1605110f67dcaf390e9fb5bff33 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Feb 2024 20:06:52 -0800 Subject: [PATCH 48/59] =?UTF-8?q?=F0=9F=92=84=20ui=20to=20pause=20indexing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../loaders/IndexingProgressBar.tsx | 70 +++++++++++++++---- 1 file changed, 55 insertions(+), 15 deletions(-) diff --git a/gui/src/components/loaders/IndexingProgressBar.tsx b/gui/src/components/loaders/IndexingProgressBar.tsx index c0d140d79..29674e271 100644 --- a/gui/src/components/loaders/IndexingProgressBar.tsx +++ b/gui/src/components/loaders/IndexingProgressBar.tsx @@ -1,7 +1,17 @@ +import { useState } from "react"; import ReactDOM from "react-dom"; import styled from "styled-components"; import { StyledTooltip, lightGray, vscForeground } from ".."; +const DIAMETER = 6; +const CircleDiv = styled.div` + background-color: #bb0; + box-shadow: 0px 0px 2px 1px #bb0; + width: ${DIAMETER}px; + height: ${DIAMETER}px; + border-radius: ${DIAMETER / 2}px; +`; + const ProgressBarWrapper = styled.div` width: 100px; height: 6px; @@ -52,22 +62,52 @@ const IndexingProgressBar = ({ const tooltipPortalDiv = document.getElementById("tooltip-portal-div"); + const [expanded, setExpanded] = useState(true); + const [hovered, setHovered] = useState(false); + return ( - <> - - - - -

    Indexing ({Math.trunc((completed / total) * 100)}%)

    -
    - {tooltipPortalDiv && - ReactDOM.createPortal( - - {currentlyIndexing} - , - tooltipPortalDiv - )} - +
    setExpanded((prev) => !prev)} + className="cursor-pointer" + > + {expanded ? ( + <> + setHovered(true)} + onMouseLeave={() => setHovered(false)} + > + + + +

    + {hovered + ? "Click to pause" + : `Indexing (${Math.trunc((completed / total) * 100)}%)`} +

    +
    + {tooltipPortalDiv && + ReactDOM.createPortal( + + {currentlyIndexing} + , + tooltipPortalDiv + )} + + ) : ( + <> + + {tooltipPortalDiv && + ReactDOM.createPortal( + + Click to unpause indexing ( + {Math.trunc((completed / total) * 100)}%) + , + tooltipPortalDiv + )} + + )} +
    ); }; From d2bcd081b32d26c31cc676b0586648f03a0e53e4 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 19 Feb 2024 22:10:10 -0800 Subject: [PATCH 49/59] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20run=20transformers.j?= =?UTF-8?q?s=20in=20a=20worker=20thread?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../TransformersJsEmbeddingsProvider.ts | 73 ++++++------------- .../embeddings/TransformersJsWorkerThread.js | 58 +++++++++++++++ core/protocol.ts | 2 +- core/tsconfig.json | 2 +- gui/src/redux/slices/serverStateReducer.ts | 4 +- 5 files changed, 82 insertions(+), 57 deletions(-) create mode 100644 core/indexing/embeddings/TransformersJsWorkerThread.js diff --git a/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts b/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts index 4773e6f0b..e959b699f 100644 --- a/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts +++ b/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts @@ -1,37 +1,12 @@ -import { - PipelineType, - env, - pipeline, -} from "../../vendor/node_modules/@xenova/transformers"; - +import { Worker } from "worker_threads"; import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider"; -env.allowLocalModels = true; -env.allowRemoteModels = false; -if (typeof window === "undefined") { - // The embeddings provider should just never be called in the browser - env.localModelPath = `${__dirname}/../models`; -} - -class EmbeddingsPipeline { - static task: PipelineType = "feature-extraction"; - static model = "all-MiniLM-L6-v2"; - static instance: any | null = null; - - static async getInstance() { - if (this.instance === null) { - this.instance = await pipeline(this.task, this.model); - } - - return this.instance; - } -} - class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider { static MaxGroupSize: number = 4; + static ModelName: string = "all-MiniLM-L2-v6"; constructor() { - super({ model: "all-MiniLM-L2-v6" }); + super({ model: TransformersJsEmbeddingsProvider.ModelName }); } get id(): string { @@ -39,33 +14,27 @@ class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider { } async embed(chunks: string[]) { - let extractor = await EmbeddingsPipeline.getInstance(); + return new Promise((resolve, reject) => { + const worker = new Worker("./TransformersJsWorkerThread.js"); - if (!extractor) { - throw new Error("TransformerJS embeddings pipeline is not initialized"); - } + worker.postMessage(chunks); - if (chunks.length === 0) { - return []; - } - - let outputs = []; - for ( - let i = 0; - i < chunks.length; - i += TransformersJsEmbeddingsProvider.MaxGroupSize - ) { - let chunkGroup = chunks.slice( - i, - i + TransformersJsEmbeddingsProvider.MaxGroupSize - ); - let output = await extractor(chunkGroup, { - pooling: "mean", - normalize: true, + worker.on("message", (result) => { + if (result.error) { + reject(new Error(result.error)); + } else { + resolve(result); + } }); - outputs.push(...output.tolist()); - } - return outputs; + + worker.on("error", reject); + + worker.on("exit", (code) => { + if (code !== 0) { + reject(new Error(`Worker stopped with exit code ${code}`)); + } + }); + }) as any; } } diff --git a/core/indexing/embeddings/TransformersJsWorkerThread.js b/core/indexing/embeddings/TransformersJsWorkerThread.js new file mode 100644 index 000000000..775e16a05 --- /dev/null +++ b/core/indexing/embeddings/TransformersJsWorkerThread.js @@ -0,0 +1,58 @@ +import { + env, + pipeline, +} from "../../vendor/node_modules/@xenova/transformers/types/transformers"; +import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider"; +const { parentPort } = require("worker_threads"); + +env.allowLocalModels = true; +env.allowRemoteModels = false; +if (typeof window === "undefined") { + // The embeddings provider should just never be called in the browser + env.localModelPath = `${__dirname}/../models`; +} + +class EmbeddingsPipeline { + static task = "feature-extraction"; + static model = TransformersJsEmbeddingsProvider.ModelName; + static instance = null; + + static async getInstance() { + if (this.instance === null) { + this.instance = await pipeline(this.task, this.model); + } + + return this.instance; + } +} + +parentPort.on("message", async (chunks) => { + try { + const extractor = await EmbeddingsPipeline.getInstance(); + + if (!extractor) { + throw new Error("TransformerJS embeddings pipeline is not initialized"); + } + + let outputs = []; + for ( + let i = 0; + i < chunks.length; + i += TransformersJsEmbeddingsProvider.MaxGroupSize + ) { + let chunkGroup = chunks.slice( + i, + i + TransformersJsEmbeddingsProvider.MaxGroupSize + ); + let output = await extractor(chunkGroup, { + pooling: "mean", + normalize: true, + }); + outputs.push(...output.tolist()); + } + + parentPort.postMessage(outputs); + } catch (error) { + parentPort.postMessage({ error: error.message }); + } +}); diff --git a/core/protocol.ts b/core/protocol.ts index a0259393d..4247291e9 100644 --- a/core/protocol.ts +++ b/core/protocol.ts @@ -1,4 +1,5 @@ import { + BrowserSerializedContinueConfig, ChatMessage, ContextItemWithId, ContextSubmenuItem, @@ -9,7 +10,6 @@ import { SerializedContinueConfig, SessionInfo, } from "."; -import { BrowserSerializedContinueConfig } from "./config/load"; export type ProtocolGeneratorType = AsyncGenerator<{ done?: boolean; diff --git a/core/tsconfig.json b/core/tsconfig.json index c92ea029b..26315457b 100644 --- a/core/tsconfig.json +++ b/core/tsconfig.json @@ -18,5 +18,5 @@ "noEmitOnError": false, "types": ["jest", "node"] }, - "include": ["./**/*.ts"] + "include": ["./**/*.ts", "indexing/embeddings/TransformersJsWorkerThread.js"] } diff --git a/gui/src/redux/slices/serverStateReducer.ts b/gui/src/redux/slices/serverStateReducer.ts index ae3eaf8c6..77b6cf795 100644 --- a/gui/src/redux/slices/serverStateReducer.ts +++ b/gui/src/redux/slices/serverStateReducer.ts @@ -1,5 +1,4 @@ import { createSlice } from "@reduxjs/toolkit"; -import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider"; import FreeTrial from "core/llm/llms/FreeTrial"; import { RootStore } from "../store"; @@ -27,8 +26,7 @@ const initialState: RootStore["serverState"] = { new FreeTrial({ model: "gpt-4" }), new FreeTrial({ model: "gpt-3.5-turbo" }), ], - embeddingsProvider: new TransformersJsEmbeddingsProvider(), - }, + } as any, contextProviders: [], savedContextGroups: [], indexingProgress: 1.0, From c2a7f7c5acd308e92d5edf249fbdd72f110f24e2 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 20 Feb 2024 14:47:42 -0800 Subject: [PATCH 50/59] =?UTF-8?q?=F0=9F=90=9B=20disable=20off-screen=20ren?= =?UTF-8?q?dering=20in=20intellij=20webview=20(fixes=20korean=20input)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../toolWindow/ContinuePluginToolWindowFactory.kt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt index 681c14bb7..e13c74698 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinuePluginToolWindowFactory.kt @@ -76,11 +76,11 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { init { System.setProperty("ide.browser.jcef.jsQueryPoolSize", JS_QUERY_POOL_SIZE) -// System.setProperty("ide.browser.jcef.osr.enabled", "true") + System.setProperty("ide.browser.jcef.osr.enabled", "false") } val webView: JBCefBrowser by lazy { - val browser = JBCefBrowser() + val browser = JBCefBrowser.createBuilder().setOffScreenRendering(false).build() browser.jbCefClient.setProperty( JBCefClient.Properties.JS_QUERY_POOL_SIZE, JS_QUERY_POOL_SIZE @@ -88,6 +88,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware { registerAppSchemeHandler() browser.loadURL("http://continue/index.html") +// browser.loadHTML("") // browser.loadURL("http://localhost:5173/index.html") Disposer.register(project, browser) From 17bd6d2771ebc1bda9ef463e29addc1b241c5090 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 20 Feb 2024 14:58:20 -0800 Subject: [PATCH 51/59] =?UTF-8?q?=F0=9F=90=9B=20fix=20errorPopup=20handlin?= =?UTF-8?q?g?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../continueintellijextension/continue/IdeProtocolClient.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 144027ed4..0c0f049d4 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -333,7 +333,9 @@ class IdeProtocolClient ( // Running commands not yet supported in JetBrains } "errorPopup" -> { - showMessage(data as String) + val data = data as Map + val message = data["message"] as String + showMessage(message) respond(null) } From bc40ef92f8ff78cb7419755abd887a6ad2d2a517 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 20 Feb 2024 15:11:14 -0800 Subject: [PATCH 52/59] =?UTF-8?q?=F0=9F=94=96=20update=20intellij=20versio?= =?UTF-8?q?n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extensions/intellij/gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 97afe4e9e..652a008c3 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -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.29 +pluginVersion = 0.0.31 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild = 223 From f4a749f35152f410cef3c1042074918370eb9e5d Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 20 Feb 2024 15:55:43 -0800 Subject: [PATCH 53/59] =?UTF-8?q?=F0=9F=90=9B=20set=20proper=20permissions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extensions/intellij/gradle.properties | 2 +- .../continue/CoreMessenger.kt | 29 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 652a008c3..9b55bff67 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -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.31 +pluginVersion = 0.0.32 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild = 223 diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index 8e3524c34..413713b72 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -6,6 +6,9 @@ import java.io.OutputStreamWriter import java.io.* import com.google.gson.Gson +import java.nio.file.Files +import java.nio.file.Paths +import java.nio.file.attribute.PosixFilePermission class CoreMessenger(continueCorePath: String, ideProtocolClient: IdeProtocolClient) { private val writer: OutputStreamWriter @@ -106,7 +109,33 @@ class CoreMessenger(continueCorePath: String, ideProtocolClient: IdeProtocolClie "getIdeInfo" ) + private fun setPermissions(destination: String) { + val osName = System.getProperty("os.name").toLowerCase() + if (osName.contains("mac") || osName.contains("darwin")) { + ProcessBuilder( + "xattr", + "-dr", + "com.apple.quarantine", + destination + ).start() + setFilePermissions(destination, "rwxr-xr-x") + } else if (osName.contains("nix") || osName.contains("nux") || osName.contains("mac")) { + setFilePermissions(destination, "rwxr-xr-x") + } + } + + private fun setFilePermissions(path: String, posixPermissions: String) { + val perms = HashSet() + if (posixPermissions.contains("r")) perms.add(PosixFilePermission.OWNER_READ) + if (posixPermissions.contains("w")) perms.add(PosixFilePermission.OWNER_WRITE) + if (posixPermissions.contains("x")) perms.add(PosixFilePermission.OWNER_EXECUTE) + Files.setPosixFilePermissions(Paths.get(path), perms) + } + init { + // Set proper permissions + setPermissions(continueCorePath) + // Start the subprocess val processBuilder = ProcessBuilder(continueCorePath) process = processBuilder.start() From d0c55edbc5146749ce270b42ab7861b8e85218cd Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 21 Feb 2024 13:44:21 -0800 Subject: [PATCH 54/59] =?UTF-8?q?=F0=9F=92=84=20ask=20anything?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gui/src/components/mainInput/TipTapEditor.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 591b59a01..c869ff618 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -235,7 +235,7 @@ function TipTapEditor(props: TipTapEditorProps) { Placeholder.configure({ placeholder: () => historyLengthRef.current === 0 - ? "Ask a question, '/' for slash commands, '@' to add context" + ? "Ask anything, '/' for slash commands, '@' to add context" : "Ask a follow-up", }), Paragraph.extend({ From 10b987ec24160e97325484f28744ab65fc4781d4 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 21 Feb 2024 19:01:33 -0800 Subject: [PATCH 55/59] =?UTF-8?q?=F0=9F=91=B7=20download=20esbuild=20binar?= =?UTF-8?q?ies=20to=20out=20dir=20for=20pkg?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/build.js | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/pkg/build.js b/pkg/build.js index ab0db2c14..89d1352cd 100644 --- a/pkg/build.js +++ b/pkg/build.js @@ -34,8 +34,8 @@ const targetToLanceDb = { // Copy node_modules for pre-built binaries const DYNAMIC_IMPORTS = [ - // "esbuild", - // "@esbuild", + "esbuild", + "@esbuild", // // "@lancedb", // "posthog-node", // "@octokit", @@ -84,6 +84,29 @@ const targetToLanceDb = { } } + console.log("[info] Downloading prebuilt esbuild..."); + const esbuildDir = "out/node_modules/@esbuild"; + for (const target of targets) { + const targetDir = `${esbuildDir}/${target}`; + + console.log(`[info] Downloading ${target}...`); + fs.mkdirSync(`${targetDir}/bin`, { + recursive: true, + }); + execSync( + `curl -o ${esbuildDir}/esbuild.tgz https://registry.npmjs.org/@esbuild/${target}/-/${target}-0.19.11.tgz` + ); + execSync(`tar -xzvf ${esbuildDir}/esbuild.tgz -C ${esbuildDir}`); + await new Promise((resolve) => + ncp(`${esbuildDir}/package`, targetDir, resolve) + ); + fs.rmSync(`${esbuildDir}/esbuild.tgz`); + fs.rmSync(`${esbuildDir}/package`, { + force: true, + recursive: true, + }); + } + console.log("[info] Building with esbuild..."); // Bundles the extension into one file await esbuild.build({ From c9c1a20f5188b7fd816f3d52b2ea83330f030983 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 21 Feb 2024 23:21:48 -0800 Subject: [PATCH 56/59] =?UTF-8?q?=F0=9F=91=B7=20package=20esbuild=20binary?= =?UTF-8?q?=20along=20with=20pkg?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/config/load.ts | 73 ++++++++++++++++++++++++++++--------- core/util/paths.ts | 8 +--- extensions/vscode/yarn.lock | 5 --- pkg/build.js | 61 ++++++++++++++----------------- pkg/src/index.ts | 1 + 5 files changed, 87 insertions(+), 61 deletions(-) diff --git a/core/config/load.ts b/core/config/load.ts index d230916bb..fcd3545bc 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -1,4 +1,5 @@ import * as fs from "fs"; +import path from "path"; import { BaseCompletionOptions, Config, @@ -16,7 +17,6 @@ import { SlashCommand, SlashCommandDescription, } from ".."; - import { slashCommandFromDescription, slashFromCustomCommand, @@ -36,6 +36,7 @@ import { getConfigTsPath, migrate, } from "../util/paths"; +const { execSync } = require("child_process"); function loadSerializedConfig( workspaceConfigs: ContinueRcJson[], @@ -323,24 +324,62 @@ function finalToBrowserConfig( }; } -async function buildConfigTs(browser: boolean) { +function getTarget() { + const os = + { + aix: "linux", + darwin: "darwin", + freebsd: "linux", + linux: "linux", + openbsd: "linux", + sunos: "linux", + win32: "win32", + }[process.platform as string] ?? "linux"; + const arch = { + arm: "arm64", + arm64: "arm64", + ia32: "x64", + loong64: "arm64", + mips: "arm64", + mipsel: "arm64", + ppc: "x64", + ppc64: "x64", + riscv64: "arm64", + s390: "x64", + s390x: "x64", + x64: "x64", + }[process.arch]; + + return `${os}-${arch}`; +} + +async function buildConfigTs() { if (!fs.existsSync(getConfigTsPath())) { return undefined; } try { - // Dynamic import esbuild so potentially disastrous errors can be caught - const esbuild = require("esbuild"); + if (process.env.IS_BINARY === "true") { + execSync( + path.dirname(process.execPath) + + `/esbuild${ + getTarget().startsWith("win32") ? ".exe" : "" + } ${getConfigTsPath()} --bundle --outfile=${getConfigJsPath()} --platform=node --format=cjs --sourcemap --external:fetch --external:fs --external:path --external:os --external:child_process` + ); + } else { + // Dynamic import esbuild so potentially disastrous errors can be caught + const esbuild = require("esbuild"); - await esbuild.build({ - entryPoints: [getConfigTsPath()], - bundle: true, - platform: browser ? "browser" : "node", - format: browser ? "esm" : "cjs", - outfile: getConfigJsPath(!browser), - external: ["fetch", "fs", "path", "os", "child_process"], - sourcemap: true, - }); + await esbuild.build({ + entryPoints: [getConfigTsPath()], + bundle: true, + platform: "node", + format: "cjs", + outfile: getConfigJsPath(), + external: ["fetch", "fs", "path", "os", "child_process"], + sourcemap: true, + }); + } } catch (e) { console.log( "Build error. Please check your ~/.continue/config.ts file: " + e @@ -348,10 +387,10 @@ async function buildConfigTs(browser: boolean) { return undefined; } - if (!fs.existsSync(getConfigJsPath(!browser))) { + if (!fs.existsSync(getConfigJsPath())) { return undefined; } - return fs.readFileSync(getConfigJsPath(!browser), "utf8"); + return fs.readFileSync(getConfigJsPath(), "utf8"); } async function loadFullConfigNode( @@ -362,11 +401,11 @@ async function loadFullConfigNode( let serialized = loadSerializedConfig(workspaceConfigs, ideType); let intermediate = serializedToIntermediateConfig(serialized); - const configJsContents = await buildConfigTs(false); + const configJsContents = await buildConfigTs(); if (configJsContents) { try { // Try config.ts first - const configJsPath = getConfigJsPath(true); + const configJsPath = getConfigJsPath(); const module = await require(configJsPath); delete require.cache[require.resolve(configJsPath)]; if (!module.modifyConfig) { diff --git a/core/util/paths.ts b/core/util/paths.ts index ccdc84c50..29343363e 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -90,13 +90,9 @@ export function getConfigTsPath(): string { return p; } -export function getConfigJsPath(node: boolean): string { +export function getConfigJsPath(): string { // Do not create automatically - return path.join( - getContinueGlobalPath(), - "out", - `config${node ? ".node" : ""}.js` - ); + return path.join(getContinueGlobalPath(), "out", "config.js"); } export function getTsConfigPath(): string { diff --git a/extensions/vscode/yarn.lock b/extensions/vscode/yarn.lock index be8c6d1c0..9c2abe910 100644 --- a/extensions/vscode/yarn.lock +++ b/extensions/vscode/yarn.lock @@ -696,11 +696,6 @@ resolved "https://registry.npmjs.org/@jsdevtools/ono/-/ono-7.1.3.tgz" integrity sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg== -"@lancedb/vectordb-darwin-arm64@*": - version "0.4.10" - resolved "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.10.tgz" - integrity sha512-y/uHOGb0g15pvqv5tdTyZ6oN+0QVpBmZDzKFWW6pPbuSZjB2uPqcs+ti0RB+AUdmS21kavVQqaNsw/HLKEGrHA== - "@lancedb/vectordb-darwin-arm64@0.4.8": version "0.4.8" resolved "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.8.tgz" diff --git a/pkg/build.js b/pkg/build.js index 89d1352cd..623df780d 100644 --- a/pkg/build.js +++ b/pkg/build.js @@ -34,8 +34,8 @@ const targetToLanceDb = { // Copy node_modules for pre-built binaries const DYNAMIC_IMPORTS = [ - "esbuild", - "@esbuild", + // "esbuild", + // "@esbuild", // // "@lancedb", // "posthog-node", // "@octokit", @@ -84,36 +84,13 @@ const targetToLanceDb = { } } - console.log("[info] Downloading prebuilt esbuild..."); - const esbuildDir = "out/node_modules/@esbuild"; - for (const target of targets) { - const targetDir = `${esbuildDir}/${target}`; - - console.log(`[info] Downloading ${target}...`); - fs.mkdirSync(`${targetDir}/bin`, { - recursive: true, - }); - execSync( - `curl -o ${esbuildDir}/esbuild.tgz https://registry.npmjs.org/@esbuild/${target}/-/${target}-0.19.11.tgz` - ); - execSync(`tar -xzvf ${esbuildDir}/esbuild.tgz -C ${esbuildDir}`); - await new Promise((resolve) => - ncp(`${esbuildDir}/package`, targetDir, resolve) - ); - fs.rmSync(`${esbuildDir}/esbuild.tgz`); - fs.rmSync(`${esbuildDir}/package`, { - force: true, - recursive: true, - }); - } - console.log("[info] Building with esbuild..."); // Bundles the extension into one file await esbuild.build({ entryPoints: ["src/index.ts"], bundle: true, outfile: esbuildOutputFile, - external: DYNAMIC_IMPORTS, + external: ["esbuild", ...DYNAMIC_IMPORTS], format: "cjs", platform: "node", sourcemap: true, @@ -134,26 +111,44 @@ const targetToLanceDb = { console.log("[info] Building binaries with pkg..."); for (const target of targets) { + const targetDir = `bin/${target}`; console.log(`[info] Building ${target}...`); execSync( - `npx pkg --no-bytecode --public-packages "*" --public pkgJson/${target} --out-path bin/${target}` + `npx pkg --no-bytecode --public-packages "*" --public pkgJson/${target} --out-path ${targetDir}` ); // Download and unzip prebuilt sqlite3 binary for the target const downloadUrl = `https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-${ target === "win32-arm64" ? "win32-ia32" : target }.tar.gz`; - execSync(`curl -L -o bin/${target}/build.tar.gz ${downloadUrl}`); - execSync(`cd bin/${target} && tar -xvzf build.tar.gz`); + execSync(`curl -L -o ${targetDir}/build.tar.gz ${downloadUrl}`); + execSync(`cd ${targetDir} && tar -xvzf build.tar.gz`); fs.copyFileSync( - `bin/${target}/build/Release/node_sqlite3.node`, - `bin/${target}/node_sqlite3.node` + `${targetDir}/build/Release/node_sqlite3.node`, + `${targetDir}/node_sqlite3.node` ); - fs.unlinkSync(`bin/${target}/build.tar.gz`); - fs.rmSync(`bin/${target}/build`, { + fs.unlinkSync(`${targetDir}/build.tar.gz`); + fs.rmSync(`${targetDir}/build`, { recursive: true, force: true, }); + + // Download and unzip prebuilt esbuild binary for the target + console.log(`[info] Downloading esbuild for ${target}...`); + execSync( + `curl -o ${targetDir}/esbuild.tgz https://registry.npmjs.org/@esbuild/${target}/-/${target}-0.19.11.tgz` + ); + execSync(`tar -xzvf ${targetDir}/esbuild.tgz -C ${targetDir}`); + if (target.startsWith("win32")) { + fs.cpSync(`${targetDir}/package/esbuild.exe`, `${targetDir}/esbuild.exe`); + } else { + fs.cpSync(`${targetDir}/package/bin/esbuild`, `${targetDir}/esbuild`); + } + fs.rmSync(`${targetDir}/esbuild.tgz`); + fs.rmSync(`${targetDir}/package`, { + force: true, + recursive: true, + }); } // execSync( // `npx pkg out/index.js --target node18-darwin-arm64 --no-bytecode --public-packages "*" --public -o bin/pkg` diff --git a/pkg/src/index.ts b/pkg/src/index.ts index 1c7134639..4f6c8448e 100644 --- a/pkg/src/index.ts +++ b/pkg/src/index.ts @@ -1,3 +1,4 @@ +process.env.IS_BINARY = "true"; import { Command } from "commander"; import { getCoreLogsPath } from "core/util/paths"; import fs from "fs"; From 9585ea9ec16a6c0773355a14028bf8a9766af988 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 21 Feb 2024 23:29:25 -0800 Subject: [PATCH 57/59] =?UTF-8?q?=F0=9F=93=9D=20improve=20keyboard=20short?= =?UTF-8?q?cut=20descriptions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extensions/vscode/yarn.lock | 5 +++++ gui/src/components/dialogs/KeyboardShortcuts.tsx | 8 ++++---- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/extensions/vscode/yarn.lock b/extensions/vscode/yarn.lock index 9c2abe910..be8c6d1c0 100644 --- a/extensions/vscode/yarn.lock +++ b/extensions/vscode/yarn.lock @@ -696,6 +696,11 @@ resolved "https://registry.npmjs.org/@jsdevtools/ono/-/ono-7.1.3.tgz" integrity sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg== +"@lancedb/vectordb-darwin-arm64@*": + version "0.4.10" + resolved "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.10.tgz" + integrity sha512-y/uHOGb0g15pvqv5tdTyZ6oN+0QVpBmZDzKFWW6pPbuSZjB2uPqcs+ti0RB+AUdmS21kavVQqaNsw/HLKEGrHA== + "@lancedb/vectordb-darwin-arm64@0.4.8": version "0.4.8" resolved "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.8.tgz" diff --git a/gui/src/components/dialogs/KeyboardShortcuts.tsx b/gui/src/components/dialogs/KeyboardShortcuts.tsx index 271f7078a..aad58e4c4 100644 --- a/gui/src/components/dialogs/KeyboardShortcuts.tsx +++ b/gui/src/components/dialogs/KeyboardShortcuts.tsx @@ -57,7 +57,7 @@ const vscodeShortcuts: KeyboardShortcutProps[] = [ { mac: "⌘ M", windows: "⌃ M", - description: "Ask about Highlighted Code", + description: "Select Code + New Session", }, { mac: "⌘ ⇧ L", @@ -67,7 +67,7 @@ const vscodeShortcuts: KeyboardShortcutProps[] = [ { mac: "⌘ ⇧ M", windows: "⌃ ⇧ M", - description: "Ask Follow-Up about Highlighted Code", + description: "Select Code", }, { mac: "⌘ ⇧ ⏎", @@ -110,12 +110,12 @@ const jetbrainsShortcuts: KeyboardShortcutProps[] = [ { mac: "⌘ J", windows: "⌃ J", - description: "Ask about Highlighted Code", + description: "Select Code + New Session", }, { mac: "⌘ ⇧ J", windows: "⌃ ⇧ J", - description: "Ask Follow-Up about Highlighted Code", + description: "Select Code", }, { mac: "⌘ ⇧ ⏎", From e195ad713b87503ee2db704acb4de34b212051e0 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 21 Feb 2024 23:41:53 -0800 Subject: [PATCH 58/59] =?UTF-8?q?=F0=9F=90=9B=20escape=20space=20in=20path?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/config/load.ts | 10 +++++++++- extensions/intellij/gradle.properties | 2 +- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/core/config/load.ts b/core/config/load.ts index fcd3545bc..d475707c0 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -353,6 +353,10 @@ function getTarget() { return `${os}-${arch}`; } +function escapeSpacesInPath(p: string): string { + return p.replace(/ /g, "\\ "); +} + async function buildConfigTs() { if (!fs.existsSync(getConfigTsPath())) { return undefined; @@ -364,7 +368,11 @@ async function buildConfigTs() { path.dirname(process.execPath) + `/esbuild${ getTarget().startsWith("win32") ? ".exe" : "" - } ${getConfigTsPath()} --bundle --outfile=${getConfigJsPath()} --platform=node --format=cjs --sourcemap --external:fetch --external:fs --external:path --external:os --external:child_process` + } ${escapeSpacesInPath( + getConfigTsPath() + )} --bundle --outfile=${escapeSpacesInPath( + getConfigJsPath() + )} --platform=node --format=cjs --sourcemap --external:fetch --external:fs --external:path --external:os --external:child_process` ); } else { // Dynamic import esbuild so potentially disastrous errors can be caught diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 9b55bff67..bd4b41270 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -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.32 +pluginVersion = 0.0.33 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild = 223 From fde13803e9923c8527126f25390c72d770f4e3ee Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Thu, 22 Feb 2024 18:57:31 -0800 Subject: [PATCH 59/59] =?UTF-8?q?=F0=9F=90=9B=20escape=20spaces=20in=20esb?= =?UTF-8?q?uild=20binary=20path?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/config/load.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/config/load.ts b/core/config/load.ts index d475707c0..023b7d852 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -365,7 +365,7 @@ async function buildConfigTs() { try { if (process.env.IS_BINARY === "true") { execSync( - path.dirname(process.execPath) + + escapeSpacesInPath(path.dirname(process.execPath)) + `/esbuild${ getTarget().startsWith("win32") ? ".exe" : "" } ${escapeSpacesInPath(