forked from google-gemini/gemini-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.ts
More file actions
1129 lines (1017 loc) · 36.4 KB
/
executor.ts
File metadata and controls
1129 lines (1017 loc) · 36.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 type { Config } from '../config/config.js';
import { reportError } from '../utils/errorReporting.js';
import { GeminiChat, StreamEventType } from '../core/geminiChat.js';
import { Type } from '@google/genai';
import type {
Content,
Part,
FunctionCall,
FunctionDeclaration,
Schema,
} from '@google/genai';
import { executeToolCall } from '../core/nonInteractiveToolExecutor.js';
import { ToolRegistry } from '../tools/tool-registry.js';
import { type ToolCallRequestInfo, CompressionStatus } from '../core/turn.js';
import { ChatCompressionService } from '../services/chatCompressionService.js';
import { getDirectoryContextString } from '../utils/environmentContext.js';
import {
GLOB_TOOL_NAME,
GREP_TOOL_NAME,
LS_TOOL_NAME,
MEMORY_TOOL_NAME,
READ_FILE_TOOL_NAME,
READ_MANY_FILES_TOOL_NAME,
WEB_SEARCH_TOOL_NAME,
} from '../tools/tool-names.js';
import { promptIdContext } from '../utils/promptIdContext.js';
import {
logAgentStart,
logAgentFinish,
logRecoveryAttempt,
} from '../telemetry/loggers.js';
import {
AgentStartEvent,
AgentFinishEvent,
RecoveryAttemptEvent,
} from '../telemetry/types.js';
import type {
AgentDefinition,
AgentInputs,
OutputObject,
SubagentActivityEvent,
} from './types.js';
import { AgentTerminateMode } from './types.js';
import { templateString } from './utils.js';
import { parseThought } from '../utils/thoughtUtils.js';
import { type z } from 'zod';
import { zodToJsonSchema } from 'zod-to-json-schema';
import { debugLogger } from '../utils/debugLogger.js';
import { getModelConfigAlias } from './registry.js';
/** A callback function to report on agent activity. */
export type ActivityCallback = (activity: SubagentActivityEvent) => void;
const TASK_COMPLETE_TOOL_NAME = 'complete_task';
const GRACE_PERIOD_MS = 60 * 1000; // 1 min
/** The possible outcomes of a single agent turn. */
type AgentTurnResult =
| {
status: 'continue';
nextMessage: Content;
}
| {
status: 'stop';
terminateReason: AgentTerminateMode;
finalResult: string | null;
};
/**
* Executes an agent loop based on an {@link AgentDefinition}.
*
* This executor runs the agent in a loop, calling tools until it calls the
* mandatory `complete_task` tool to signal completion.
*/
export class AgentExecutor<TOutput extends z.ZodTypeAny> {
readonly definition: AgentDefinition<TOutput>;
private readonly agentId: string;
private readonly toolRegistry: ToolRegistry;
private readonly runtimeContext: Config;
private readonly onActivity?: ActivityCallback;
private readonly compressionService: ChatCompressionService;
private hasFailedCompressionAttempt = false;
/**
* Creates and validates a new `AgentExecutor` instance.
*
* This method ensures that all tools specified in the agent's definition are
* safe for non-interactive use before creating the executor.
*
* @param definition The definition object for the agent.
* @param runtimeContext The global runtime configuration.
* @param onActivity An optional callback to receive activity events.
* @returns A promise that resolves to a new `AgentExecutor` instance.
*/
static async create<TOutput extends z.ZodTypeAny>(
definition: AgentDefinition<TOutput>,
runtimeContext: Config,
onActivity?: ActivityCallback,
): Promise<AgentExecutor<TOutput>> {
// Create an isolated tool registry for this agent instance.
const agentToolRegistry = new ToolRegistry(runtimeContext);
const parentToolRegistry = await runtimeContext.getToolRegistry();
if (definition.toolConfig) {
for (const toolRef of definition.toolConfig.tools) {
if (typeof toolRef === 'string') {
// If the tool is referenced by name, retrieve it from the parent
// registry and register it with the agent's isolated registry.
const toolFromParent = parentToolRegistry.getTool(toolRef);
if (toolFromParent) {
agentToolRegistry.registerTool(toolFromParent);
}
} else if (
typeof toolRef === 'object' &&
'name' in toolRef &&
'build' in toolRef
) {
agentToolRegistry.registerTool(toolRef);
}
// Note: Raw `FunctionDeclaration` objects in the config don't need to be
// registered; their schemas are passed directly to the model later.
}
agentToolRegistry.sortTools();
// Validate that all registered tools are safe for non-interactive
// execution.
await AgentExecutor.validateTools(agentToolRegistry, definition.name);
}
// Get the parent prompt ID from context
const parentPromptId = promptIdContext.getStore();
return new AgentExecutor(
definition,
runtimeContext,
agentToolRegistry,
parentPromptId,
onActivity,
);
}
/**
* Constructs a new AgentExecutor instance.
*
* @private This constructor is private. Use the static `create` method to
* instantiate the class.
*/
private constructor(
definition: AgentDefinition<TOutput>,
runtimeContext: Config,
toolRegistry: ToolRegistry,
parentPromptId: string | undefined,
onActivity?: ActivityCallback,
) {
this.definition = definition;
this.runtimeContext = runtimeContext;
this.toolRegistry = toolRegistry;
this.onActivity = onActivity;
this.compressionService = new ChatCompressionService();
const randomIdPart = Math.random().toString(36).slice(2, 8);
// parentPromptId will be undefined if this agent is invoked directly
// (top-level), rather than as a sub-agent.
const parentPrefix = parentPromptId ? `${parentPromptId}-` : '';
this.agentId = `${parentPrefix}${this.definition.name}-${randomIdPart}`;
}
/**
* Executes a single turn of the agent's logic, from calling the model
* to processing its response.
*
* @returns An {@link AgentTurnResult} object indicating whether to continue
* or stop the agent loop.
*/
private async executeTurn(
chat: GeminiChat,
currentMessage: Content,
turnCounter: number,
combinedSignal: AbortSignal,
timeoutSignal: AbortSignal, // Pass the timeout controller's signal
): Promise<AgentTurnResult> {
const promptId = `${this.agentId}#${turnCounter}`;
await this.tryCompressChat(chat, promptId);
const { functionCalls } = await promptIdContext.run(promptId, async () =>
this.callModel(chat, currentMessage, combinedSignal, promptId),
);
if (combinedSignal.aborted) {
const terminateReason = timeoutSignal.aborted
? AgentTerminateMode.TIMEOUT
: AgentTerminateMode.ABORTED;
return {
status: 'stop',
terminateReason,
finalResult: null, // 'run' method will set the final timeout string
};
}
// If the model stops calling tools without calling complete_task, it's an error.
if (functionCalls.length === 0) {
this.emitActivity('ERROR', {
error: `Agent stopped calling tools but did not call '${TASK_COMPLETE_TOOL_NAME}' to finalize the session.`,
context: 'protocol_violation',
});
return {
status: 'stop',
terminateReason: AgentTerminateMode.ERROR_NO_COMPLETE_TASK_CALL,
finalResult: null,
};
}
const { nextMessage, submittedOutput, taskCompleted } =
await this.processFunctionCalls(functionCalls, combinedSignal, promptId);
if (taskCompleted) {
const finalResult = submittedOutput ?? 'Task completed successfully.';
return {
status: 'stop',
terminateReason: AgentTerminateMode.GOAL,
finalResult,
};
}
// Task is not complete, continue to the next turn.
return {
status: 'continue',
nextMessage,
};
}
/**
* Generates a specific warning message for the agent's final turn.
*/
private getFinalWarningMessage(
reason:
| AgentTerminateMode.TIMEOUT
| AgentTerminateMode.MAX_TURNS
| AgentTerminateMode.ERROR_NO_COMPLETE_TASK_CALL,
): string {
let explanation = '';
switch (reason) {
case AgentTerminateMode.TIMEOUT:
explanation = 'You have exceeded the time limit.';
break;
case AgentTerminateMode.MAX_TURNS:
explanation = 'You have exceeded the maximum number of turns.';
break;
case AgentTerminateMode.ERROR_NO_COMPLETE_TASK_CALL:
explanation = 'You have stopped calling tools without finishing.';
break;
default:
throw new Error(`Unknown terminate reason: ${reason}`);
}
return `${explanation} You have one final chance to complete the task with a short grace period. You MUST call \`${TASK_COMPLETE_TOOL_NAME}\` immediately with your best answer and explain that your investigation was interrupted. Do not call any other tools.`;
}
/**
* Attempts a single, final recovery turn if the agent stops for a recoverable reason.
* Gives the agent a grace period to call `complete_task`.
*
* @returns The final result string if recovery was successful, or `null` if it failed.
*/
private async executeFinalWarningTurn(
chat: GeminiChat,
turnCounter: number,
reason:
| AgentTerminateMode.TIMEOUT
| AgentTerminateMode.MAX_TURNS
| AgentTerminateMode.ERROR_NO_COMPLETE_TASK_CALL,
externalSignal: AbortSignal, // The original signal passed to run()
): Promise<string | null> {
this.emitActivity('THOUGHT_CHUNK', {
text: `Execution limit reached (${reason}). Attempting one final recovery turn with a grace period.`,
});
const recoveryStartTime = Date.now();
let success = false;
const gracePeriodMs = GRACE_PERIOD_MS;
const graceTimeoutController = new AbortController();
const graceTimeoutId = setTimeout(
() => graceTimeoutController.abort(new Error('Grace period timed out.')),
gracePeriodMs,
);
try {
const recoveryMessage: Content = {
role: 'user',
parts: [{ text: this.getFinalWarningMessage(reason) }],
};
// We monitor both the external signal and our new grace period timeout
const combinedSignal = AbortSignal.any([
externalSignal,
graceTimeoutController.signal,
]);
const turnResult = await this.executeTurn(
chat,
recoveryMessage,
turnCounter, // This will be the "last" turn number
combinedSignal,
graceTimeoutController.signal, // Pass grace signal to identify a *grace* timeout
);
if (
turnResult.status === 'stop' &&
turnResult.terminateReason === AgentTerminateMode.GOAL
) {
// Success!
this.emitActivity('THOUGHT_CHUNK', {
text: 'Graceful recovery succeeded.',
});
success = true;
return turnResult.finalResult ?? 'Task completed during grace period.';
}
// Any other outcome (continue, error, non-GOAL stop) is a failure.
this.emitActivity('ERROR', {
error: `Graceful recovery attempt failed. Reason: ${turnResult.status}`,
context: 'recovery_turn',
});
return null;
} catch (error) {
// This catch block will likely catch the 'Grace period timed out' error.
this.emitActivity('ERROR', {
error: `Graceful recovery attempt failed: ${String(error)}`,
context: 'recovery_turn',
});
return null;
} finally {
clearTimeout(graceTimeoutId);
logRecoveryAttempt(
this.runtimeContext,
new RecoveryAttemptEvent(
this.agentId,
this.definition.name,
reason,
Date.now() - recoveryStartTime,
success,
turnCounter,
),
);
}
}
/**
* Runs the agent.
*
* @param inputs The validated input parameters for this invocation.
* @param signal An `AbortSignal` for cancellation.
* @returns A promise that resolves to the agent's final output.
*/
async run(inputs: AgentInputs, signal: AbortSignal): Promise<OutputObject> {
const startTime = Date.now();
let turnCounter = 0;
let terminateReason: AgentTerminateMode = AgentTerminateMode.ERROR;
let finalResult: string | null = null;
const { max_time_minutes } = this.definition.runConfig;
const timeoutController = new AbortController();
const timeoutId = setTimeout(
() => timeoutController.abort(new Error('Agent timed out.')),
max_time_minutes * 60 * 1000,
);
// Combine the external signal with the internal timeout signal.
const combinedSignal = AbortSignal.any([signal, timeoutController.signal]);
logAgentStart(
this.runtimeContext,
new AgentStartEvent(this.agentId, this.definition.name),
);
let chat: GeminiChat | undefined;
let tools: FunctionDeclaration[] | undefined;
try {
tools = this.prepareToolsList();
chat = await this.createChatObject(inputs, tools);
const query = this.definition.promptConfig.query
? templateString(this.definition.promptConfig.query, inputs)
: 'Get Started!';
let currentMessage: Content = { role: 'user', parts: [{ text: query }] };
while (true) {
// Check for termination conditions like max turns.
// const reason = this.checkTermination(startTime, turnCounter);
// if (reason) {
// terminateReason = reason;
// break;
// }
// Check for timeout or external abort.
if (combinedSignal.aborted) {
// Determine which signal caused the abort.
terminateReason = timeoutController.signal.aborted
? AgentTerminateMode.TIMEOUT
: AgentTerminateMode.ABORTED;
break;
}
// Check if this will be the last turn before executing it
const isLastTurn = this.checkIsLastTurn(turnCounter);
const turnResult = await this.executeTurn(
chat,
currentMessage,
turnCounter++,
combinedSignal,
timeoutController.signal,
);
if (turnResult.status === 'stop') {
terminateReason = turnResult.terminateReason;
// Only set finalResult if the turn provided one (e.g., error or goal).
if (turnResult.finalResult) {
finalResult = turnResult.finalResult;
}
break; // Exit the loop for *any* stop reason.
}
// If this was the last allowed turn and task is not complete, append warning to the response
if (isLastTurn && turnResult.status === 'continue') {
// Append warning message to the tool results
const warningText = this.getFinalWarningMessage(
AgentTerminateMode.MAX_TURNS,
);
const nextMessageParts = turnResult.nextMessage.parts || [];
nextMessageParts.push({ text: warningText });
currentMessage = {
role: 'user',
parts: nextMessageParts,
};
// Execute one more turn with the warning included
const finalTurnResult = await this.executeTurn(
chat,
currentMessage,
turnCounter++,
combinedSignal,
timeoutController.signal,
);
if (
finalTurnResult.status === 'stop' &&
finalTurnResult.terminateReason === AgentTerminateMode.GOAL
) {
terminateReason = AgentTerminateMode.GOAL;
finalResult = finalTurnResult.finalResult;
} else {
terminateReason = AgentTerminateMode.MAX_TURNS;
}
break;
}
// If status is 'continue', update message for the next loop
currentMessage = turnResult.nextMessage;
}
// === UNIFIED RECOVERY BLOCK ===
// Only attempt recovery if it's a known recoverable reason.
// We don't recover from GOAL (already done) or ABORTED (user cancelled).
if (
terminateReason !== AgentTerminateMode.ERROR &&
terminateReason !== AgentTerminateMode.ABORTED &&
terminateReason !== AgentTerminateMode.GOAL
) {
const recoveryResult = await this.executeFinalWarningTurn(
chat,
turnCounter, // Use current turnCounter for the recovery attempt
terminateReason,
signal, // Pass the external signal
);
if (recoveryResult !== null) {
// Recovery Succeeded
terminateReason = AgentTerminateMode.GOAL;
finalResult = recoveryResult;
} else {
// Recovery Failed. Set the final error message based on the *original* reason.
if (terminateReason === AgentTerminateMode.TIMEOUT) {
finalResult = `Agent timed out after ${this.definition.runConfig.max_time_minutes} minutes.`;
this.emitActivity('ERROR', {
error: finalResult,
context: 'timeout',
});
} else if (terminateReason === AgentTerminateMode.MAX_TURNS) {
finalResult = `Agent reached max turns limit (${this.definition.runConfig.max_turns}).`;
this.emitActivity('ERROR', {
error: finalResult,
context: 'max_turns',
});
} else if (
terminateReason === AgentTerminateMode.ERROR_NO_COMPLETE_TASK_CALL
) {
// The finalResult was already set by executeTurn, but we re-emit just in case.
finalResult =
finalResult ||
`Agent stopped calling tools but did not call '${TASK_COMPLETE_TOOL_NAME}'.`;
this.emitActivity('ERROR', {
error: finalResult,
context: 'protocol_violation',
});
}
}
}
// === FINAL RETURN LOGIC ===
if (terminateReason === AgentTerminateMode.GOAL) {
return {
result: finalResult || 'Task completed.',
terminate_reason: terminateReason,
};
}
return {
result:
finalResult || 'Agent execution was terminated before completion.',
terminate_reason: terminateReason,
};
} catch (error) {
// Check if the error is an AbortError caused by our internal timeout.
if (
error instanceof Error &&
error.name === 'AbortError' &&
timeoutController.signal.aborted &&
!signal.aborted // Ensure the external signal was not the cause
) {
terminateReason = AgentTerminateMode.TIMEOUT;
// Also use the unified recovery logic here
if (chat && tools) {
const recoveryResult = await this.executeFinalWarningTurn(
chat,
turnCounter, // Use current turnCounter
AgentTerminateMode.TIMEOUT,
signal,
);
if (recoveryResult !== null) {
// Recovery Succeeded
terminateReason = AgentTerminateMode.GOAL;
finalResult = recoveryResult;
return {
result: finalResult,
terminate_reason: terminateReason,
};
}
}
// Recovery failed or wasn't possible
finalResult = `Agent timed out after ${this.definition.runConfig.max_time_minutes} minutes.`;
this.emitActivity('ERROR', {
error: finalResult,
context: 'timeout',
});
return {
result: finalResult,
terminate_reason: terminateReason,
};
}
this.emitActivity('ERROR', { error: String(error) });
throw error; // Re-throw other errors or external aborts.
} finally {
clearTimeout(timeoutId);
logAgentFinish(
this.runtimeContext,
new AgentFinishEvent(
this.agentId,
this.definition.name,
Date.now() - startTime,
turnCounter,
terminateReason,
),
);
}
}
private async tryCompressChat(
chat: GeminiChat,
prompt_id: string,
): Promise<void> {
const model = this.definition.modelConfig.model;
const { newHistory, info } = await this.compressionService.compress(
chat,
prompt_id,
false,
model,
this.runtimeContext,
this.hasFailedCompressionAttempt,
);
if (
info.compressionStatus ===
CompressionStatus.COMPRESSION_FAILED_INFLATED_TOKEN_COUNT
) {
this.hasFailedCompressionAttempt = true;
} else if (info.compressionStatus === CompressionStatus.COMPRESSED) {
if (newHistory) {
chat.setHistory(newHistory);
this.hasFailedCompressionAttempt = false;
}
}
}
/**
* Calls the generative model with the current context and tools.
*
* @returns The model's response, including any tool calls or text.
*/
private async callModel(
chat: GeminiChat,
message: Content,
signal: AbortSignal,
promptId: string,
): Promise<{ functionCalls: FunctionCall[]; textResponse: string }> {
const responseStream = await chat.sendMessageStream(
{
model: getModelConfigAlias(this.definition),
overrideScope: this.definition.name,
},
message.parts || [],
promptId,
signal,
);
const functionCalls: FunctionCall[] = [];
let textResponse = '';
for await (const resp of responseStream) {
if (signal.aborted) break;
if (resp.type === StreamEventType.CHUNK) {
const chunk = resp.value;
const parts = chunk.candidates?.[0]?.content?.parts;
// Extract and emit any subject "thought" content from the model.
const { subject } = parseThought(
parts?.find((p) => p.thought)?.text || '',
);
if (subject) {
this.emitActivity('THOUGHT_CHUNK', { text: subject });
}
// Collect any function calls requested by the model.
if (chunk.functionCalls) {
functionCalls.push(...chunk.functionCalls);
}
// Handle text response (non-thought text)
const text =
parts
?.filter((p) => !p.thought && p.text)
.map((p) => p.text)
.join('') || '';
if (text) {
textResponse += text;
}
}
}
return { functionCalls, textResponse };
}
/** Initializes a `GeminiChat` instance for the agent run. */
private async createChatObject(
inputs: AgentInputs,
tools: FunctionDeclaration[],
): Promise<GeminiChat> {
const { promptConfig } = this.definition;
if (!promptConfig.systemPrompt && !promptConfig.initialMessages) {
throw new Error(
'PromptConfig must define either `systemPrompt` or `initialMessages`.',
);
}
const startHistory = this.applyTemplateToInitialMessages(
promptConfig.initialMessages ?? [],
inputs,
);
// Build system instruction from the templated prompt string.
const systemInstruction = promptConfig.systemPrompt
? await this.buildSystemPrompt(inputs)
: undefined;
try {
return new GeminiChat(
this.runtimeContext,
systemInstruction,
[{ functionDeclarations: tools }],
startHistory,
);
} catch (error) {
await reportError(
error,
`Error initializing Gemini chat for agent ${this.definition.name}.`,
startHistory,
'startChat',
);
// Re-throw as a more specific error after reporting.
throw new Error(`Failed to create chat object: ${error}`);
}
}
/**
* Executes function calls requested by the model and returns the results.
*
* @returns A new `Content` object for history, any submitted output, and completion status.
*/
private async processFunctionCalls(
functionCalls: FunctionCall[],
signal: AbortSignal,
promptId: string,
): Promise<{
nextMessage: Content;
submittedOutput: string | null;
taskCompleted: boolean;
}> {
const allowedToolNames = new Set(this.toolRegistry.getAllToolNames());
// Always allow the completion tool
allowedToolNames.add(TASK_COMPLETE_TOOL_NAME);
let submittedOutput: string | null = null;
let taskCompleted = false;
// We'll collect promises for the tool executions
const toolExecutionPromises: Array<Promise<Part[] | void>> = [];
// And we'll need a place to store the synchronous results (like complete_task or blocked calls)
const syncResponseParts: Part[] = [];
for (const [index, functionCall] of functionCalls.entries()) {
const callId = functionCall.id ?? `${promptId}-${index}`;
const args = (functionCall.args ?? {}) as Record<string, unknown>;
this.emitActivity('TOOL_CALL_START', {
name: functionCall.name,
args,
});
if (functionCall.name === TASK_COMPLETE_TOOL_NAME) {
if (taskCompleted) {
// We already have a completion from this turn. Ignore subsequent ones.
const error =
'Task already marked complete in this turn. Ignoring duplicate call.';
syncResponseParts.push({
functionResponse: {
name: TASK_COMPLETE_TOOL_NAME,
response: { error },
id: callId,
},
});
this.emitActivity('ERROR', {
context: 'tool_call',
name: functionCall.name,
error,
});
continue;
}
const { outputConfig } = this.definition;
taskCompleted = true; // Signal completion regardless of output presence
if (outputConfig) {
const outputName = outputConfig.outputName;
if (args[outputName] !== undefined) {
const outputValue = args[outputName];
const validationResult = outputConfig.schema.safeParse(outputValue);
if (!validationResult.success) {
taskCompleted = false; // Validation failed, revoke completion
const error = `Output validation failed: ${JSON.stringify(validationResult.error.flatten())}`;
syncResponseParts.push({
functionResponse: {
name: TASK_COMPLETE_TOOL_NAME,
response: { error },
id: callId,
},
});
this.emitActivity('ERROR', {
context: 'tool_call',
name: functionCall.name,
error,
});
continue;
}
const validatedOutput = validationResult.data;
if (this.definition.processOutput) {
submittedOutput = this.definition.processOutput(validatedOutput);
} else {
submittedOutput =
typeof outputValue === 'string'
? outputValue
: JSON.stringify(outputValue, null, 2);
}
syncResponseParts.push({
functionResponse: {
name: TASK_COMPLETE_TOOL_NAME,
response: { result: 'Output submitted and task completed.' },
id: callId,
},
});
this.emitActivity('TOOL_CALL_END', {
name: functionCall.name,
output: 'Output submitted and task completed.',
});
} else {
// Failed to provide required output.
taskCompleted = false; // Revoke completion status
const error = `Missing required argument '${outputName}' for completion.`;
syncResponseParts.push({
functionResponse: {
name: TASK_COMPLETE_TOOL_NAME,
response: { error },
id: callId,
},
});
this.emitActivity('ERROR', {
context: 'tool_call',
name: functionCall.name,
error,
});
}
} else {
// No output expected. Just signal completion.
submittedOutput = 'Task completed successfully.';
syncResponseParts.push({
functionResponse: {
name: TASK_COMPLETE_TOOL_NAME,
response: { status: 'Task marked complete.' },
id: callId,
},
});
this.emitActivity('TOOL_CALL_END', {
name: functionCall.name,
output: 'Task marked complete.',
});
}
continue;
}
// Handle standard tools
if (!allowedToolNames.has(functionCall.name as string)) {
const error = `Unauthorized tool call: '${functionCall.name}' is not available to this agent.`;
debugLogger.warn(`[AgentExecutor] Blocked call: ${error}`);
syncResponseParts.push({
functionResponse: {
name: functionCall.name as string,
id: callId,
response: { error },
},
});
this.emitActivity('ERROR', {
context: 'tool_call_unauthorized',
name: functionCall.name,
callId,
error,
});
continue;
}
const requestInfo: ToolCallRequestInfo = {
callId,
name: functionCall.name as string,
args,
isClientInitiated: true,
prompt_id: promptId,
};
// Create a promise for the tool execution
const executionPromise = (async () => {
const { response: toolResponse } = await executeToolCall(
this.runtimeContext,
requestInfo,
signal,
);
if (toolResponse.error) {
this.emitActivity('ERROR', {
context: 'tool_call',
name: functionCall.name,
error: toolResponse.error.message,
});
} else {
this.emitActivity('TOOL_CALL_END', {
name: functionCall.name,
output: toolResponse.resultDisplay,
});
}
return toolResponse.responseParts;
})();
toolExecutionPromises.push(executionPromise);
}
// Wait for all tool executions to complete
const asyncResults = await Promise.all(toolExecutionPromises);
// Combine all response parts
const toolResponseParts: Part[] = [...syncResponseParts];
for (const result of asyncResults) {
if (result) {
toolResponseParts.push(...result);
}
}
// If all authorized tool calls failed (and task isn't complete), provide a generic error.
if (
functionCalls.length > 0 &&
toolResponseParts.length === 0 &&
!taskCompleted
) {
toolResponseParts.push({
text: 'All tool calls failed or were unauthorized. Please analyze the errors and try an alternative approach.',
});
}
return {
nextMessage: { role: 'user', parts: toolResponseParts },
submittedOutput,
taskCompleted,
};
}
/**
* Prepares the list of tool function declarations to be sent to the model.
*/
private prepareToolsList(): FunctionDeclaration[] {
const toolsList: FunctionDeclaration[] = [];
const { toolConfig, outputConfig } = this.definition;
if (toolConfig) {
const toolNamesToLoad: string[] = [];
for (const toolRef of toolConfig.tools) {
if (typeof toolRef === 'string') {
toolNamesToLoad.push(toolRef);
} else if (typeof toolRef === 'object' && 'schema' in toolRef) {
// Tool instance with an explicit schema property.
toolsList.push(toolRef.schema as FunctionDeclaration);
} else {
// Raw `FunctionDeclaration` object.
toolsList.push(toolRef as FunctionDeclaration);
}
}
// Add schemas from tools that were registered by name.
toolsList.push(
...this.toolRegistry.getFunctionDeclarationsFiltered(toolNamesToLoad),
);
}
// Always inject complete_task.
// Configure its schema based on whether output is expected.
const completeTool: FunctionDeclaration = {
name: TASK_COMPLETE_TOOL_NAME,
description: outputConfig
? 'Call this tool to submit your final answer and complete the task. This is the ONLY way to finish.'
: 'Call this tool to signal that you have completed your task. This is the ONLY way to finish.',
parameters: {
type: Type.OBJECT,
properties: {},
required: [],
},
};
if (outputConfig) {
const jsonSchema = zodToJsonSchema(outputConfig.schema);
const {
$schema: _$schema,
definitions: _definitions,
...schema
} = jsonSchema;
completeTool.parameters!.properties![outputConfig.outputName] =
schema as Schema;
completeTool.parameters!.required!.push(outputConfig.outputName);
}
toolsList.push(completeTool);
return toolsList;
}