-
Notifications
You must be signed in to change notification settings - Fork 809
/
CoreMessenger.kt
270 lines (247 loc) · 9.66 KB
/
CoreMessenger.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
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.service
import com.intellij.openapi.project.Project
import java.net.Socket
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.PosixFilePermission
class CoreMessenger(private val project: Project, esbuildPath: String, continueCorePath: String, ideProtocolClient: IdeProtocolClient) {
private var writer: Writer? = null
private var reader: BufferedReader? = null
private var process: Process? = null
private val gson = Gson()
private val responseListeners = mutableMapOf<String, (String) -> Unit>()
private val ideProtocolClient = ideProtocolClient
private val useTcp: Boolean = false
private fun write(message: String) {
writer?.write(message + "\r\n")
writer?.flush()
}
private fun close() {
writer?.close()
reader?.close()
val exitCode = process?.waitFor()
println("Subprocess exited with code: $exitCode")
}
fun request(messageType: String, data: Any?, messageId: String?, onResponse: (String) -> Unit) {
val id = messageId ?: uuid()
val message = gson.toJson(mapOf(
"messageId" to id,
"messageType" to messageType,
"data" to data
))
responseListeners[id] = onResponse
write(message)
}
private fun handleMessage(json: String) {
val responseMap = gson.fromJson(json, Map::class.java)
val messageId = responseMap["messageId"].toString()
val messageType = responseMap["messageType"].toString()
val data = gson.toJson(responseMap["data"])
// IDE listeners
if (ideMessageTypes.contains(messageType)) {
ideProtocolClient.handleMessage(json) { data ->
val message = gson.toJson(mapOf(
"messageId" to messageId,
"messageType" to messageType,
"data" to data
))
write(message)
};
}
// Forward to webview
if (PASS_THROUGH_TO_WEBVIEW.contains(messageType)) {
// TODO: Currently we aren't set up to receive a response back from the webview
// Can circumvent for getDefaultsModelTitle here for now
if (messageType == "getDefaultModelTitle") {
val continueSettingsService = service<ContinueExtensionSettings>()
val defaultModelTitle = continueSettingsService.continueState.lastSelectedInlineEditModel;
val message = gson.toJson(mapOf(
"messageId" to messageId,
"messageType" to messageType,
"data" to defaultModelTitle
))
write(message)
}
val continuePluginService = project.service<ContinuePluginService>()
continuePluginService.sendToWebview(messageType, responseMap["data"], messageType)
}
// Responses for messageId
responseListeners[messageId]?.let { listener ->
listener(data)
if (generatorTypes.contains(messageType)) {
val parsedData = gson.fromJson(data, Map::class.java)
val done = parsedData["done"] as Boolean?
if (done == true) {
responseListeners.remove(messageId)
} else {}
} else {
responseListeners.remove(messageId)
}
}
}
private val generatorTypes = listOf(
"llm/streamComplete",
"llm/streamChat",
"command/run",
"streamDiffLines"
)
private val ideMessageTypes = listOf(
"readRangeInFile",
"isTelemetryEnabled",
"getUniqueId",
"getWorkspaceConfigs",
"getDiff",
"getTerminalContents",
"listWorkspaceContents",
"getWorkspaceDirs",
"showLines",
"listFolders",
"getContinueDir",
"writeFile",
"showVirtualFile",
"openFile",
"runCommand",
"saveFile",
"readFile",
"showDiff",
"getOpenFiles",
"getCurrentFile",
"getPinnedFiles",
"getSearchResults",
"getProblems",
"subprocess",
"getBranch",
"getIdeInfo",
"getIdeSettings",
"errorPopup",
"getRepoName",
"listDir",
"getGitRootPath",
"getLastModified",
"insertAtCursor",
"applyToFile",
"getGitHubAuthToken",
"setGitHubAuthToken",
)
private val PASS_THROUGH_TO_WEBVIEW = listOf<String>(
"configUpdate",
"getDefaultModelTitle",
"indexProgress",
"refreshSubmenuItems"
)
private fun setPermissions(destination: String) {
val osName = System.getProperty("os.name").toLowerCase()
if (osName.contains("mac") || osName.contains("darwin")) {
ProcessBuilder(
"xattr",
"-dr",
"com.apple.quarantine",
destination
).start()
setFilePermissions(destination, "rwxr-xr-x")
} else if (osName.contains("nix") || osName.contains("nux") || osName.contains("mac")) {
setFilePermissions(destination, "rwxr-xr-x")
}
}
private fun setFilePermissions(path: String, posixPermissions: String) {
val perms = HashSet<PosixFilePermission>()
if (posixPermissions.contains("r")) perms.add(PosixFilePermission.OWNER_READ)
if (posixPermissions.contains("w")) perms.add(PosixFilePermission.OWNER_WRITE)
if (posixPermissions.contains("x")) perms.add(PosixFilePermission.OWNER_EXECUTE)
Files.setPosixFilePermissions(Paths.get(path), perms)
}
init {
if (useTcp) {
try {
val socket = Socket("localhost", 3000)
val writer = PrintWriter(socket.getOutputStream(), true)
this.writer = writer
val reader = BufferedReader(InputStreamReader(socket.getInputStream()))
this.reader = reader
Thread {
try {
while (true) {
val line = reader.readLine()
if (line != null && line.isNotEmpty()) {
try {
handleMessage(line)
} catch (e: Exception) {
println("Error handling message: $line")
println(e)
}
} else {
Thread.sleep(100)
}
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
reader.close()
writer.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}.start()
} catch (e: Exception) {
println("An error occurred: ${e.message}")
}
} else {
// Set proper permissions
setPermissions(continueCorePath)
setPermissions(esbuildPath)
// Start the subprocess
val processBuilder = ProcessBuilder(continueCorePath)
.directory(File(continueCorePath).parentFile)
process = processBuilder.start()
val outputStream = process!!.outputStream
val inputStream = process!!.inputStream
writer = OutputStreamWriter(outputStream, StandardCharsets.UTF_8)
reader = BufferedReader(InputStreamReader(inputStream, StandardCharsets.UTF_8))
process!!.onExit().thenRun {
val err = process?.errorStream?.bufferedReader()?.readText()?.trim()
println("Core process exited with output: $err")
ideProtocolClient.showMessage("Core process exited with output: $err")
}
Thread {
try {
while (true) {
val line = reader?.readLine()
if (line != null && line.isNotEmpty()) {
try {
handleMessage(line)
} catch (e: Exception) {
println("Error handling message: $line")
println(e)
}
} else {
Thread.sleep(100)
}
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
reader?.close()
writer?.close()
outputStream.close()
inputStream.close()
process?.destroy()
} catch (e: IOException) {
e.printStackTrace()
}
}
}.start()
}
}
}