@codingame/monaco-vscode-chat-service-override 3.2.3 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/chat.js +16 -14
  2. package/package.json +2 -2
  3. package/vscode/src/vs/workbench/contrib/chat/browser/codeBlockContextProviderService.js +16 -0
  4. package/external/tslib/tslib.es6.js +0 -11
  5. package/external/vscode-marked/lib/marked.esm.js +0 -2200
  6. package/override/vs/platform/dialogs/common/dialogs.js +0 -8
  7. package/vscode/src/vs/workbench/contrib/chat/browser/actions/chatClear.js +0 -17
  8. package/vscode/src/vs/workbench/contrib/chat/browser/actions/chatClearActions.js +0 -115
  9. package/vscode/src/vs/workbench/contrib/chat/browser/actions/chatCodeblockActions.js +0 -501
  10. package/vscode/src/vs/workbench/contrib/chat/browser/actions/chatCopyActions.js +0 -82
  11. package/vscode/src/vs/workbench/contrib/chat/browser/actions/chatFileTreeActions.js +0 -77
  12. package/vscode/src/vs/workbench/contrib/chat/browser/actions/chatImportExport.js +0 -110
  13. package/vscode/src/vs/workbench/contrib/chat/browser/actions/chatMoveActions.js +0 -171
  14. package/vscode/src/vs/workbench/contrib/chat/browser/actions/chatTitleActions.js +0 -271
  15. package/vscode/src/vs/workbench/contrib/chat/browser/chat.contribution.js +0 -299
  16. package/vscode/src/vs/workbench/contrib/chat/browser/chatAccessibilityService.js +0 -60
  17. package/vscode/src/vs/workbench/contrib/chat/browser/chatContributionServiceImpl.js +0 -179
  18. package/vscode/src/vs/workbench/contrib/chat/browser/chatEditor.js +0 -87
  19. package/vscode/src/vs/workbench/contrib/chat/browser/chatQuick.js +0 -271
  20. package/vscode/src/vs/workbench/contrib/chat/browser/chatVariables.js +0 -74
  21. package/vscode/src/vs/workbench/contrib/chat/browser/chatViewPane.js +0 -174
  22. package/vscode/src/vs/workbench/contrib/chat/browser/contrib/chatHistoryVariables.js +0 -26
  23. package/vscode/src/vs/workbench/contrib/chat/browser/contrib/chatInputEditorContrib.js +0 -580
  24. package/vscode/src/vs/workbench/contrib/chat/common/chatColors.js +0 -36
  25. package/vscode/src/vs/workbench/contrib/chat/common/chatServiceImpl.js +0 -601
  26. package/vscode/src/vs/workbench/contrib/inlineChat/browser/inlineChat.contribution.js +0 -43
  27. package/vscode/src/vs/workbench/contrib/inlineChat/browser/inlineChatAccessibleView.js +0 -41
  28. package/vscode/src/vs/workbench/contrib/inlineChat/browser/inlineChatActions.js +0 -814
  29. package/vscode/src/vs/workbench/contrib/inlineChat/browser/inlineChatNotebook.js +0 -72
  30. package/vscode/src/vs/workbench/contrib/inlineChat/browser/inlineChatSavingServiceImpl.js +0 -236
  31. package/vscode/src/vs/workbench/contrib/inlineChat/browser/inlineChatSessionServiceImpl.js +0 -223
  32. package/vscode/src/vs/workbench/contrib/inlineChat/common/inlineChatServiceImpl.js +0 -33
