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