forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGitHubCopilotService.swift
More file actions
314 lines (285 loc) · 11.7 KB
/
GitHubCopilotService.swift
File metadata and controls
314 lines (285 loc) · 11.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
import SuggestionModel
import Foundation
import LanguageClient
import LanguageServerProtocol
import Logger
import Preferences
import XPCShared
public protocol GitHubCopilotAuthServiceType {
func checkStatus() async throws -> GitHubCopilotAccountStatus
func signInInitiate() async throws -> (verificationUri: String, userCode: 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,
cursorPosition: CursorPosition,
tabSize: Int,
indentSize: Int,
usesTabsForIndentation: Bool,
ignoreSpaceOnlySuggestions: Bool
) async throws -> [CodeSuggestion]
func notifyAccepted(_ completion: CodeSuggestion) async
func notifyRejected(_ completions: [CodeSuggestion]) async
func notifyOpenTextDocument(fileURL: URL, content: String) async throws
func notifyChangeTextDocument(fileURL: URL, content: String) async throws
func notifyCloseTextDocument(fileURL: URL) async throws
func notifySaveTextDocument(fileURL: URL) async throws
}
protocol GitHubCopilotLSP {
func sendRequest<E: GitHubCopilotRequestType>(_ endpoint: E) async throws -> E.Response
func sendNotification(_ notif: ClientNotification) async throws
}
public class GitHubCopilotBaseService {
let projectRootURL: URL
var server: GitHubCopilotLSP
init(designatedServer: GitHubCopilotLSP) {
projectRootURL = URL(fileURLWithPath: "/")
server = designatedServer
}
init(projectRootURL: URL) {
self.projectRootURL = projectRootURL
server = {
let supportURL = FileManager.default.urls(
for: .applicationSupportDirectory,
in: .userDomainMask
).first!.appendingPathComponent("com.intii.CopilotForXcode")
if !FileManager.default.fileExists(atPath: supportURL.path) {
try? FileManager.default
.createDirectory(at: supportURL, withIntermediateDirectories: false)
}
var userEnvPath = ProcessInfo.processInfo.userEnvironment["PATH"] ?? ""
if userEnvPath.isEmpty {
userEnvPath = "/usr/bin:/usr/local/bin" // fallback
}
let executionParams: Process.ExecutionParameters
let runner = UserDefaults.shared.value(for: \.runNodeWith)
switch runner {
case .bash:
let nodePath = UserDefaults.shared.value(for: \.nodePath)
let command = [
nodePath.isEmpty ? "node" : nodePath,
"\"\(Bundle.main.url(forResource: "agent", withExtension: "js", subdirectory: "copilot/dist")!.path)\"",
"--stdio",
].joined(separator: " ")
executionParams = {
Process.ExecutionParameters(
path: "/bin/bash",
arguments: ["-i", "-l", "-c", command],
environment: [:],
currentDirectoryURL: supportURL
)
}()
case .shell:
let shell = ProcessInfo.processInfo.userEnvironment["SHELL"] ?? "/bin/bash"
let nodePath = UserDefaults.shared.value(for: \.nodePath)
let command = [
nodePath.isEmpty ? "node" : nodePath,
"\"\(Bundle.main.url(forResource: "agent", withExtension: "js", subdirectory: "copilot/dist")!.path)\"",
"--stdio",
].joined(separator: " ")
executionParams = {
Process.ExecutionParameters(
path: shell,
arguments: ["-i", "-l", "-c", command],
environment: [:],
currentDirectoryURL: supportURL
)
}()
case .env:
executionParams = {
let nodePath = UserDefaults.shared.value(for: \.nodePath)
return Process.ExecutionParameters(
path: "/usr/bin/env",
arguments: [
nodePath.isEmpty ? "node" : nodePath,
Bundle.main.url(
forResource: "agent",
withExtension: "js",
subdirectory: "copilot/dist"
)!.path,
"--stdio",
],
environment: [
"PATH": userEnvPath,
],
currentDirectoryURL: supportURL
)
}()
}
let localServer = CopilotLocalProcessServer(executionParameters: executionParams)
localServer.logMessages = false
localServer.notificationHandler = { _, respond in
respond(.timeout)
}
let server = InitializingServer(server: localServer)
server.initializeParamsProvider = {
let capabilities = ClientCapabilities(
workspace: nil,
textDocument: nil,
window: nil,
general: nil,
experimental: nil
)
return InitializeParams(
processId: Int(ProcessInfo.processInfo.processIdentifier),
clientInfo: .init(name: "Copilot for Xcode"),
locale: nil,
rootPath: projectRootURL.path,
rootUri: projectRootURL.path,
initializationOptions: nil,
capabilities: capabilities,
trace: .off,
workspaceFolders: nil
)
}
return server
}()
}
}
public final class GitHubCopilotAuthService: GitHubCopilotBaseService, GitHubCopilotAuthServiceType {
public init() {
let home = FileManager.default.homeDirectoryForCurrentUser
super.init(projectRootURL: home)
Task {
try? await server.sendRequest(GitHubCopilotRequest.SetEditorInfo())
}
}
public func checkStatus() async throws -> GitHubCopilotAccountStatus {
try await server.sendRequest(GitHubCopilotRequest.CheckStatus()).status
}
public func signInInitiate() async throws -> (verificationUri: String, userCode: String) {
let result = try await server.sendRequest(GitHubCopilotRequest.SignInInitiate())
return (result.verificationUri, result.userCode)
}
public func signInConfirm(userCode: String) async throws
-> (username: String, status: GitHubCopilotAccountStatus)
{
let result = try await server.sendRequest(GitHubCopilotRequest.SignInConfirm(userCode: userCode))
return (result.user, result.status)
}
public func signOut() async throws -> GitHubCopilotAccountStatus {
try await server.sendRequest(GitHubCopilotRequest.SignOut()).status
}
public func version() async throws -> String {
try await server.sendRequest(GitHubCopilotRequest.GetVersion()).version
}
}
public final class GitHubCopilotSuggestionService: GitHubCopilotBaseService, GitHubCopilotSuggestionServiceType {
override public init(projectRootURL: URL = URL(fileURLWithPath: "/")) {
super.init(projectRootURL: projectRootURL)
}
override init(designatedServer: GitHubCopilotLSP) {
super.init(designatedServer: designatedServer)
}
public func getCompletions(
fileURL: URL,
content: String,
cursorPosition: CursorPosition,
tabSize: Int,
indentSize: Int,
usesTabsForIndentation: Bool,
ignoreSpaceOnlySuggestions: Bool
) async throws -> [CodeSuggestion] {
let languageId = languageIdentifierFromFileURL(fileURL)
let relativePath = {
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
}()
let completions = try await server
.sendRequest(GitHubCopilotRequest.GetCompletionsCycling(doc: .init(
source: content,
tabSize: tabSize,
indentSize: indentSize,
insertSpaces: !usesTabsForIndentation,
path: fileURL.path,
uri: fileURL.path,
relativePath: relativePath,
languageId: languageId,
position: cursorPosition
)))
.completions
.filter { completion in
if ignoreSpaceOnlySuggestions {
return !completion.text.allSatisfy { $0.isWhitespace || $0.isNewline }
}
return true
}
return completions
}
public func notifyAccepted(_ completion: CodeSuggestion) async {
_ = try? await server.sendRequest(
GitHubCopilotRequest.NotifyAccepted(completionUUID: completion.uuid)
)
}
public func notifyRejected(_ completions: [CodeSuggestion]) async {
_ = try? await server.sendRequest(
GitHubCopilotRequest.NotifyRejected(completionUUIDs: completions.map(\.uuid))
)
}
public func notifyOpenTextDocument(
fileURL: URL,
content: String
) async throws {
let languageId = languageIdentifierFromFileURL(fileURL)
let uri = "file://\(fileURL.path)"
// Logger.service.debug("Open \(uri)")
try await server.sendNotification(
.didOpenTextDocument(
DidOpenTextDocumentParams(
textDocument: .init(
uri: uri,
languageId: languageId.rawValue,
version: 0,
text: content
)
)
)
)
}
public func notifyChangeTextDocument(fileURL: URL, content: String) async throws {
let uri = "file://\(fileURL.path)"
// Logger.service.debug("Change \(uri)")
try await server.sendNotification(
.didChangeTextDocument(
DidChangeTextDocumentParams(
uri: uri,
version: 0,
contentChange: .init(
range: nil,
rangeLength: nil,
text: content
)
)
)
)
}
public func notifySaveTextDocument(fileURL: URL) async throws {
let uri = "file://\(fileURL.path)"
// Logger.service.debug("Save \(uri)")
try await server.sendNotification(.didSaveTextDocument(.init(uri: uri)))
}
public func notifyCloseTextDocument(fileURL: URL) async throws {
let uri = "file://\(fileURL.path)"
// Logger.service.debug("Close \(uri)")
try await server.sendNotification(.didCloseTextDocument(.init(uri: uri)))
}
}
extension InitializingServer: GitHubCopilotLSP {
func sendRequest<E: GitHubCopilotRequestType>(_ endpoint: E) async throws -> E.Response {
try await sendRequest(endpoint.request)
}
}