@@ -1,601 +0,0 @@
1
- import { __decorate, __param } from '../../../../../../../external/tslib/tslib.es6.js';
2
- import { Action } from 'vscode/vscode/vs/base/common/actions';
3
- import { CancellationToken, CancellationTokenSource } from 'vscode/vscode/vs/base/common/cancellation';
4
- import { Emitter, Event } from 'vscode/vscode/vs/base/common/event';
5
- import { MarkdownString } from 'vscode/vscode/vs/base/common/htmlContent';
6
- import { Iterable } from 'vscode/vscode/vs/base/common/iterator';
7
- import { Disposable, DisposableMap, toDisposable } from 'vscode/vscode/vs/base/common/lifecycle';
8
- import { revive } from 'vscode/vscode/vs/base/common/marshalling';
9
- import { StopWatch } from 'vscode/vscode/vs/base/common/stopwatch';
10
- import { URI } from 'vscode/vscode/vs/base/common/uri';
11
- import { localizeWithPath } from 'vscode/vscode/vs/nls';
12
- import { CommandsRegistry, ICommandService } from 'vscode/vscode/vs/platform/commands/common/commands';
13
- import { IContextKeyService } from 'vscode/vscode/vs/platform/contextkey/common/contextkey';
14
- import { IInstantiationService } from 'vscode/vscode/vs/platform/instantiation/common/instantiation';
15
- import { ILogService } from 'vscode/vscode/vs/platform/log/common/log';
16
- import { Severity, INotificationService } from 'vscode/vscode/vs/platform/notification/common/notification';
17
- import { Progress } from 'vscode/vscode/vs/platform/progress/common/progress';
18
- import { IStorageService } from 'vscode/vscode/vs/platform/storage/common/storage';
19
- import { ITelemetryService } from 'vscode/vscode/vs/platform/telemetry/common/telemetry';
20
- import { IWorkspaceContextService } from 'vscode/vscode/vs/platform/workspace/common/workspace';
21
- import { IChatAgentService } from 'vscode/vscode/vs/workbench/contrib/chat/common/chatAgents';
22
- import { CONTEXT_PROVIDER_EXISTS } from 'vscode/vscode/vs/workbench/contrib/chat/common/chatContextKeys';
23
- import { ChatModel, ChatWelcomeMessageModel, ChatModelInitState, getHistoryEntriesFromModel, updateRanges } from 'vscode/vscode/vs/workbench/contrib/chat/common/chatModel';
24
- import { ChatRequestAgentPart, ChatRequestAgentSubcommandPart, ChatRequestSlashCommandPart, getPromptText } from 'vscode/vscode/vs/workbench/contrib/chat/common/chatParserTypes';
25
- import { ChatRequestParser } from 'vscode/vscode/vs/workbench/contrib/chat/common/chatRequestParser';
26
- import { InteractiveSessionVoteDirection, ChatCopyKind } from 'vscode/vscode/vs/workbench/contrib/chat/common/chatService';
27
- import { IChatSlashCommandService } from 'vscode/vscode/vs/workbench/contrib/chat/common/chatSlashCommands';
28
- import { IChatVariablesService } from 'vscode/vscode/vs/workbench/contrib/chat/common/chatVariables';
29
- import { IExtensionService } from 'vscode/vscode/vs/workbench/services/extensions/common/extensions';
30
-
31
- const serializedChatKey = 'interactive.sessions';
32
- const globalChatKey = 'chat.workspaceTransfer';
33
- const SESSION_TRANSFER_EXPIRATION_IN_MILLISECONDS = 1000 * 60;
34
- const maxPersistedSessions = 25;
35
- let ChatService = class ChatService extends Disposable {
36
- get transferredSessionData() {
37
- return this._transferredSessionData;
38
- }
39
- constructor(storageService, logService, extensionService, instantiationService, telemetryService, contextKeyService, workspaceContextService, chatSlashCommandService, chatVariablesService, chatAgentService, notificationService, commandService) {
40
- super();
41
- this.storageService = storageService;
42
- this.logService = logService;
43
- this.extensionService = extensionService;
44
- this.instantiationService = instantiationService;
45
- this.telemetryService = telemetryService;
46
- this.contextKeyService = contextKeyService;
47
- this.workspaceContextService = workspaceContextService;
48
- this.chatSlashCommandService = chatSlashCommandService;
49
- this.chatVariablesService = chatVariablesService;
50
- this.chatAgentService = chatAgentService;
51
- this.notificationService = notificationService;
52
- this.commandService = commandService;
53
- this._providers = ( new Map());
54
- this._sessionModels = this._register(( new DisposableMap()));
55
- this._pendingRequests = this._register(( new DisposableMap()));
56
- this._onDidPerformUserAction = this._register(( new Emitter()));
57
- this.onDidPerformUserAction = this._onDidPerformUserAction.event;
58
- this._onDidDisposeSession = this._register(( new Emitter()));
59
- this.onDidDisposeSession = this._onDidDisposeSession.event;
60
- this._onDidRegisterProvider = this._register(( new Emitter()));
61
- this.onDidRegisterProvider = this._onDidRegisterProvider.event;
62
- this._onDidUnregisterProvider = this._register(( new Emitter()));
63
- this.onDidUnregisterProvider = this._onDidUnregisterProvider.event;
64
- this._sessionFollowupCancelTokens = this._register(( new DisposableMap()));
65
- this._hasProvider = CONTEXT_PROVIDER_EXISTS.bindTo(this.contextKeyService);
66
- const sessionData = storageService.get(serializedChatKey, 1 , '');
67
- if (sessionData) {
68
- this._persistedSessions = this.deserializeChats(sessionData);
69
- const countsForLog = ( Object.keys(this._persistedSessions)).length;
70
- if (countsForLog > 0) {
71
- this.trace('constructor', `Restored ${countsForLog} persisted sessions`);
72
- }
73
- }
74
- else {
75
- this._persistedSessions = {};
76
- }
77
- const transferredData = this.getTransferredSessionData();
78
- const transferredChat = transferredData?.chat;
79
- if (transferredChat) {
80
- this.trace('constructor', `Transferred session ${transferredChat.sessionId}`);
81
- this._persistedSessions[transferredChat.sessionId] = transferredChat;
82
- this._transferredSessionData = { sessionId: transferredChat.sessionId, inputValue: transferredData.inputValue };
83
- }
84
- this._register(storageService.onWillSaveState(() => this.saveState()));
85
- this._register(Event.debounce(this.chatAgentService.onDidChangeAgents, () => { }, 500)(() => {
86
- for (const model of ( this._sessionModels.values())) {
87
- this.warmSlashCommandCache(model);
88
- }
89
- }));
90
- }
91
- saveState() {
92
- let allSessions = Array.from(( this._sessionModels.values()))
93
- .filter(session => session.getRequests().length > 0);
94
- allSessions = allSessions.concat(( Object.values(this._persistedSessions))
95
- .filter(session => !( this._sessionModels.has(session.sessionId)))
96
- .filter(session => session.requests.length));
97
- allSessions.sort((a, b) => (b.creationDate ?? 0) - (a.creationDate ?? 0));
98
- allSessions = allSessions.slice(0, maxPersistedSessions);
99
- if (allSessions.length) {
100
- this.trace('onWillSaveState', `Persisting ${allSessions.length} sessions`);
101
- }
102
- const serialized = JSON.stringify(allSessions);
103
- if (allSessions.length) {
104
- this.trace('onWillSaveState', `Persisting ${serialized.length} chars`);
105
- }
106
- this.storageService.store(serializedChatKey, serialized, 1 , 1 );
107
- }
108
- notifyUserAction(action) {
109
- if (action.action.kind === 'vote') {
110
- this.telemetryService.publicLog2('interactiveSessionVote', {
111
- providerId: action.providerId,
112
- direction: action.action.direction === InteractiveSessionVoteDirection.Up ? 'up' : 'down'
113
- });
114
- }
115
- else if (action.action.kind === 'copy') {
116
- this.telemetryService.publicLog2('interactiveSessionCopy', {
117
- providerId: action.providerId,
118
- copyKind: action.action.copyKind === ChatCopyKind.Action ? 'action' : 'toolbar'
119
- });
120
- }
121
- else if (action.action.kind === 'insert') {
122
- this.telemetryService.publicLog2('interactiveSessionInsert', {
123
- providerId: action.providerId,
124
- newFile: !!action.action.newFile
125
- });
126
- }
127
- else if (action.action.kind === 'command') {
128
- const command = CommandsRegistry.getCommand(action.action.commandButton.command.id);
129
- const commandId = command ? action.action.commandButton.command.id : 'INVALID';
130
- this.telemetryService.publicLog2('interactiveSessionCommand', {
131
- providerId: action.providerId,
132
- commandId
133
- });
134
- }
135
- else if (action.action.kind === 'runInTerminal') {
136
- this.telemetryService.publicLog2('interactiveSessionRunInTerminal', {
137
- providerId: action.providerId,
138
- languageId: action.action.languageId ?? ''
139
- });
140
- }
141
- this._onDidPerformUserAction.fire(action);
142
- }
143
- trace(method, message) {
144
- this.logService.trace(`ChatService#${method}: ${message}`);
145
- }
146
- error(method, message) {
147
- this.logService.error(`ChatService#${method} ${message}`);
148
- }
149
- deserializeChats(sessionData) {
150
- try {
151
- const arrayOfSessions = revive(JSON.parse(sessionData));
152
- if (!Array.isArray(arrayOfSessions)) {
153
- throw new Error('Expected array');
154
- }
155
- const sessions = arrayOfSessions.reduce((acc, session) => {
156
- for (const request of session.requests) {
157
- if (Array.isArray(request.response)) {
158
- request.response = ( request.response.map((response) => {
159
- if (typeof response === 'string') {
160
- return ( new MarkdownString(response));
161
- }
162
- return response;
163
- }));
164
- }
165
- else if (typeof request.response === 'string') {
166
- request.response = [( new MarkdownString(request.response))];
167
- }
168
- }
169
- acc[session.sessionId] = session;
170
- return acc;
171
- }, {});
172
- return sessions;
173
- }
174
- catch (err) {
175
- this.error('deserializeChats', `Malformed session data: ${err}. [${sessionData.substring(0, 20)}${sessionData.length > 20 ? '...' : ''}]`);
176
- return {};
177
- }
178
- }
179
- getTransferredSessionData() {
180
- const data = this.storageService.getObject(globalChatKey, 0 , []);
181
- const workspaceUri = this.workspaceContextService.getWorkspace().folders[0]?.uri;
182
- if (!workspaceUri) {
183
- return;
184
- }
185
- const thisWorkspace = ( workspaceUri.toString());
186
- const currentTime = Date.now();
187
- const transferred = data.find(item => ( URI.revive(item.toWorkspace).toString()) === thisWorkspace && (currentTime - item.timestampInMilliseconds < SESSION_TRANSFER_EXPIRATION_IN_MILLISECONDS));
188
- const filtered = data.filter(item => ( URI.revive(item.toWorkspace).toString()) !== thisWorkspace && (currentTime - item.timestampInMilliseconds < SESSION_TRANSFER_EXPIRATION_IN_MILLISECONDS));
189
- this.storageService.store(globalChatKey, JSON.stringify(filtered), 0 , 1 );
190
- return transferred;
191
- }
192
- getHistory() {
193
- const sessions = ( Object.values(this._persistedSessions))
194
- .filter(session => session.requests.length > 0);
195
- sessions.sort((a, b) => (b.creationDate ?? 0) - (a.creationDate ?? 0));
196
- return ( sessions
197
- .filter(session => !( this._sessionModels.has(session.sessionId)))
198
- .filter(session => !session.isImported)
199
- .map(item => {
200
- const title = ChatModel.getDefaultTitle(item.requests);
201
- return {
202
- sessionId: item.sessionId,
203
- title
204
- };
205
- }));
206
- }
207
- removeHistoryEntry(sessionId) {
208
- delete this._persistedSessions[sessionId];
209
- this.saveState();
210
- }
211
- clearAllHistoryEntries() {
212
- this._persistedSessions = {};
213
- this.saveState();
214
- }
215
- startSession(providerId, token) {
216
- this.trace('startSession', `providerId=${providerId}`);
217
- return this._startSession(providerId, undefined, token);
218
- }
219
- _startSession(providerId, someSessionHistory, token) {
220
- this.trace('_startSession', `providerId=${providerId}`);
221
- const model = this.instantiationService.createInstance(ChatModel, providerId, someSessionHistory);
222
- this._sessionModels.set(model.sessionId, model);
223
- this.initializeSession(model, token);
224
- return model;
225
- }
226
- reinitializeModel(model) {
227
- this.trace('reinitializeModel', `Start reinit`);
228
- this.initializeSession(model, CancellationToken.None);
229
- }
230
- warmSlashCommandCache(model, agent) {
231
- const agents = agent ? [agent] : this.chatAgentService.getAgents();
232
- agents.forEach(agent => agent.provideSlashCommands(model, [], CancellationToken.None));
233
- }
234
- async initializeSession(model, token) {
235
- try {
236
- this.trace('initializeSession', `Initialize session ${model.sessionId}`);
237
- this.warmSlashCommandCache(model);
238
- model.startInitialize();
239
- await this.extensionService.activateByEvent(`onInteractiveSession:${model.providerId}`);
240
- const provider = this._providers.get(model.providerId);
241
- if (!provider) {
242
- throw new Error(`Unknown provider: ${model.providerId}`);
243
- }
244
- let session;
245
- try {
246
- session = (await provider.prepareSession(token)) ?? undefined;
247
- }
248
- catch (err) {
249
- this.trace('initializeSession', `Provider initializeSession threw: ${err}`);
250
- }
251
- if (!session) {
252
- throw new Error('Provider returned no session');
253
- }
254
- this.trace('startSession', `Provider returned session`);
255
- const defaultAgent = this.chatAgentService.getDefaultAgent();
256
- if (!defaultAgent) {
257
- this.notificationService.notify({
258
- severity: Severity.Error,
259
- message: ( localizeWithPath(
260
- 'vs/workbench/contrib/chat/common/chatServiceImpl',
261
- 'chatFailErrorMessage',
262
- "Chat failed to load. Please ensure that the GitHub Copilot Chat extension is up to date."
263
- )),
264
- actions: {
265
- primary: [
266
- ( new Action('showExtension', ( localizeWithPath(
267
- 'vs/workbench/contrib/chat/common/chatServiceImpl',
268
- 'action.showExtension',
269
- "Show Extension"
270
- )), undefined, true, () => {
271
- return this.commandService.executeCommand('workbench.extensions.action.showExtensionsWithIds', ['GitHub.copilot-chat']);
272
- }))
273
- ]
274
- }
275
- });
276
- throw new Error('No default agent');
277
- }
278
- const welcomeMessage = model.welcomeMessage ? undefined : (await defaultAgent.provideWelcomeMessage?.(token)) ?? undefined;
279
- const welcomeModel = welcomeMessage && ( new ChatWelcomeMessageModel(model, ( welcomeMessage.map(item => typeof item === 'string' ? ( new MarkdownString(item)) : item)), (await defaultAgent.provideSampleQuestions?.(token)) ?? []));
280
- model.initialize(session, welcomeModel);
281
- }
282
- catch (err) {
283
- this.trace('startSession', `initializeSession failed: ${err}`);
284
- model.setInitializationError(err);
285
- this._sessionModels.deleteAndDispose(model.sessionId);
286
- this._onDidDisposeSession.fire({ sessionId: model.sessionId, providerId: model.providerId, reason: 'initializationFailed' });
287
- }
288
- }
289
- getSession(sessionId) {
290
- return this._sessionModels.get(sessionId);
291
- }
292
- getSessionId(sessionProviderId) {
293
- return Iterable.find(( this._sessionModels.values()), model => model.session?.id === sessionProviderId)?.sessionId;
294
- }
295
- getOrRestoreSession(sessionId) {
296
- this.trace('getOrRestoreSession', `sessionId: ${sessionId}`);
297
- const model = this._sessionModels.get(sessionId);
298
- if (model) {
299
- return model;
300
- }
301
- const sessionData = this._persistedSessions[sessionId];
302
- if (!sessionData) {
303
- return undefined;
304
- }
305
- if (sessionId === this.transferredSessionData?.sessionId) {
306
- this._transferredSessionData = undefined;
307
- }
308
- return this._startSession(sessionData.providerId, sessionData, CancellationToken.None);
309
- }
310
- loadSessionFromContent(data) {
311
- return this._startSession(data.providerId, data, CancellationToken.None);
312
- }
313
- async sendRequest(sessionId, request) {
314
- this.trace('sendRequest', `sessionId: ${sessionId}, message: ${request.substring(0, 20)}${request.length > 20 ? '[...]' : ''}}`);
315
- if (!request.trim()) {
316
- this.trace('sendRequest', 'Rejected empty message');
317
- return;
318
- }
319
- const model = this._sessionModels.get(sessionId);
320
- if (!model) {
321
- throw new Error(`Unknown session: ${sessionId}`);
322
- }
323
- await model.waitForInitialization();
324
- const provider = this._providers.get(model.providerId);
325
- if (!provider) {
326
- throw new Error(`Unknown provider: ${model.providerId}`);
327
- }
328
- if (( this._pendingRequests.has(sessionId))) {
329
- this.trace('sendRequest', `Session ${sessionId} already has a pending request`);
330
- return;
331
- }
332
- const parsedRequest = this.instantiationService.createInstance(ChatRequestParser).parseChatRequest(sessionId, request);
333
- const agent = parsedRequest.parts.find((r) => r instanceof ChatRequestAgentPart)?.agent ?? this.chatAgentService.getDefaultAgent();
334
- const agentSlashCommandPart = parsedRequest.parts.find((r) => r instanceof ChatRequestAgentSubcommandPart);
335
- return {
336
- responseCompletePromise: this._sendRequestAsync(model, sessionId, provider, parsedRequest),
337
- agent,
338
- slashCommand: agentSlashCommandPart?.command,
339
- };
340
- }
341
- refreshFollowupsCancellationToken(sessionId) {
342
- this._sessionFollowupCancelTokens.get(sessionId)?.cancel();
343
- const newTokenSource = ( new CancellationTokenSource());
344
- this._sessionFollowupCancelTokens.set(sessionId, newTokenSource);
345
- return newTokenSource.token;
346
- }
347
- async _sendRequestAsync(model, sessionId, provider, parsedRequest) {
348
- const followupsCancelToken = this.refreshFollowupsCancellationToken(sessionId);
349
- let request;
350
- const agentPart = 'kind' in parsedRequest ? undefined : parsedRequest.parts.find((r) => r instanceof ChatRequestAgentPart);
351
- const agentSlashCommandPart = 'kind' in parsedRequest ? undefined : parsedRequest.parts.find((r) => r instanceof ChatRequestAgentSubcommandPart);
352
- const commandPart = 'kind' in parsedRequest ? undefined : parsedRequest.parts.find((r) => r instanceof ChatRequestSlashCommandPart);
353
- let gotProgress = false;
354
- const requestType = commandPart ? 'slashCommand' : 'string';
355
- const source = ( new CancellationTokenSource());
356
- const token = source.token;
357
- const sendRequestInternal = async () => {
358
- const progressCallback = (progress) => {
359
- if (token.isCancellationRequested) {
360
- return;
361
- }
362
- gotProgress = true;
363
- if (progress.kind === 'content' || progress.kind === 'markdownContent') {
364
- this.trace('sendRequest', `Provider returned progress for session ${model.sessionId}, ${typeof progress.content === 'string' ? progress.content.length : progress.content.value.length} chars`);
365
- }
366
- else {
367
- this.trace('sendRequest', `Provider returned progress: ${JSON.stringify(progress)}`);
368
- }
369
- model.acceptResponseProgress(request, progress);
370
- };
371
- const stopWatch = ( new StopWatch(false));
372
- const listener = token.onCancellationRequested(() => {
373
- this.trace('sendRequest', `Request for session ${model.sessionId} was cancelled`);
374
- this.telemetryService.publicLog2('interactiveSessionProviderInvoked', {
375
- providerId: provider.id,
376
- timeToFirstProgress: undefined,
377
- totalTime: stopWatch.elapsed(),
378
- result: 'cancelled',
379
- requestType,
380
- agent: agentPart?.agent.id ?? '',
381
- slashCommand: agentSlashCommandPart ? agentSlashCommandPart.command.name : commandPart?.slashCommand.command,
382
- chatSessionId: model.sessionId
383
- });
384
- model.cancelRequest(request);
385
- });
386
- try {
387
- let rawResult;
388
- let agentOrCommandFollowups = undefined;
389
- const defaultAgent = this.chatAgentService.getDefaultAgent();
390
- if (agentPart || (defaultAgent && !commandPart)) {
391
- const agent = (agentPart?.agent ?? defaultAgent);
392
- const history = getHistoryEntriesFromModel(model);
393
- const initVariableData = { variables: [] };
394
- request = model.addRequest(parsedRequest, initVariableData, agent, agentSlashCommandPart?.command);
395
- const variableData = await this.chatVariablesService.resolveVariables(parsedRequest, model, progressCallback, token);
396
- request.variableData = variableData;
397
- const promptTextResult = getPromptText(request.message);
398
- const requestProps = {
399
- sessionId,
400
- requestId: request.id,
401
- agentId: agent.id,
402
- message: promptTextResult.message,
403
- command: agentSlashCommandPart?.command.name,
404
- variables: updateRanges(variableData, promptTextResult.diff)
405
- };
406
- const agentResult = await this.chatAgentService.invokeAgent(agent.id, requestProps, progressCallback, history, token);
407
- rawResult = agentResult;
408
- agentOrCommandFollowups = this.chatAgentService.getFollowups(agent.id, requestProps, agentResult, followupsCancelToken);
409
- }
410
- else if (commandPart && this.chatSlashCommandService.hasCommand(commandPart.slashCommand.command)) {
411
- request = model.addRequest(parsedRequest, { variables: [] });
412
- const history = [];
413
- for (const request of model.getRequests()) {
414
- if (!request.response) {
415
- continue;
416
- }
417
- history.push({ role: 1 , content: request.message.text });
418
- history.push({ role: 2 , content: request.response.response.asString() });
419
- }
420
- const message = parsedRequest.text;
421
- const commandResult = await this.chatSlashCommandService.executeCommand(commandPart.slashCommand.command, message.substring(commandPart.slashCommand.command.length + 1).trimStart(), ( new Progress(p => {
422
- progressCallback(p);
423
- })), history, token);
424
- agentOrCommandFollowups = Promise.resolve(commandResult?.followUp);
425
- rawResult = {};
426
- }
427
- else {
428
- throw new Error(`Cannot handle request`);
429
- }
430
- if (token.isCancellationRequested) {
431
- return;
432
- }
433
- else {
434
- if (!rawResult) {
435
- this.trace('sendRequest', `Provider returned no response for session ${model.sessionId}`);
436
- rawResult = { errorDetails: { message: ( localizeWithPath(
437
- 'vs/workbench/contrib/chat/common/chatServiceImpl',
438
- 'emptyResponse',
439
- "Provider returned null response"
440
- )) } };
441
- }
442
- const result = rawResult.errorDetails?.responseIsFiltered ? 'filtered' :
443
- rawResult.errorDetails && gotProgress ? 'errorWithOutput' :
444
- rawResult.errorDetails ? 'error' :
445
- 'success';
446
- this.telemetryService.publicLog2('interactiveSessionProviderInvoked', {
447
- providerId: provider.id,
448
- timeToFirstProgress: rawResult.timings?.firstProgress,
449
- totalTime: rawResult.timings?.totalElapsed,
450
- result,
451
- requestType,
452
- agent: agentPart?.agent.id ?? '',
453
- slashCommand: agentSlashCommandPart ? agentSlashCommandPart.command.name : commandPart?.slashCommand.command,
454
- chatSessionId: model.sessionId
455
- });
456
- model.setResponse(request, rawResult);
457
- this.trace('sendRequest', `Provider returned response for session ${model.sessionId}`);
458
- model.completeResponse(request);
459
- if (agentOrCommandFollowups) {
460
- agentOrCommandFollowups.then(followups => {
461
- model.setFollowups(request, followups);
462
- });
463
- }
464
- }
465
- }
466
- finally {
467
- listener.dispose();
468
- }
469
- };
470
- const rawResponsePromise = sendRequestInternal();
471
- this._pendingRequests.set(model.sessionId, source);
472
- rawResponsePromise.finally(() => {
473
- this._pendingRequests.deleteAndDispose(model.sessionId);
474
- });
475
- return rawResponsePromise;
476
- }
477
- async removeRequest(sessionId, requestId) {
478
- const model = this._sessionModels.get(sessionId);
479
- if (!model) {
480
- throw new Error(`Unknown session: ${sessionId}`);
481
- }
482
- await model.waitForInitialization();
483
- const provider = this._providers.get(model.providerId);
484
- if (!provider) {
485
- throw new Error(`Unknown provider: ${model.providerId}`);
486
- }
487
- model.removeRequest(requestId);
488
- }
489
- async sendRequestToProvider(sessionId, message) {
490
- this.trace('sendRequestToProvider', `sessionId: ${sessionId}`);
491
- return await this.sendRequest(sessionId, message.message);
492
- }
493
- getProviders() {
494
- return Array.from(( this._providers.keys()));
495
- }
496
- async addCompleteRequest(sessionId, message, variableData, response) {
497
- this.trace('addCompleteRequest', `message: ${message}`);
498
- const model = this._sessionModels.get(sessionId);
499
- if (!model) {
500
- throw new Error(`Unknown session: ${sessionId}`);
501
- }
502
- await model.waitForInitialization();
503
- const parsedRequest = typeof message === 'string' ?
504
- this.instantiationService.createInstance(ChatRequestParser).parseChatRequest(sessionId, message) :
505
- message;
506
- const request = model.addRequest(parsedRequest, variableData || { variables: [] });
507
- if (typeof response.message === 'string') {
508
- model.acceptResponseProgress(request, { content: response.message, kind: 'content' });
509
- }
510
- else {
511
- for (const part of response.message) {
512
- model.acceptResponseProgress(request, part, true);
513
- }
514
- }
515
- model.setResponse(request, response.result || {});
516
- if (response.followups !== undefined) {
517
- model.setFollowups(request, response.followups);
518
- }
519
- model.completeResponse(request);
520
- }
521
- cancelCurrentRequestForSession(sessionId) {
522
- this.trace('cancelCurrentRequestForSession', `sessionId: ${sessionId}`);
523
- this._pendingRequests.get(sessionId)?.cancel();
524
- this._pendingRequests.deleteAndDispose(sessionId);
525
- }
526
- clearSession(sessionId) {
527
- this.trace('clearSession', `sessionId: ${sessionId}`);
528
- const model = this._sessionModels.get(sessionId);
529
- if (!model) {
530
- throw new Error(`Unknown session: ${sessionId}`);
531
- }
532
- this._persistedSessions[sessionId] = model.toJSON();
533
- this._sessionModels.deleteAndDispose(sessionId);
534
- this._pendingRequests.get(sessionId)?.cancel();
535
- this._pendingRequests.deleteAndDispose(sessionId);
536
- this._onDidDisposeSession.fire({ sessionId, providerId: model.providerId, reason: 'cleared' });
537
- }
538
- registerProvider(provider) {
539
- this.trace('registerProvider', `Adding new chat provider`);
540
- if (( this._providers.has(provider.id))) {
541
- throw new Error(`Provider ${provider.id} already registered`);
542
- }
543
- this._providers.set(provider.id, provider);
544
- this._hasProvider.set(true);
545
- this._onDidRegisterProvider.fire({ providerId: provider.id });
546
- Array.from(( this._sessionModels.values()))
547
- .filter(model => model.providerId === provider.id)
548
- .filter(model => model.initState === ChatModelInitState.Created)
549
- .forEach(model => this.reinitializeModel(model));
550
- return toDisposable(() => {
551
- this.trace('registerProvider', `Disposing chat provider`);
552
- this._providers.delete(provider.id);
553
- this._hasProvider.set(this._providers.size > 0);
554
- Array.from(( this._sessionModels.values()))
555
- .filter(model => model.providerId === provider.id)
556
- .forEach(model => model.deinitialize());
557
- this._onDidUnregisterProvider.fire({ providerId: provider.id });
558
- });
559
- }
560
- hasSessions(providerId) {
561
- return !!( Object.values(this._persistedSessions)).find((session) => session.providerId === providerId);
562
- }
563
- getProviderInfos() {
564
- return ( Array.from(( this._providers.values())).map(provider => {
565
- return {
566
- id: provider.id,
567
- };
568
- }));
569
- }
570
- transferChatSession(transferredSessionData, toWorkspace) {
571
- const model = Iterable.find(( this._sessionModels.values()), model => model.sessionId === transferredSessionData.sessionId);
572
- if (!model) {
573
- throw new Error(`Failed to transfer session. Unknown session ID: ${transferredSessionData.sessionId}`);
574
- }
575
- const existingRaw = this.storageService.getObject(globalChatKey, 0 , []);
576
- existingRaw.push({
577
- chat: model.toJSON(),
578
- timestampInMilliseconds: Date.now(),
579
- toWorkspace: toWorkspace,
580
- inputValue: transferredSessionData.inputValue,
581
- });
582
- this.storageService.store(globalChatKey, JSON.stringify(existingRaw), 0 , 1 );
583
- this.trace('transferChatSession', `Transferred session ${model.sessionId} to workspace ${( toWorkspace.toString())}`);
584
- }
585
- };
586
- ChatService = ( __decorate([
587
- ( __param(0, IStorageService)),
588
- ( __param(1, ILogService)),
589
- ( __param(2, IExtensionService)),
590
- ( __param(3, IInstantiationService)),
591
- ( __param(4, ITelemetryService)),
592
- ( __param(5, IContextKeyService)),
593
- ( __param(6, IWorkspaceContextService)),
594
- ( __param(7, IChatSlashCommandService)),
595
- ( __param(8, IChatVariablesService)),
596
- ( __param(9, IChatAgentService)),
597
- ( __param(10, INotificationService)),
598
- ( __param(11, ICommandService))
599
- ], ChatService));
600
-
601
- export { ChatService };
@@ -1,43 +0,0 @@
1
- import { registerEditorContribution } from 'vscode/vscode/vs/editor/browser/editorExtensions';
2
- import { registerAction2 } from 'vscode/vscode/vs/platform/actions/common/actions';
3
- import { InlineChatController } from 'vscode/vscode/vs/workbench/contrib/inlineChat/browser/inlineChatController';
4
- import { InlineAccessibilityHelpContribution, StartSessionAction, CloseAction, ConfigureInlineChatAction, UnstashSessionAction, MakeRequestAction, StopRequestAction, ReRunRequestAction, DiscardHunkAction, DiscardAction, DiscardToClipboardAction, DiscardUndoToNewFileAction, CancelSessionAction, MoveToNextHunk, MoveToPreviousHunk, ArrowOutUpAction, ArrowOutDownAction, FocusInlineChat, PreviousFromHistory, NextFromHistory, ViewInChatAction, ExpandMessageAction, ContractMessageAction, ToggleDiffForChange, FeebackHelpfulCommand, FeebackUnhelpfulCommand, ReportIssueForBugCommand, AcceptChanges, CopyRecordings } from './inlineChatActions.js';
5
- import { INLINE_CHAT_ID, INTERACTIVE_EDITOR_ACCESSIBILITY_HELP_ID } from 'vscode/vscode/vs/workbench/contrib/inlineChat/common/inlineChat';
6
- import { Registry } from 'vscode/vscode/vs/platform/registry/common/platform';
7
- import { InlineChatNotebookContribution } from './inlineChatNotebook.js';
8
- import { Extensions } from 'vscode/vscode/vs/workbench/common/contributions';
9
- import { InlineChatAccessibleViewContribution } from './inlineChatAccessibleView.js';
10
-
11
- registerEditorContribution(INLINE_CHAT_ID, InlineChatController, 0 );
12
- registerEditorContribution(INTERACTIVE_EDITOR_ACCESSIBILITY_HELP_ID, InlineAccessibilityHelpContribution, 3 );
13
- registerAction2(StartSessionAction);
14
- registerAction2(CloseAction);
15
- registerAction2(ConfigureInlineChatAction);
16
- registerAction2(UnstashSessionAction);
17
- registerAction2(MakeRequestAction);
18
- registerAction2(StopRequestAction);
19
- registerAction2(ReRunRequestAction);
20
- registerAction2(DiscardHunkAction);
21
- registerAction2(DiscardAction);
22
- registerAction2(DiscardToClipboardAction);
23
- registerAction2(DiscardUndoToNewFileAction);
24
- registerAction2(CancelSessionAction);
25
- registerAction2(MoveToNextHunk);
26
- registerAction2(MoveToPreviousHunk);
27
- registerAction2(ArrowOutUpAction);
28
- registerAction2(ArrowOutDownAction);
29
- registerAction2(FocusInlineChat);
30
- registerAction2(PreviousFromHistory);
31
- registerAction2(NextFromHistory);
32
- registerAction2(ViewInChatAction);
33
- registerAction2(ExpandMessageAction);
34
- registerAction2(ContractMessageAction);
35
- registerAction2(ToggleDiffForChange);
36
- registerAction2(FeebackHelpfulCommand);
37
- registerAction2(FeebackUnhelpfulCommand);
38
- registerAction2(ReportIssueForBugCommand);
39
- registerAction2(AcceptChanges);
40
- registerAction2(CopyRecordings);
41
- const workbenchContributionsRegistry = ( Registry.as(Extensions.Workbench));
42
- workbenchContributionsRegistry.registerWorkbenchContribution(InlineChatNotebookContribution, 3 );
43
- workbenchContributionsRegistry.registerWorkbenchContribution(InlineChatAccessibleViewContribution, 4 );