forked from github/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopilotLocalProcessServer.swift
More file actions
422 lines (367 loc) · 15.3 KB
/
CopilotLocalProcessServer.swift
File metadata and controls
422 lines (367 loc) · 15.3 KB
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
import Combine
import Foundation
import JSONRPC
import LanguageClient
import LanguageServerProtocol
import Logger
import ProcessEnv
import Status
/// A clone of the `LocalProcessServer`.
/// We need it because the original one does not allow us to handle custom notifications.
class CopilotLocalProcessServer {
public var notificationPublisher: PassthroughSubject<AnyJSONRPCNotification, Never> = PassthroughSubject<AnyJSONRPCNotification, Never>()
public var serverRequestPublisher: PassthroughSubject<(AnyJSONRPCRequest, (AnyJSONRPCResponse) -> Void), Never> = PassthroughSubject<(AnyJSONRPCRequest, (AnyJSONRPCResponse) -> Void), Never>()
private let transport: StdioDataTransport
private let customTransport: CustomDataTransport
private let process: Process
private var wrappedServer: CustomJSONRPCLanguageServer?
private var cancellables = Set<AnyCancellable>()
var terminationHandler: (() -> Void)?
@MainActor var ongoingCompletionRequestIDs: [JSONId] = []
@MainActor var ongoingConversationRequestIDs = [String: JSONId]()
public convenience init(
path: String,
arguments: [String],
environment: [String: String]? = nil
) {
let params = Process.ExecutionParameters(
path: path,
arguments: arguments,
environment: environment
)
self.init(executionParameters: params)
}
init(executionParameters parameters: Process.ExecutionParameters) {
transport = StdioDataTransport()
let framing = SeperatedHTTPHeaderMessageFraming()
let messageTransport = MessageTransport(
dataTransport: transport,
messageProtocol: framing
)
customTransport = CustomDataTransport(nextTransport: messageTransport)
wrappedServer = CustomJSONRPCLanguageServer(dataTransport: customTransport)
process = Process()
// Because the implementation of LanguageClient is so closed,
// we need to get the request IDs from a custom transport before the data
// is written to the language server.
customTransport.onWriteRequest = { [weak self] request in
if request.method == "getCompletionsCycling" {
Task { @MainActor [weak self] in
self?.ongoingCompletionRequestIDs.append(request.id)
}
} else if request.method == "conversation/create" {
Task { @MainActor [weak self] in
if let paramsData = try? JSONEncoder().encode(request.params) {
do {
let params = try JSONDecoder().decode(ConversationCreateParams.self, from: paramsData)
self?.ongoingConversationRequestIDs[params.workDoneToken] = request.id
} catch {
// Handle decoding error
print("Error decoding ConversationCreateParams: \(error)")
Logger.gitHubCopilot.error("Error decoding ConversationCreateParams: \(error)")
}
}
}
} else if request.method == "conversation/turn" {
Task { @MainActor [weak self] in
if let paramsData = try? JSONEncoder().encode(request.params) {
do {
let params = try JSONDecoder().decode(TurnCreateParams.self, from: paramsData)
self?.ongoingConversationRequestIDs[params.workDoneToken] = request.id
} catch {
// Handle decoding error
print("Error decoding TurnCreateParams: \(error)")
Logger.gitHubCopilot.error("Error decoding TurnCreateParams: \(error)")
}
}
}
}
}
wrappedServer?.notificationPublisher.sink(receiveValue: { [weak self] notification in
self?.notificationPublisher.send(notification)
}).store(in: &cancellables)
wrappedServer?.serverRequestPublisher.sink(receiveValue: { [weak self] (request, callback) in
self?.serverRequestPublisher.send((request, callback))
}).store(in: &cancellables)
process.standardInput = transport.stdinPipe
process.standardOutput = transport.stdoutPipe
process.standardError = transport.stderrPipe
process.parameters = parameters
process.terminationHandler = { [unowned self] task in
self.processTerminated(task)
}
process.launch()
}
deinit {
process.terminationHandler = nil
process.terminate()
transport.close()
}
private func processTerminated(_: Process) {
transport.close()
// releasing the server here will short-circuit any pending requests,
// which might otherwise take a while to time out, if ever.
wrappedServer = nil
terminationHandler?()
}
var logMessages: Bool {
get { return wrappedServer?.logMessages ?? false }
set { wrappedServer?.logMessages = newValue }
}
}
extension CopilotLocalProcessServer: LanguageServerProtocol.Server {
public var requestHandler: RequestHandler? {
get { return wrappedServer?.requestHandler }
set { wrappedServer?.requestHandler = newValue }
}
public var notificationHandler: NotificationHandler? {
get { wrappedServer?.notificationHandler }
set { wrappedServer?.notificationHandler = newValue }
}
public func sendNotification(
_ notif: ClientNotification,
completionHandler: @escaping (ServerError?) -> Void
) {
guard let server = wrappedServer, process.isRunning else {
completionHandler(.serverUnavailable)
return
}
server.sendNotification(notif, completionHandler: completionHandler)
}
/// send copilot specific notification
public func sendCopilotNotification(
_ notif: CopilotClientNotification,
completionHandler: @escaping (ServerError?) -> Void
) {
guard let server = wrappedServer, process.isRunning else {
completionHandler(.serverUnavailable)
return
}
server.sendCopilotNotification(notif, completionHandler: completionHandler)
}
/// Cancel ongoing completion requests.
public func cancelOngoingTasks() async {
let task = Task { @MainActor in
for id in ongoingCompletionRequestIDs {
await cancelTask(id)
}
self.ongoingCompletionRequestIDs = []
}
await task.value
}
public func cancelOngoingTask(_ workDoneToken: String) async {
let task = Task { @MainActor in
guard let id = ongoingConversationRequestIDs[workDoneToken] else { return }
await cancelTask(id)
}
await task.value
}
public func cancelTask(_ id: JSONId) async {
guard let server = wrappedServer, process.isRunning else {
return
}
switch id {
case let .numericId(id):
try? await server.sendNotification(.protocolCancelRequest(.init(id: id)))
case let .stringId(id):
try? await server.sendNotification(.protocolCancelRequest(.init(id: id)))
}
}
public func sendRequest<Response: Codable>(
_ request: ClientRequest,
completionHandler: @escaping (ServerResult<Response>) -> Void
) {
guard let server = wrappedServer, process.isRunning else {
completionHandler(.failure(.serverUnavailable))
return
}
server.sendRequest(request, completionHandler: completionHandler)
}
}
protocol CopilotNotificationJSONRPCLanguageServer {
func sendCopilotNotification(_ notif: CopilotClientNotification, completionHandler: @escaping (ServerError?) -> Void)
}
final class CustomJSONRPCLanguageServer: Server {
let internalServer: JSONRPCLanguageServer
typealias ProtocolResponse<T: Codable> = ProtocolTransport.ResponseResult<T>
private let protocolTransport: ProtocolTransport
public var requestHandler: RequestHandler?
public var notificationHandler: NotificationHandler?
public var notificationPublisher: PassthroughSubject<AnyJSONRPCNotification, Never> = PassthroughSubject<AnyJSONRPCNotification, Never>()
public var serverRequestPublisher: PassthroughSubject<(AnyJSONRPCRequest, (AnyJSONRPCResponse) -> Void), Never> = PassthroughSubject<(AnyJSONRPCRequest, (AnyJSONRPCResponse) -> Void), Never>()
private var outOfBandError: Error?
init(protocolTransport: ProtocolTransport) {
self.protocolTransport = protocolTransport
internalServer = JSONRPCLanguageServer(protocolTransport: protocolTransport)
let previouseRequestHandler = protocolTransport.requestHandler
let previouseNotificationHandler = protocolTransport.notificationHandler
protocolTransport
.requestHandler = { [weak self] in
guard let self else { return }
if !self.handleRequest($0, data: $1, callback: $2) {
previouseRequestHandler?($0, $1, $2)
}
}
protocolTransport
.notificationHandler = { [weak self] in
guard let self else { return }
if !self.handleNotification($0, data: $1, block: $2) {
previouseNotificationHandler?($0, $1, $2)
}
}
}
convenience init(dataTransport: DataTransport) {
self.init(protocolTransport: ProtocolTransport(dataTransport: dataTransport))
}
deinit {
protocolTransport.requestHandler = nil
protocolTransport.notificationHandler = nil
}
var logMessages: Bool {
get { return internalServer.logMessages }
set { internalServer.logMessages = newValue }
}
}
extension CustomJSONRPCLanguageServer {
private func handleNotification(
_ anyNotification: AnyJSONRPCNotification,
data: Data,
block: @escaping (Error?) -> Void
) -> Bool {
let methodName = anyNotification.method
let debugDescription = encodeJSONParams(params: anyNotification.params)
if let method = ServerNotification.Method(rawValue: methodName) {
switch method {
case .windowLogMessage:
Logger.gitHubCopilot.info("\(anyNotification.method): \(debugDescription)")
block(nil)
return true
case .protocolProgress:
notificationPublisher.send(anyNotification)
block(nil)
return true
default:
return false
}
} else {
switch methodName {
case "LogMessage":
Logger.gitHubCopilot.info("\(anyNotification.method): \(debugDescription)")
block(nil)
return true
case "didChangeStatus":
Logger.gitHubCopilot.info("\(anyNotification.method): \(debugDescription)")
if let payload = GitHubCopilotNotification.StatusNotification.decode(fromParams: anyNotification.params) {
Task {
await Status.shared
.updateCLSStatus(
payload.kind.clsStatus,
busy: payload.busy,
message: payload.message ?? ""
)
}
}
block(nil)
return true
case "featureFlagsNotification":
notificationPublisher.send(anyNotification)
block(nil)
return true
case "copilot/mcpTools":
notificationPublisher.send(anyNotification)
block(nil)
return true
case "conversation/preconditionsNotification", "statusNotification":
// Ignore
block(nil)
return true
default:
return false
}
}
}
public func sendNotification(
_ notif: ClientNotification,
completionHandler: @escaping (ServerError?) -> Void
) {
internalServer.sendNotification(notif, completionHandler: completionHandler)
}
}
extension CustomJSONRPCLanguageServer {
private func handleRequest(
_ request: AnyJSONRPCRequest,
data: Data,
callback: @escaping (AnyJSONRPCResponse) -> Void
) -> Bool {
let methodName = request.method
let debugDescription = encodeJSONParams(params: request.params)
serverRequestPublisher.send((request: request, callback: callback))
switch methodName {
case "conversation/invokeClientTool":
return true
case "conversation/invokeClientToolConfirmation":
return true
case "conversation/context":
return true
case "copilot/watchedFiles":
return true
case "window/showMessageRequest":
Logger.gitHubCopilot.info("\(methodName): \(debugDescription)")
return true
default:
return false // delegate the default handling to the server
}
}
}
func encodeJSONParams(params: JSONValue?) -> String {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
if let jsonData = try? encoder.encode(params),
let text = String(data: jsonData, encoding: .utf8)
{
return text
}
return "N/A"
}
extension CustomJSONRPCLanguageServer {
public func sendRequest<Response: Codable>(
_ request: ClientRequest,
completionHandler: @escaping (ServerResult<Response>) -> Void
) {
internalServer.sendRequest(request, completionHandler: completionHandler)
}
}
// MARK: - Copilot custom notification
public struct CopilotDidChangeWatchedFilesParams: Codable, Hashable {
/// The CLS need an additional paramter `workspaceUri` for "workspace/didChangeWatchedFiles" event
public var workspaceUri: String
public var changes: [FileEvent]
public init(workspaceUri: String, changes: [FileEvent]) {
self.workspaceUri = workspaceUri
self.changes = changes
}
}
public enum CopilotClientNotification {
public enum Method: String {
case workspaceDidChangeWatchedFiles = "workspace/didChangeWatchedFiles"
}
case copilotDidChangeWatchedFiles(CopilotDidChangeWatchedFilesParams)
public var method: Method {
switch self {
case .copilotDidChangeWatchedFiles:
return .workspaceDidChangeWatchedFiles
}
}
}
extension CustomJSONRPCLanguageServer: CopilotNotificationJSONRPCLanguageServer {
public func sendCopilotNotification(_ notif: CopilotClientNotification, completionHandler: @escaping (ServerError?) -> Void) {
let method = notif.method.rawValue
switch notif {
case .copilotDidChangeWatchedFiles(let params):
// the protocolTransport is not exposed by LSP Server, need to use it directly
protocolTransport.sendNotification(params, method: method) { error in
completionHandler(error.map({ .unableToSendNotification($0) }))
}
}
}
}