-
Notifications
You must be signed in to change notification settings - Fork 14.4k
Expand file tree
/
Copy pathclient.ts
More file actions
1299 lines (1157 loc) · 40.4 KB
/
Copy pathclient.ts
File metadata and controls
1299 lines (1157 loc) · 40.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {
createUserContent,
type GenerateContentConfig,
type PartListUnion,
type Content,
type Tool,
type GenerateContentResponse,
} from '@google/genai';
import { partListUnionToString } from './geminiRequest.js';
import {
getDirectoryContextString,
getInitialChatHistory,
} from '../utils/environmentContext.js';
import {
CompressionStatus,
Turn,
GeminiEventType,
type ServerGeminiStreamEvent,
type ChatCompressionInfo,
} from './turn.js';
import type { Config } from '../config/config.js';
import { type AgentLoopContext } from '../config/agent-loop-context.js';
import { getCoreSystemPrompt } from './prompts.js';
import { checkNextSpeaker } from '../utils/nextSpeakerChecker.js';
import { reportError } from '../utils/errorReporting.js';
import { GeminiChat } from './geminiChat.js';
import {
retryWithBackoff,
type RetryAvailabilityContext,
} from '../utils/retry.js';
import type { ValidationRequiredError } from '../utils/googleQuotaErrors.js';
import { getErrorMessage, isAbortError } from '../utils/errors.js';
import { tokenLimit } from './tokenLimits.js';
import type {
ChatRecordingService,
ResumedSessionData,
} from '../services/chatRecordingService.js';
import type { ContentGenerator } from './contentGenerator.js';
import { LoopDetectionService } from '../services/loopDetectionService.js';
import { ChatCompressionService } from '../context/chatCompressionService.js';
import { AgentHistoryProvider } from '../context/agentHistoryProvider.js';
import type { ContextManager } from '../context/contextManager.js';
import type { HistoryTurn } from './agentChatHistory.js';
import { ideContextStore } from '../ide/ideContext.js';
import { logNextSpeakerCheck } from '../telemetry/loggers.js';
import type {
DefaultHookOutput,
AfterAgentHookOutput,
} from '../hooks/types.js';
import { NextSpeakerCheckEvent, LlmRole } from '../telemetry/types.js';
import { uiTelemetryService } from '../telemetry/uiTelemetry.js';
import type { IdeContext, File } from '../ide/types.js';
import { handleFallback } from '../fallback/handler.js';
import type { RoutingContext } from '../routing/routingStrategy.js';
import { debugLogger } from '../utils/debugLogger.js';
import type { ModelConfigKey } from '../services/modelConfigService.js';
import { ToolOutputMaskingService } from '../context/toolOutputMaskingService.js';
import { calculateRequestTokenCount } from '../utils/tokenCalculation.js';
import {
applyModelSelection,
createAvailabilityContextProvider,
} from '../availability/policyHelpers.js';
import { getDisplayString, resolveModel } from '../config/models.js';
import { partToString } from '../utils/partUtils.js';
import { randomUUID } from 'node:crypto';
import {
coreEvents,
CoreEvent,
type ApprovalModeChangedPayload,
} from '../utils/events.js';
import { initializeContextManager } from '../context/initializer.js';
const MAX_TURNS = 100;
type BeforeAgentHookReturn =
| {
type: GeminiEventType.AgentExecutionStopped;
value: { reason: string; systemMessage?: string };
}
| {
type: GeminiEventType.AgentExecutionBlocked;
value: { reason: string; systemMessage?: string };
}
| { additionalContext: string | undefined }
| undefined;
export class GeminiClient {
private chat?: GeminiChat;
private sessionTurnCount = 0;
private readonly loopDetector: LoopDetectionService;
private readonly compressionService: ChatCompressionService;
private readonly agentHistoryProvider: AgentHistoryProvider;
private readonly toolOutputMaskingService: ToolOutputMaskingService;
private contextManager?: ContextManager;
private lastPromptId: string;
private currentSequenceModel: string | null = null;
private lastSentIdeContext: IdeContext | undefined;
private forceFullIdeContext = true;
/**
* At any point in this conversation, was compression triggered without
* being forced and did it fail?
*/
private hasFailedCompressionAttempt = false;
constructor(private readonly context: AgentLoopContext) {
this.loopDetector = new LoopDetectionService(this.config);
this.compressionService = new ChatCompressionService();
this.agentHistoryProvider = new AgentHistoryProvider(
this.config.agentHistoryProviderConfig,
this.config,
);
this.toolOutputMaskingService = new ToolOutputMaskingService();
this.lastPromptId = this.config.getSessionId();
coreEvents.on(CoreEvent.ModelChanged, this.handleModelChanged);
coreEvents.on(CoreEvent.MemoryChanged, this.handleMemoryChanged);
coreEvents.on(
CoreEvent.ApprovalModeChanged,
this.handleApprovalModeChanged,
);
}
private get config(): Config {
return this.context.config;
}
private handleModelChanged = () => {
this.currentSequenceModel = null;
};
private handleMemoryChanged = () => {
this.updateSystemInstruction();
};
private handleApprovalModeChanged = (payload: ApprovalModeChangedPayload) => {
if (payload.sessionId === this.config.getSessionId()) {
this.updateSystemInstruction();
}
};
clearCurrentSequenceModel(): void {
this.currentSequenceModel = null;
}
// Hook state to deduplicate BeforeAgent calls and track response for
// AfterAgent
private hookStateMap = new Map<
string,
{
hasFiredBeforeAgent: boolean;
cumulativeResponse: string;
activeCalls: number;
originalRequest: PartListUnion;
}
>();
private async fireBeforeAgentHookSafe(
request: PartListUnion,
prompt_id: string,
): Promise<BeforeAgentHookReturn> {
let hookState = this.hookStateMap.get(prompt_id);
if (!hookState) {
hookState = {
hasFiredBeforeAgent: false,
cumulativeResponse: '',
activeCalls: 0,
originalRequest: request,
};
this.hookStateMap.set(prompt_id, hookState);
}
// Increment active calls for this prompt_id
// This is called at the start of sendMessageStream, so it acts as an entry
// counter. We increment here, assuming this helper is ALWAYS called at
// entry.
hookState.activeCalls++;
if (hookState.hasFiredBeforeAgent) {
return undefined;
}
const hookOutput = await this.config
.getHookSystem()
?.fireBeforeAgentEvent(partToString(request));
hookState.hasFiredBeforeAgent = true;
if (hookOutput?.shouldStopExecution()) {
return {
type: GeminiEventType.AgentExecutionStopped,
value: {
reason: hookOutput.getEffectiveReason(),
systemMessage: hookOutput.systemMessage,
},
};
}
if (hookOutput?.isBlockingDecision()) {
return {
type: GeminiEventType.AgentExecutionBlocked,
value: {
reason: hookOutput.getEffectiveReason(),
systemMessage: hookOutput.systemMessage,
},
};
}
const additionalContext = hookOutput?.getAdditionalContext();
if (additionalContext) {
return { additionalContext };
}
return undefined;
}
private async fireAfterAgentHookSafe(
currentRequest: PartListUnion,
prompt_id: string,
turn?: Turn,
stopHookActive: boolean = false,
): Promise<DefaultHookOutput | undefined> {
const hookState = this.hookStateMap.get(prompt_id);
// Only fire on the outermost call (when activeCalls is 1)
if (!hookState || (hookState.activeCalls !== 1 && !stopHookActive)) {
return undefined;
}
if (turn && turn.pendingToolCalls.length > 0) {
return undefined;
}
const finalResponseText =
hookState.cumulativeResponse ||
turn?.getResponseText() ||
'[no response text]';
const finalRequest = hookState.originalRequest || currentRequest;
const hookOutput = await this.config
.getHookSystem()
?.fireAfterAgentEvent(
partToString(finalRequest),
finalResponseText,
stopHookActive,
);
return hookOutput;
}
private updateTelemetryTokenCount() {
if (this.chat) {
uiTelemetryService.setLastPromptTokenCount(
this.chat.getLastPromptTokenCount(),
);
}
}
async initialize() {
this.chat = await this.startChat();
this.updateTelemetryTokenCount();
}
private getContentGeneratorOrFail(): ContentGenerator {
if (!this.config.getContentGenerator()) {
throw new Error('Content generator not initialized');
}
return this.config.getContentGenerator();
}
async addHistory(content: Content) {
this.getChat().addHistory(content);
}
getChat(): GeminiChat {
if (!this.chat) {
throw new Error('Chat not initialized');
}
return this.chat;
}
isInitialized(): boolean {
return this.chat !== undefined;
}
getHistory(): readonly Content[] {
return this.getChat().getHistory();
}
stripThoughtsFromHistory() {
this.getChat().stripThoughtsFromHistory();
}
setHistory(history: ReadonlyArray<Content | HistoryTurn>) {
this.getChat().setHistory(history);
this.updateTelemetryTokenCount();
this.forceFullIdeContext = true;
}
private lastUsedModelId?: string;
async setTools(modelId?: string): Promise<void> {
if (!this.chat) {
return;
}
if (modelId && modelId === this.lastUsedModelId) {
return;
}
this.lastUsedModelId = modelId;
const toolRegistry = this.context.toolRegistry;
const toolDeclarations = toolRegistry.getFunctionDeclarations(modelId);
const tools: Tool[] = [{ functionDeclarations: toolDeclarations }];
this.getChat().setTools(tools);
}
async resetChat(): Promise<void> {
this.chat = await this.startChat();
this.updateTelemetryTokenCount();
// Reset JIT context loaded paths so subdirectory context can be
// re-discovered in the new session.
await this.config.getMemoryContextManager()?.refresh();
}
dispose() {
coreEvents.off(CoreEvent.ModelChanged, this.handleModelChanged);
coreEvents.off(CoreEvent.MemoryChanged, this.handleMemoryChanged);
coreEvents.off(
CoreEvent.ApprovalModeChanged,
this.handleApprovalModeChanged,
);
}
async resumeChat(
history: ReadonlyArray<Content | HistoryTurn>,
resumedSessionData?: ResumedSessionData,
): Promise<void> {
this.chat = await this.startChat(history, resumedSessionData);
this.updateTelemetryTokenCount();
}
getChatRecordingService(): ChatRecordingService | undefined {
return this.chat?.getChatRecordingService();
}
getLoopDetectionService(): LoopDetectionService {
return this.loopDetector;
}
getCurrentSequenceModel(): string | null {
return this.currentSequenceModel;
}
async addDirectoryContext(): Promise<void> {
if (!this.chat) {
return;
}
this.getChat().addHistory({
role: 'user',
parts: [{ text: await getDirectoryContextString(this.config) }],
});
}
updateSystemInstruction(): void {
if (!this.isInitialized()) {
return;
}
const systemMemory = this.config.getSystemInstructionMemory();
const systemInstruction = getCoreSystemPrompt(this.config, systemMemory);
this.getChat().setSystemInstruction(systemInstruction);
}
async startChat(
extraHistory?: ReadonlyArray<Content | HistoryTurn>,
resumedSessionData?: ResumedSessionData,
): Promise<GeminiChat> {
this.forceFullIdeContext = true;
this.hasFailedCompressionAttempt = false;
this.lastUsedModelId = undefined;
const toolRegistry = this.context.toolRegistry;
const toolDeclarations = toolRegistry.getFunctionDeclarations();
const tools: Tool[] = [{ functionDeclarations: toolDeclarations }];
const history = await getInitialChatHistory(this.config, extraHistory);
try {
const systemMemory = this.config.getSystemInstructionMemory();
const systemInstruction = getCoreSystemPrompt(this.config, systemMemory);
const chat = new GeminiChat(
this.config,
systemInstruction,
tools,
[...history],
resumedSessionData,
async (modelId: string) => {
this.lastUsedModelId = modelId;
const toolRegistry = this.context.toolRegistry;
const toolDeclarations =
toolRegistry.getFunctionDeclarations(modelId);
return [{ functionDeclarations: toolDeclarations }];
},
);
await chat.initialize(resumedSessionData, 'main');
this.contextManager = await initializeContextManager(
this.config,
chat,
this.lastPromptId,
);
return chat;
} catch (error) {
await reportError(
error,
'Error initializing Gemini chat session.',
[...history],
'startChat',
);
throw new Error(`Failed to initialize chat: ${getErrorMessage(error)}`);
}
}
private getIdeContextParts(forceFullContext: boolean): {
contextParts: string[];
newIdeContext: IdeContext | undefined;
} {
const currentIdeContext = ideContextStore.get();
if (!currentIdeContext) {
return { contextParts: [], newIdeContext: undefined };
}
if (forceFullContext || !this.lastSentIdeContext) {
// Send full context as JSON
const openFiles = currentIdeContext.workspaceState?.openFiles || [];
const activeFile = openFiles.find((f) => f.isActive);
const otherOpenFiles = openFiles
.filter((f) => !f.isActive)
.map((f) => f.path);
const contextData: Record<string, unknown> = {};
if (activeFile) {
contextData['activeFile'] = {
path: activeFile.path,
cursor: activeFile.cursor
? {
line: activeFile.cursor.line,
character: activeFile.cursor.character,
}
: undefined,
selectedText: activeFile.selectedText || undefined,
};
}
if (otherOpenFiles.length > 0) {
contextData['otherOpenFiles'] = otherOpenFiles;
}
if (Object.keys(contextData).length === 0) {
return { contextParts: [], newIdeContext: currentIdeContext };
}
const jsonString = JSON.stringify(contextData, null, 2);
const contextParts = [
"Here is the user's editor context as a JSON object. This is for your information only.",
'```json',
jsonString,
'```',
];
if (this.config.getDebugMode()) {
debugLogger.log(contextParts.join('\n'));
}
return {
contextParts,
newIdeContext: currentIdeContext,
};
} else {
// Calculate and send delta as JSON
const delta: Record<string, unknown> = {};
const changes: Record<string, unknown> = {};
const lastFiles = new Map(
(this.lastSentIdeContext.workspaceState?.openFiles || []).map(
(f: File) => [f.path, f],
),
);
const currentFiles = new Map(
(currentIdeContext.workspaceState?.openFiles || []).map((f: File) => [
f.path,
f,
]),
);
const openedFiles: string[] = [];
for (const [path] of currentFiles.entries()) {
if (!lastFiles.has(path)) {
openedFiles.push(path);
}
}
if (openedFiles.length > 0) {
changes['filesOpened'] = openedFiles;
}
const closedFiles: string[] = [];
for (const [path] of lastFiles.entries()) {
if (!currentFiles.has(path)) {
closedFiles.push(path);
}
}
if (closedFiles.length > 0) {
changes['filesClosed'] = closedFiles;
}
const lastActiveFile = (
this.lastSentIdeContext.workspaceState?.openFiles || []
).find((f: File) => f.isActive);
const currentActiveFile = (
currentIdeContext.workspaceState?.openFiles || []
).find((f: File) => f.isActive);
if (currentActiveFile) {
if (!lastActiveFile || lastActiveFile.path !== currentActiveFile.path) {
changes['activeFileChanged'] = {
path: currentActiveFile.path,
cursor: currentActiveFile.cursor
? {
line: currentActiveFile.cursor.line,
character: currentActiveFile.cursor.character,
}
: undefined,
selectedText: currentActiveFile.selectedText || undefined,
};
} else {
const lastCursor = lastActiveFile.cursor;
const currentCursor = currentActiveFile.cursor;
if (
currentCursor &&
(!lastCursor ||
lastCursor.line !== currentCursor.line ||
lastCursor.character !== currentCursor.character)
) {
changes['cursorMoved'] = {
path: currentActiveFile.path,
cursor: {
line: currentCursor.line,
character: currentCursor.character,
},
};
}
const lastSelectedText = lastActiveFile.selectedText || '';
const currentSelectedText = currentActiveFile.selectedText || '';
if (lastSelectedText !== currentSelectedText) {
changes['selectionChanged'] = {
path: currentActiveFile.path,
selectedText: currentSelectedText,
};
}
}
} else if (lastActiveFile) {
changes['activeFileChanged'] = {
path: null,
previousPath: lastActiveFile.path,
};
}
if (Object.keys(changes).length === 0) {
return { contextParts: [], newIdeContext: currentIdeContext };
}
delta['changes'] = changes;
const jsonString = JSON.stringify(delta, null, 2);
const contextParts = [
"Here is a summary of changes in the user's editor context, in JSON format. This is for your information only.",
'```json',
jsonString,
'```',
];
if (this.config.getDebugMode()) {
debugLogger.log(contextParts.join('\n'));
}
return {
contextParts,
newIdeContext: currentIdeContext,
};
}
}
private _getActiveModelForCurrentTurn(): string {
if (this.currentSequenceModel) {
return this.currentSequenceModel;
}
// Availability logic: The configured model is the source of truth,
// including any permanent fallbacks (config.setModel) or manual overrides.
return resolveModel(
this.config.getActiveModel(),
this.config.getGemini31LaunchedSync?.() ?? false,
false,
this.config.getHasAccessToPreviewModel?.() ?? true,
this.config,
this.config.hasGemini35FlashGAAccess?.() ?? false,
);
}
private async *processTurn(
request: PartListUnion,
signal: AbortSignal,
prompt_id: string,
boundedTurns: number,
displayContent?: PartListUnion,
): AsyncGenerator<ServerGeminiStreamEvent, Turn> {
// Re-initialize turn (it was empty before if in loop, or new instance)
let turn = new Turn(this.getChat(), prompt_id);
this.sessionTurnCount++;
if (
this.config.getMaxSessionTurns() > 0 &&
this.sessionTurnCount > this.config.getMaxSessionTurns()
) {
yield { type: GeminiEventType.MaxSessionTurns };
return turn;
}
if (!boundedTurns) {
return turn;
}
// Check for context window overflow
const modelForLimitCheck = this._getActiveModelForCurrentTurn();
let currentBaseUnits = 0;
let apiHistoryOverride: Content[] | undefined = undefined;
if (this.config.getContextManagementConfig().enabled) {
if (this.contextManager) {
const rawPendingRequest = createUserContent(request);
const pendingRequest = {
id: randomUUID(),
content: rawPendingRequest,
};
const {
history: newHistory,
apiHistory,
pendingApiHistory,
baseUnits,
} = await this.contextManager.renderHistory(
pendingRequest,
undefined,
signal,
);
currentBaseUnits = baseUnits;
// Use the PROCESSED pending content if available (e.g. if cleaned or distilled)
const finalPendingContent =
pendingApiHistory.length > 0
? pendingApiHistory[0]
: rawPendingRequest;
// Late-bind the prompt: Append the active request to the managed history
// only for the purpose of the upcoming API call.
apiHistoryOverride = [...apiHistory, finalPendingContent];
this.getChat().setHistory(newHistory);
// Use the original request for display/recording,
// but the processed one for the API and durable history.
displayContent = rawPendingRequest.parts || [];
request = finalPendingContent.parts || [];
} else {
const newHistory = await this.agentHistoryProvider.manageHistory(
this.getHistory(),
signal,
);
if (newHistory.length !== this.getHistory().length) {
this.getChat().setHistory(newHistory);
}
}
} else {
const compressed = await this.tryCompressChat(prompt_id, false, signal);
if (compressed.compressionStatus === CompressionStatus.COMPRESSED) {
yield { type: GeminiEventType.ChatCompressed, value: compressed };
}
}
const remainingTokenCount =
tokenLimit(modelForLimitCheck) - this.getChat().getLastPromptTokenCount();
await this.tryMaskToolOutputs(this.getHistory());
// Estimate tokens. For text-only requests, we estimate based on character length.
// For requests with non-text parts (like images, tools), we use the countTokens API.
const estimatedRequestTokenCount = await calculateRequestTokenCount(
request,
this.getContentGeneratorOrFail(),
modelForLimitCheck,
);
if (estimatedRequestTokenCount > remainingTokenCount) {
yield {
type: GeminiEventType.ContextWindowWillOverflow,
value: { estimatedRequestTokenCount, remainingTokenCount },
};
return turn;
}
// Prevent context updates from being sent while a tool call is
// waiting for a response. The Gemini API requires that a functionResponse
// part from the user immediately follows a functionCall part from the model
// in the conversation history . The IDE context is not discarded; it will
// be included in the next regular message sent to the model.
const history = this.getHistory();
const lastMessage =
history.length > 0 ? history[history.length - 1] : undefined;
const hasPendingToolCall =
!!lastMessage &&
lastMessage.role === 'model' &&
(lastMessage.parts?.some((p) => 'functionCall' in p) || false);
if (this.config.getIdeMode() && !hasPendingToolCall) {
const { contextParts, newIdeContext } = this.getIdeContextParts(
this.forceFullIdeContext || history.length === 0,
);
if (contextParts.length > 0) {
this.getChat().addHistory({
role: 'user',
parts: [{ text: contextParts.join('\n') }],
});
}
this.lastSentIdeContext = newIdeContext;
this.forceFullIdeContext = false;
}
// Re-initialize turn with fresh history
turn = new Turn(this.getChat(), prompt_id);
const loopResult = await this.loopDetector.turnStarted(signal);
if (loopResult.count > 1) {
yield { type: GeminiEventType.LoopDetected };
return turn;
} else if (loopResult.count === 1) {
if (boundedTurns <= 1) {
yield { type: GeminiEventType.MaxSessionTurns };
return turn;
}
return yield* this._recoverFromLoop(
loopResult,
signal,
prompt_id,
boundedTurns,
displayContent,
);
}
const routingContext: RoutingContext = {
history: this.getChat().getHistory(/*curated=*/ true),
request,
signal,
requestedModel: this.config.getModel(),
};
let modelToUse: string;
// Determine Model (Stickiness vs. Routing)
if (this.currentSequenceModel) {
modelToUse = this.currentSequenceModel;
} else {
const router = this.config.getModelRouterService();
const decision = await router.route(routingContext);
modelToUse = decision.model;
}
// availability logic
const modelConfigKey: ModelConfigKey = {
model: modelToUse,
isChatModel: true,
};
const { model: finalModel } = applyModelSelection(
this.config,
modelConfigKey,
{ consumeAttempt: false },
);
modelToUse = finalModel;
if (!signal.aborted && !this.currentSequenceModel) {
yield { type: GeminiEventType.ModelInfo, value: modelToUse };
}
this.currentSequenceModel = modelToUse;
// Update tools with the final modelId to ensure model-dependent descriptions are used.
await this.setTools(modelToUse);
const resultStream = turn.run(modelConfigKey, request, signal, {
displayContent,
role: LlmRole.MAIN,
apiHistoryOverride,
});
let isError = false;
let loopDetectedAbort = false;
let loopRecoverResult: { detail?: string } | undefined;
for await (const event of resultStream) {
const loopResult = this.loopDetector.addAndCheck(event);
if (loopResult.count > 1) {
yield { type: GeminiEventType.LoopDetected };
loopDetectedAbort = true;
break;
} else if (loopResult.count === 1) {
if (boundedTurns <= 1) {
yield { type: GeminiEventType.MaxSessionTurns };
loopDetectedAbort = true;
break;
}
loopRecoverResult = loopResult;
break;
}
yield event;
if (event.type === GeminiEventType.Finished && this.contextManager) {
const usageMetadata = event.value.usageMetadata;
if (usageMetadata && usageMetadata.promptTokenCount !== undefined) {
this.contextManager.getEnvironment().eventBus.emitTokenGroundTruth({
actualTokens: usageMetadata.promptTokenCount,
promptBaseUnits: currentBaseUnits,
});
}
}
this.updateTelemetryTokenCount();
if (event.type === GeminiEventType.Error) {
isError = true;
}
}
if (loopDetectedAbort) {
return turn;
}
if (loopRecoverResult) {
return yield* this._recoverFromLoop(
loopRecoverResult,
signal,
prompt_id,
boundedTurns,
displayContent,
);
}
if (isError) {
return turn;
}
// Update cumulative response in hook state
// We do this immediately after the stream finishes for THIS turn.
const hooksEnabled = this.config.getEnableHooks();
if (hooksEnabled) {
const responseText = turn.getResponseText() || '';
const hookState = this.hookStateMap.get(prompt_id);
if (hookState && responseText) {
// Append with newline if not empty
hookState.cumulativeResponse = hookState.cumulativeResponse
? `${hookState.cumulativeResponse}\n${responseText}`
: responseText;
}
}
if (!turn.pendingToolCalls.length && signal && !signal.aborted) {
if (
!this.config.getQuotaErrorOccurred() &&
!this.config.getSkipNextSpeakerCheck()
) {
const nextSpeakerCheck = await checkNextSpeaker(
this.getChat(),
this.config.getBaseLlmClient(),
signal,
prompt_id,
);
logNextSpeakerCheck(
this.config,
new NextSpeakerCheckEvent(
prompt_id,
turn.finishReason?.toString() || '',
nextSpeakerCheck?.next_speaker || '',
),
);
if (nextSpeakerCheck?.next_speaker === 'model') {
const nextRequest = [{ text: 'Please continue.' }];
turn = yield* this.sendMessageStream(
nextRequest,
signal,
prompt_id,
boundedTurns - 1,
displayContent,
);
return turn;
}
}
}
return turn;
}
async *sendMessageStream(
request: PartListUnion,
signal: AbortSignal,
prompt_id: string,
turns: number = MAX_TURNS,
displayContent?: PartListUnion,
stopHookActive: boolean = false,
): AsyncGenerator<ServerGeminiStreamEvent, Turn> {
this.config.resetTurn();
const hooksEnabled = this.config.getEnableHooks();
const messageBus = this.context.messageBus;
if (this.lastPromptId !== prompt_id) {
this.loopDetector.reset(prompt_id, partListUnionToString(request));
this.hookStateMap.delete(this.lastPromptId);
this.lastPromptId = prompt_id;
this.currentSequenceModel = null;
}
if (hooksEnabled && messageBus) {
const hookResult = await this.fireBeforeAgentHookSafe(request, prompt_id);
if (hookResult) {
if (
'type' in hookResult &&
hookResult.type === GeminiEventType.AgentExecutionStopped
) {
// Add user message to history before returning so it's kept in the transcript
this.getChat().addHistory(createUserContent(request));
yield hookResult;
return new Turn(this.getChat(), prompt_id);
} else if (
'type' in hookResult &&
hookResult.type === GeminiEventType.AgentExecutionBlocked
) {
yield hookResult;
return new Turn(this.getChat(), prompt_id);
} else if ('additionalContext' in hookResult) {
const additionalContext = hookResult.additionalContext;
if (additionalContext) {
const requestArray = Array.isArray(request) ? request : [request];
request = [
...requestArray,
{ text: `<hook_context>${additionalContext}</hook_context>` },
];
}
}
}
}
const boundedTurns = Math.min(turns, MAX_TURNS);
let turn = new Turn(this.getChat(), prompt_id);
let continuationHandled = false;
try {
turn = yield* this.processTurn(
request,
signal,
prompt_id,
boundedTurns,
displayContent,
);
// Fire AfterAgent hook if we have a turn and no pending tools
if (hooksEnabled && messageBus) {
const hookOutput = await this.fireAfterAgentHookSafe(
request,
prompt_id,
turn,
stopHookActive,
);
// Cast to AfterAgentHookOutput for access to shouldClearContext()
const afterAgentOutput = hookOutput as AfterAgentHookOutput | undefined;
if (afterAgentOutput?.shouldStopExecution()) {
const contextCleared = afterAgentOutput.shouldClearContext();
yield {
type: GeminiEventType.AgentExecutionStopped,
value: {
reason: afterAgentOutput.getEffectiveReason(),
systemMessage: afterAgentOutput.systemMessage,
contextCleared,
},
};
// Clear context if requested (honor both stop + clear)
if (contextCleared) {
await this.resetChat();
}
return turn;
}