forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeiumService.swift
More file actions
479 lines (432 loc) · 17.6 KB
/
CodeiumService.swift
File metadata and controls
479 lines (432 loc) · 17.6 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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
import AppKit
import Foundation
import LanguageClient
import LanguageServerProtocol
import Logger
import SuggestionBasic
import XcodeInspector
public protocol CodeiumSuggestionServiceType {
func getCompletions(
fileURL: URL,
content: String,
cursorPosition: CursorPosition,
tabSize: Int,
indentSize: Int,
usesTabsForIndentation: Bool
) async throws -> [CodeSuggestion]
func notifyAccepted(_ suggestion: CodeSuggestion) async
func getChatURL() async throws -> URL
func notifyOpenTextDocument(fileURL: URL, content: String) async throws
func notifyChangeTextDocument(fileURL: URL, content: String) async throws
func notifyCloseTextDocument(fileURL: URL) async throws
func cancelRequest() async
func terminate()
}
enum CodeiumError: Error, LocalizedError {
case languageServerNotInstalled
case languageServerOutdated
case languageServiceIsInstalling
case failedToConstructChatURL
var errorDescription: String? {
switch self {
case .languageServerNotInstalled:
return "Language server is not installed. Please install it in the host app."
case .languageServerOutdated:
return "Language server is outdated. Please update it in the host app or update the extension."
case .languageServiceIsInstalling:
return "Language service is installing, please try again later."
case .failedToConstructChatURL:
return "Failed to construct chat URL."
}
}
}
public class CodeiumService {
static let sessionId = UUID().uuidString
let projectRootURL: URL
var server: CodeiumLSP?
var heartbeatTask: Task<Void, Error>?
var workspaceTask: Task<Void, Error>?
var requestCounter: UInt64 = 0
var cancellationCounter: UInt64 = 0
let openedDocumentPool = OpenedDocumentPool()
let onServiceLaunched: () -> Void
let onServiceTerminated: () -> Void
let languageServerURL: URL
let supportURL: URL
let authService = CodeiumAuthService()
var fallbackXcodeVersion = "14.0.0"
var languageServerVersion = CodeiumInstallationManager.latestSupportedVersion
private var ongoingTasks = Set<Task<[CodeSuggestion], Error>>()
init(designatedServer: CodeiumLSP) {
projectRootURL = URL(fileURLWithPath: "/")
server = designatedServer
onServiceLaunched = {}
onServiceTerminated = {}
languageServerURL = URL(fileURLWithPath: "/")
supportURL = URL(fileURLWithPath: "/")
}
public init(
projectRootURL: URL,
onServiceLaunched: @escaping () -> Void,
onServiceTerminated: @escaping () -> Void
) throws {
self.projectRootURL = projectRootURL
self.onServiceLaunched = onServiceLaunched
self.onServiceTerminated = onServiceTerminated
let urls = try CodeiumService.createFoldersIfNeeded()
languageServerURL = urls.executableURL.appendingPathComponent("language_server")
supportURL = urls.supportURL
Task {
try await setupServerIfNeeded()
}
}
@discardableResult
func setupServerIfNeeded() async throws -> CodeiumLSP {
if let server { return server }
let binaryManager = CodeiumInstallationManager()
let installationStatus = await binaryManager.checkInstallation()
switch installationStatus {
case let .installed(version), let .unsupported(version, _):
languageServerVersion = version
case .notInstalled:
throw CodeiumError.languageServerNotInstalled
case let .outdated(version, _):
languageServerVersion = version
throw CodeiumError.languageServerOutdated
}
let metadata = try await getMetadata()
let tempFolderURL = FileManager.default.temporaryDirectory
let managerDirectoryURL = tempFolderURL
.appendingPathComponent("com.intii.CopilotForXcode")
.appendingPathComponent(UUID().uuidString)
if !FileManager.default.fileExists(atPath: managerDirectoryURL.path) {
try FileManager.default.createDirectory(
at: managerDirectoryURL,
withIntermediateDirectories: true
)
}
let server = CodeiumLanguageServer(
languageServerExecutableURL: languageServerURL,
managerDirectoryURL: managerDirectoryURL,
supportURL: supportURL
)
server.terminationHandler = { [weak self] in
self?.server = nil
self?.heartbeatTask?.cancel()
self?.workspaceTask?.cancel()
self?.requestCounter = 0
self?.cancellationCounter = 0
self?.onServiceTerminated()
Logger.codeium.info("Language server is terminated, will be restarted when needed.")
}
server.launchHandler = { [weak self] in
guard let self else { return }
self.onServiceLaunched()
self.heartbeatTask = Task { [weak self, metadata] in
while true {
try Task.checkCancellation()
_ = try? await self?.server?.sendRequest(
CodeiumRequest.Heartbeat(requestBody: .init(metadata: metadata))
)
try await Task.sleep(nanoseconds: 5_000_000_000)
}
}
self.workspaceTask = Task { [weak self] in
while true {
try Task.checkCancellation()
_ = await self?.server?.updateIndexing()
try await Task.sleep(nanoseconds: 5_000_000_000)
}
}
}
self.server = server
server.start()
return server
}
public static func createFoldersIfNeeded() throws -> (
applicationSupportURL: URL,
gitHubCopilotURL: URL,
executableURL: URL,
supportURL: URL
) {
let supportURL = FileManager.default.urls(
for: .applicationSupportDirectory,
in: .userDomainMask
).first!.appendingPathComponent(
Bundle.main
.object(forInfoDictionaryKey: "APPLICATION_SUPPORT_FOLDER") as! String
)
if !FileManager.default.fileExists(atPath: supportURL.path) {
try? FileManager.default
.createDirectory(at: supportURL, withIntermediateDirectories: false)
}
let gitHubCopilotFolderURL = supportURL.appendingPathComponent("Codeium")
if !FileManager.default.fileExists(atPath: gitHubCopilotFolderURL.path) {
try? FileManager.default
.createDirectory(at: gitHubCopilotFolderURL, withIntermediateDirectories: false)
}
let supportFolderURL = gitHubCopilotFolderURL.appendingPathComponent("support")
if !FileManager.default.fileExists(atPath: supportFolderURL.path) {
try? FileManager.default
.createDirectory(at: supportFolderURL, withIntermediateDirectories: false)
}
let executableFolderURL = gitHubCopilotFolderURL.appendingPathComponent("executable")
if !FileManager.default.fileExists(atPath: executableFolderURL.path) {
try? FileManager.default
.createDirectory(at: executableFolderURL, withIntermediateDirectories: false)
}
return (supportURL, gitHubCopilotFolderURL, executableFolderURL, supportFolderURL)
}
}
extension CodeiumService {
func getMetadata() async throws -> Metadata {
guard let key = authService.key else {
struct E: Error, LocalizedError {
var errorDescription: String? { "Codeium not signed in." }
}
throw E()
}
var ideVersion = await XcodeInspector.shared.safe.latestActiveXcode?.version
?? fallbackXcodeVersion
let versionNumberSegmentCount = ideVersion.split(separator: ".").count
if versionNumberSegmentCount == 2 {
ideVersion += ".0"
} else if versionNumberSegmentCount == 1 {
ideVersion += ".0.0"
}
return Metadata(
ide_name: "xcode",
ide_version: ideVersion,
extension_version: languageServerVersion,
api_key: key,
session_id: CodeiumService.sessionId,
request_id: requestCounter
)
}
func getRelativePath(of fileURL: URL) -> String {
let filePath = fileURL.path
let rootPath = projectRootURL.path
if let range = filePath.range(of: rootPath),
range.lowerBound == filePath.startIndex
{
let relativePath = filePath.replacingCharacters(
in: filePath.startIndex..<range.upperBound,
with: ""
)
return relativePath
}
return filePath
}
}
extension CodeiumService: CodeiumSuggestionServiceType {
public func getCompletions(
fileURL: URL,
content: String,
cursorPosition: CursorPosition,
tabSize: Int,
indentSize: Int,
usesTabsForIndentation: Bool
) async throws -> [CodeSuggestion] {
ongoingTasks.forEach { $0.cancel() }
ongoingTasks.removeAll()
await cancelRequest()
requestCounter += 1
let languageId = languageIdentifierFromFileURL(fileURL)
let relativePath = getRelativePath(of: fileURL)
let task = Task {
let request = try await CodeiumRequest.GetCompletion(requestBody: .init(
metadata: getMetadata(),
document: .init(
absolute_path: fileURL.path,
relative_path: relativePath,
text: content,
editor_language: languageId.rawValue,
language: .init(codeLanguage: languageId),
cursor_position: .init(
row: cursorPosition.line,
col: cursorPosition.character
)
),
editor_options: .init(tab_size: indentSize, insert_spaces: !usesTabsForIndentation),
other_documents: openedDocumentPool.getOtherDocuments(exceptURL: fileURL)
.map { openedDocument in
let languageId = languageIdentifierFromFileURL(openedDocument.url)
return .init(
absolute_path: openedDocument.url.path,
relative_path: openedDocument.relativePath,
text: openedDocument.content,
editor_language: languageId.rawValue,
language: .init(codeLanguage: languageId)
)
}
))
try Task.checkCancellation()
let result = try await (await setupServerIfNeeded()).sendRequest(request)
try Task.checkCancellation()
return result.completionItems?.map { item in
CodeSuggestion(
id: item.completion.completionId,
text: item.completion.text,
position: cursorPosition,
range: CursorRange(
start: .init(
line: item.range.startPosition?.row.flatMap(Int.init) ?? 0,
character: item.range.startPosition?.col.flatMap(Int.init) ?? 0
),
end: .init(
line: item.range.endPosition?.row.flatMap(Int.init) ?? 0,
character: item.range.endPosition?.col.flatMap(Int.init) ?? 0
)
)
)
} ?? []
}
ongoingTasks.insert(task)
return try await task.value
}
public func cancelRequest() async {
_ = try? await server?.sendRequest(
CodeiumRequest.CancelRequest(requestBody: .init(
request_id: requestCounter,
session_id: CodeiumService.sessionId
))
)
}
public func getChatURL() async throws -> URL {
let metadata = try await getMetadata()
let ports = try await server?.sendRequest(
CodeiumRequest.GetProcesses(requestBody: .init())
)
guard let chatClientPort = ports?.chatClientPort,
let chatWebServerPort = ports?.chatWebServerPort
else { throw CodeiumError.failedToConstructChatURL }
let webServerUrl = "ws://127.0.0.1:\(chatWebServerPort)"
var components = URLComponents()
components.scheme = "http"
components.host = "127.0.0.1"
components.port = Int(chatClientPort)
components.path = "/"
components.queryItems = [
URLQueryItem(name: "api_key", value: metadata.api_key),
URLQueryItem(name: "locale", value: "en"),
URLQueryItem(name: "extension_name", value: "Copilot for XCode"),
URLQueryItem(name: "extension_version", value: metadata.extension_version),
URLQueryItem(name: "ide_name", value: metadata.ide_name),
URLQueryItem(name: "ide_version", value: metadata.ide_version),
URLQueryItem(name: "web_server_url", value: webServerUrl),
URLQueryItem(name: "ide_telemetry_enabled", value: "true"),
URLQueryItem(name: "has_enterprise_extension", value: String(UserDefaults.shared.value(for: \.codeiumEnterpriseMode))),
URLQueryItem(name: "has_index_service", value: String(UserDefaults.shared.value(for: \.codeiumIndexEnabled)))
]
if let url = components.url {
print(url)
return url
} else {
throw CodeiumError.failedToConstructChatURL
}
}
public func notifyAccepted(_ suggestion: CodeSuggestion) async {
_ = try? await (try setupServerIfNeeded())
.sendRequest(CodeiumRequest.AcceptCompletion(requestBody: .init(
metadata: getMetadata(),
completion_id: suggestion.id
)))
}
public func notifyOpenTextDocument(fileURL: URL, content: String) async throws {
let relativePath = getRelativePath(of: fileURL)
await openedDocumentPool.openDocument(
url: fileURL,
relativePath: relativePath,
content: content
)
}
public func notifyChangeTextDocument(fileURL: URL, content: String) async throws {
let relativePath = getRelativePath(of: fileURL)
await openedDocumentPool.updateDocument(
url: fileURL,
relativePath: relativePath,
content: content
)
}
public func notifyCloseTextDocument(fileURL: URL) async throws {
await openedDocumentPool.closeDocument(url: fileURL)
}
public func notifyOpenWorkspace(workspaceURL: URL) async throws {
_ = try await (setupServerIfNeeded()).sendRequest(
CodeiumRequest
.AddTrackedWorkspace(requestBody: .init(workspace: workspaceURL.path))
)
}
public func notifyCloseWorkspace(workspaceURL: URL) async throws {
_ = try await (setupServerIfNeeded()).sendRequest(
CodeiumRequest
.RemoveTrackedWorkspace(requestBody: .init(workspace: workspaceURL.path))
)
}
public func refreshIDEContext(
fileURL: URL,
content: String,
cursorPosition: CursorPosition,
tabSize: Int,
indentSize: Int,
usesTabsForIndentation: Bool,
workspaceURL: URL
) async throws {
let languageId = languageIdentifierFromFileURL(fileURL)
let relativePath = getRelativePath(of: fileURL)
let request = await CodeiumRequest.RefreshContextForIdeAction(requestBody: .init(
active_document: .init(
absolute_path: fileURL.path,
relative_path: relativePath,
text: content,
editor_language: languageId.rawValue,
language: .init(codeLanguage: languageId),
cursor_position: .init(
row: cursorPosition.line,
col: cursorPosition.character
)
),
open_document_filepaths: openedDocumentPool.getOtherDocuments(exceptURL: fileURL)
.map(\.url.path),
workspace_paths: [workspaceURL.path]
))
_ = try await (setupServerIfNeeded()).sendRequest(request)
}
public func terminate() {
server?.terminate()
server = nil
}
}
func getXcodeVersion() async throws -> String {
let task = Process()
task.launchPath = "/usr/bin/xcodebuild"
task.arguments = ["-version"]
let outpipe = Pipe()
task.standardOutput = outpipe
task.standardError = Pipe()
return try await withUnsafeThrowingContinuation { continuation in
do {
task.terminationHandler = { _ in
do {
if let data = try outpipe.fileHandleForReading.readToEnd(),
let content = String(data: data, encoding: .utf8)
{
let firstLine = content.split(whereSeparator: \.isNewline).first ?? ""
var version = firstLine.replacingOccurrences(of: "Xcode ", with: "")
if version.isEmpty {
version = "14.0"
}
continuation.resume(returning: version)
return
}
continuation.resume(returning: "")
} catch {
continuation.resume(throwing: error)
}
}
try task.run()
} catch {
continuation.resume(throwing: error)
}
}
}