-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathGitHubCopilotService.swift
More file actions
1598 lines (1443 loc) · 63.7 KB
/
GitHubCopilotService.swift
File metadata and controls
1598 lines (1443 loc) · 63.7 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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import AppKit
import TelemetryServiceProvider
import Combine
import ConversationServiceProvider
import Foundation
import JSONRPC
import LanguageClient
import LanguageServerProtocol
import Logger
import Preferences
import Status
import SuggestionBasic
import SystemUtils
import Persist
public protocol GitHubCopilotAuthServiceType {
func checkStatus() async throws -> GitHubCopilotAccountStatus
func checkQuota() async throws -> GitHubCopilotQuotaInfo
func signInInitiate() async throws -> (status: SignInInitiateStatus, verificationUri: String?, userCode: String?, user: String?)
func signInConfirm(userCode: String) async throws
-> (username: String, status: GitHubCopilotAccountStatus)
func signOut() async throws -> GitHubCopilotAccountStatus
func version() async throws -> String
}
public protocol GitHubCopilotSuggestionServiceType {
func getCompletions(
fileURL: URL,
content: String,
originalContent: String,
cursorPosition: CursorPosition,
tabSize: Int,
indentSize: Int,
usesTabsForIndentation: Bool
) async throws -> [CodeSuggestion]
func getCopilotInlineEdit(
fileURL: URL,
content: String,
cursorPosition: CursorPosition
) async throws -> [CodeSuggestion]
func notifyShown(_ completion: CodeSuggestion) async
func notifyCopilotInlineEditShown(_ completion: CodeSuggestion) async
func notifyAccepted(_ completion: CodeSuggestion, acceptedLength: Int?) async
func notifyCopilotInlineEditAccepted(_ completion: CodeSuggestion) async
func notifyRejected(_ completions: [CodeSuggestion]) async
func notifyOpenTextDocument(fileURL: URL, content: String) async throws
func notifyChangeTextDocument(
fileURL: URL,
content: String,
version: Int,
contentChanges: [TextDocumentContentChangeEvent]?
) async throws
func notifyCloseTextDocument(fileURL: URL) async throws
func notifySaveTextDocument(fileURL: URL) async throws
func cancelRequest() async
func terminate() async
}
public protocol GitHubCopilotTelemetryServiceType {
func sendError(transaction: String?,
stacktrace: String?,
properties: [String: String]?,
platform: String?,
exceptionDetail: [ExceptionDetail]?) async throws
}
public protocol GitHubCopilotConversationServiceType {
func createConversation(_ message: MessageContent,
workDoneToken: String,
workspaceFolder: String,
workspaceFolders: [WorkspaceFolder]?,
activeDoc: Doc?,
skills: [String],
ignoredSkills: [String]?,
references: [ConversationAttachedReference],
model: String?,
modelProviderName: String?,
turns: [TurnSchema],
agentMode: Bool,
customChatModeId: String?,
userLanguage: String?) async throws -> ConversationCreateResponse
func createTurn(_ message: MessageContent,
workDoneToken: String,
conversationId: String,
turnId: String?,
activeDoc: Doc?,
ignoredSkills: [String]?,
references: [ConversationAttachedReference],
model: String?,
modelProviderName: String?,
workspaceFolder: String,
workspaceFolders: [WorkspaceFolder]?,
agentMode: Bool,
customChatModeId: String?) async throws -> ConversationCreateResponse
func deleteTurn(conversationId: String, turnId: String) async throws
func rateConversation(turnId: String, rating: ConversationRating) async throws
func copyCode(turnId: String, codeBlockIndex: Int, copyType: CopyKind, copiedCharacters: Int, totalCharacters: Int, copiedText: String) async throws
func cancelProgress(token: String) async
func templates(workspaceFolders: [WorkspaceFolder]?) async throws -> [ChatTemplate]
func modes(workspaceFolders: [WorkspaceFolder]?) async throws -> [ConversationMode]
func models() async throws -> [CopilotModel]
func registerTools(tools: [LanguageModelToolInformation]) async throws -> [LanguageModelTool]
func updateToolsStatus(params: UpdateToolsStatusParams) async throws -> [LanguageModelTool]
}
protocol GitHubCopilotLSP {
var eventSequence: ServerConnection.EventSequence { get }
func sendRequest<E: GitHubCopilotRequestType>(_ endpoint: E) async throws -> E.Response
func sendNotification(_ notif: ClientNotification) async throws
}
protocol GitHubCopilotLSPNotification {
func sendCopilotNotification(_ notif: CopilotClientNotification) async throws
}
public enum GitHubCopilotError: Error, LocalizedError {
case languageServerNotInstalled
case languageServerError(ServerError)
case failedToInstallStartScript
public var errorDescription: String? {
switch self {
case .languageServerNotInstalled:
return "Language server is not installed."
case .failedToInstallStartScript:
return "Failed to install start script."
case let .languageServerError(error):
switch error {
case let .handlerUnavailable(handler):
return "Language server error: Handler \(handler) unavailable"
case let .unhandledMethod(method):
return "Language server error: Unhandled method \(method)"
case let .notificationDispatchFailed(error):
return "Language server error: Notification dispatch failed: \(error)"
case let .requestDispatchFailed(error):
return "Language server error: Request dispatch failed: \(error)"
case let .clientDataUnavailable(error):
return "Language server error: Client data unavailable: \(error)"
case .serverUnavailable:
return "Language server error: Server unavailable, please make sure that:\n1. The path to node is correctly set.\n2. The node is not a shim executable.\n3. the node version is high enough."
case .missingExpectedParameter:
return "Language server error: Missing expected parameter"
case .missingExpectedResult:
return "Language server error: Missing expected result"
case let .unableToDecodeRequest(error):
return "Language server error: Unable to decode request: \(error)"
case let .unableToSendRequest(error):
return "Language server error: Unable to send request: \(error)"
case let .unableToSendNotification(error):
return "Language server error: Unable to send notification: \(error)"
case let .serverError(code: code, message: message, data: data):
return "Language server error: Server error: \(code) \(message) \(String(describing: data))"
case .invalidRequest:
return "Language server error: Invalid request"
case .timeout:
return "Language server error: Timeout, please try again later"
case .unknownError:
return "Language server error: An unknown error occurred: \(error)"
}
}
}
}
public extension Notification.Name {
static let gitHubCopilotShouldRefreshEditorInformation = Notification
.Name("com.github.CopilotForXcode.GitHubCopilotShouldRefreshEditorInformation")
static let githubCopilotAgentMaxToolCallingLoopDidChange = Notification
.Name("com.github.CopilotForXcode.GithubCopilotAgentMaxToolCallingLoopDidChange")
static let githubCopilotAgentAutoApprovalDidChange = Notification
.Name("com.github.CopilotForXcode.GithubCopilotAgentAutoApprovalDidChange")
static let githubCopilotAgentTrustToolAnnotationsDidChange = Notification
.Name("com.github.CopilotForXcode.GithubCopilotAgentTrustToolAnnotationsDidChange")
static let githubCopilotAgentAutoCompressDidChange = Notification
.Name("com.github.CopilotForXcode.GithubCopilotAgentAutoCompressDidChange")
}
public class GitHubCopilotBaseService {
let projectRootURL: URL
var server: GitHubCopilotLSP
var localProcessServer: CopilotLocalProcessServer?
let sessionId: String
init(designatedServer: GitHubCopilotLSP) {
projectRootURL = URL(fileURLWithPath: "/")
server = designatedServer
sessionId = UUID().uuidString
}
init(projectRootURL: URL, workspaceURL: URL = URL(fileURLWithPath: "/")) throws {
self.projectRootURL = projectRootURL
self.sessionId = UUID().uuidString
let (server, localServer) = try {
let urls = try GitHubCopilotBaseService.createFoldersIfNeeded()
var path = SystemUtils.shared.getXcodeBinaryPath()
var args = ["--stdio"]
let home = ProcessInfo.processInfo.homePath
var environment: [String: String] = ["HOME": home]
let envVarNamesToFetch = ["PATH", "NODE_EXTRA_CA_CERTS", "NODE_TLS_REJECT_UNAUTHORIZED"]
let terminalEnvVars = getTerminalEnvironmentVariables(envVarNamesToFetch)
for varName in envVarNamesToFetch {
if let value = terminalEnvVars[varName] ?? ProcessInfo.processInfo.environment[varName] {
environment[varName] = value
Logger.gitHubCopilot.info("Setting env \(varName): \(value)")
}
}
environment["PATH"] = SystemUtils.shared.appendCommonBinPaths(path: environment["PATH"] ?? "")
let versionNumber = JSONValue(
stringLiteral: SystemUtils.editorPluginVersion ?? ""
)
let xcodeVersion = JSONValue(
stringLiteral: SystemUtils.xcodeVersion ?? ""
)
let watchedFiles = JSONValue(
booleanLiteral: projectRootURL.path == "/" ? false : true
)
let enableSubagent = UserDefaults.shared.value(for: \.enableSubagent)
#if DEBUG
// Use local language server if set and available
if let languageServerPath = Bundle.main.infoDictionary?["LANGUAGE_SERVER_PATH"] as? String {
let jsPath = URL(fileURLWithPath: NSString(string: languageServerPath).expandingTildeInPath)
.appendingPathComponent("dist")
.appendingPathComponent("language-server.js")
let nodePath = Bundle.main.infoDictionary?["NODE_PATH"] as? String ?? "node"
if FileManager.default.fileExists(atPath: jsPath.path) {
path = "/usr/bin/env"
if projectRootURL.path == "/" {
args = [nodePath, jsPath.path, "--stdio"]
} else {
args = [nodePath, "--inspect", jsPath.path, "--stdio"]
}
Logger.debug.info("Using local language server \(path) \(args)")
}
}
// Add debug-specific environment variables
environment["GH_COPILOT_DEBUG_UI_PORT"] = "8180"
environment["GH_COPILOT_VERBOSE"] = "true"
#else
// Add release-specific environment variables
if UserDefaults.shared.value(for: \.verboseLoggingEnabled) {
environment["GH_COPILOT_VERBOSE"] = "true"
}
#endif
let executionParams = Process.ExecutionParameters(
path: path,
arguments: args,
environment: environment,
currentDirectoryURL: urls.supportURL
)
Logger.gitHubCopilot.info("Starting language server in \(urls.supportURL), \(environment)")
Logger.gitHubCopilot.info("Running on Xcode \(xcodeVersion), extension version \(versionNumber)")
let localServer = CopilotLocalProcessServer(executionParameters: executionParams)
let initializeParamsProvider = { @Sendable () -> InitializeParams in
let capabilities = ClientCapabilities(
workspace: .init(
applyEdit: false,
workspaceEdit: nil,
didChangeConfiguration: nil,
didChangeWatchedFiles: nil,
symbol: nil,
executeCommand: nil,
/// enable for "watchedFiles capability", set others to default value
workspaceFolders: true,
configuration: nil,
semanticTokens: nil
),
textDocument: nil,
window: nil,
general: nil,
experimental: nil
)
let authAppId = Bundle.main.infoDictionary?["GITHUB_APP_ID"] as? String
return InitializeParams(
processId: Int(ProcessInfo.processInfo.processIdentifier),
locale: nil,
rootPath: projectRootURL.path,
rootUri: projectRootURL.path,
initializationOptions: [
"editorInfo": [
"name": "Xcode",
"version": xcodeVersion,
],
"editorPluginInfo": [
"name": "copilot-xcode",
"version": versionNumber,
],
"copilotCapabilities": [
/// The editor has support for watching files over LSP
"watchedFiles": watchedFiles,
"didChangeFeatureFlags": true,
"stateDatabase": true,
"subAgent": JSONValue(booleanLiteral: enableSubagent),
"mcpAllowlist": true,
],
"githubAppId": authAppId.map(JSONValue.string) ?? .null,
],
capabilities: capabilities,
trace: .off,
workspaceFolders: [WorkspaceFolder(
uri: projectRootURL.absoluteString,
name: projectRootURL.lastPathComponent
)]
)
}
let server = SafeInitializingServer(InitializingServer(server: localServer, initializeParamsProvider: initializeParamsProvider))
return (server, localServer)
}()
self.server = server
localProcessServer = localServer
}
public static func createFoldersIfNeeded() throws -> (
applicationSupportURL: URL,
gitHubCopilotURL: URL,
executableURL: URL,
supportURL: URL
) {
guard let supportURL = FileManager.default.urls(
for: .applicationSupportDirectory,
in: .userDomainMask
).first?.appendingPathComponent(
Bundle.main
.object(forInfoDictionaryKey: "APPLICATION_SUPPORT_FOLDER") as? String
?? "com.github.CopilotForXcode"
) else {
throw CancellationError()
}
if !FileManager.default.fileExists(atPath: supportURL.path) {
try? FileManager.default
.createDirectory(at: supportURL, withIntermediateDirectories: false)
}
let gitHubCopilotFolderURL = supportURL.appendingPathComponent("GitHub Copilot")
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)
}
public func getSessionId() -> String {
return sessionId
}
}
func getTerminalEnvironmentVariables(_ variableNames: [String]) -> [String: String] {
var results = [String: String]()
guard !variableNames.isEmpty else { return results }
let userShell: String? = {
if let shell = ProcessInfo.processInfo.environment["SHELL"] {
return shell
}
// Check for zsh executable
if FileManager.default.fileExists(atPath: "/bin/zsh") {
Logger.gitHubCopilot.info("SHELL not found, falling back to /bin/zsh")
return "/bin/zsh"
}
// Check for bash executable
if FileManager.default.fileExists(atPath: "/bin/bash") {
Logger.gitHubCopilot.info("SHELL not found, falling back to /bin/bash")
return "/bin/bash"
}
Logger.gitHubCopilot.info("Cannot determine user's shell, returning empty environment")
return nil // No shell found
}()
guard let shell = userShell else {
return results
}
if let env = SystemUtils.shared.getLoginShellEnvironment(shellPath: shell) {
variableNames.forEach { varName in
if let value = env[varName] {
results[varName] = value
}
}
}
return results
}
@globalActor public enum GitHubCopilotSuggestionActor {
public actor TheActor {}
public static let shared = TheActor()
}
actor ToolInitializationActor {
private var isInitialized = false
private var unrestoredTools: [ToolStatusUpdate] = []
func loadUnrestoredToolsIfNeeded() -> [ToolStatusUpdate] {
guard !isInitialized else { return unrestoredTools }
isInitialized = true
// Load tools only once
if let savedJSON = AppState.shared.get(key: "languageModelToolsStatus"),
let data = try? JSONEncoder().encode(savedJSON),
let savedTools = try? JSONDecoder().decode([ToolStatusUpdate].self, from: data) {
let currentlyAvailableTools = CopilotLanguageModelToolManager.getAvailableLanguageModelTools() ?? []
let availableToolNames = Set(currentlyAvailableTools.map { $0.name })
unrestoredTools = savedTools.filter {
availableToolNames.contains($0.name) && $0.status == .disabled
}
}
return unrestoredTools
}
}
public final class GitHubCopilotService:
GitHubCopilotBaseService,
GitHubCopilotSuggestionServiceType,
GitHubCopilotConversationServiceType,
GitHubCopilotAuthServiceType,
GitHubCopilotTelemetryServiceType
{
private var ongoingTasks = Set<Task<[CodeSuggestion], Error>>()
private var serverNotificationHandler: ServerNotificationHandler = ServerNotificationHandlerImpl.shared
private var serverRequestHandler: ServerRequestHandler = ServerRequestHandlerImpl.shared
private var cancellables = Set<AnyCancellable>()
private var statusWatcher: CopilotAuthStatusWatcher?
private static var services: [GitHubCopilotService] = [] // cache all alive copilot service instances
private var mcpRuntimeLogFileName: String = ""
private static let toolInitializationActor = ToolInitializationActor()
private var lastSentConfiguration: JSONValue?
private var mcpToolsContinuation: AsyncStream<AnyJSONRPCNotification>.Continuation?
override init(designatedServer: any GitHubCopilotLSP) {
super.init(designatedServer: designatedServer)
}
override public init(projectRootURL: URL = URL(fileURLWithPath: "/"), workspaceURL: URL = URL(fileURLWithPath: "/")) throws {
do {
try super.init(projectRootURL: projectRootURL, workspaceURL: workspaceURL)
self.handleSendWorkspaceDidChangeNotifications()
let (stream, continuation) = AsyncStream.makeStream(of: AnyJSONRPCNotification.self)
self.mcpToolsContinuation = continuation
Task { [weak self] in
for await notification in stream {
await self?.handleMCPToolsNotification(notification)
}
}
localProcessServer?.notificationPublisher.sink(receiveValue: { [weak self] notification in
if notification.method == "copilot/mcpTools" && projectRootURL.path != "/" {
self?.mcpToolsContinuation?.yield(notification)
}
if notification.method == "copilot/mcpRuntimeLogs" && projectRootURL.path != "/" {
DispatchQueue.main.async { [weak self] in
guard let self else { return }
Task { @MainActor in
await self.handleMCPRuntimeLogsNotification(notification)
}
}
}
self?.serverNotificationHandler.handleNotification(notification)
}).store(in: &cancellables)
Task {
for await event in server.eventSequence {
switch event {
case let .request(id, request):
self.serverRequestHandler.handleRequest(
id: id,
request,
workspaceURL: workspaceURL,
service: self
)
default:
break
}
}
}
updateStatusInBackground()
GitHubCopilotService.services.append(self)
Task {
let tools = await registerClientTools(server: self)
CopilotLanguageModelToolManager.updateToolsStatus(tools)
await restoreRegisteredToolsStatus()
}
} catch {
Logger.gitHubCopilot.error(error)
throw error
}
}
deinit {
GitHubCopilotService.services.removeAll { $0 === self }
}
@GitHubCopilotSuggestionActor
public func getCompletions(
fileURL: URL,
content: String,
originalContent: String,
cursorPosition: SuggestionBasic.CursorPosition,
tabSize: Int,
indentSize: Int,
usesTabsForIndentation: Bool
) async throws -> [CodeSuggestion] {
ongoingTasks.forEach { $0.cancel() }
ongoingTasks.removeAll()
await localProcessServer?.cancelOngoingTasks()
func sendRequest(maxTry: Int = 5) async throws -> [CodeSuggestion] {
do {
let completions = try await self
.sendRequest(GitHubCopilotRequest.InlineCompletion(doc: .init(
textDocument: .init(uri: fileURL.absoluteString, version: 0),
position: cursorPosition,
formattingOptions: .init(
tabSize: tabSize,
insertSpaces: !usesTabsForIndentation
),
context: .init(triggerKind: .invoked)
)))
.items
.compactMap { (item: _) -> CodeSuggestion? in
guard let range = item.range else { return nil }
let suggestion = CodeSuggestion(
id: item.command?.arguments?.first ?? UUID().uuidString,
text: item.insertText,
position: cursorPosition,
range: .init(start: range.start, end: range.end)
)
return suggestion
}
try Task.checkCancellation()
return completions
} catch let error as ServerError {
switch error {
case .serverError:
// sometimes the content inside language server is not new enough, which can
// lead to an version mismatch error. We can try a few times until the content
// is up to date.
if maxTry <= 0 {
Logger.gitHubCopilot.error(
"Max retry for getting suggestions reached: \(GitHubCopilotError.languageServerError(error).localizedDescription)"
)
break
}
Logger.gitHubCopilot.info(
"Try getting suggestions again: \(GitHubCopilotError.languageServerError(error).localizedDescription)"
)
try await Task.sleep(nanoseconds: 200_000_000)
return try await sendRequest(maxTry: maxTry - 1)
default:
break
}
throw GitHubCopilotError.languageServerError(error)
} catch {
throw error
}
}
let task = Task { @GitHubCopilotSuggestionActor in
do {
let maxTry: Int = 5
try Task.checkCancellation()
return try await sendRequest(maxTry: maxTry)
} catch {
throw error
}
}
ongoingTasks.insert(task)
return try await task.value
}
// MARK: - NES
@GitHubCopilotSuggestionActor
public func getCopilotInlineEdit(
fileURL: URL,
content: String,
cursorPosition: CursorPosition
) async throws -> [CodeSuggestion] {
ongoingTasks.forEach { $0.cancel() }
ongoingTasks.removeAll()
await localProcessServer?.cancelOngoingTasks()
do {
let completions = try await sendRequest(
GitHubCopilotRequest.CopilotInlineEdit(
params: CopilotInlineEditsParams(
textDocument: .init(uri: fileURL.absoluteString, version: 0),
position: cursorPosition
)
))
.edits
.compactMap { edit in
CodeSuggestion.init(
id: edit.command?.arguments.first ?? UUID().uuidString,
text: edit.text,
position: cursorPosition,
range: edit.range
)
}
return completions
} catch {
Logger.gitHubCopilot.error("Failed to get copilot inline edit: \(error.localizedDescription)")
throw error
}
}
@GitHubCopilotSuggestionActor
public func createConversation(
_ message: MessageContent,
workDoneToken: String,
workspaceFolder: String,
workspaceFolders: [WorkspaceFolder]? = nil,
activeDoc: Doc?,
skills: [String],
ignoredSkills: [String]?,
references: [ConversationAttachedReference],
model: String?,
modelProviderName: String?,
turns: [TurnSchema],
agentMode: Bool,
customChatModeId: String?,
userLanguage: String?
) async throws -> ConversationCreateResponse {
var conversationCreateTurns: [TurnSchema] = []
// invoke conversation history
if turns.count > 0 {
conversationCreateTurns.append(
contentsOf: turns.map {
TurnSchema(
request: $0.request,
response: $0.response,
agentSlug: $0.agentSlug,
turnId: $0.turnId
)
}
)
}
conversationCreateTurns.append(TurnSchema(request: message))
let params = ConversationCreateParams(workDoneToken: workDoneToken,
turns: conversationCreateTurns,
capabilities: ConversationCreateParams.Capabilities(
skills: skills,
allSkills: false),
textDocument: activeDoc,
references: references.map { Reference.from($0) },
source: .panel,
workspaceFolder: workspaceFolder,
workspaceFolders: workspaceFolders,
ignoredSkills: ignoredSkills,
model: model,
modelProviderName: modelProviderName,
chatMode: agentMode ? "Agent" : nil,
customChatModeId: customChatModeId,
needToolCallConfirmation: true,
userLanguage: userLanguage)
do {
return try await sendRequest(
GitHubCopilotRequest.CreateConversation(params: params))
} catch {
print("Failed to create conversation. Error: \(error)")
throw error
}
}
@GitHubCopilotSuggestionActor
public func createTurn(
_ message: MessageContent,
workDoneToken: String,
conversationId: String,
turnId: String?,
activeDoc: Doc?,
ignoredSkills: [String]?,
references: [ConversationAttachedReference],
model: String?,
modelProviderName: String?,
workspaceFolder: String,
workspaceFolders: [WorkspaceFolder]? = nil,
agentMode: Bool,
customChatModeId: String?
) async throws -> ConversationCreateResponse {
do {
let params = TurnCreateParams(workDoneToken: workDoneToken,
conversationId: conversationId,
turnId: turnId,
message: message,
textDocument: activeDoc,
ignoredSkills: ignoredSkills,
references: references.map { Reference.from($0) },
model: model,
modelProviderName: modelProviderName,
workspaceFolder: workspaceFolder,
workspaceFolders: workspaceFolders,
chatMode: agentMode ? "Agent" : nil,
customChatModeId: customChatModeId,
needToolCallConfirmation: true)
return try await sendRequest(
GitHubCopilotRequest.CreateTurn(params: params))
} catch {
print("Failed to create turn. Error: \(error)")
throw error
}
}
@GitHubCopilotSuggestionActor
public func deleteTurn(conversationId: String, turnId: String) async throws {
do {
let params = TurnDeleteParams(conversationId: conversationId, turnId: turnId, source: .panel)
_ = try await sendRequest(GitHubCopilotRequest.DeleteTurn(params: params))
} catch {
throw error
}
}
@GitHubCopilotSuggestionActor
public func templates(workspaceFolders: [WorkspaceFolder]? = nil) async throws -> [ChatTemplate] {
do {
let params = ConversationTemplatesParams(workspaceFolders: workspaceFolders)
let response = try await sendRequest(
GitHubCopilotRequest.GetTemplates(params: params)
)
return response
} catch {
throw error
}
}
@GitHubCopilotSuggestionActor
public func modes(workspaceFolders: [WorkspaceFolder]? = nil) async throws -> [ConversationMode] {
do {
let params = ConversationModesParams(workspaceFolders: workspaceFolders)
let response = try await sendRequest(
GitHubCopilotRequest.GetModes(params: params)
)
return response
} catch {
throw error
}
}
@GitHubCopilotSuggestionActor
public func models() async throws -> [CopilotModel] {
do {
let response = try await sendRequest(
GitHubCopilotRequest.CopilotModels()
)
return response
} catch {
throw error
}
}
@GitHubCopilotSuggestionActor
public func agents() async throws -> [ChatAgent] {
do {
let response = try await sendRequest(
GitHubCopilotRequest.GetAgents()
)
return response
} catch {
throw error
}
}
@GitHubCopilotSuggestionActor
public func reviewChanges(params: ReviewChangesParams) async throws -> CodeReviewResult {
do {
let response = try await sendRequest(
GitHubCopilotRequest.ReviewChanges(params: params)
)
return response
} catch {
throw error
}
}
@GitHubCopilotSuggestionActor
public func registerTools(tools: [LanguageModelToolInformation]) async throws -> [LanguageModelTool] {
do {
let response = try await sendRequest(
GitHubCopilotRequest.RegisterTools(params: RegisterToolsParams(tools: tools))
)
return response
} catch {
throw error
}
}
@GitHubCopilotSuggestionActor
public func updateToolsStatus(params: UpdateToolsStatusParams) async throws -> [LanguageModelTool] {
do {
let response = try await sendRequest(
GitHubCopilotRequest.UpdateToolsStatus(params: params)
)
return response
} catch {
throw error
}
}
@GitHubCopilotSuggestionActor
public func updateMCPToolsStatus(params: UpdateMCPToolsStatusParams) async throws -> [MCPServerToolsCollection] {
do {
let response = try await sendRequest(
GitHubCopilotRequest.UpdatedMCPToolsStatus(params: params)
)
return response
} catch {
throw error
}
}
@GitHubCopilotSuggestionActor
public func listMCPRegistryServers(_ params: MCPRegistryListServersParams) async throws -> MCPRegistryServerList {
do {
let response = try await sendRequest(
GitHubCopilotRequest.MCPRegistryListServers(params: params)
)
return response
} catch {
throw error
}
}
@GitHubCopilotSuggestionActor
public func getMCPRegistryServer(_ params: MCPRegistryGetServerParams) async throws -> MCPRegistryServerDetail {
do {
let response = try await sendRequest(
GitHubCopilotRequest.MCPRegistryGetServer(params: params)
)
return response
} catch {
throw error
}
}
@GitHubCopilotSuggestionActor
public func getMCPRegistryAllowlist() async throws -> GetMCPRegistryAllowlistResult {
do {
let response = try await sendRequest(
GitHubCopilotRequest.MCPRegistryGetAllowlist()
)
return response
} catch {
throw error
}
}
@GitHubCopilotSuggestionActor
public func rateConversation(turnId: String, rating: ConversationRating) async throws {
do {
let params = ConversationRatingParams(turnId: turnId, rating: rating)
let _ = try await sendRequest(
GitHubCopilotRequest.ConversationRating(params: params)
)
} catch {
throw error
}
}
@GitHubCopilotSuggestionActor
public func copyCode(turnId: String, codeBlockIndex: Int, copyType: CopyKind, copiedCharacters: Int, totalCharacters: Int, copiedText: String) async throws {
let params = CopyCodeParams(turnId: turnId, codeBlockIndex: codeBlockIndex, copyType: copyType, copiedCharacters: copiedCharacters, totalCharacters: totalCharacters, copiedText: copiedText)
do {
let _ = try await sendRequest(
GitHubCopilotRequest.CopyCode(params: params)
)
} catch {
print("Failed to register copied code block. Error: \(error)")
throw error
}
}
@GitHubCopilotSuggestionActor
public func cancelRequest() async {
ongoingTasks.forEach { $0.cancel() }
ongoingTasks.removeAll()
await localProcessServer?.cancelOngoingTasks()
}
@GitHubCopilotSuggestionActor
public func cancelProgress(token: String) async {
await localProcessServer?.cancelOngoingTask(token)
}
@GitHubCopilotSuggestionActor
public func notifyShown(_ completion: CodeSuggestion) async {
_ = try? await sendRequest(
GitHubCopilotRequest.NotifyShown(completionUUID: completion.id)
)
}
@GitHubCopilotSuggestionActor
public func notifyCopilotInlineEditShown(_ completion: CodeSuggestion) async {
try? await sendCopilotNotification(.textDocumentDidShowInlineEdit(.from(id: completion.id)))
}
@GitHubCopilotSuggestionActor
public func notifyAccepted(_ completion: CodeSuggestion, acceptedLength: Int? = nil) async {
_ = try? await sendRequest(
GitHubCopilotRequest.NotifyAccepted(completionUUID: completion.id, acceptedLength: acceptedLength)
)
}
@GitHubCopilotSuggestionActor
public func notifyCopilotInlineEditAccepted(_ completion: CodeSuggestion) async {
_ = try? await sendRequest(
GitHubCopilotRequest.NotifyCopilotInlineEditAccepted(params: [completion.id])
)
}
@GitHubCopilotSuggestionActor
public func notifyRejected(_ completions: [CodeSuggestion]) async {
_ = try? await sendRequest(
GitHubCopilotRequest.NotifyRejected(completionUUIDs: completions.map(\.id))
)
}
@GitHubCopilotSuggestionActor
public func notifyOpenTextDocument(
fileURL: URL,
content: String
) async throws {
let languageId = languageIdentifierFromFileURL(fileURL)
let uri = "file://\(fileURL.path)"
// Logger.service.debug("Open \(uri), \(content.count)")
try await server.sendNotification(
.textDocumentDidOpen(
DidOpenTextDocumentParams(
textDocument: .init(
uri: uri,
languageId: languageId.rawValue,
version: 0,
text: content
)
)
)
)
}
@GitHubCopilotSuggestionActor
public func notifyChangeTextDocument(
fileURL: URL,
content: String,
version: Int,
contentChanges: [TextDocumentContentChangeEvent]? = nil
) async throws {
let uri = fileURL.absoluteString
let changes: [TextDocumentContentChangeEvent] = contentChanges ?? [.init(range: nil, rangeLength: nil, text: content)]
// Logger.service.debug("Change \(uri), \(content.count)")
try await server.sendNotification(
.textDocumentDidChange(
DidChangeTextDocumentParams(
uri: uri,
version: version,
contentChanges: changes
)
)
)
}
@GitHubCopilotSuggestionActor
public func notifySaveTextDocument(fileURL: URL) async throws {
let uri = "file://\(fileURL.path)"