-
Notifications
You must be signed in to change notification settings - Fork 38.3k
Expand file tree
/
Copy pathchatServiceImpl.ts
More file actions
1562 lines (1349 loc) · 65.4 KB
/
chatServiceImpl.ts
File metadata and controls
1562 lines (1349 loc) · 65.4 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { DeferredPromise } from '../../../../../base/common/async.js';
import { CancellationToken, CancellationTokenSource } from '../../../../../base/common/cancellation.js';
import { toErrorMessage } from '../../../../../base/common/errorMessage.js';
import { BugIndicatingError, ErrorNoTelemetry } from '../../../../../base/common/errors.js';
import { Emitter, Event } from '../../../../../base/common/event.js';
import { MarkdownString } from '../../../../../base/common/htmlContent.js';
import { Iterable } from '../../../../../base/common/iterator.js';
import { Disposable, DisposableResourceMap, DisposableStore, IDisposable, MutableDisposable } from '../../../../../base/common/lifecycle.js';
import { revive } from '../../../../../base/common/marshalling.js';
import { Schemas } from '../../../../../base/common/network.js';
import { autorun, derived, IObservable, ISettableObservable, observableValue } from '../../../../../base/common/observable.js';
import { isEqual } from '../../../../../base/common/resources.js';
import { StopWatch } from '../../../../../base/common/stopwatch.js';
import { isDefined } from '../../../../../base/common/types.js';
import { URI } from '../../../../../base/common/uri.js';
import { generateUuid } from '../../../../../base/common/uuid.js';
import { OffsetRange } from '../../../../../editor/common/core/ranges/offsetRange.js';
import { localize } from '../../../../../nls.js';
import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js';
import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js';
import { ILogService } from '../../../../../platform/log/common/log.js';
import { Progress } from '../../../../../platform/progress/common/progress.js';
import { IStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js';
import { ITelemetryService } from '../../../../../platform/telemetry/common/telemetry.js';
import { IWorkspaceContextService } from '../../../../../platform/workspace/common/workspace.js';
import { IExtensionService } from '../../../../services/extensions/common/extensions.js';
import { IChatEntitlementService } from '../../../../services/chat/common/chatEntitlementService.js';
import { IChatDebugService } from '../chatDebugService.js';
import { InlineChatConfigKeys } from '../../../inlineChat/common/inlineChat.js';
import { IMcpService } from '../../../mcp/common/mcpTypes.js';
import { awaitStatsForSession } from '../chat.js';
import { IChatAgentCommand, IChatAgentData, IChatAgentHistoryEntry, IChatAgentRequest, IChatAgentResult, IChatAgentService } from '../participants/chatAgents.js';
import { chatEditingSessionIsReady } from '../editing/chatEditingService.js';
import { ChatModel, ChatRequestModel, ChatRequestRemovalReason, IChatModel, IChatRequestModel, IChatRequestVariableData, IChatResponseModel, IExportableChatData, ISerializableChatData, ISerializableChatDataIn, ISerializableChatsData, ISerializedChatDataReference, normalizeSerializableChatData, toChatHistoryContent, updateRanges } from '../model/chatModel.js';
import { ChatModelStore, IStartSessionProps } from '../model/chatModelStore.js';
import { chatAgentLeader, ChatRequestAgentPart, ChatRequestAgentSubcommandPart, ChatRequestSlashCommandPart, ChatRequestTextPart, chatSubcommandLeader, getPromptText, IParsedChatRequest } from '../requestParser/chatParserTypes.js';
import { ChatRequestParser } from '../requestParser/chatRequestParser.js';
import { ChatMcpServersStarting, ChatPendingRequestChangeClassification, ChatPendingRequestChangeEvent, ChatPendingRequestChangeEventName, ChatRequestQueueKind, ChatSendResult, ChatSendResultQueued, ChatStopCancellationNoopClassification, ChatStopCancellationNoopEvent, ChatStopCancellationNoopEventName, IChatCompleteResponse, IChatDetail, IChatFollowup, IChatModelReference, IChatProgress, IChatSendRequestOptions, IChatSendRequestResponseState, IChatService, IChatSessionContext, IChatSessionStartOptions, IChatUserActionEvent, ResponseModelState } from './chatService.js';
import { ChatRequestTelemetry, ChatServiceTelemetry } from './chatServiceTelemetry.js';
import { IChatSessionsService } from '../chatSessionsService.js';
import { ChatSessionStore, IChatSessionEntryMetadata } from '../model/chatSessionStore.js';
import { IChatSlashCommandService } from '../participants/chatSlashCommands.js';
import { IChatTransferService } from '../model/chatTransferService.js';
import { LocalChatSessionUri } from '../model/chatUri.js';
import { IChatRequestVariableEntry } from '../attachments/chatVariableEntries.js';
import { ChatAgentLocation, ChatModeKind } from '../constants.js';
import { ChatMessageRole, IChatMessage, ILanguageModelsService } from '../languageModels.js';
import { ILanguageModelToolsService } from '../tools/languageModelToolsService.js';
import { ChatSessionOperationLog } from '../model/chatSessionOperationLog.js';
import { IPromptsService } from '../promptSyntax/service/promptsService.js';
import { ChatRequestHooks, mergeHooks } from '../promptSyntax/hookSchema.js';
const serializedChatKey = 'interactive.sessions';
class CancellableRequest implements IDisposable {
private readonly _yieldRequested: ISettableObservable<boolean> = observableValue(this, false);
get yieldRequested(): IObservable<boolean> {
return this._yieldRequested;
}
constructor(
public readonly cancellationTokenSource: CancellationTokenSource,
public requestId: string | undefined,
@ILanguageModelToolsService private readonly toolsService: ILanguageModelToolsService
) { }
dispose() {
if (this.requestId) {
this.toolsService.cancelToolCallsForRequest(this.requestId);
}
this.cancellationTokenSource.dispose();
}
cancel() {
if (this.requestId) {
this.toolsService.cancelToolCallsForRequest(this.requestId);
}
this.cancellationTokenSource.cancel();
}
setYieldRequested(): void {
this._yieldRequested.set(true, undefined);
}
resetYieldRequested(): void {
this._yieldRequested.set(false, undefined);
}
}
export class ChatService extends Disposable implements IChatService {
declare _serviceBrand: undefined;
private readonly _sessionModels: ChatModelStore;
private readonly _pendingRequests = this._register(new DisposableResourceMap<CancellableRequest>());
private readonly _queuedRequestDeferreds = new Map<string, DeferredPromise<ChatSendResult>>();
private _saveModelsEnabled = true;
private _transferredSessionResource: URI | undefined;
public get transferredSessionResource(): URI | undefined {
return this._transferredSessionResource;
}
private readonly _onDidSubmitRequest = this._register(new Emitter<{ readonly chatSessionResource: URI; readonly message?: IParsedChatRequest }>());
public readonly onDidSubmitRequest = this._onDidSubmitRequest.event;
public get onDidCreateModel() { return this._sessionModels.onDidCreateModel; }
private readonly _onDidPerformUserAction = this._register(new Emitter<IChatUserActionEvent>());
public readonly onDidPerformUserAction: Event<IChatUserActionEvent> = this._onDidPerformUserAction.event;
private readonly _onDidReceiveQuestionCarouselAnswer = this._register(new Emitter<{ requestId: string; resolveId: string; answers: Record<string, unknown> | undefined }>());
public readonly onDidReceiveQuestionCarouselAnswer = this._onDidReceiveQuestionCarouselAnswer.event;
private readonly _onDidDisposeSession = this._register(new Emitter<{ readonly sessionResource: URI[]; reason: 'cleared' }>());
public readonly onDidDisposeSession = this._onDidDisposeSession.event;
private readonly _sessionFollowupCancelTokens = this._register(new DisposableResourceMap<CancellationTokenSource>());
private readonly _chatServiceTelemetry: ChatServiceTelemetry;
private readonly _chatSessionStore: ChatSessionStore;
readonly requestInProgressObs: IObservable<boolean>;
readonly chatModels: IObservable<Iterable<IChatModel>>;
/**
* For test use only
*/
setSaveModelsEnabled(enabled: boolean): void {
this._saveModelsEnabled = enabled;
}
/**
* For test use only
*/
waitForModelDisposals(): Promise<void> {
return this._sessionModels.waitForModelDisposals();
}
private get isEmptyWindow(): boolean {
const workspace = this.workspaceContextService.getWorkspace();
return !workspace.configuration && workspace.folders.length === 0;
}
constructor(
@IStorageService private readonly storageService: IStorageService,
@ILogService private readonly logService: ILogService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IExtensionService private readonly extensionService: IExtensionService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IWorkspaceContextService private readonly workspaceContextService: IWorkspaceContextService,
@IChatSlashCommandService private readonly chatSlashCommandService: IChatSlashCommandService,
@IChatAgentService private readonly chatAgentService: IChatAgentService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@IChatTransferService private readonly chatTransferService: IChatTransferService,
@IChatSessionsService private readonly chatSessionService: IChatSessionsService,
@IMcpService private readonly mcpService: IMcpService,
@IPromptsService private readonly promptsService: IPromptsService,
@IChatEntitlementService private readonly chatEntitlementService: IChatEntitlementService,
@ILanguageModelsService private readonly languageModelsService: ILanguageModelsService,
@IChatDebugService private readonly chatDebugService: IChatDebugService,
) {
super();
this._sessionModels = this._register(instantiationService.createInstance(ChatModelStore, {
createModel: (props: IStartSessionProps) => this._startSession(props),
willDisposeModel: async (model: ChatModel) => {
const localSessionId = LocalChatSessionUri.parseLocalSessionId(model.sessionResource);
if (localSessionId && this.shouldStoreSession(model)) {
// Always preserve sessions that have custom titles, even if empty
if (model.getRequests().length === 0 && !model.customTitle) {
await this._chatSessionStore.deleteSession(localSessionId);
} else if (this._saveModelsEnabled) {
await this._chatSessionStore.storeSessions([model]);
}
} else if (!localSessionId && model.getRequests().length > 0) {
await this._chatSessionStore.storeSessionsMetadataOnly([model]);
}
}
}));
this._register(this._sessionModels.onDidDisposeModel(model => {
this.chatDebugService.endSession(model.sessionResource);
this._onDidDisposeSession.fire({ sessionResource: [model.sessionResource], reason: 'cleared' });
}));
this._chatServiceTelemetry = this.instantiationService.createInstance(ChatServiceTelemetry);
this._chatSessionStore = this._register(this.instantiationService.createInstance(ChatSessionStore));
this._chatSessionStore.migrateDataIfNeeded(() => this.migrateData());
const transferredData = this._chatSessionStore.getTransferredSessionData();
if (transferredData) {
this.trace('constructor', `Transferred session ${transferredData}`);
this._transferredSessionResource = transferredData;
}
this.reviveSessionsWithEdits();
this._register(storageService.onWillSaveState(() => this.saveState()));
this.chatModels = derived(this, reader => [...this._sessionModels.observable.read(reader).values()]);
this.requestInProgressObs = derived(reader => {
const models = this._sessionModels.observable.read(reader).values();
return Iterable.some(models, model => model.requestInProgress.read(reader));
});
}
public get editingSessions() {
return [...this._sessionModels.values()].map(v => v.editingSession).filter(isDefined);
}
isEnabled(location: ChatAgentLocation): boolean {
return this.chatAgentService.getContributedDefaultAgent(location) !== undefined;
}
private migrateData(): ISerializableChatsData | undefined {
const sessionData = this.storageService.get(serializedChatKey, this.isEmptyWindow ? StorageScope.APPLICATION : StorageScope.WORKSPACE, '');
if (sessionData) {
const persistedSessions = this.deserializeChats(sessionData);
const countsForLog = Object.keys(persistedSessions).length;
if (countsForLog > 0) {
this.info('migrateData', `Restored ${countsForLog} persisted sessions`);
}
return persistedSessions;
}
return;
}
private saveState(): void {
if (!this._saveModelsEnabled) {
return;
}
const liveLocalChats = Array.from(this._sessionModels.values())
.filter(session => this.shouldStoreSession(session));
this._chatSessionStore.storeSessions(liveLocalChats);
const liveNonLocalChats = Array.from(this._sessionModels.values())
.filter(session => !LocalChatSessionUri.parseLocalSessionId(session.sessionResource));
this._chatSessionStore.storeSessionsMetadataOnly(liveNonLocalChats);
}
/**
* Only persist local sessions from chat that are not imported.
*/
private shouldStoreSession(session: ChatModel): boolean {
if (!LocalChatSessionUri.parseLocalSessionId(session.sessionResource)) {
return false;
}
return session.initialLocation === ChatAgentLocation.Chat && !session.isImported;
}
notifyUserAction(action: IChatUserActionEvent): void {
this._chatServiceTelemetry.notifyUserAction(action);
this._onDidPerformUserAction.fire(action);
if (action.action.kind === 'chatEditingSessionAction') {
const model = this._sessionModels.get(action.sessionResource);
if (model) {
model.notifyEditingAction(action.action);
}
}
}
notifyQuestionCarouselAnswer(requestId: string, resolveId: string, answers: Record<string, unknown> | undefined): void {
this._onDidReceiveQuestionCarouselAnswer.fire({ requestId, resolveId, answers });
}
async setChatSessionTitle(sessionResource: URI, title: string): Promise<void> {
const model = this._sessionModels.get(sessionResource);
if (model) {
model.setCustomTitle(title);
}
// Update the title in the file storage
const localSessionId = LocalChatSessionUri.parseLocalSessionId(sessionResource);
if (localSessionId) {
await this._chatSessionStore.setSessionTitle(localSessionId, title);
// Trigger immediate save to ensure consistency
this.saveState();
}
}
private trace(method: string, message?: string): void {
if (message) {
this.logService.trace(`ChatService#${method}: ${message}`);
} else {
this.logService.trace(`ChatService#${method}`);
}
}
private info(method: string, message?: string): void {
if (message) {
this.logService.info(`ChatService#${method}: ${message}`);
} else {
this.logService.info(`ChatService#${method}`);
}
}
private error(method: string, message: string): void {
this.logService.error(`ChatService#${method} ${message}`);
}
private deserializeChats(sessionData: string): ISerializableChatsData {
try {
const arrayOfSessions: ISerializableChatDataIn[] = revive(JSON.parse(sessionData)); // Revive serialized URIs in session data
if (!Array.isArray(arrayOfSessions)) {
throw new Error('Expected array');
}
const sessions = arrayOfSessions.reduce<ISerializableChatsData>((acc, session) => {
// Revive serialized markdown strings in response data
for (const request of session.requests) {
if (Array.isArray(request.response)) {
request.response = request.response.map((response) => {
if (typeof response === 'string') {
return new MarkdownString(response);
}
return response;
});
} else if (typeof request.response === 'string') {
request.response = [new MarkdownString(request.response)];
}
}
acc[session.sessionId] = normalizeSerializableChatData(session);
return acc;
}, {});
return sessions;
} catch (err) {
this.error('deserializeChats', `Malformed session data: ${err}. [${sessionData.substring(0, 20)}${sessionData.length > 20 ? '...' : ''}]`);
return {};
}
}
/**
* todo@connor4312 This will be cleaned up with the globalization of edits.
*/
private async reviveSessionsWithEdits(): Promise<void> {
const idx = await this._chatSessionStore.getIndex();
await Promise.all(Object.values(idx).map(async session => {
if (!session.hasPendingEdits) {
return;
}
let sessionResource: URI;
// Non-local sessions store the full uri as the sessionId, so try parsing that first
if (session.sessionId.includes(':')) {
try {
sessionResource = URI.parse(session.sessionId, true);
} catch {
// Noop
}
}
sessionResource ??= LocalChatSessionUri.forSession(session.sessionId);
const sessionRef = await this.acquireOrLoadSession(sessionResource, ChatAgentLocation.Chat, CancellationToken.None);
if (sessionRef?.object.editingSession) {
await chatEditingSessionIsReady(sessionRef.object.editingSession);
// the session will hold a self-reference as long as there are modified files
sessionRef.dispose();
}
}));
}
/**
* Returns an array of chat details for all persisted chat sessions that have at least one request.
* Chat sessions that have already been loaded into the chat view are excluded from the result.
* Imported chat sessions are also excluded from the result.
* TODO this is only used by the old "show chats" command which can be removed when the pre-agents view
* options are removed.
*/
async getLocalSessionHistory(): Promise<IChatDetail[]> {
const liveSessionItems = await this.getLiveSessionItems();
const historySessionItems = await this.getHistorySessionItems();
return [...liveSessionItems, ...historySessionItems];
}
/**
* Returns an array of chat details for all local live chat sessions.
*/
async getLiveSessionItems(): Promise<IChatDetail[]> {
return await Promise.all(Array.from(this._sessionModels.values())
.filter(session => this.shouldBeInHistory(session))
.map(async (session): Promise<IChatDetail> => {
const title = session.title || localize('newChat', "New Chat");
return {
sessionResource: session.sessionResource,
title,
lastMessageDate: session.lastMessageDate,
timing: session.timing,
isActive: true,
stats: await awaitStatsForSession(session),
lastResponseState: session.lastRequest?.response?.state ?? ResponseModelState.Pending,
};
}));
}
/**
* Returns an array of chat details for all local chat sessions in history (not currently loaded).
*/
async getHistorySessionItems(): Promise<IChatDetail[]> {
const index = await this._chatSessionStore.getIndex();
return Object.values(index)
.filter(entry => !entry.isExternal)
.filter(entry => !this._sessionModels.has(LocalChatSessionUri.forSession(entry.sessionId)) && entry.initialLocation === ChatAgentLocation.Chat && !entry.isEmpty)
.map((entry): IChatDetail => {
const sessionResource = LocalChatSessionUri.forSession(entry.sessionId);
return ({
...entry,
sessionResource,
isActive: this._sessionModels.has(sessionResource),
});
});
}
async getMetadataForSession(sessionResource: URI): Promise<IChatDetail | undefined> {
const index = await this._chatSessionStore.getIndex();
const metadata: IChatSessionEntryMetadata | undefined = index[sessionResource.toString()];
if (metadata) {
return {
...metadata,
sessionResource,
isActive: this._sessionModels.has(sessionResource),
};
}
return undefined;
}
private shouldBeInHistory(entry: ChatModel): boolean {
return !entry.isImported && !!LocalChatSessionUri.parseLocalSessionId(entry.sessionResource) && entry.initialLocation === ChatAgentLocation.Chat;
}
async removeHistoryEntry(sessionResource: URI): Promise<void> {
await this._chatSessionStore.deleteSession(this.toLocalSessionId(sessionResource));
this._onDidDisposeSession.fire({ sessionResource: [sessionResource], reason: 'cleared' });
}
async clearAllHistoryEntries(): Promise<void> {
await this._chatSessionStore.clearAllSessions();
}
startNewLocalSession(location: ChatAgentLocation, options?: IChatSessionStartOptions): IChatModelReference {
this.trace('startNewLocalSession');
const sessionResource = LocalChatSessionUri.forSession(generateUuid());
return this._sessionModels.acquireOrCreate({
initialData: undefined,
location,
sessionResource,
canUseTools: options?.canUseTools ?? true,
disableBackgroundKeepAlive: options?.disableBackgroundKeepAlive
});
}
private _startSession(props: IStartSessionProps): ChatModel {
const { initialData, location, sessionResource, canUseTools, transferEditingSession, disableBackgroundKeepAlive, inputState } = props;
const model = this.instantiationService.createInstance(ChatModel, initialData, { initialLocation: location, canUseTools, resource: sessionResource, disableBackgroundKeepAlive, inputState });
if (location === ChatAgentLocation.Chat) {
model.startEditingSession(true, transferEditingSession);
}
this.initializeSession(model);
return model;
}
private initializeSession(model: ChatModel): void {
this.trace('initializeSession', `Initialize session ${model.sessionResource}`);
// Activate the default extension provided agent but do not wait
// for it to be ready so that the session can be used immediately
// without having to wait for the agent to be ready.
this.activateDefaultAgent(model.initialLocation).catch(e => this.logService.error(e));
}
async activateDefaultAgent(location: ChatAgentLocation): Promise<void> {
await this.extensionService.whenInstalledExtensionsRegistered();
const defaultAgentData = this.chatAgentService.getContributedDefaultAgent(location) ?? this.chatAgentService.getContributedDefaultAgent(ChatAgentLocation.Chat);
if (!defaultAgentData) {
throw new ErrorNoTelemetry('No default agent contributed');
}
// Await activation of the extension provided agent
// Using `activateById` as workaround for the issue
// https://github.com/microsoft/vscode/issues/250590
if (!defaultAgentData.isCore) {
await this.extensionService.activateById(defaultAgentData.extensionId, {
activationEvent: `onChatParticipant:${defaultAgentData.id}`,
extensionId: defaultAgentData.extensionId,
startup: false
});
}
const defaultAgent = this.chatAgentService.getActivatedAgents().find(agent => agent.id === defaultAgentData.id);
if (!defaultAgent) {
throw new ErrorNoTelemetry('No default agent registered');
}
}
getSession(sessionResource: URI): IChatModel | undefined {
return this._sessionModels.get(sessionResource);
}
acquireExistingSession(sessionResource: URI): IChatModelReference | undefined {
return this._sessionModels.acquireExisting(sessionResource);
}
private async acquireOrRestoreLocalSession(sessionResource: URI): Promise<IChatModelReference | undefined> {
this.trace('acquireOrRestoreSession', `${sessionResource}`);
const existingRef = this.acquireExistingSession(sessionResource);
if (existingRef) {
return existingRef;
}
let sessionData: ISerializedChatDataReference | undefined;
if (isEqual(this.transferredSessionResource, sessionResource)) {
this._transferredSessionResource = undefined;
sessionData = await this._chatSessionStore.readTransferredSession(sessionResource);
} else {
const localSessionId = LocalChatSessionUri.parseLocalSessionId(sessionResource);
if (localSessionId) {
sessionData = await this._chatSessionStore.readSession(localSessionId);
}
}
if (!sessionData) {
return undefined;
}
const sessionRef = this._sessionModels.acquireOrCreate({
initialData: sessionData,
location: sessionData.value.initialLocation ?? ChatAgentLocation.Chat,
sessionResource,
canUseTools: true,
});
return sessionRef;
}
// There are some cases where this returns a real string. What happens if it doesn't?
// This had titles restored from the index, so just return titles from index instead, sync.
getSessionTitle(sessionResource: URI): string | undefined {
const sessionId = LocalChatSessionUri.parseLocalSessionId(sessionResource);
if (!sessionId) {
return undefined;
}
return this._sessionModels.get(sessionResource)?.title ??
this._chatSessionStore.getMetadataForSessionSync(sessionResource)?.title;
}
loadSessionFromData(data: IExportableChatData | ISerializableChatData): IChatModelReference {
const sessionId = (data as ISerializableChatData).sessionId ?? generateUuid();
const sessionResource = LocalChatSessionUri.forSession(sessionId);
return this._sessionModels.acquireOrCreate({
initialData: { value: data, serializer: new ChatSessionOperationLog() },
location: data.initialLocation ?? ChatAgentLocation.Chat,
sessionResource,
canUseTools: true,
});
}
async acquireOrLoadSession(sessionResource: URI, location: ChatAgentLocation, token: CancellationToken): Promise<IChatModelReference | undefined> {
if (sessionResource.scheme === Schemas.vscodeLocalChatSession) {
return this.acquireOrRestoreLocalSession(sessionResource);
} else {
return this.loadRemoteSession(sessionResource, location, token);
}
}
private async loadRemoteSession(sessionResource: URI, location: ChatAgentLocation, token: CancellationToken): Promise<IChatModelReference | undefined> {
await this.chatSessionService.canResolveChatSession(sessionResource);
// Check if session already exists
{
const existingRef = this.acquireExistingSession(sessionResource);
if (existingRef) {
return existingRef;
}
}
const providedSession = await this.chatSessionService.getOrCreateChatSession(sessionResource, token);
// Make sure we haven't created this in the meantime
{
const existingRef = this.acquireExistingSession(sessionResource);
if (existingRef) {
providedSession.dispose();
return existingRef;
}
}
const chatSessionType = sessionResource.scheme;
// Contributed sessions do not use UI tools
const modelRef = this._sessionModels.acquireOrCreate({
initialData: undefined,
location,
sessionResource: sessionResource,
canUseTools: false,
transferEditingSession: providedSession.transferredState?.editingSession,
inputState: providedSession.transferredState?.inputState,
});
modelRef.object.setContributedChatSession({
chatSessionResource: sessionResource,
chatSessionType,
isUntitled: sessionResource.path.startsWith('/untitled-') //TODO(jospicer)
});
if (providedSession.title) {
modelRef.object.setCustomTitle(providedSession.title);
}
const model = modelRef.object;
const disposables = new DisposableStore();
disposables.add(modelRef.object.onDidDispose(() => {
disposables.dispose();
providedSession.dispose();
}));
let lastRequest: ChatRequestModel | undefined;
for (const message of providedSession.history) {
if (message.type === 'request') {
if (lastRequest) {
lastRequest.response?.complete();
}
const requestText = message.prompt;
const parsedRequest: IParsedChatRequest = {
text: requestText,
parts: [new ChatRequestTextPart(
new OffsetRange(0, requestText.length),
{ startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: requestText.length + 1 },
requestText
)]
};
const agent =
message.participant
? this.chatAgentService.getAgent(message.participant) // TODO(jospicer): Remove and always hardcode?
: this.chatAgentService.getAgent(chatSessionType);
lastRequest = model.addRequest(parsedRequest,
message.variableData ?? { variables: [] },
0, // attempt
undefined,
agent,
undefined, // slashCommand
undefined, // confirmation
undefined, // locationData
undefined, // attachments
false, // Do not treat as requests completed, else edit pills won't show.
message.modelId,
undefined,
message.id
);
} else {
// response
if (lastRequest) {
for (const part of message.parts) {
model.acceptResponseProgress(lastRequest, part);
}
}
}
}
if (providedSession.isCompleteObs?.get()) {
lastRequest?.response?.complete();
}
if (providedSession.progressObs && lastRequest && providedSession.interruptActiveResponseCallback) {
const initialCancellationRequest = this.instantiationService.createInstance(CancellableRequest, new CancellationTokenSource(), undefined);
this._pendingRequests.set(model.sessionResource, initialCancellationRequest);
this.telemetryService.publicLog2<ChatPendingRequestChangeEvent, ChatPendingRequestChangeClassification>(ChatPendingRequestChangeEventName, { action: 'add', source: 'remoteSession' });
const cancellationListener = disposables.add(new MutableDisposable());
const createCancellationListener = (token: CancellationToken) => {
return token.onCancellationRequested(() => {
providedSession.interruptActiveResponseCallback?.().then(userConfirmedInterruption => {
if (!userConfirmedInterruption) {
// User cancelled the interruption
const newCancellationRequest = this.instantiationService.createInstance(CancellableRequest, new CancellationTokenSource(), undefined);
this._pendingRequests.set(model.sessionResource, newCancellationRequest);
this.telemetryService.publicLog2<ChatPendingRequestChangeEvent, ChatPendingRequestChangeClassification>(ChatPendingRequestChangeEventName, { action: 'add', source: 'remoteSession' });
cancellationListener.value = createCancellationListener(newCancellationRequest.cancellationTokenSource.token);
}
});
});
};
cancellationListener.value = createCancellationListener(initialCancellationRequest.cancellationTokenSource.token);
let lastProgressLength = 0;
disposables.add(autorun(reader => {
const progressArray = providedSession.progressObs?.read(reader) ?? [];
const isComplete = providedSession.isCompleteObs?.read(reader) ?? false;
// Process only new progress items
if (progressArray.length > lastProgressLength) {
const newProgress = progressArray.slice(lastProgressLength);
for (const progress of newProgress) {
model?.acceptResponseProgress(lastRequest, progress);
}
lastProgressLength = progressArray.length;
}
// Handle completion
if (isComplete) {
lastRequest.response?.complete();
cancellationListener.clear();
}
}));
} else {
this.telemetryService.publicLog2<ChatPendingRequestChangeEvent, ChatPendingRequestChangeClassification>(ChatPendingRequestChangeEventName, { action: 'notCancelable', source: 'remoteSession' });
if (lastRequest && model.editingSession) {
// wait for timeline to load so that a 'changes' part is added when the response completes
await chatEditingSessionIsReady(model.editingSession);
lastRequest.response?.complete();
}
}
return modelRef;
}
getChatSessionFromInternalUri(sessionResource: URI): IChatSessionContext | undefined {
const model = this._sessionModels.get(sessionResource);
if (!model) {
return;
}
const { contributedChatSession } = model;
return contributedChatSession;
}
async resendRequest(request: IChatRequestModel, options?: IChatSendRequestOptions): Promise<void> {
const model = this._sessionModels.get(request.session.sessionResource);
if (!model && model !== request.session) {
throw new Error(`Unknown session: ${request.session.sessionResource}`);
}
const cts = this._pendingRequests.get(request.session.sessionResource);
if (cts) {
this.trace('resendRequest', `Session ${request.session.sessionResource} already has a pending request, cancelling...`);
cts.cancel();
}
const location = options?.location ?? model.initialLocation;
const attempt = options?.attempt ?? 0;
const enableCommandDetection = !options?.noCommandDetection;
const defaultAgent = this.chatAgentService.getDefaultAgent(location, options?.modeInfo?.kind)!;
model.removeRequest(request.id, ChatRequestRemovalReason.Resend);
const resendOptions: IChatSendRequestOptions = {
...options,
locationData: request.locationData,
attachedContext: request.attachedContext,
};
await this._sendRequestAsync(model, model.sessionResource, request.message, attempt, enableCommandDetection, defaultAgent, location, resendOptions).responseCompletePromise;
}
private queuePendingRequest(model: ChatModel, sessionResource: URI, request: string, options: IChatSendRequestOptions): ChatSendResultQueued {
const location = options.location ?? model.initialLocation;
const parsedRequest = this.parseChatRequest(sessionResource, request, location, options);
const requestModel = new ChatRequestModel({
session: model,
message: parsedRequest,
variableData: { variables: options.attachedContext ?? [] },
timestamp: Date.now(),
modeInfo: options.modeInfo,
locationData: options.locationData,
attachedContext: options.attachedContext,
modelId: options.userSelectedModelId,
userSelectedTools: options.userSelectedTools?.get(),
});
const deferred = new DeferredPromise<ChatSendResult>();
this._queuedRequestDeferreds.set(requestModel.id, deferred);
model.addPendingRequest(requestModel, options.queue ?? ChatRequestQueueKind.Queued, { ...options, queue: undefined });
if (options.queue === ChatRequestQueueKind.Steering) {
this.setYieldRequested(sessionResource);
}
this.trace('sendRequest', `Queued message for session ${sessionResource}`);
return { kind: 'queued', deferred: deferred.p };
}
async sendRequest(sessionResource: URI, request: string, options?: IChatSendRequestOptions): Promise<ChatSendResult> {
this.trace('sendRequest', `sessionResource: ${sessionResource.toString()}, message: ${request.substring(0, 20)}${request.length > 20 ? '[...]' : ''}}`);
if (!request.trim() && !options?.slashCommand && !options?.agentId && !options?.agentIdSilent) {
this.trace('sendRequest', 'Rejected empty message');
return { kind: 'rejected', reason: 'Empty message' };
}
const model = this._sessionModels.get(sessionResource);
if (!model) {
throw new Error(`Unknown session: ${sessionResource}`);
}
const hasPendingRequest = this._pendingRequests.has(sessionResource);
if (options?.queue) {
const queued = this.queuePendingRequest(model, sessionResource, request, options);
if (!options.pauseQueue) {
this.processPendingRequests(sessionResource);
}
return queued;
} else if (hasPendingRequest) {
this.trace('sendRequest', `Session ${sessionResource} already has a pending request`);
return { kind: 'rejected', reason: 'Request already in progress' };
}
const requests = model.getRequests();
for (let i = requests.length - 1; i >= 0; i -= 1) {
const request = requests[i];
if (request.shouldBeRemovedOnSend) {
if (request.shouldBeRemovedOnSend.afterUndoStop) {
request.response?.finalizeUndoState();
} else {
await this.removeRequest(sessionResource, request.id);
}
}
}
const location = options?.location ?? model.initialLocation;
const attempt = options?.attempt ?? 0;
const defaultAgent = this.chatAgentService.getDefaultAgent(location, options?.modeInfo?.kind)!;
const parsedRequest = this.parseChatRequest(sessionResource, request, location, options);
const silentAgent = options?.agentIdSilent ? this.chatAgentService.getAgent(options.agentIdSilent) : undefined;
const agent = silentAgent ?? parsedRequest.parts.find((r): r is ChatRequestAgentPart => r instanceof ChatRequestAgentPart)?.agent ?? defaultAgent;
const agentSlashCommandPart = parsedRequest.parts.find((r): r is ChatRequestAgentSubcommandPart => r instanceof ChatRequestAgentSubcommandPart);
// This method is only returning whether the request was accepted - don't block on the actual request
return {
kind: 'sent',
data: {
...this._sendRequestAsync(model, sessionResource, parsedRequest, attempt, !options?.noCommandDetection, silentAgent ?? defaultAgent, location, options),
agent,
slashCommand: agentSlashCommandPart?.command,
},
};
}
private parseChatRequest(sessionResource: URI, request: string, location: ChatAgentLocation, options: IChatSendRequestOptions | undefined): IParsedChatRequest {
let parserContext = options?.parserContext;
if (options?.agentId) {
const agent = this.chatAgentService.getAgent(options.agentId);
if (!agent) {
throw new Error(`Unknown agent: ${options.agentId}`);
}
parserContext = { selectedAgent: agent, mode: options.modeInfo?.kind };
const commandPart = options.slashCommand ? ` ${chatSubcommandLeader}${options.slashCommand}` : '';
request = `${chatAgentLeader}${agent.name}${commandPart} ${request}`;
} else if (options?.agentIdSilent && !parserContext?.forcedAgent) {
// Resolve slash commandsin the context of locked participant so its subcommands take precedence over global
// slash commands with the same name.
const silentAgent = this.chatAgentService.getAgent(options.agentIdSilent);
if (silentAgent) {
parserContext = { ...parserContext, forcedAgent: silentAgent };
}
}
const parsedRequest = this.instantiationService.createInstance(ChatRequestParser).parseChatRequest(sessionResource, request, location, parserContext);
return parsedRequest;
}
private refreshFollowupsCancellationToken(sessionResource: URI): CancellationToken {
this._sessionFollowupCancelTokens.get(sessionResource)?.cancel();
const newTokenSource = new CancellationTokenSource();
this._sessionFollowupCancelTokens.set(sessionResource, newTokenSource);
return newTokenSource.token;
}
private _sendRequestAsync(model: ChatModel, sessionResource: URI, parsedRequest: IParsedChatRequest, attempt: number, enableCommandDetection: boolean, defaultAgent: IChatAgentData, location: ChatAgentLocation, options?: IChatSendRequestOptions): IChatSendRequestResponseState {
const followupsCancelToken = this.refreshFollowupsCancellationToken(sessionResource);
let request: ChatRequestModel | undefined;
const agentPart = parsedRequest.parts.find((r): r is ChatRequestAgentPart => r instanceof ChatRequestAgentPart);
const agentSlashCommandPart = parsedRequest.parts.find((r): r is ChatRequestAgentSubcommandPart => r instanceof ChatRequestAgentSubcommandPart);
const commandPart = parsedRequest.parts.find((r): r is ChatRequestSlashCommandPart => r instanceof ChatRequestSlashCommandPart);
const requests = [...model.getRequests()];
const requestTelemetry = this.instantiationService.createInstance(ChatRequestTelemetry, {
agent: agentPart?.agent ?? defaultAgent,
agentSlashCommandPart,
commandPart,
sessionResource: model.sessionResource,
location: model.initialLocation,
options,
enableCommandDetection
});
let gotProgress = false;
const requestType = commandPart ? 'slashCommand' : 'string';
const responseCreated = new DeferredPromise<IChatResponseModel>();
let responseCreatedComplete = false;
function completeResponseCreated(): void {
if (!responseCreatedComplete && request?.response) {
responseCreated.complete(request.response);
responseCreatedComplete = true;
}
}
const store = new DisposableStore();
const source = store.add(new CancellationTokenSource());
const token = source.token;
const sendRequestInternal = async () => {
const progressCallback = (progress: IChatProgress[]) => {
if (token.isCancellationRequested) {
return;
}
gotProgress = true;
for (let i = 0; i < progress.length; i++) {
const isLast = i === progress.length - 1;
const progressItem = progress[i];
if (progressItem.kind === 'markdownContent') {
this.trace('sendRequest', `Provider returned progress for session ${model.sessionResource}, ${progressItem.content.value.length} chars`);
} else {
this.trace('sendRequest', `Provider returned progress: ${JSON.stringify(progressItem)}`);
}
if (request) {
model.acceptResponseProgress(request, progressItem, !isLast);
}
}
completeResponseCreated();
};
let detectedAgent: IChatAgentData | undefined;
let detectedCommand: IChatAgentCommand | undefined;
// Collect hooks from hook .json files
let collectedHooks: ChatRequestHooks | undefined;
let hasDisabledClaudeHooks = false;
try {
const hooksInfo = await this.promptsService.getHooks(token, model.sessionResource);
if (hooksInfo) {
collectedHooks = hooksInfo.hooks;
hasDisabledClaudeHooks = hooksInfo.hasDisabledClaudeHooks;
}
} catch (error) {
this.logService.warn('[ChatService] Failed to collect hooks:', error);
}
// Merge hooks from the selected custom agent's frontmatter (if any)
const agentName = options?.modeInfo?.modeInstructions?.name;
if (agentName) {
try {
const agents = await this.promptsService.getCustomAgents(token, model.sessionResource);
const customAgent = agents.find(a => a.name === agentName);
if (customAgent?.hooks) {
collectedHooks = mergeHooks(collectedHooks, customAgent.hooks);
}
} catch (error) {
this.logService.warn('[ChatService] Failed to collect agent hooks:', error);
}
}
const stopWatch = new StopWatch(false);
store.add(token.onCancellationRequested(() => {
this.trace('sendRequest', `Request for session ${model.sessionResource} was cancelled`);
if (!request) {
return;
}
requestTelemetry.complete({
timeToFirstProgress: undefined,
result: 'cancelled',
// Normally timings happen inside the EH around the actual provider. For cancellation we can measure how long the user waited before cancelling
totalTime: stopWatch.elapsed(),
requestType,
detectedAgent,
request,
});
model.cancelRequest(request);
}));
try {
let rawResult: IChatAgentResult | null | undefined;
let agentOrCommandFollowups: Promise<IChatFollowup[] | undefined> | undefined = undefined;
if (agentPart || (defaultAgent && !commandPart)) {
const prepareChatAgentRequest = (agent: IChatAgentData, command?: IChatAgentCommand, enableCommandDetection?: boolean, chatRequest?: ChatRequestModel, isParticipantDetected?: boolean): IChatAgentRequest => {