-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathtoolCallingLoop.ts
More file actions
1881 lines (1708 loc) · 85 KB
/
toolCallingLoop.ts
File metadata and controls
1881 lines (1708 loc) · 85 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 * as l10n from '@vscode/l10n';
import { Raw } from '@vscode/prompt-tsx';
import type { CancellationToken, ChatRequest, ChatResponseProgressPart, ChatResponseReferencePart, ChatResponseStream, ChatResult, LanguageModelToolInformation, Progress } from 'vscode';
import { IAuthenticationChatUpgradeService } from '../../../platform/authentication/common/authenticationUpgrade';
import { IChatDebugFileLoggerService } from '../../../platform/chat/common/chatDebugFileLoggerService';
import { IChatHookService, SessionStartHookInput, SessionStartHookOutput, StopHookInput, StopHookOutput, SubagentStartHookInput, SubagentStartHookOutput, SubagentStopHookInput, SubagentStopHookOutput } from '../../../platform/chat/common/chatHookService';
import { FetchStreamSource, IResponsePart } from '../../../platform/chat/common/chatMLFetcher';
import { CanceledResult, ChatFetchResponseType, ChatResponse } from '../../../platform/chat/common/commonTypes';
import { IHistoricalTurn, ISessionTranscriptService, ToolRequest } from '../../../platform/chat/common/sessionTranscriptService';
import { ConfigKey, IConfigurationService } from '../../../platform/configuration/common/configurationService';
import { isAnthropicFamily, isGeminiFamily } from '../../../platform/endpoint/common/chatModelCapabilities';
import { IEndpointProvider } from '../../../platform/endpoint/common/endpointProvider';
import { rawPartAsThinkingData } from '../../../platform/endpoint/common/thinkingDataContainer';
import { IFileSystemService } from '../../../platform/filesystem/common/fileSystemService';
import { IGitService } from '../../../platform/git/common/gitService';
import { ILogService } from '../../../platform/log/common/logService';
import { isOpenAIContextManagementResponse, OpenAiFunctionDef } from '../../../platform/networking/common/fetch';
import { IMakeChatRequestOptions } from '../../../platform/networking/common/networking';
import { OpenAIContextManagementResponse } from '../../../platform/networking/common/openai';
import { CopilotChatAttr, emitAgentTurnEvent, emitSessionStartEvent, GenAiAttr, GenAiMetrics, GenAiOperationName, GenAiProviderName, resolveWorkspaceOTelMetadata, StdAttr, truncateForOTel, workspaceMetadataToOTelAttributes } from '../../../platform/otel/common/index';
import { IOTelService, ISpanHandle, SpanKind, SpanStatusCode } from '../../../platform/otel/common/otelService';
import { getCurrentCapturingToken, IRequestLogger } from '../../../platform/requestLogger/node/requestLogger';
import { IExperimentationService } from '../../../platform/telemetry/common/nullExperimentationService';
import { ITelemetryService } from '../../../platform/telemetry/common/telemetry';
import { computePromptTokenDetails } from '../../../platform/tokenizer/node/promptTokenDetails';
import { tryFinalizeResponseStream } from '../../../util/common/chatResponseStreamImpl';
import { ChatExtPerfMark, markChatExt } from '../../../util/common/performance';
import { DeferredPromise, timeout } from '../../../util/vs/base/common/async';
import { CancellationError, isCancellationError } from '../../../util/vs/base/common/errors';
import { Emitter } from '../../../util/vs/base/common/event';
import { Disposable } from '../../../util/vs/base/common/lifecycle';
import { Mutable } from '../../../util/vs/base/common/types';
import { URI } from '../../../util/vs/base/common/uri';
import { generateUuid } from '../../../util/vs/base/common/uuid';
import { IInstantiationService } from '../../../util/vs/platform/instantiation/common/instantiation';
import { ChatResponsePullRequestPart, LanguageModelDataPart2, LanguageModelPartAudience, LanguageModelTextPart, LanguageModelToolResult2, MarkdownString } from '../../../vscodeTypes';
import { InteractionOutcomeComputer } from '../../inlineChat/node/promptCraftingTypes';
import { ChatVariablesCollection } from '../../prompt/common/chatVariablesCollection';
import { AnthropicTokenUsageMetadata, Conversation, IResultMetadata, ResponseStreamParticipant, TurnStatus } from '../../prompt/common/conversation';
import { IBuildPromptContext, InternalToolReference, IToolCall, IToolCallRound } from '../../prompt/common/intents';
import { cancelText, IToolCallIterationIncrease } from '../../prompt/common/specialRequestTypes';
import { ThinkingDataItem, ToolCallRound } from '../../prompt/common/toolCallRound';
import { IBuildPromptResult, IResponseProcessor } from '../../prompt/node/intents';
import { PseudoStopStartResponseProcessor } from '../../prompt/node/pseudoStartStopConversationCallback';
import { ResponseProcessorContext } from '../../prompt/node/responseProcessorContext';
import { extractInlineSummary, InlineSummarizationRequestedMetadata, SummarizedConversationHistoryMetadata } from '../../prompts/node/agent/summarizedConversationHistory';
import { ToolFailureEncountered, ToolResultMetadata } from '../../prompts/node/panel/toolCalling';
import { ToolName } from '../../tools/common/toolNames';
import { IToolsService, ToolCallCancelledError } from '../../tools/common/toolsService';
import { ReadFileParams } from '../../tools/node/readFileTool';
import { isHookAbortError, processHookResults } from './hookResultProcessor';
import { applyPromptOverrides } from './promptOverride';
export const enum ToolCallLimitBehavior {
Confirm,
Stop,
}
export interface IToolCallingLoopOptions {
conversation: Conversation;
toolCallLimit: number;
/**
* What to do when the limit is hit. Defaults to {@link ToolCallLimitBehavior.Stop}.
* If set to confirm you can use {@link isToolCallLimitCancellation} and
* {@link isToolCallIterationIncrease} to get followup data.
*/
onHitToolCallLimit?: ToolCallLimitBehavior;
/**
* "mixins" that can be used to wrap the response stream.
*/
streamParticipants?: ResponseStreamParticipant[];
/**
* Optional custom response stream processor.
*/
responseProcessor?: IResponseProcessor;
/** Context for the {@link InteractionOutcomeComputer} */
interactionContext?: URI;
/**
* The current chat request
*/
request: ChatRequest;
/**
* A getter that returns true if VS Code has requested the extension to
* gracefully yield. When set, it's likely that the editor will immediately
* follow up with a new request in the same conversation.
*/
yieldRequested?: () => boolean;
}
export interface IToolCallingResponseEvent {
response: ChatResponse;
interactionOutcome: InteractionOutcomeComputer;
toolCalls: IToolCall[];
}
export interface IToolCallingBuiltPromptEvent {
result: IBuildPromptResult;
tools: LanguageModelToolInformation[];
}
export type ToolCallingLoopFetchOptions = Required<Pick<IMakeChatRequestOptions, 'messages' | 'finishedCb' | 'requestOptions' | 'userInitiatedRequest' | 'turnId'>> & Pick<IMakeChatRequestOptions, 'enableThinking' | 'reasoningEffort'>;
interface StartHookResult {
/**
* Additional context to add to the agent's context, if any.
*/
readonly additionalContext?: string;
}
interface StopHookResult {
/**
* Whether the agent should continue (not stop).
*/
readonly shouldContinue: boolean;
/**
* The reasons the agent should continue, if shouldContinue is true.
* Multiple hooks may block with different reasons.
*/
readonly reasons?: readonly string[];
}
interface SubagentStartHookResult {
/**
* Additional context to add to the subagent's context, if any.
*/
readonly additionalContext?: string;
}
interface SubagentStopHookResult {
/**
* Whether the subagent should continue (not stop).
*/
readonly shouldContinue: boolean;
/**
* The reasons the subagent should continue, if shouldContinue is true.
* Multiple hooks may block with different reasons.
*/
readonly reasons?: readonly string[];
}
/**
* Formats a hook context message from blocking reasons.
* @param reasons The reasons hooks blocked the agent from stopping
* @returns A formatted message for the model to address the requirements
*/
function formatHookContext(reasons: readonly string[]): string {
if (reasons.length === 1) {
return `You were about to complete but a hook blocked you with the following message: "${reasons[0]}". Please address this requirement before completing.`;
}
const formattedReasons = reasons.map((reason, i) => `${i + 1}. ${reason}`).join('\n');
return `You were about to complete but multiple hooks blocked you with the following messages:\n${formattedReasons}\n\nPlease address all of these requirements before completing.`;
}
/**
* This is a base class that can be used to implement a tool calling loop
* against a model. It requires only that you build a prompt and is decoupled
* from intents (i.e. the {@link DefaultIntentRequestHandler}), allowing easier
* programmatic use.
*/
export abstract class ToolCallingLoop<TOptions extends IToolCallingLoopOptions = IToolCallingLoopOptions> extends Disposable {
private static NextToolCallId = Date.now();
private static readonly TASK_COMPLETE_TOOL_NAME = 'task_complete';
private toolCallResults: Record<string, LanguageModelToolResult2> = Object.create(null);
private toolCallRounds: IToolCallRound[] = [];
private stopHookReason: string | undefined;
private additionalHookContext: string | undefined;
private stopHookUserInitiated = false;
private agentSpan: ISpanHandle | undefined;
private chatSessionIdForTools: string | undefined;
private toolsAvailableEmitted = false;
public appendAdditionalHookContext(context: string): void {
if (!context) {
return;
}
this.additionalHookContext = this.additionalHookContext
? `${this.additionalHookContext}\n${context}`
: context;
}
private readonly _onDidBuildPrompt = this._register(new Emitter<{ result: IBuildPromptResult; tools: LanguageModelToolInformation[]; promptTokenLength: number; toolTokenCount: number }>());
public readonly onDidBuildPrompt = this._onDidBuildPrompt.event;
private readonly _onDidReceiveResponse = this._register(new Emitter<IToolCallingResponseEvent>());
public readonly onDidReceiveResponse = this._onDidReceiveResponse.event;
private get turn() {
return this.options.conversation.getLatestTurn();
}
constructor(
protected readonly options: TOptions,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@IEndpointProvider private readonly _endpointProvider: IEndpointProvider,
@ILogService protected readonly _logService: ILogService,
@IRequestLogger private readonly _requestLogger: IRequestLogger,
@IAuthenticationChatUpgradeService private readonly _authenticationChatUpgradeService: IAuthenticationChatUpgradeService,
@ITelemetryService protected readonly _telemetryService: ITelemetryService,
@IConfigurationService protected readonly _configurationService: IConfigurationService,
@IExperimentationService protected readonly _experimentationService: IExperimentationService,
@IChatHookService private readonly _chatHookService: IChatHookService,
@ISessionTranscriptService protected readonly _sessionTranscriptService: ISessionTranscriptService,
@IFileSystemService private readonly _fileSystemService: IFileSystemService,
@IOTelService protected readonly _otelService: IOTelService,
@IGitService private readonly _gitService: IGitService,
) {
super();
}
/** Builds a prompt with the context. */
protected abstract buildPrompt(buildPromptContext: IBuildPromptContext, progress: Progress<ChatResponseReferencePart | ChatResponseProgressPart>, token: CancellationToken): Promise<IBuildPromptResult>;
/** Gets the tools that should be callable by the model. */
protected abstract getAvailableTools(outputStream: ChatResponseStream | undefined, token: CancellationToken): Promise<LanguageModelToolInformation[]>;
/** Creates the prompt context for the request. */
protected createPromptContext(availableTools: LanguageModelToolInformation[], outputStream: ChatResponseStream | undefined): Mutable<IBuildPromptContext> {
const { request } = this.options;
const chatVariables = new ChatVariablesCollection(request.references);
const isContinuation = this.turn.isContinuation || !!this.stopHookReason;
let query: string;
let hasStopHookQuery = false;
if (this.stopHookReason) {
// Include the stop hook reason as a user message so the model knows what to do.
// Wrap with context so the model understands it needs to take action.
query = formatHookContext([this.stopHookReason]);
this._logService.info(`[ToolCallingLoop] Using stop hook reason as query: ${query}`);
this.stopHookReason = undefined; // Clear after use
hasStopHookQuery = true;
} else if (isContinuation) {
query = 'Please continue';
} else {
query = this.turn.request.message;
}
// exclude turns from the history that errored due to prompt filtration
const history = this.options.conversation.turns.slice(0, -1).filter(turn => turn.responseStatus !== TurnStatus.PromptFiltered);
return {
requestId: this.turn.id,
query,
history,
toolCallResults: this.toolCallResults,
toolCallRounds: this.toolCallRounds,
editedFileEvents: this.options.request.editedFileEvents,
request: this.options.request,
stream: outputStream,
conversation: this.options.conversation,
chatVariables,
tools: {
toolReferences: request.toolReferences.map(InternalToolReference.from),
toolInvocationToken: request.toolInvocationToken,
availableTools
},
isContinuation,
hasStopHookQuery,
modeInstructions: this.options.request.modeInstructions2,
additionalHookContext: this.additionalHookContext,
};
}
protected abstract fetch(
options: ToolCallingLoopFetchOptions,
token: CancellationToken
): Promise<ChatResponse>;
/**
* The context window widget in chat input should represent only the parent request.
* Subagent usage must stay isolated to avoid inflating the parent widget.
*/
private shouldReportUsageToContextWidget(): boolean {
return !this.options.request.subAgentInvocationId;
}
/**
* Called before the loop stops to give hooks a chance to block the stop.
* @param input The stop hook input containing stop_hook_active flag
* @param outputStream The output stream for displaying messages
* @param token Cancellation token
* @returns Result indicating whether to continue and the reasons
*/
protected async executeStopHook(input: StopHookInput, sessionId: string, outputStream: ChatResponseStream | undefined, token: CancellationToken): Promise<StopHookResult> {
try {
const results = await this._chatHookService.executeHook('Stop', this.options.request.hooks, input, sessionId, token);
const blockingReasons = new Set<string>();
processHookResults({
hookType: 'Stop',
results,
outputStream,
logService: this._logService,
onSuccess: (output) => {
if (typeof output === 'object' && output !== null) {
const hookOutput = output as StopHookOutput;
const specific = hookOutput.hookSpecificOutput;
this._logService.trace(`[ToolCallingLoop] Checking hook output: decision=${specific?.decision}, reason=${specific?.reason}`);
if (specific?.decision === 'block' && specific.reason) {
this._logService.trace(`[ToolCallingLoop] Stop hook blocked: ${specific.reason}`);
blockingReasons.add(specific.reason);
}
}
},
// Collect errors as blocking reasons (stderr from exit code != 0)
onError: (errorMessage) => {
if (errorMessage) {
this._logService.trace(`[ToolCallingLoop] Stop hook error collected as blocking reason: ${errorMessage}`);
blockingReasons.add(errorMessage);
}
},
});
if (blockingReasons.size > 0) {
return { shouldContinue: true, reasons: [...blockingReasons] };
}
return { shouldContinue: false };
} catch (error) {
if (isHookAbortError(error)) {
throw error;
}
this._logService.error('[ToolCallingLoop] Error executing Stop hook', error);
return { shouldContinue: false };
}
}
/**
* Shows a message when the stop hook blocks the agent from stopping.
* Override in subclasses to customize the display.
* @param outputStream The output stream for displaying messages
* @param reasons The reasons the stop hook blocked stopping
*/
protected showStopHookBlockedMessage(outputStream: ChatResponseStream | undefined, reasons: readonly string[]): void {
if (outputStream) {
if (reasons.length === 1) {
outputStream.hookProgress('Stop', reasons[0]);
} else {
const formattedReasons = reasons.map((r, i) => `${i + 1}. ${r}`).join('\n');
outputStream.hookProgress('Stop', formattedReasons);
}
}
this._logService.trace(`[ToolCallingLoop] Stop hook blocked stopping: ${reasons.join('; ')}`);
}
private static readonly MAX_AUTOPILOT_RETRIES = 3;
private static readonly MAX_AUTOPILOT_ITERATIONS = 5;
private autopilotRetryCount = 0;
private autopilotIterationCount = 0;
private taskCompleted = false;
private autopilotStopHookActive = false;
private autopilotProgressDeferred: DeferredPromise<void> | undefined;
private inlineSummarizationProgressDeferred: DeferredPromise<void> | undefined;
/** Set to true before calling fetch() when the current iteration is an inline summarization request. */
protected _isInlineSummarizationRequest = false;
/**
* Autopilot stop hook — the model needs to call `task_complete` to signal it's done.
* If it stops without calling it, we nudge it to keep going. Returns a continuation
* message or `undefined` to let the loop stop.
*/
protected shouldAutopilotContinue(result: IToolCallSingleResult): string | undefined {
if (this.taskCompleted) {
this._logService.info('[ToolCallingLoop] Autopilot: task_complete was called, stopping');
return undefined;
}
// might have called task_complete alongside other tools in an earlier round
const calledTaskComplete = this.toolCallRounds.some(
round => round.toolCalls.some(tc => tc.name === ToolCallingLoop.TASK_COMPLETE_TOOL_NAME)
);
if (calledTaskComplete) {
this.taskCompleted = true;
this._logService.info('[ToolCallingLoop] Autopilot: task_complete found in history, stopping');
return undefined;
}
// safety valve — only give up after exhausting all continuation attempts
if (this.autopilotIterationCount >= ToolCallingLoop.MAX_AUTOPILOT_ITERATIONS) {
this._logService.info(`[ToolCallingLoop] Autopilot: hit max iterations (${ToolCallingLoop.MAX_AUTOPILOT_ITERATIONS}), letting it stop`);
return undefined;
}
this.autopilotIterationCount++;
return 'You have not yet marked the task as complete using the task_complete tool. ' +
'You must call task_complete when done — whether the task involved code changes, answering a question, or any other interaction.\n\n' +
'Do NOT repeat or restate your previous response. Pick up where you left off.\n\n' +
'If you were planning, stop planning and start implementing. ' +
'You are not done until you have fully completed the task.\n\n' +
'IMPORTANT: Do NOT call task_complete if:\n' +
'- You have open questions or ambiguities — make good decisions and keep working\n' +
'- You encountered an error — try to resolve it or find an alternative approach\n' +
'- There are remaining steps — complete them first\n\n' +
'When you ARE done, first provide a brief text summary of what was accomplished, then call task_complete. ' +
'Both the summary message and the tool call are required.\n\n' +
'Keep working autonomously until the task is truly finished, then call task_complete.';
}
/**
* Shows a progress spinner in the chat stream while autopilot continues.
* The spinner resolves to the past-tense message when {@link resolveAutopilotProgress} is called.
*/
private showAutopilotProgress(outputStream: ChatResponseStream | undefined, message: string, pastTenseMessage: string): void {
this.resolveAutopilotProgress();
const deferred = new DeferredPromise<void>();
this.autopilotProgressDeferred = deferred;
outputStream?.progress(message, async () => {
await deferred.p;
return pastTenseMessage;
});
}
/**
* Resolves any pending autopilot progress spinner, transitioning it to its past-tense message.
*/
private resolveAutopilotProgress(): void {
if (this.autopilotProgressDeferred) {
this.autopilotProgressDeferred.complete(undefined);
this.autopilotProgressDeferred = undefined;
}
}
/**
* Ensures the `task_complete` tool is present in the available tools when running in
* autopilot mode. If it's missing (e.g. filtered out by the tool picker), it's resolved
* from the tools service and appended so the model can always signal completion.
*/
protected ensureAutopilotTools(availableTools: LanguageModelToolInformation[]): LanguageModelToolInformation[] {
if (this.options.request.permissionLevel !== 'autopilot') {
return availableTools;
}
if (availableTools.some(t => t.name === ToolCallingLoop.TASK_COMPLETE_TOOL_NAME)) {
return availableTools;
}
const taskCompleteTool = this._instantiationService.invokeFunction(
accessor => accessor.get(IToolsService).getTool(ToolCallingLoop.TASK_COMPLETE_TOOL_NAME)
);
if (taskCompleteTool) {
this._logService.info('[ToolCallingLoop] Added task_complete tool for autopilot mode');
return [...availableTools, taskCompleteTool];
}
this._logService.warn('[ToolCallingLoop] task_complete tool not found — autopilot completion may not work');
return availableTools;
}
/**
* Whether the loop should auto-retry after a failed fetch in auto-approve/autopilot mode.
* Does not retry rate-limited, quota-exceeded, or cancellation errors.
*/
private shouldAutoRetry(response: ChatResponse): boolean {
const permLevel = this.options.request.permissionLevel;
if (permLevel !== 'autoApprove' && permLevel !== 'autopilot') {
return false;
}
if (this.autopilotRetryCount >= ToolCallingLoop.MAX_AUTOPILOT_RETRIES) {
return false;
}
switch (response.type) {
case ChatFetchResponseType.RateLimited:
case ChatFetchResponseType.QuotaExceeded:
case ChatFetchResponseType.Canceled:
case ChatFetchResponseType.OffTopic:
return false;
default:
return response.type !== ChatFetchResponseType.Success;
}
}
/**
* Called when a session starts to allow hooks to provide additional context.
* @param input The session start hook input containing source
* @param outputStream The output stream for displaying messages
* @param token Cancellation token
* @returns Result containing additional context from hooks
*/
protected async executeSessionStartHook(input: SessionStartHookInput, sessionId: string, outputStream: ChatResponseStream | undefined, token: CancellationToken): Promise<StartHookResult> {
try {
const results = await this._chatHookService.executeHook('SessionStart', this.options.request.hooks, input, sessionId, token);
const additionalContexts: string[] = [];
processHookResults({
hookType: 'SessionStart',
results,
outputStream,
logService: this._logService,
onSuccess: (output) => {
if (typeof output === 'object' && output !== null) {
const hookOutput = output as SessionStartHookOutput;
const additionalContext = hookOutput.hookSpecificOutput?.additionalContext;
if (additionalContext) {
additionalContexts.push(additionalContext);
this._logService.trace(`[ToolCallingLoop] SessionStart hook provided context: ${additionalContext.substring(0, 100)}...`);
}
}
},
// SessionStart blocking errors and stopReason are silently ignored
ignoreErrors: true,
});
return {
additionalContext: additionalContexts.length > 0 ? additionalContexts.join('\n') : undefined
};
} catch (error) {
if (isHookAbortError(error)) {
throw error;
}
this._logService.error('[ToolCallingLoop] Error executing SessionStart hook', error);
return {};
}
}
/**
* Called when a subagent starts to allow hooks to provide additional context.
* @param input The subagent start hook input containing agent_id and agent_type
* @param outputStream The output stream for displaying messages
* @param token Cancellation token
* @returns Result containing additional context from hooks
*/
protected async executeSubagentStartHook(input: SubagentStartHookInput, sessionId: string, outputStream: ChatResponseStream | undefined, token: CancellationToken): Promise<SubagentStartHookResult> {
try {
const results = await this._chatHookService.executeHook('SubagentStart', this.options.request.hooks, input, sessionId, token);
const additionalContexts: string[] = [];
processHookResults({
hookType: 'SubagentStart',
results,
outputStream,
logService: this._logService,
onSuccess: (output) => {
if (typeof output === 'object' && output !== null) {
const hookOutput = output as SubagentStartHookOutput;
const additionalContext = hookOutput.hookSpecificOutput?.additionalContext;
if (additionalContext) {
additionalContexts.push(additionalContext);
this._logService.trace(`[ToolCallingLoop] SubagentStart hook provided context: ${additionalContext.substring(0, 100)}...`);
}
}
},
// SubagentStart blocking errors and stopReason are silently ignored
ignoreErrors: true,
});
return {
additionalContext: additionalContexts.length > 0 ? additionalContexts.join('\n') : undefined
};
} catch (error) {
if (isHookAbortError(error)) {
throw error;
}
this._logService.error('[ToolCallingLoop] Error executing SubagentStart hook', error);
return {};
}
}
/**
* Called before a subagent stops to give hooks a chance to block the stop.
* @param input The subagent stop hook input containing agent_id, agent_type, and stop_hook_active flag
* @param outputStream The output stream for displaying messages
* @param token Cancellation token
* @returns Result indicating whether to continue and the reasons
*/
protected async executeSubagentStopHook(input: SubagentStopHookInput, sessionId: string, outputStream: ChatResponseStream | undefined, token: CancellationToken): Promise<SubagentStopHookResult> {
try {
const results = await this._chatHookService.executeHook('SubagentStop', this.options.request.hooks, input, sessionId, token);
const blockingReasons = new Set<string>();
processHookResults({
hookType: 'SubagentStop',
results,
outputStream,
logService: this._logService,
onSuccess: (output) => {
if (typeof output === 'object' && output !== null) {
const hookOutput = output as SubagentStopHookOutput;
const specific = hookOutput.hookSpecificOutput;
this._logService.trace(`[ToolCallingLoop] Checking SubagentStop hook output: decision=${specific?.decision}, reason=${specific?.reason}`);
if (specific?.decision === 'block' && specific.reason) {
this._logService.trace(`[ToolCallingLoop] SubagentStop hook blocked: ${specific.reason}`);
blockingReasons.add(specific.reason);
}
}
},
// Collect errors as blocking reasons (stderr from exit code != 0)
onError: (errorMessage) => {
if (errorMessage) {
this._logService.trace(`[ToolCallingLoop] SubagentStop hook error collected as blocking reason: ${errorMessage}`);
blockingReasons.add(errorMessage);
}
},
});
if (blockingReasons.size > 0) {
return { shouldContinue: true, reasons: [...blockingReasons] };
}
return { shouldContinue: false };
} catch (error) {
if (isHookAbortError(error)) {
throw error;
}
this._logService.error('[ToolCallingLoop] Error executing SubagentStop hook', error);
return { shouldContinue: false };
}
}
/**
* Shows a message when the subagent stop hook blocks the subagent from stopping.
* Override in subclasses to customize the display.
* @param outputStream The output stream for displaying messages
* @param reasons The reasons the subagent stop hook blocked stopping
*/
protected showSubagentStopHookBlockedMessage(outputStream: ChatResponseStream | undefined, reasons: readonly string[]): void {
if (outputStream) {
if (reasons.length === 1) {
outputStream.hookProgress('SubagentStop', reasons[0]);
} else {
const formattedReasons = reasons.map((r, i) => `${i + 1}. ${r}`).join('\n');
outputStream.hookProgress('SubagentStop', formattedReasons);
}
}
this._logService.trace(`[ToolCallingLoop] SubagentStop hook blocked stopping: ${reasons.join('; ')}`);
}
private throwIfCancelled(token: CancellationToken) {
if (token.isCancellationRequested) {
this.turn.setResponse(TurnStatus.Cancelled, undefined, undefined, CanceledResult);
throw new CancellationError();
}
}
/**
* Executes start hooks (SessionStart for regular sessions, SubagentStart for subagents).
* Should be called before run() to allow hooks to provide context before the first prompt.
*
* - For subagents: Always executes SubagentStart hook
* - For regular sessions: Only executes SessionStart hook on the first turn
* @throws HookAbortError if a hook requests the session/subagent to abort
*/
public async runStartHooks(outputStream: ChatResponseStream | undefined, token: CancellationToken): Promise<void> {
const sessionId = this.options.conversation.sessionId;
const hasHooks = this.options.request.hasHooksEnabled;
// Report which hooks are configured for this request
this._chatHookService.logConfiguredHooks(this.options.request.hooks);
// Execute SubagentStart hook for subagent requests, or SessionStart hook for first turn of regular sessions
if (this.options.request.subAgentInvocationId) {
const startHookResult = await this.executeSubagentStartHook({
agent_id: this.options.request.subAgentInvocationId,
agent_type: this.options.request.subAgentName ?? 'default',
}, sessionId, outputStream, token);
if (startHookResult.additionalContext) {
this.additionalHookContext = startHookResult.additionalContext;
this._logService.info(`[ToolCallingLoop] SubagentStart hook provided context for subagent ${this.options.request.subAgentInvocationId}`);
}
} else {
const isFirstTurn = this.options.conversation.turns.length === 1;
if (hasHooks) {
// Build history from prior turns (excluding the current one) for transcript replay
const priorTurns = this.options.conversation.turns.slice(0, -1);
const history: IHistoricalTurn[] = priorTurns.map(turn => ({
userMessage: turn.request.message,
timestamp: turn.startTime,
rounds: turn.rounds.map(round => ({
response: round.response,
toolCalls: round.toolCalls.map(tc => ({
name: tc.name,
arguments: tc.arguments,
id: tc.id,
})),
reasoningText: round.thinking
? (Array.isArray(round.thinking.text) ? round.thinking.text.join('') : round.thinking.text)
: undefined,
timestamp: round.timestamp,
})),
}));
// Start the transcript (will replay history if no file exists yet)
await this._sessionTranscriptService.startSession(sessionId, undefined, history.length > 0 ? history : undefined);
}
if (isFirstTurn) {
const startHookResult = await this.executeSessionStartHook({
source: 'new',
}, sessionId, outputStream, token);
if (startHookResult.additionalContext) {
this.additionalHookContext = startHookResult.additionalContext;
this._logService.info('[ToolCallingLoop] SessionStart hook provided context for session');
}
}
}
// Log the user message for the transcript (no-ops if session was not started)
this._sessionTranscriptService.logUserMessage(
sessionId,
this.turn.request.message,
);
}
public async run(outputStream: ChatResponseStream | undefined, token: CancellationToken): Promise<IToolCallLoopResult> {
const agentName = (this.options.request as { subAgentName?: string }).subAgentName
?? (this.options.request as { participant?: string }).participant
?? 'GitHub Copilot Chat';
// Extract custom mode name for debug logging (kept separate from agentName to avoid metric cardinality)
const modeInstructions = (this.options.request as { modeInstructions2?: { name?: string; isBuiltin?: boolean } }).modeInstructions2;
const customModeName = modeInstructions?.name && !modeInstructions.isBuiltin ? modeInstructions.name : undefined;
// If this is a subagent request, look up the parent trace context stored by the parent agent's execute_tool span
// Try subAgentInvocationId first (unique per subagent, supports parallel), then request-level key
const subAgentInvocationId = this.options.request.subAgentInvocationId;
const parentRequestId = this.options.request.parentRequestId;
const parentTraceContext = (subAgentInvocationId
? this._otelService.getStoredTraceContext(`subagent:invocation:${subAgentInvocationId}`)
: undefined)
?? (() => {
// For request-level fallback, read and re-store so parallel subagents can all read it
if (!parentRequestId) { return undefined; }
const ctx = this._otelService.getStoredTraceContext(`subagent:request:${parentRequestId}`);
if (ctx) { this._otelService.storeTraceContext(`subagent:request:${parentRequestId}`, ctx); }
return ctx;
})();
// Get the VS Code chat session ID from the CapturingToken (same mechanism as old debug panel)
const chatSessionId = getCurrentCapturingToken()?.chatSessionId;
const parentChatSessionId = getCurrentCapturingToken()?.parentChatSessionId;
const debugLogLabel = getCurrentCapturingToken()?.debugLogLabel;
return this._otelService.startActiveSpan(
`invoke_agent ${agentName}`,
{
kind: SpanKind.INTERNAL,
attributes: {
[GenAiAttr.OPERATION_NAME]: GenAiOperationName.INVOKE_AGENT,
[GenAiAttr.PROVIDER_NAME]: GenAiProviderName.GITHUB,
[GenAiAttr.AGENT_NAME]: agentName,
[GenAiAttr.CONVERSATION_ID]: this.options.conversation.sessionId,
[CopilotChatAttr.SESSION_ID]: this.options.conversation.sessionId,
...(chatSessionId ? { [CopilotChatAttr.CHAT_SESSION_ID]: chatSessionId } : {}),
...(parentChatSessionId ? { [CopilotChatAttr.PARENT_CHAT_SESSION_ID]: parentChatSessionId } : {}),
...(debugLogLabel ? { [CopilotChatAttr.DEBUG_LOG_LABEL]: debugLogLabel } : {}),
...(customModeName ? { 'copilot_chat.mode_name': customModeName } : {}),
...workspaceMetadataToOTelAttributes(resolveWorkspaceOTelMetadata(this._gitService)),
},
parentTraceContext,
},
async (span) => {
const otelStartTime = Date.now();
// Register this session as a child of its parent so that debug
// log entries are routed to a dedicated child JSONL file.
// parentChatSessionId is only set on subagent requests
// (see CapturingToken setup in defaultIntentRequestHandler).
if (parentChatSessionId && chatSessionId) {
const childLabel = debugLogLabel ?? `runSubagent-${agentName}`;
this._instantiationService.invokeFunction(accessor =>
accessor.get(IChatDebugFileLoggerService).startChildSession(
chatSessionId, parentChatSessionId, childLabel, parentTraceContext?.spanId));
}
// Emit session start event and metric for top-level agent invocations (not subagents)
if (!parentTraceContext) {
GenAiMetrics.incrementSessionCount(this._otelService);
try {
const endpoint = await this._endpointProvider.getChatEndpoint(this.options.request);
emitSessionStartEvent(this._otelService, this.options.conversation.sessionId, endpoint.model, agentName);
} catch {
emitSessionStartEvent(this._otelService, this.options.conversation.sessionId, 'unknown', agentName);
}
}
// Set request model from the endpoint
try {
const endpoint = await this._endpointProvider.getChatEndpoint(this.options.request);
span.setAttribute(GenAiAttr.REQUEST_MODEL, endpoint.model);
} catch { /* endpoint not available yet, will be set on response */ }
// Always capture user input message for the debug panel
{
const userMessage = this.turn.request.message;
span.setAttribute(GenAiAttr.INPUT_MESSAGES, truncateForOTel(JSON.stringify([
{ role: 'user', parts: [{ type: 'text', content: userMessage }] }
])));
// Emit user_message span event for real-time debug panel streaming
if (userMessage) {
span.addEvent('user_message', { content: userMessage, ...(chatSessionId ? { [CopilotChatAttr.CHAT_SESSION_ID]: chatSessionId } : {}) });
}
}
// Accumulate token usage across all LLM turns per GenAI agent span spec
let totalInputTokens = 0;
let totalOutputTokens = 0;
let lastResolvedModel: string | undefined;
let turnIndex = 0;
const tokenListener = this.onDidReceiveResponse(({ response }) => {
const turnInputTokens = response.type === ChatFetchResponseType.Success ? (response.usage?.prompt_tokens || 0) : 0;
const turnOutputTokens = response.type === ChatFetchResponseType.Success ? (response.usage?.completion_tokens || 0) : 0;
if (response.type === ChatFetchResponseType.Success && response.usage) {
totalInputTokens += turnInputTokens;
totalOutputTokens += turnOutputTokens;
}
if (response.type === ChatFetchResponseType.Success && response.resolvedModel) {
lastResolvedModel = response.resolvedModel;
}
emitAgentTurnEvent(this._otelService, turnIndex, turnInputTokens, turnOutputTokens, 0);
turnIndex++;
});
try {
const result = await this._runLoop(outputStream, token, span, chatSessionId);
span.setAttributes({
[CopilotChatAttr.TURN_COUNT]: result.toolCallRounds.length,
[GenAiAttr.USAGE_INPUT_TOKENS]: totalInputTokens,
[GenAiAttr.USAGE_OUTPUT_TOKENS]: totalOutputTokens,
...(lastResolvedModel ? { [GenAiAttr.RESPONSE_MODEL]: lastResolvedModel } : {}),
});
// Always capture agent output message and tool definitions for the debug panel
{
const lastRound = result.toolCallRounds.at(-1);
if (lastRound?.response) {
const responseText = Array.isArray(lastRound.response) ? lastRound.response.join('') : lastRound.response;
span.setAttribute(GenAiAttr.OUTPUT_MESSAGES, truncateForOTel(JSON.stringify([
{ role: 'assistant', parts: [{ type: 'text', content: responseText }] }
])));
}
// Log tool definitions once on the agent span (same set across all turns)
if (result.availableTools.length > 0) {
span.setAttribute(GenAiAttr.TOOL_DEFINITIONS, JSON.stringify(
result.availableTools.map(t => ({ type: 'function', name: t.name, description: t.description }))
));
}
}
span.setStatus(SpanStatusCode.OK);
// Record agent-level metrics
const durationSec = (Date.now() - otelStartTime) / 1000;
GenAiMetrics.recordAgentDuration(this._otelService, agentName, durationSec);
GenAiMetrics.recordAgentTurnCount(this._otelService, agentName, result.toolCallRounds.length);
return result;
} catch (err) {
span.setStatus(SpanStatusCode.ERROR, err instanceof Error ? err.message : String(err));
span.setAttribute(StdAttr.ERROR_TYPE, err instanceof Error ? err.constructor.name : 'Error');
throw err;
} finally {
tokenListener.dispose();
}
},
);
}
private async _runLoop(outputStream: ChatResponseStream | undefined, token: CancellationToken, agentSpan?: ISpanHandle, chatSessionId?: string): Promise<IToolCallLoopResult> {
let i = 0;
let lastResult: IToolCallSingleResult | undefined;
let lastRequestMessagesStartingIndexForRun: number | undefined;
let stopHookActive = false;
const sessionId = this.options.conversation.sessionId;
// Store span context so runOne() can emit tools_available on first call
this.agentSpan = agentSpan;
this.chatSessionIdForTools = chatSessionId;
this.toolsAvailableEmitted = false;
while (true) {
if (lastResult && i++ >= this.options.toolCallLimit) {
// In Autopilot mode, silently increase the limit and continue
// without showing the confirmation dialog, up to a hard cap.
const permLevel = this.options.request.permissionLevel;
if (permLevel === 'autopilot' && this.options.toolCallLimit < 200) {
this.options.toolCallLimit = Math.min(Math.round(this.options.toolCallLimit * 3 / 2), 200);
this.showAutopilotProgress(outputStream, l10n.t('Extending tool call limit with Autopilot...'), l10n.t('Extended tool call limit with Autopilot'));
} else {
lastResult = this.hitToolCallLimit(outputStream, lastResult);
break;
}
}
// Check if VS Code has requested we gracefully yield before starting the next iteration.
// In autopilot mode, don't yield until the task is actually complete.
if (lastResult && this.options.yieldRequested?.()) {
if (this.options.request.permissionLevel !== 'autopilot' || this.taskCompleted) {
break;
}
}
try {
const turnId = String(i);
this._sessionTranscriptService.logAssistantTurnStart(sessionId, turnId);
agentSpan?.addEvent('turn_start', { turnId, ...(chatSessionId ? { [CopilotChatAttr.CHAT_SESSION_ID]: chatSessionId } : {}) });
this.resolveAutopilotProgress();
const result = await this.runOne(outputStream, i, token);
if (lastRequestMessagesStartingIndexForRun === undefined) {
lastRequestMessagesStartingIndexForRun = result.lastRequestMessages.length - 1;
}
lastResult = {
...result,
hadIgnoredFiles: lastResult?.hadIgnoredFiles || result.hadIgnoredFiles
};
this.toolCallRounds.push(result.round);
this._sessionTranscriptService.logAssistantTurnEnd(sessionId, turnId);
agentSpan?.addEvent('turn_end', { turnId, ...(chatSessionId ? { [CopilotChatAttr.CHAT_SESSION_ID]: chatSessionId } : {}) });
// Inline summarization: the model responded with summary text only (no tool calls).
// Extract the summary, store it on the appropriate round, and continue the loop.
if (result.inlineSummarizationRequested && !result.round.toolCalls.length) {
if (result.response.type !== ChatFetchResponseType.Success) {
this.inlineSummarizationProgressDeferred?.complete(undefined);
this.inlineSummarizationProgressDeferred = undefined;
} else {
const summaryText = extractInlineSummary(result.round.response);
if (summaryText !== undefined) {
const summarizedRound = this.applySummaryToRound(summaryText);
if (summarizedRound) {
// Persist summary on the turn so normalizeSummariesOnRounds can restore it
const turn = this.turn;
const resolvedModel = result.response.resolvedModel;
const usage = result.response.usage;
turn.addPendingSummary(summarizedRound, summaryText);
const history = this.options.conversation.turns.slice(0, -1);
// Exclude the summarization round from telemetry counts for parity with separate-call summarization
const toolCallRoundsForTelemetry = this.toolCallRounds.slice(0, -1);
const numRoundsInHistory = history.reduce((sum, t) => sum + t.rounds.length, 0);
const numRoundsInCurrentTurn = toolCallRoundsForTelemetry.length;
const numRounds = numRoundsInHistory + numRoundsInCurrentTurn;
const lastUsedTool = toolCallRoundsForTelemetry.at(-1)?.toolCalls.at(-1)?.name
?? history.at(-1)?.rounds.at(-1)?.toolCalls.at(-1)?.name ?? 'none';
// Compute rounds since last summarization (same logic as ConversationHistorySummarizer)
let numRoundsSinceLastSummarization = -1;
for (let ri = toolCallRoundsForTelemetry.length - 1; ri >= 0; ri--) {
if (toolCallRoundsForTelemetry[ri].summary) {
numRoundsSinceLastSummarization = toolCallRoundsForTelemetry.length - 1 - ri;
break;
}
}
if (numRoundsSinceLastSummarization === -1) {
let count = numRoundsInCurrentTurn;
outerLoop: for (let ti = history.length - 1; ti >= 0; ti--) {
for (let ri = history[ti].rounds.length - 1; ri >= 0; ri--) {
if (history[ti].rounds[ri].summary) {
numRoundsSinceLastSummarization = count;
break outerLoop;
}
count++;
}
}
}
const inlineSummarizationMeta = new SummarizedConversationHistoryMetadata(
summarizedRound,
summaryText,
{
usage,
model: resolvedModel,
summarizationMode: 'inline',
numRounds,
numRoundsSinceLastSummarization,
source: 'foreground',
outcome: 'success',
},
);
turn.setMetadata(inlineSummarizationMeta);
// Fire telemetry matching the existing summarizedConversationHistory event
/* __GDPR__
"summarizedConversationHistory" : {
"owner": "bhavyau",
"comment": "Tracks inline summarization",
"outcome": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The success state." },
"model": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The model ID." },
"summarizationMode": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The summarization mode." },
"source": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "Whether background or foreground." },
"conversationId": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "Session id." },
"chatRequestId": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The chat request ID." },
"lastUsedTool": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The last tool used before summarization." },
"requestId": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "comment": "The request ID from the summarization call." },
"numRounds": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "Total tool call rounds." },
"numRoundsSinceLastSummarization": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "Rounds since last summarization." },
"turnIndex": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "The index of the current turn." },
"curTurnRoundIndex": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "The index of the current round within the current turn." },
"isDuringToolCalling": { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true, "comment": "Whether this was triggered during tool calling." },
"promptTokenCount": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true, "comment": "Prompt tokens." },
"promptCacheTokenCount": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true, "comment": "Cached prompt tokens." },
"responseTokenCount": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true, "comment": "Output tokens." }
}
*/
this._telemetryService.sendMSFTTelemetryEvent('summarizedConversationHistory', {
outcome: 'success',
model: resolvedModel,
summarizationMode: 'inline',
source: 'foreground',
conversationId: this.options.conversation.sessionId,