-
Notifications
You must be signed in to change notification settings - Fork 565
/
Copy pathmessages.ts
256 lines (233 loc) · 9.73 KB
/
messages.ts
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
/*!
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
import {
isValidAuthFollowUpType,
INSERT_TO_CURSOR_POSITION,
AUTH_FOLLOW_UP_CLICKED,
CHAT_OPTIONS,
COPY_TO_CLIPBOARD,
AuthFollowUpType,
DISCLAIMER_ACKNOWLEDGED,
} from '@aws/chat-client-ui-types'
import {
ChatResult,
chatRequestType,
ChatParams,
followUpClickNotificationType,
quickActionRequestType,
QuickActionResult,
QuickActionParams,
insertToCursorPositionNotificationType,
} from '@aws/language-server-runtimes/protocol'
import { v4 as uuidv4 } from 'uuid'
import { window } from 'vscode'
import { Disposable, LanguageClient, Position, State, TextDocumentIdentifier } from 'vscode-languageclient'
import * as jose from 'jose'
import { AmazonQChatViewProvider } from './webviewProvider'
import { AuthUtil } from 'aws-core-vscode/codewhisperer'
import { AmazonQPromptSettings } from 'aws-core-vscode/shared'
export function registerLanguageServerEventListener(languageClient: LanguageClient, provider: AmazonQChatViewProvider) {
languageClient.onDidChangeState(({ oldState, newState }) => {
if (oldState === State.Starting && newState === State.Running) {
languageClient.info(
'Language client received initializeResult from server:',
JSON.stringify(languageClient.initializeResult)
)
const chatOptions = languageClient.initializeResult?.awsServerCapabilities?.chatOptions
void provider.webview?.postMessage({
command: CHAT_OPTIONS,
params: chatOptions,
})
}
})
languageClient.onTelemetry((e) => {
languageClient.info(`[VSCode Client] Received telemetry event from server ${JSON.stringify(e)}`)
})
}
export function registerMessageListeners(
languageClient: LanguageClient,
provider: AmazonQChatViewProvider,
encryptionKey: Buffer
) {
provider.webview?.onDidReceiveMessage(async (message) => {
languageClient.info(`[VSCode Client] Received ${JSON.stringify(message)} from chat`)
switch (message.command) {
case COPY_TO_CLIPBOARD:
// TODO see what we need to hook this up
languageClient.info('[VSCode Client] Copy to clipboard event received')
break
case INSERT_TO_CURSOR_POSITION: {
const editor = window.activeTextEditor
let textDocument: TextDocumentIdentifier | undefined = undefined
let cursorPosition: Position | undefined = undefined
if (editor) {
cursorPosition = editor.selection.active
textDocument = { uri: editor.document.uri.toString() }
}
languageClient.sendNotification(insertToCursorPositionNotificationType.method, {
...message.params,
cursorPosition,
textDocument,
})
break
}
case AUTH_FOLLOW_UP_CLICKED: {
languageClient.info('[VSCode Client] AuthFollowUp clicked')
const authType = message.params.authFollowupType
const reAuthTypes: AuthFollowUpType[] = ['re-auth', 'missing_scopes']
const fullAuthTypes: AuthFollowUpType[] = ['full-auth', 'use-supported-auth']
if (reAuthTypes.includes(authType)) {
try {
await AuthUtil.instance.reauthenticate()
} catch (e) {
languageClient.error(
`[VSCode Client] Failed to re-authenticate after AUTH_FOLLOW_UP_CLICKED: ${(e as Error).message}`
)
}
}
if (fullAuthTypes.includes(authType)) {
try {
await AuthUtil.instance.secondaryAuth.deleteConnection()
} catch (e) {
languageClient.error(
`[VSCode Client] Failed to authenticate after AUTH_FOLLOW_UP_CLICKED: ${(e as Error).message}`
)
}
}
break
}
case DISCLAIMER_ACKNOWLEDGED: {
void AmazonQPromptSettings.instance.update('amazonQChatDisclaimerAcknowledged', true)
break
}
case chatRequestType.method: {
const partialResultToken = uuidv4()
const chatDisposable = languageClient.onProgress(chatRequestType, partialResultToken, (partialResult) =>
handlePartialResult<ChatResult>(partialResult, encryptionKey, provider, message.params.tabId)
)
const editor =
window.activeTextEditor ||
window.visibleTextEditors.find((editor) => editor.document.languageId !== 'Log')
if (editor) {
message.params.cursorPosition = [editor.selection.active]
message.params.textDocument = { uri: editor.document.uri.toString() }
}
const chatRequest = await encryptRequest<ChatParams>(message.params, encryptionKey)
const chatResult = (await languageClient.sendRequest(chatRequestType.method, {
...chatRequest,
partialResultToken,
})) as string | ChatResult
void handleCompleteResult<ChatResult>(
chatResult,
encryptionKey,
provider,
message.params.tabId,
chatDisposable
)
break
}
case quickActionRequestType.method: {
const quickActionPartialResultToken = uuidv4()
const quickActionDisposable = languageClient.onProgress(
quickActionRequestType,
quickActionPartialResultToken,
(partialResult) =>
handlePartialResult<QuickActionResult>(
partialResult,
encryptionKey,
provider,
message.params.tabId
)
)
const quickActionRequest = await encryptRequest<QuickActionParams>(message.params, encryptionKey)
const quickActionResult = (await languageClient.sendRequest(quickActionRequestType.method, {
...quickActionRequest,
partialResultToken: quickActionPartialResultToken,
})) as string | ChatResult
void handleCompleteResult<ChatResult>(
quickActionResult,
encryptionKey,
provider,
message.params.tabId,
quickActionDisposable
)
break
}
case followUpClickNotificationType.method:
if (!isValidAuthFollowUpType(message.params.followUp.type)) {
languageClient.sendNotification(followUpClickNotificationType.method, message.params)
}
break
default:
if (isServerEvent(message.command)) {
languageClient.sendNotification(message.command, message.params)
}
break
}
}, undefined)
}
function isServerEvent(command: string) {
return command.startsWith('aws/chat/') || command === 'telemetry/event'
}
async function encryptRequest<T>(params: T, encryptionKey: Buffer): Promise<{ message: string } | T> {
const payload = new TextEncoder().encode(JSON.stringify(params))
const encryptedMessage = await new jose.CompactEncrypt(payload)
.setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
.encrypt(encryptionKey)
return { message: encryptedMessage }
}
async function decodeRequest<T>(request: string, key: Buffer): Promise<T> {
const result = await jose.jwtDecrypt(request, key, {
clockTolerance: 60, // Allow up to 60 seconds to account for clock differences
contentEncryptionAlgorithms: ['A256GCM'],
keyManagementAlgorithms: ['dir'],
})
if (!result.payload) {
throw new Error('JWT payload not found')
}
return result.payload as T
}
/**
* Decodes partial chat responses from the language server before sending them to mynah UI
*/
async function handlePartialResult<T extends ChatResult>(
partialResult: string | T,
encryptionKey: Buffer | undefined,
provider: AmazonQChatViewProvider,
tabId: string
) {
const decryptedMessage =
typeof partialResult === 'string' && encryptionKey
? await decodeRequest<T>(partialResult, encryptionKey)
: (partialResult as T)
if (decryptedMessage.body) {
void provider.webview?.postMessage({
command: chatRequestType.method,
params: decryptedMessage,
isPartialResult: true,
tabId: tabId,
})
}
}
/**
* Decodes the final chat responses from the language server before sending it to mynah UI.
* Once this is called the answer response is finished
*/
async function handleCompleteResult<T>(
result: string | T,
encryptionKey: Buffer | undefined,
provider: AmazonQChatViewProvider,
tabId: string,
disposable: Disposable
) {
const decryptedMessage =
typeof result === 'string' && encryptionKey ? await decodeRequest(result, encryptionKey) : result
void provider.webview?.postMessage({
command: chatRequestType.method,
params: decryptedMessage,
tabId: tabId,
})
disposable.dispose()
}