This repository was archived by the owner on May 20, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathxtabProvider.ts
More file actions
1807 lines (1546 loc) · 77.2 KB
/
xtabProvider.ts
File metadata and controls
1807 lines (1546 loc) · 77.2 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 { Raw } from '@vscode/prompt-tsx';
import { createInitialFetchErrorDetector, FetchStreamSource } from '../../../platform/chat/common/chatMLFetcher';
import { ChatFetchError, ChatFetchResponseType, ChatLocation, RESPONSE_CONTAINED_NO_CHOICES } from '../../../platform/chat/common/commonTypes';
import { ConfigKey, IConfigurationService, XTabProviderId } from '../../../platform/configuration/common/configurationService';
import { IDiffService } from '../../../platform/diff/common/diffService';
import { ChatEndpoint } from '../../../platform/endpoint/node/chatEndpoint';
import { createProxyXtabEndpoint } from '../../../platform/endpoint/node/proxyXtabEndpoint';
import { IIgnoreService } from '../../../platform/ignore/common/ignoreService';
import { Copilot } from '../../../platform/inlineCompletions/common/api';
import { DocumentId } from '../../../platform/inlineEdits/common/dataTypes/documentId';
import { Edits } from '../../../platform/inlineEdits/common/dataTypes/edit';
import { LanguageContextEntry, LanguageContextResponse } from '../../../platform/inlineEdits/common/dataTypes/languageContext';
import { LanguageId } from '../../../platform/inlineEdits/common/dataTypes/languageId';
import { NextCursorLinePrediction, NextCursorLinePredictionCursorPlacement } from '../../../platform/inlineEdits/common/dataTypes/nextCursorLinePrediction';
import * as xtabPromptOptions from '../../../platform/inlineEdits/common/dataTypes/xtabPromptOptions';
import { AggressivenessSetting, isAggressivenessStrategy, LanguageContextLanguages, LanguageContextOptions } from '../../../platform/inlineEdits/common/dataTypes/xtabPromptOptions';
import { InlineEditRequestLogContext } from '../../../platform/inlineEdits/common/inlineEditLogContext';
import { IInlineEditsModelService } from '../../../platform/inlineEdits/common/inlineEditsModelService';
import { ResponseProcessor } from '../../../platform/inlineEdits/common/responseProcessor';
import { EditStreaming, EditStreamingWithTelemetry, IStatelessNextEditProvider, NoNextEditReason, RequestEditWindow, RequestEditWindowWithCursorJump, StatelessNextEditDocument, StatelessNextEditRequest, StatelessNextEditTelemetryBuilder, WithStatelessProviderTelemetry } from '../../../platform/inlineEdits/common/statelessNextEditProvider';
import { editWouldDeleteWhatWasJustInserted, editWouldDeleteWhatWasJustInserted2, IgnoreEmptyLineAndLeadingTrailingWhitespaceChanges, IgnoreWhitespaceOnlyChanges } from '../../../platform/inlineEdits/common/statelessNextEditProviders';
import { ILanguageContextProviderService, ProviderTarget } from '../../../platform/languageContextProvider/common/languageContextProviderService';
import { ILanguageDiagnosticsService } from '../../../platform/languages/common/languageDiagnosticsService';
import { ContextKind, SnippetContext } from '../../../platform/languageServer/common/languageContextService';
import { ILogger } from '../../../platform/log/common/logService';
import { OptionalChatRequestParams, Prediction } from '../../../platform/networking/common/fetch';
import { IChatEndpoint } from '../../../platform/networking/common/networking';
import { ISimulationTestContext } from '../../../platform/simulationTestContext/common/simulationTestContext';
import { IExperimentationService } from '../../../platform/telemetry/common/nullExperimentationService';
import { IWorkspaceService } from '../../../platform/workspace/common/workspaceService';
import { raceFilter } from '../../../util/common/async';
import { AsyncIterUtils, AsyncIterUtilsExt } from '../../../util/common/asyncIterableUtils';
import { ErrorUtils } from '../../../util/common/errors';
import { Result } from '../../../util/common/result';
import { assertNever } from '../../../util/vs/base/common/assert';
import { DeferredPromise, raceCancellation, raceTimeout, timeout } from '../../../util/vs/base/common/async';
import { CancellationToken } from '../../../util/vs/base/common/cancellation';
import { isAbsolute } from '../../../util/vs/base/common/path';
import { StopWatch } from '../../../util/vs/base/common/stopwatch';
import { URI } from '../../../util/vs/base/common/uri';
import { LineEdit, LineReplacement } from '../../../util/vs/editor/common/core/edits/lineEdit';
import { StringEdit } from '../../../util/vs/editor/common/core/edits/stringEdit';
import { Position } from '../../../util/vs/editor/common/core/position';
import { Range } from '../../../util/vs/editor/common/core/range';
import { LineRange } from '../../../util/vs/editor/common/core/ranges/lineRange';
import { OffsetRange } from '../../../util/vs/editor/common/core/ranges/offsetRange';
import { StringText } from '../../../util/vs/editor/common/core/text/abstractText';
import { IInstantiationService } from '../../../util/vs/platform/instantiation/common/instantiation';
import { Position as VscodePosition } from '../../../vscodeTypes';
import { DelaySession } from '../../inlineEdits/common/delay';
import { getOrDeduceSelectionFromLastEdit } from '../../inlineEdits/common/nearbyCursorInlineEditProvider';
import { UserInteractionMonitor } from '../../inlineEdits/common/userInteractionMonitor';
import { IgnoreImportChangesAspect } from '../../inlineEdits/node/importFiltering';
import { determineIsInlineSuggestionPosition } from '../common/inlineSuggestion';
import { LintErrors } from '../common/lintErrors';
import { ClippedDocument, constructTaggedFile, getUserPrompt, N_LINES_ABOVE, N_LINES_AS_CONTEXT, N_LINES_BELOW, PromptPieces } from '../common/promptCrafting';
import { countTokensForLines, toUniquePath } from '../common/promptCraftingUtils';
import { ISimilarFilesContextService } from '../common/similarFilesContextService';
import { nes41Miniv3SystemPrompt, simplifiedPrompt, systemPromptTemplate, unifiedModelSystemPrompt, xtab275SystemPrompt } from '../common/systemMessages';
import { PromptTags, ResponseTags } from '../common/tags';
import { TerminalMonitor } from '../common/terminalOutput';
import { CurrentDocument } from '../common/xtabCurrentDocument';
import { XtabCustomDiffPatchResponseHandler } from './xtabCustomDiffPatchResponseHandler';
import { XtabEndpoint } from './xtabEndpoint';
import { CursorJumpPrediction, XtabNextCursorPredictor } from './xtabNextCursorPredictor';
import { charCount, constructMessages, linesWithBackticksRemoved } from './xtabUtils';
/**
* Returns true if the user has made document edits since the request was created.
* Used to skip costly sub-requests (e.g. next cursor prediction) whose results will
* be stale by the time they return.
*/
function hasUserTypedSinceRequestStarted(request: StatelessNextEditRequest): boolean {
return request.intermediateUserEdit === undefined || !request.intermediateUserEdit.isEmpty();
}
namespace RetryState {
export class NotRetrying { public static INSTANCE = new NotRetrying(); }
export class Retrying { constructor(public readonly reason: 'cursorJump' | 'expandedWindow') { } }
export type t =
| NotRetrying
| Retrying;
}
export interface ModelConfig extends xtabPromptOptions.PromptOptions {
modelName: string | undefined;
}
export class XtabProvider implements IStatelessNextEditProvider {
public static readonly ID = XTabProviderId;
public readonly ID = XtabProvider.ID;
private static computeTokens = (s: string) => Math.floor(s.length / 4);
private readonly userInteractionMonitor: UserInteractionMonitor;
private readonly terminalMonitor: TerminalMonitor;
private forceUseDefaultModel: boolean = false;
private nextCursorPredictor: XtabNextCursorPredictor;
constructor(
@IInlineEditsModelService private readonly modelService: IInlineEditsModelService,
@ISimulationTestContext private readonly simulationCtx: ISimulationTestContext,
@IInstantiationService private readonly instaService: IInstantiationService,
@IWorkspaceService private readonly workspaceService: IWorkspaceService,
@IDiffService private readonly diffService: IDiffService,
@IConfigurationService private readonly configService: IConfigurationService,
@IExperimentationService private readonly expService: IExperimentationService,
@ILanguageContextProviderService private readonly langCtxService: ILanguageContextProviderService,
@ILanguageDiagnosticsService private readonly langDiagService: ILanguageDiagnosticsService,
@IIgnoreService private readonly ignoreService: IIgnoreService,
@ISimilarFilesContextService private readonly similarFilesContextService: ISimilarFilesContextService,
) {
this.userInteractionMonitor = this.instaService.createInstance(UserInteractionMonitor);
this.terminalMonitor = this.instaService.createInstance(TerminalMonitor);
this.nextCursorPredictor = this.instaService.createInstance(XtabNextCursorPredictor, XtabProvider.computeTokens);
}
public handleAcceptance(): void {
this.userInteractionMonitor.handleAcceptance();
}
public handleRejection(): void {
this.userInteractionMonitor.handleRejection();
}
public handleIgnored(): void {
this.userInteractionMonitor.handleIgnored();
}
public async *provideNextEdit(request: StatelessNextEditRequest, logger: ILogger, logContext: InlineEditRequestLogContext, cancellationToken: CancellationToken): EditStreamingWithTelemetry {
const telemetry = new StatelessNextEditTelemetryBuilder(request.headerRequestId);
logContext.setProviderStartTime();
try {
if (request.xtabEditHistory.length === 0) {
const noSuggestionReason = new NoNextEditReason.ActiveDocumentHasNoEdits();
return new WithStatelessProviderTelemetry(noSuggestionReason, telemetry.build(Result.error(noSuggestionReason)));
}
const delaySession = this.userInteractionMonitor.createDelaySession(request.providerRequestStartDateTime);
const iterator = this.doGetNextEdit(request, delaySession, logger, logContext, cancellationToken, telemetry, RetryState.NotRetrying.INSTANCE);
let res = await iterator.next(); // for-async-await loop doesn't work because we need to access the final return value
while (!res.done) {
yield new WithStatelessProviderTelemetry(res.value, telemetry.build(Result.ok(undefined)));
res = await iterator.next();
}
const noNextEditReason = res.value;
if (noNextEditReason instanceof NoNextEditReason.GotCancelled) {
logContext.setIsSkipped();
}
return new WithStatelessProviderTelemetry(noNextEditReason, telemetry.build(Result.error(noNextEditReason)));
} catch (err: unknown) {
const error = ErrorUtils.fromUnknown(err);
const noSuggestionReason = new NoNextEditReason.Unexpected(error);
return new WithStatelessProviderTelemetry(noSuggestionReason, telemetry.build(Result.error(noSuggestionReason)));
} finally {
logContext.setProviderEndTime();
}
}
private doGetNextEdit(
request: StatelessNextEditRequest,
delaySession: DelaySession,
logger: ILogger,
logContext: InlineEditRequestLogContext,
cancellationToken: CancellationToken,
telemetryBuilder: StatelessNextEditTelemetryBuilder,
retryState: RetryState.t,
): EditStreaming {
return this.doGetNextEditWithSelection(
request,
getOrDeduceSelectionFromLastEdit(request.getActiveDocument()),
delaySession,
logger,
logContext,
cancellationToken,
telemetryBuilder,
retryState,
);
}
private async *doGetNextEditWithSelection(
request: StatelessNextEditRequest,
selection: Range | null,
delaySession: DelaySession,
parentTracer: ILogger,
logContext: InlineEditRequestLogContext,
cancellationToken: CancellationToken,
telemetryBuilder: StatelessNextEditTelemetryBuilder,
retryState: RetryState.t,
/**
* For cursor jump scenarios, this is the edit window around the original cursor position
* (before the jump). When provided, yielded edits will include this as `originalWindow`
* so the cache can serve the edit when the cursor is in either location.
*/
originalEditWindow?: OffsetRange,
): EditStreaming {
const tracer = parentTracer.createSubLogger(['XtabProvider', 'doGetNextEditWithSelection']);
const activeDocument = request.getActiveDocument();
if (selection === null) {
return new NoNextEditReason.Uncategorized(new Error('NoSelection'));
}
const { promptOptions, modelServiceConfig } = this.determineModelConfiguration(activeDocument);
telemetryBuilder.setModelConfig(JSON.stringify(modelServiceConfig));
const endpoint = this.getEndpointWithLogging(promptOptions.modelName, logContext, telemetryBuilder);
const cursorPosition = new Position(selection.endLineNumber, selection.endColumn);
const currentDocument = new CurrentDocument(activeDocument.documentAfterEdits, cursorPosition);
this._configureDebounceTimings(request, currentDocument, promptOptions, telemetryBuilder, delaySession, tracer);
const areaAroundEditWindowLinesRange = computeAreaAroundEditWindowLinesRange(currentDocument);
const editWindowLinesRange = this.computeEditWindowLinesRange(currentDocument, request, tracer, telemetryBuilder);
const cursorOriginalLinesOffset = Math.max(0, currentDocument.cursorLineOffset - editWindowLinesRange.start);
const editWindowLastLineLength = currentDocument.transformer.getLineLength(editWindowLinesRange.endExclusive);
const editWindow = currentDocument.transformer.getOffsetRange(new Range(editWindowLinesRange.start + 1, 1, editWindowLinesRange.endExclusive, editWindowLastLineLength + 1));
request.requestEditWindow = originalEditWindow
? new RequestEditWindowWithCursorJump(editWindow, originalEditWindow)
: new RequestEditWindow(editWindow);
const editWindowLines = currentDocument.lines.slice(editWindowLinesRange.start, editWindowLinesRange.endExclusive);
const editWindowTokenLimit = this.configService.getExperimentBasedConfig(ConfigKey.TeamInternal.InlineEditsXtabEditWindowMaxTokens, this.expService);
if (editWindowTokenLimit !== undefined && countTokensForLines(editWindowLines, XtabProvider.computeTokens) > editWindowTokenLimit) {
return new NoNextEditReason.PromptTooLarge('editWindow');
}
// Expected: editWindow.substring(activeDocument.documentAfterEdits.value) === editWindowLines.join('\n')
const doesIncludeCursorTag = editWindowLines.some(line => line.includes(PromptTags.CURSOR));
const shouldRemoveCursorTagFromResponse = !doesIncludeCursorTag; // we'd like to remove the tag only if the original edit-window didn't include the tag
const taggedCurrentFileContentResult = constructTaggedFile(
currentDocument,
editWindowLinesRange,
areaAroundEditWindowLinesRange,
promptOptions,
XtabProvider.computeTokens,
{
includeLineNumbers: {
areaAroundCodeToEdit: xtabPromptOptions.IncludeLineNumbersOption.None,
currentFileContent: promptOptions.currentFile.includeLineNumbers,
}
}
);
if (taggedCurrentFileContentResult.isError()) {
return new NoNextEditReason.PromptTooLarge('currentFile');
}
const { clippedTaggedCurrentDoc, areaAroundCodeToEdit } = taggedCurrentFileContentResult.val;
telemetryBuilder.setNLinesOfCurrentFileInPrompt(clippedTaggedCurrentDoc.lines.length);
const { aggressivenessLevel, userHappinessScore } = this.userInteractionMonitor.getAggressivenessLevel();
// Log user's raw aggressiveness setting when explicitly changed from default
const userAggressivenessSetting = this.configService.getExperimentBasedConfig(ConfigKey.Advanced.InlineEditsAggressiveness, this.expService);
telemetryBuilder.setUserAggressivenessSetting(userAggressivenessSetting);
// Log aggressiveness level and user happiness score
telemetryBuilder.setXtabAggressivenessLevel(aggressivenessLevel);
if (userHappinessScore !== undefined) {
telemetryBuilder.setXtabUserHappinessScore(userHappinessScore);
}
const langCtx = await this.getAndProcessLanguageContext(
request,
delaySession,
activeDocument,
cursorPosition,
promptOptions,
tracer,
logContext,
cancellationToken,
);
if (cancellationToken.isCancellationRequested) {
return new NoNextEditReason.GotCancelled('afterLanguageContextAwait');
}
const lintErrors = new LintErrors(activeDocument.id, currentDocument, this.langDiagService, request.xtabEditHistory);
const promptPieces = new PromptPieces(
currentDocument,
editWindowLinesRange,
areaAroundEditWindowLinesRange,
activeDocument,
request.xtabEditHistory,
clippedTaggedCurrentDoc.lines,
areaAroundCodeToEdit,
langCtx,
aggressivenessLevel,
lintErrors,
XtabProvider.computeTokens,
promptOptions
);
const { prompt: userPrompt, nDiffsInPrompt, diffTokensInPrompt } = getUserPrompt(promptPieces);
telemetryBuilder.setNDiffsInPrompt(nDiffsInPrompt);
telemetryBuilder.setDiffTokensInPrompt(diffTokensInPrompt);
const responseFormat = xtabPromptOptions.ResponseFormat.fromPromptingStrategy(promptOptions.promptingStrategy);
const prediction = this.getPredictedOutput(activeDocument, editWindowLines, responseFormat);
const messages = constructMessages({
systemMsg: pickSystemPrompt(promptOptions.promptingStrategy),
userMsg: userPrompt,
});
logContext.setPrompt(messages);
telemetryBuilder.setPrompt(messages);
const HARD_CHAR_LIMIT = 30000 * 4; // 30K tokens, assuming 4 chars per token -- we use approximation here because counting tokens exactly is time-consuming
const promptCharCount = charCount(messages);
if (promptCharCount > HARD_CHAR_LIMIT) {
return new NoNextEditReason.PromptTooLarge('final');
}
await this.debounce(delaySession, retryState, tracer, telemetryBuilder, cancellationToken);
if (cancellationToken.isCancellationRequested) {
return new NoNextEditReason.GotCancelled('afterDebounce');
}
// Fire-and-forget: collect lint errors and terminal output for telemetry in background to avoid blocking the main path
Promise.resolve().then(() => {
const lintErrorsData = lintErrors.getData();
telemetryBuilder.setLintErrors(lintErrorsData);
logContext.setDiagnosticsData(lintErrorsData);
const terminalOutputData = this.terminalMonitor.getData();
telemetryBuilder.setTerminalOutput(terminalOutputData);
logContext.setTerminalData(terminalOutputData);
});
// Fire-and-forget: compute GhostText-style similar files context for telemetry
telemetryBuilder.setSimilarFilesContext(
this.similarFilesContextService.compute(activeDocument.id.uri, activeDocument.languageId, activeDocument.documentAfterEdits.value, currentDocument.cursorOffset)
);
request.fetchIssued = true;
return yield* this.streamEditsWithFiltering(
request,
endpoint,
modelServiceConfig,
messages,
clippedTaggedCurrentDoc,
editWindow,
editWindowLines,
cursorOriginalLinesOffset,
editWindowLinesRange,
promptPieces,
prediction,
{
shouldRemoveCursorTagFromResponse,
responseFormat,
retryState,
aggressivenessLevel,
userHappinessScore,
},
delaySession,
tracer,
telemetryBuilder,
logContext,
cancellationToken,
originalEditWindow,
);
}
private _configureDebounceTimings(
request: StatelessNextEditRequest,
currentDocument: CurrentDocument,
promptOptions: ModelConfig,
telemetry: StatelessNextEditTelemetryBuilder,
delaySession: DelaySession,
tracer: ILogger,
) {
const isCursorAtEndOfLine = currentDocument.isCursorAtEndOfLine();
telemetry.setIsCursorAtLineEnd(isCursorAtEndOfLine);
// Apply extra debounce based on cursor position - only one applies
const isInlineSuggestionPosition = determineIsInlineSuggestionPosition(currentDocument);
telemetry.setIsInlineSuggestion(!!isInlineSuggestionPosition);
if (request.isSpeculative) {
tracer.trace('No extra debounce applied for speculative request');
} else {
const inlineSuggestionDebounce = this.configService.getExperimentBasedConfig(ConfigKey.TeamInternal.InlineEditsExtraDebounceInlineSuggestion, this.expService);
if (isInlineSuggestionPosition && inlineSuggestionDebounce > 0) {
tracer.trace('Debouncing for inline suggestion position');
delaySession.setExtraDebounce(inlineSuggestionDebounce);
} else if (isCursorAtEndOfLine) {
tracer.trace('Debouncing for cursor at end of line');
delaySession.setExtraDebounce(this.configService.getExperimentBasedConfig(ConfigKey.TeamInternal.InlineEditsExtraDebounceEndOfLine, this.expService));
} else {
tracer.trace('No extra debounce applied');
}
}
// Adjust debounce based on user aggressiveness setting for non-aggressiveness models
if (!isAggressivenessStrategy(promptOptions.promptingStrategy)) {
this._applyAggressivenessSettings(delaySession, tracer);
}
}
private _applyAggressivenessSettings(delaySession: DelaySession, tracer: ILogger): void {
const userAggressiveness = this.configService.getExperimentBasedConfig(ConfigKey.Advanced.InlineEditsAggressiveness, this.expService);
type MinResponseTimeConfigKey = typeof ConfigKey.TeamInternal.InlineEditsAggressivenessLowMinResponseTimeMs;
type DebounceConfigKey = typeof ConfigKey.TeamInternal.InlineEditsAggressivenessHighDebounceMs;
const configsByLevel: Record<AggressivenessSetting, { debounceConfigKey?: DebounceConfigKey; minResponseConfigKey?: MinResponseTimeConfigKey } | undefined> = {
[AggressivenessSetting.Low]: { minResponseConfigKey: ConfigKey.TeamInternal.InlineEditsAggressivenessLowMinResponseTimeMs },
[AggressivenessSetting.Medium]: { minResponseConfigKey: ConfigKey.TeamInternal.InlineEditsAggressivenessMediumMinResponseTimeMs },
[AggressivenessSetting.High]: { debounceConfigKey: ConfigKey.TeamInternal.InlineEditsAggressivenessHighDebounceMs },
[AggressivenessSetting.Default]: undefined,
};
const entry = configsByLevel[userAggressiveness];
if (!entry) {
return;
}
// Apply debounce override if configured for this level
if (entry.debounceConfigKey) {
const debounceMs = this.configService.getExperimentBasedConfig(entry.debounceConfigKey, this.expService);
delaySession.setBaseDebounceTime(debounceMs);
tracer.trace(`Aggressiveness ${userAggressiveness}: debounce set to ${debounceMs}ms`);
}
// Apply min response time if configured for this level
if (entry.minResponseConfigKey) {
// Skip min response time delay if the user just accepted a suggestion
if (this.userInteractionMonitor.wasLastActionAcceptance) {
tracer.trace(`Aggressiveness ${userAggressiveness}: skipping min response time (last action was acceptance)`);
return;
}
const minResponseTimeMs = this.configService.getExperimentBasedConfig(entry.minResponseConfigKey, this.expService);
delaySession.setExpectedTotalTime(minResponseTimeMs);
tracer.trace(`Aggressiveness ${userAggressiveness}: min response time set to ${minResponseTimeMs}ms`);
}
}
private getAndProcessLanguageContext(
request: StatelessNextEditRequest,
delaySession: DelaySession,
activeDocument: StatelessNextEditDocument,
cursorPosition: Position,
promptOptions: ModelConfig,
tracer: ILogger,
logContext: InlineEditRequestLogContext,
cancellationToken: CancellationToken,
): Promise<LanguageContextResponse | undefined> {
const recordingEnabled = this.configService.getConfig<boolean>(ConfigKey.TeamInternal.InlineEditsLogContextRecorderEnabled);
if (!promptOptions.languageContext.enabled && !recordingEnabled) {
return Promise.resolve(undefined);
}
const langCtxPromise = this.getLanguageContext(request, delaySession, activeDocument, cursorPosition, tracer, logContext, cancellationToken);
// if recording, add diagnostics for the file to the recording and hook up the language context promise to write to the recording
if (recordingEnabled) {
langCtxPromise.then(langCtxs => {
if (langCtxs) {
logContext.setLanguageContext(langCtxs);
}
});
}
return promptOptions.languageContext.enabled
? langCtxPromise
: Promise.resolve(undefined);
}
private async getLanguageContext(
request: StatelessNextEditRequest,
delaySession: DelaySession,
activeDocument: StatelessNextEditDocument,
cursorPosition: Position,
tracer: ILogger,
logContext: InlineEditRequestLogContext,
cancellationToken: CancellationToken,
): Promise<LanguageContextResponse | undefined> {
try {
const textDoc = this.workspaceService.textDocuments.find(doc => doc.uri.toString() === activeDocument.id.uri);
if (textDoc === undefined) {
return undefined;
}
const providers = this.langCtxService.getContextProviders(textDoc, ProviderTarget.NES);
if (providers.length < 1) {
return undefined;
}
const debounceTime = delaySession.getDebounceTime();
const cursorPositionVscode = new VscodePosition(cursorPosition.lineNumber - 1, cursorPosition.column - 1);
const ctxRequest: Copilot.ResolveRequest = {
opportunityId: request.opportunityId,
completionId: request.headerRequestId,
documentContext: {
uri: textDoc.uri.toString(),
languageId: textDoc.languageId,
version: textDoc.version,
offset: textDoc.offsetAt(cursorPositionVscode),
position: cursorPositionVscode
},
activeExperiments: new Map(),
timeBudget: debounceTime,
timeoutEnd: Date.now() + debounceTime,
source: 'nes',
};
const isSnippetIgnored = async (item: SnippetContext): Promise<boolean> => {
const uris = [item.uri, ...(item.additionalUris ?? [])];
const isIgnored = await raceFilter(uris.map(uri => this.ignoreService.isCopilotIgnored(uri)), r => r);
return !!isIgnored;
};
const langCtxItems: LanguageContextEntry[] = [];
const getContextPromise = async () => {
const ctxIter = this.langCtxService.getContextItems(textDoc, ctxRequest, cancellationToken);
for await (const item of ctxIter) {
if (item.kind === ContextKind.Snippet && await isSnippetIgnored(item)) {
// If the snippet is ignored, we don't want to include it in the context
continue;
}
langCtxItems.push({ context: item, timeStamp: Date.now(), onTimeout: false });
}
};
const start = Date.now();
await raceCancellation(raceTimeout(getContextPromise(), debounceTime), cancellationToken);
if (cancellationToken.isCancellationRequested) {
return undefined;
}
const end = Date.now();
const langCtxOnTimeout = this.langCtxService.getContextItemsOnTimeout(textDoc, ctxRequest);
for (const item of langCtxOnTimeout) {
if (item.kind === ContextKind.Snippet && await isSnippetIgnored(item)) {
// If the snippet is ignored, we don't want to include it in the context
continue;
}
langCtxItems.push({ context: item, timeStamp: end, onTimeout: true });
}
return { start, end, items: langCtxItems };
} catch (error: unknown) {
logContext.setError(ErrorUtils.fromUnknown(error));
tracer.trace(`Failed to fetch language context: ${error}`);
return undefined;
}
}
private async *streamEditsWithFiltering(
request: StatelessNextEditRequest,
endpoint: IChatEndpoint,
modelServiceConfig: xtabPromptOptions.ModelConfiguration,
messages: Raw.ChatMessage[],
clippedTaggedCurrentDoc: ClippedDocument,
editWindow: OffsetRange,
editWindowLines: string[],
cursorOriginalLinesOffset: number,
editWindowLineRange: OffsetRange,
promptPieces: PromptPieces,
prediction: Prediction | undefined,
opts: {
responseFormat: xtabPromptOptions.ResponseFormat;
shouldRemoveCursorTagFromResponse: boolean;
retryState: RetryState.t;
aggressivenessLevel: xtabPromptOptions.AggressivenessLevel;
userHappinessScore: number | undefined;
},
delaySession: DelaySession,
parentTracer: ILogger,
telemetryBuilder: StatelessNextEditTelemetryBuilder,
logContext: InlineEditRequestLogContext,
cancellationToken: CancellationToken,
originalEditWindow: OffsetRange | undefined,
): EditStreaming {
const tracer = parentTracer.createSubLogger('streamEditsWithFiltering');
const iterator = this.streamEdits(
request,
endpoint,
modelServiceConfig,
messages,
clippedTaggedCurrentDoc,
editWindow,
editWindowLines,
cursorOriginalLinesOffset,
editWindowLineRange,
promptPieces,
prediction,
opts,
delaySession,
tracer,
telemetryBuilder,
logContext,
cancellationToken,
originalEditWindow,
);
let nEdits = 0;
let r = await iterator.next();
while (!r.done) {
const edit = r.value.edit;
const [filteredEdits, filterNames] = this.filterEdit(request.getActiveDocument(), [edit]);
const isFilteredOut = filteredEdits.length === 0;
if (isFilteredOut) {
tracer.trace(`Filtered out an edit: ${edit.toString()} using ${filterNames.join(', ')} filter(s)`);
} else {
tracer.trace(`Yielding an edit: ${edit.toString()}`);
yield r.value;
nEdits++;
}
r = await iterator.next();
}
if (nEdits === 0 &&
r.value instanceof NoNextEditReason.NoSuggestions // only retry if there was no error, cancellation, etc.
) {
return yield* this.doGetNextEditsWithCursorJump(request, modelServiceConfig, editWindow, promptPieces, delaySession, parentTracer, logContext, cancellationToken, telemetryBuilder, opts.retryState);
}
return r.value;
}
private async *streamEdits(
request: StatelessNextEditRequest,
endpoint: IChatEndpoint,
modelServiceConfig: xtabPromptOptions.ModelConfiguration,
messages: Raw.ChatMessage[],
clippedTaggedCurrentDoc: ClippedDocument,
editWindow: OffsetRange,
editWindowLines: string[],
cursorOriginalLinesOffset: number,
editWindowLineRange: OffsetRange,
promptPieces: PromptPieces,
prediction: Prediction | undefined,
opts: {
responseFormat: xtabPromptOptions.ResponseFormat;
shouldRemoveCursorTagFromResponse: boolean;
retryState: RetryState.t;
aggressivenessLevel: xtabPromptOptions.AggressivenessLevel;
userHappinessScore: number | undefined;
},
delaySession: DelaySession,
parentTracer: ILogger,
telemetryBuilder: StatelessNextEditTelemetryBuilder,
logContext: InlineEditRequestLogContext,
cancellationToken: CancellationToken,
originalEditWindow: OffsetRange | undefined,
): EditStreaming {
const tracer = parentTracer.createSubLogger('streamEdits');
const targetDocument = request.getActiveDocument().id;
const useFetcher = this.configService.getExperimentBasedConfig(ConfigKey.NextEditSuggestionsFetcher, this.expService) || undefined;
const fetchStreamSource = new FetchStreamSource();
const fetchRequestStopWatch = new StopWatch();
let responseSoFar = '';
let chatResponseFailure: ChatFetchError | undefined;
let ttft: number | undefined;
const { wrapFinishedCb, getInitialFetchError } = createInitialFetchErrorDetector();
logContext.setHeaderRequestId(request.headerRequestId);
telemetryBuilder.setFetchStartedAt();
logContext.setFetchStartTime();
// we must not await this promise because we want to stream edits as they come in
const fetchResultPromise = endpoint.makeChatRequest2(
{
debugName: XtabProvider.ID,
messages,
finishedCb: wrapFinishedCb(async (text, _, delta) => {
if (ttft === undefined && text !== '') {
ttft = fetchRequestStopWatch.elapsed();
logContext.addLog(`TTFT ${ttft} ms`);
}
fetchStreamSource.update(text, delta);
responseSoFar = text;
logContext.setResponse(responseSoFar);
return undefined;
}),
location: ChatLocation.Other,
source: undefined,
requestOptions: {
temperature: 0,
stream: true,
prediction,
} satisfies OptionalChatRequestParams,
userInitiatedRequest: undefined,
telemetryProperties: {
requestId: request.headerRequestId,
},
useFetcher,
customMetadata: {
aggressivenessLevel: opts.aggressivenessLevel,
userHappinessScore: opts.userHappinessScore,
},
},
cancellationToken,
);
telemetryBuilder.setResponse(fetchResultPromise.then((response) => ({ response, ttft })));
logContext.setFullResponse(fetchResultPromise.then((response) => response.type === ChatFetchResponseType.Success ? response.value : undefined));
const initialFetchError = await getInitialFetchError(fetchResultPromise);
if (initialFetchError) {
if (initialFetchError.type === ChatFetchResponseType.NotFound &&
!this.forceUseDefaultModel // if we haven't already forced using the default model; otherwise, this could cause an infinite loop
) {
this.forceUseDefaultModel = true;
return yield* this.doGetNextEdit(request, delaySession, tracer, logContext, cancellationToken, telemetryBuilder, opts.retryState); // use the same retry state
}
// diff-patch based model returns no choices if it has no edits to suggest
if (initialFetchError.type === ChatFetchResponseType.Unknown && initialFetchError.reason === RESPONSE_CONTAINED_NO_CHOICES) {
return new NoNextEditReason.NoSuggestions(request.documentBeforeEdits, editWindow);
}
return mapChatFetcherErrorToNoNextEditReason(initialFetchError);
}
fetchResultPromise
.then((response) => {
// this's a way to signal the edit-pushing code to know if the request failed and
// it shouldn't push edits constructed from an erroneous response
chatResponseFailure = response.type !== ChatFetchResponseType.Success ? response : undefined;
})
.catch((err: unknown) => {
// in principle this shouldn't happen because ChatMLFetcher's fetchOne should not throw
logContext.setError(ErrorUtils.fromUnknown(err));
logContext.addLog(`ChatMLFetcher fetch call threw -- this's UNEXPECTED!`);
}).finally(() => {
logContext.setFetchEndTime();
fetchStreamSource.resolve();
logContext.setResponse(responseSoFar);
});
const llmLinesStream = AsyncIterUtilsExt.splitLines(AsyncIterUtils.map(fetchStreamSource.stream, (chunk) => chunk.delta.text));
// logging of times
// removal of cursor tag if option is set
const linesStream: AsyncIterable<string> = (async function* () {
let i = 0;
for await (const v of llmLinesStream) {
const trace = `Line ${i++} emitted with latency ${fetchRequestStopWatch.elapsed()} ms`;
tracer.trace(trace);
yield opts.shouldRemoveCursorTagFromResponse
? v.replaceAll(PromptTags.CURSOR, '')
: v;
}
})();
const isFromCursorJump = opts.retryState instanceof RetryState.Retrying && opts.retryState.reason === 'cursorJump';
let cleanedLinesStream: AsyncIterable<string>;
if (opts.responseFormat === xtabPromptOptions.ResponseFormat.EditWindowOnly) {
cleanedLinesStream = linesStream;
} else if (opts.responseFormat === xtabPromptOptions.ResponseFormat.EditWindowWithEditIntent ||
opts.responseFormat === xtabPromptOptions.ResponseFormat.EditWindowWithEditIntentShort) {
// Determine parse mode based on response format
const parseMode = opts.responseFormat === xtabPromptOptions.ResponseFormat.EditWindowWithEditIntentShort
? EditIntentParseMode.ShortName
: EditIntentParseMode.Tags;
// Parse the edit_intent from the response
const { editIntent, remainingLinesStream, parseError } = await parseEditIntentFromStream(linesStream, tracer, parseMode);
// Log the edit intent for telemetry
telemetryBuilder.setEditIntent(editIntent);
// Log parse errors for telemetry - this helps detect malformed model output during flights
if (parseError) {
telemetryBuilder.setEditIntentParseError(parseError);
}
// Check if we should show this edit based on intent and aggressiveness
if (!xtabPromptOptions.EditIntent.shouldShowEdit(editIntent, promptPieces.aggressivenessLevel)) {
tracer.trace(`Filtered out edit due to edit intent "${editIntent}" with aggressiveness "${promptPieces.aggressivenessLevel}"`);
return new NoNextEditReason.FilteredOut(`editIntent:${editIntent} aggressivenessLevel:${promptPieces.aggressivenessLevel}`);
}
cleanedLinesStream = remainingLinesStream;
} else if (opts.responseFormat === xtabPromptOptions.ResponseFormat.CustomDiffPatch) {
const activeDoc = request.getActiveDocument();
const currentDocument = promptPieces.currentDocument;
const lastLine = currentDocument.lines[clippedTaggedCurrentDoc.keptRange.endExclusive - 1];
const lastLineLength = lastLine.length;
const pseudoEditWindow = currentDocument.transformer.getOffsetRange(new Range(clippedTaggedCurrentDoc.keptRange.start + 1, 1, clippedTaggedCurrentDoc.keptRange.endExclusive, lastLineLength + 1));
return yield* XtabCustomDiffPatchResponseHandler.handleResponse(
linesStream,
currentDocument,
activeDoc.id,
activeDoc.workspaceRoot,
pseudoEditWindow,
tracer,
() => chatResponseFailure ? mapChatFetcherErrorToNoNextEditReason(chatResponseFailure) : undefined,
);
} else if (opts.responseFormat === xtabPromptOptions.ResponseFormat.UnifiedWithXml) {
const linesIter = linesStream[Symbol.asyncIterator]();
const firstLine = await linesIter.next();
if (chatResponseFailure !== undefined) { // handle fetch failure
return new NoNextEditReason.Unexpected(ErrorUtils.fromUnknown(chatResponseFailure));
}
if (firstLine.done) { // no lines in response -- unexpected case but take as no suggestions
return new NoNextEditReason.NoSuggestions(request.documentBeforeEdits, editWindow);
}
const trimmedLines = firstLine.value.trim();
if (trimmedLines === ResponseTags.NO_CHANGE.start) {
return yield* this.doGetNextEditsWithCursorJump(request, modelServiceConfig, editWindow, promptPieces, delaySession, tracer, logContext, cancellationToken, telemetryBuilder, opts.retryState);
}
if (trimmedLines === ResponseTags.INSERT.start) {
const lineWithCursorContinued = await linesIter.next();
if (lineWithCursorContinued.done || lineWithCursorContinued.value.includes(ResponseTags.INSERT.end)) {
return new NoNextEditReason.NoSuggestions(request.documentBeforeEdits, editWindow);
}
const cursorColumnOffsetZeroBased = promptPieces.currentDocument.cursorPosition.column - 1;
const edit = new LineReplacement(
new LineRange(editWindowLineRange.start + cursorOriginalLinesOffset + 1 /* 0-based to 1-based */, editWindowLineRange.start + cursorOriginalLinesOffset + 2),
[editWindowLines[cursorOriginalLinesOffset].slice(0, cursorColumnOffsetZeroBased) + lineWithCursorContinued.value + editWindowLines[cursorOriginalLinesOffset].slice(cursorColumnOffsetZeroBased)]
);
yield { edit, isFromCursorJump, window: editWindow, originalWindow: originalEditWindow, targetDocument };
const lines: string[] = [];
let v = await linesIter.next();
while (!v.done) {
if (v.value.includes(ResponseTags.INSERT.end)) {
break;
} else {
lines.push(v.value);
}
v = await linesIter.next();
}
const line = editWindowLineRange.start + cursorOriginalLinesOffset + 2;
yield {
edit: new LineReplacement(
new LineRange(line, line),
lines
),
isFromCursorJump,
window: editWindow,
originalWindow: originalEditWindow,
targetDocument,
};
return new NoNextEditReason.NoSuggestions(request.documentBeforeEdits, editWindow);
}
if (trimmedLines === ResponseTags.EDIT.start) {
cleanedLinesStream = (async function* () {
let v = await linesIter.next();
while (!v.done) {
if (v.value.includes(ResponseTags.EDIT.end)) {
return;
}
yield v.value;
v = await linesIter.next();
}
})();
} else {
return new NoNextEditReason.Unexpected(new Error(`unexpected tag ${trimmedLines}`));
}
} else if (opts.responseFormat === xtabPromptOptions.ResponseFormat.CodeBlock) {
cleanedLinesStream = linesWithBackticksRemoved(linesStream);
} else {
assertNever(opts.responseFormat);
}
const diffOptions: ResponseProcessor.DiffParams = {
emitFastCursorLineChange: ResponseProcessor.mapEmitFastCursorLineChange(this.configService.getExperimentBasedConfig(ConfigKey.TeamInternal.InlineEditsXtabProviderEmitFastCursorLineChange, this.expService)),
nLinesToConverge: this.configService.getExperimentBasedConfig(ConfigKey.TeamInternal.InlineEditsXtabNNonSignificantLinesToConverge, this.expService),
nSignificantLinesToConverge: this.configService.getExperimentBasedConfig(ConfigKey.TeamInternal.InlineEditsXtabNSignificantLinesToConverge, this.expService),
};
tracer.trace(`starting to diff stream against edit window lines with latency ${fetchRequestStopWatch.elapsed()} ms`);
let i = 0;
let hasBeenDelayed = false;
try {
for await (const edit of ResponseProcessor.diff(editWindowLines, cleanedLinesStream, cursorOriginalLinesOffset, diffOptions)) {
tracer.trace(`ResponseProcessor streamed edit #${i} with latency ${fetchRequestStopWatch.elapsed()} ms`);
const singleLineEdits: LineReplacement[] = [];
if (edit.lineRange.startLineNumber === edit.lineRange.endLineNumberExclusive || // we don't want to run diff on insertion
edit.newLines.length === 0 || // we don't want to run diff on deletion
edit.lineRange.endLineNumberExclusive - edit.lineRange.startLineNumber === 1 && edit.newLines.length === 1 // we want to run diff on single line edits
) {
const singleLineEdit = new LineReplacement(new LineRange(edit.lineRange.startLineNumber + editWindowLineRange.start, edit.lineRange.endLineNumberExclusive + editWindowLineRange.start), edit.newLines);
singleLineEdits.push(singleLineEdit);
} else {
const affectedOriginalLines = editWindowLines.slice(edit.lineRange.startLineNumber - 1, edit.lineRange.endLineNumberExclusive - 1).join('\n');
const diffResult = await this.diffService.computeDiff(affectedOriginalLines, edit.newLines.join('\n'), {
ignoreTrimWhitespace: false,
maxComputationTimeMs: 0,
computeMoves: false
});
tracer.trace(`Ran diff for #${i} with latency ${fetchRequestStopWatch.elapsed()} ms`);
const translateByNLines = editWindowLineRange.start + edit.lineRange.startLineNumber;
for (const change of diffResult.changes) {
const singleLineEdit = new LineReplacement(
new LineRange(
translateByNLines + change.original.startLineNumber - 1,
translateByNLines + change.original.endLineNumberExclusive - 1
),
edit.newLines.slice(change.modified.startLineNumber - 1, change.modified.endLineNumberExclusive - 1)
);
singleLineEdits.push(singleLineEdit);
}
}
if (chatResponseFailure) { // do not emit edits if chat response failed
break;
}
logContext.setResponse(responseSoFar);
for (const singleLineEdit of singleLineEdits) {
tracer.trace(`extracting edit #${i}: ${singleLineEdit.toString()}`);
if (!hasBeenDelayed) { // delay only the first one
hasBeenDelayed = true;
const artificialDelay = this.determineArtificialDelayMs(delaySession, tracer, telemetryBuilder);
if (artificialDelay) {
await timeout(artificialDelay);
tracer.trace(`Artificial delay of ${artificialDelay} ms completed`);
if (cancellationToken.isCancellationRequested) {
return new NoNextEditReason.GotCancelled('afterArtificialDelay');
}
}
}
yield { edit: singleLineEdit, isFromCursorJump, window: editWindow, originalWindow: originalEditWindow, targetDocument };
i++;
}
}
if (chatResponseFailure) {
return mapChatFetcherErrorToNoNextEditReason(chatResponseFailure);
}
return new NoNextEditReason.NoSuggestions(request.documentBeforeEdits, editWindow);