forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGitHubCopilotChatService.swift
More file actions
234 lines (207 loc) · 8.42 KB
/
GitHubCopilotChatService.swift
File metadata and controls
234 lines (207 loc) · 8.42 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
import BuiltinExtension
import ChatBasic
import CopilotForXcodeKit
import Foundation
import LanguageServerProtocol
import XcodeInspector
public final class GitHubCopilotChatService: BuiltinExtensionChatServiceType {
let serviceLocator: any ServiceLocatorType
init(serviceLocator: any ServiceLocatorType) {
self.serviceLocator = serviceLocator
}
/// - note: Let's do it in a naive way for proof of concept. We will create a new chat for each
/// message in this version.
public func sendMessage(
_ message: String,
history: [Message],
references: [RetrievedContent],
workspace: WorkspaceInfo
) async -> AsyncThrowingStream<String, Error> {
guard let service = await serviceLocator.getService(from: workspace)
else { return .finished(throwing: CancellationError()) }
let id = UUID().uuidString
let editorContent = await XcodeInspector.shared.getFocusedEditorContent()
let workDoneToken = UUID().uuidString
let turns = convertHistory(history: history, message: message)
let request = GitHubCopilotRequest.ConversationCreate(requestBody: .init(
workDoneToken: workDoneToken,
turns: turns,
capabilities: .init(allSkills: true, skills: []),
doc: .init(
source: editorContent?.editorContent?.content ?? "",
tabSize: 1,
indentSize: 4,
insertSpaces: true,
path: editorContent?.documentURL.path ?? "",
uri: editorContent?.documentURL.path ?? "",
relativePath: editorContent?.relativePath ?? "",
languageId: editorContent?.language ?? .plaintext,
position: editorContent?.editorContent?.cursorPosition ?? .zero
),
source: .panel,
workspaceFolder: workspace.projectURL.path
))
let stream = AsyncThrowingStream<String, Error> { continuation in
let startTimestamp = Date()
continuation.onTermination = { _ in
Task { service.unregisterNotificationHandler(id: id) }
}
service.registerNotificationHandler(id: id) { notification, data in
// just incase the conversation is stuck, we will cancel it after timeout
if Date().timeIntervalSince(startTimestamp) > 60 * 30 {
continuation.finish(throwing: CancellationError())
return false
}
switch notification.method {
case "$/progress":
do {
let progress = try JSONDecoder().decode(
JSONRPC<StreamProgressParams>.self,
from: data
).params
guard progress.token == workDoneToken else { return false }
if let reply = progress.value.reply, progress.value.kind == "report" {
continuation.yield(reply)
} else if progress.value.kind == "end" {
if let error = progress.value.error,
progress.value.cancellationReason == nil
{
continuation.finish(
throwing: GitHubCopilotError.chatEndsWithError(error)
)
} else {
continuation.finish()
}
}
return true
} catch {
return false
}
case "conversation/context":
do {
_ = try JSONDecoder().decode(
JSONRPC<ConversationContextParams>.self,
from: data
)
throw ServerError.clientDataUnavailable(CancellationError())
} catch {
return false
}
default:
return false
}
}
Task {
do {
// this will return when the response is generated.
let createResponse = try await service.server.sendRequest(request, timeout: 120)
_ = try await service.server.sendRequest(
GitHubCopilotRequest.ConversationDestroy(requestBody: .init(
conversationId: createResponse.conversationId
))
)
} catch let error as ServerError {
continuation.finish(throwing: GitHubCopilotError.languageServerError(error))
} catch {
continuation.finish(throwing: error)
}
}
}
return stream
}
}
extension GitHubCopilotChatService {
typealias Turn = GitHubCopilotRequest.ConversationCreate.RequestBody.Turn
func convertHistory(history: [Message], message: String) -> [Turn] {
guard let firstIndexOfUserMessage = history.firstIndex(where: { $0.role == .user })
else { return [.init(request: message, response: nil)] }
var currentTurn = Turn(request: "", response: nil)
var turns: [Turn] = []
let systemPrompt = history
.filter { $0.role == .system }.compactMap(\.content)
.joined(separator: "\n\n")
if !systemPrompt.isEmpty {
turns.append(.init(request: "[System Prompt]\n\(systemPrompt)", response: "OK!"))
}
for i in firstIndexOfUserMessage..<history.endIndex {
let message = history[i]
let text = message.content ?? ""
switch message.role {
case .user:
if currentTurn.response == nil {
if currentTurn.request.isEmpty {
currentTurn.request = text
} else {
currentTurn.request += "\n\n\(text)"
}
} else { // a valid turn is created
turns.append(currentTurn)
currentTurn = Turn(request: text, response: nil)
}
case .assistant:
if let response = currentTurn.response {
currentTurn.response = "\(response)\n\n\(text)"
} else {
currentTurn.response = text
}
default:
break
}
}
if currentTurn.response == nil {
currentTurn.response = "OK"
}
turns.append(currentTurn)
turns.append(.init(request: message, response: nil))
return turns
}
func createNewMessage(references: [RetrievedContent], message: String) -> String {
return message
}
struct JSONRPC<Params: Decodable>: Decodable {
var jsonrpc: String
var method: String
var params: Params
}
struct StreamProgressParams: Decodable {
struct Value: Decodable {
struct Step: Decodable {
var id: String
var title: String
var status: String
}
struct FollowUp: Decodable {
var id: String
var type: String
var message: String
}
var kind: String
var title: String?
var conversationId: String
var turnId: String
var steps: [Step]?
var followUp: FollowUp?
var suggestedTitle: String?
var reply: String?
var annotations: [String]?
var hideText: Bool?
var cancellationReason: String?
var error: String?
}
var token: String
var value: Value
}
struct ConversationContextParams: Decodable {
enum SkillID: String, Decodable {
case currentEditor = "current-editor"
case projectLabels = "project-labels"
case recentFiles = "recent-files"
case references
case problemsInActiveDocument = "problems-in-active-document"
}
var conversationId: String
var turnId: String
var skillId: String
}
struct ConversationContextResponseBody: Encodable {}
}