-
Notifications
You must be signed in to change notification settings - Fork 519
Expand file tree
/
Copy pathrun-agent-step.ts
More file actions
1137 lines (1037 loc) · 31.7 KB
/
run-agent-step.ts
File metadata and controls
1137 lines (1037 loc) · 31.7 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
import { AnalyticsEvent } from '@codebuff/common/constants/analytics-events'
import { supportsCacheControl } from '@codebuff/common/old-constants'
import { TOOLS_WHICH_WONT_FORCE_NEXT_STEP } from '@codebuff/common/tools/constants'
import { buildArray } from '@codebuff/common/util/array'
import { AbortError, getErrorObject, isAbortError, parseApiErrorResponseBody } from '@codebuff/common/util/error'
import { serializeCacheDebugCorrelation } from '@codebuff/common/util/cache-debug'
import { systemMessage, userMessage } from '@codebuff/common/util/messages'
import { APICallError, type ToolSet } from 'ai'
import { cloneDeep, mapValues } from 'lodash'
import { CACHE_DEBUG_FULL_LOGGING } from './constants'
import { callTokenCountAPI } from './llm-api/codebuff-web-api'
import { getMCPToolData } from './mcp'
import { getAgentStreamFromTemplate } from './prompt-agent-stream'
import { runProgrammaticStep } from './run-programmatic-step'
import { additionalSystemPrompts } from './system-prompt/prompts'
import { getAgentTemplate } from './templates/agent-registry'
import { buildAgentToolSet } from './templates/prompts'
import { getAgentPrompt } from './templates/strings'
import { getToolSet } from './tools/prompts'
import { processStream } from './tools/stream-parser'
import { getAgentOutput } from './util/agent-output'
import {
createCacheDebugSnapshot,
enrichCacheDebugSnapshotWithProviderRequest,
enrichCacheDebugSnapshotWithUsage,
} from './util/cache-debug'
import {
withSystemInstructionTags,
withSystemTags as withSystemTags,
buildUserMessageContent,
expireMessages,
} from './util/messages'
import { countTokensJson } from './util/token-counter'
import type { AgentTemplate } from '@codebuff/common/types/agent-template'
import type { TrackEventFn } from '@codebuff/common/types/contracts/analytics'
import type {
AddAgentStepFn,
FinishAgentRunFn,
StartAgentRunFn,
} from '@codebuff/common/types/contracts/database'
import type { CacheDebugUsageData, PromptAiSdkFn } from '@codebuff/common/types/contracts/llm'
import type { Logger } from '@codebuff/common/types/contracts/logger'
import type {
ParamsExcluding,
} from '@codebuff/common/types/function-params'
import type {
Message,
ToolMessage,
} from '@codebuff/common/types/messages/codebuff-message'
import type {
TextPart,
ImagePart,
} from '@codebuff/common/types/messages/content-part'
import type { PrintModeEvent } from '@codebuff/common/types/print-mode'
import type {
AgentTemplateType,
AgentState,
AgentOutput,
} from '@codebuff/common/types/session-state'
import type {
CustomToolDefinitions,
ProjectFileContext,
} from '@codebuff/common/util/file'
async function additionalToolDefinitions(
params: {
agentTemplate: AgentTemplate
fileContext: ProjectFileContext
} & ParamsExcluding<
typeof getMCPToolData,
'toolNames' | 'mcpServers' | 'writeTo'
>,
): Promise<CustomToolDefinitions> {
const { agentTemplate, fileContext } = params
const defs = cloneDeep(
Object.fromEntries(
Object.entries(fileContext.customToolDefinitions).filter(([toolName]) =>
agentTemplate!.toolNames.includes(toolName),
),
),
)
return getMCPToolData({
...params,
toolNames: agentTemplate!.toolNames,
mcpServers: agentTemplate!.mcpServers,
writeTo: defs,
})
}
export const runAgentStep = async (
params: {
userId: string | undefined
userInputId: string
clientSessionId: string
costMode?: string
fingerprintId: string
repoId: string | undefined
onResponseChunk: (chunk: string | PrintModeEvent) => void
agentType: AgentTemplateType
agentTemplate: AgentTemplate
fileContext: ProjectFileContext
agentState: AgentState
localAgentTemplates: Record<string, AgentTemplate>
prompt: string | undefined
spawnParams: Record<string, any> | undefined
system: string
n?: number
trackEvent: TrackEventFn
promptAiSdk: PromptAiSdkFn
} & ParamsExcluding<
typeof processStream,
| 'agentContext'
| 'agentState'
| 'agentStepId'
| 'agentTemplate'
| 'fullResponse'
| 'messages'
| 'onCostCalculated'
| 'repoId'
| 'stream'
> &
ParamsExcluding<
typeof getAgentStreamFromTemplate,
| 'agentId'
| 'includeCacheControl'
| 'messages'
| 'onCostCalculated'
| 'template'
> &
ParamsExcluding<typeof getAgentTemplate, 'agentId'> &
ParamsExcluding<
typeof getAgentPrompt,
'agentTemplate' | 'promptType' | 'agentState' | 'agentTemplates'
> &
ParamsExcluding<
typeof getMCPToolData,
'toolNames' | 'mcpServers' | 'writeTo'
> &
ParamsExcluding<
PromptAiSdkFn,
'messages' | 'model' | 'onCostCalculated' | 'n'
>,
): Promise<{
agentState: AgentState
fullResponse: string
shouldEndTurn: boolean
messageId: string | null
nResponses?: string[]
}> => {
const {
agentType,
clientSessionId,
fileContext,
agentTemplate,
fingerprintId,
localAgentTemplates,
logger,
prompt,
repoId,
spawnParams,
system,
userId,
userInputId,
onResponseChunk,
promptAiSdk,
trackEvent,
additionalToolDefinitions,
} = params
let agentState = params.agentState
const { agentContext } = agentState
const startTime = Date.now()
// Generates a unique ID for each main prompt run (ie: a step of the agent loop)
// This is used to link logs within a single agent loop
const agentStepId = crypto.randomUUID()
trackEvent({
event: AnalyticsEvent.AGENT_STEP,
userId: userId ?? '',
properties: {
agentStepId,
clientSessionId,
fingerprintId,
userInputId,
userId,
repoName: repoId,
},
logger,
})
if (agentState.stepsRemaining <= 0) {
logger.warn(
`Detected too many consecutive assistant messages without user prompt`,
)
onResponseChunk(`${STEP_WARNING_MESSAGE}\n\n`)
// Update message history to include the warning
agentState = {
...agentState,
messageHistory: [
...expireMessages(agentState.messageHistory, 'userPrompt'),
userMessage(
withSystemTags(
`The assistant has responded too many times in a row. The assistant's turn has automatically been ended. The maximum number of responses can be configured via maxAgentSteps.`,
),
),
],
}
return {
agentState,
fullResponse: STEP_WARNING_MESSAGE,
shouldEndTurn: true,
messageId: null,
}
}
const stepPrompt = await getAgentPrompt({
...params,
agentTemplate,
promptType: { type: 'stepPrompt' },
fileContext,
agentState,
agentTemplates: localAgentTemplates,
logger,
additionalToolDefinitions,
})
const agentMessagesUntruncated = buildArray<Message>(
...expireMessages(agentState.messageHistory, 'agentStep'),
stepPrompt &&
userMessage({
content: stepPrompt,
tags: ['STEP_PROMPT'],
// James: Deprecate the below, only use tags, which are not prescriptive.
timeToLive: 'agentStep' as const,
keepDuringTruncation: true,
}),
)
agentState.messageHistory = agentMessagesUntruncated
const { model } = agentTemplate
let stepCreditsUsed = 0
const onCostCalculated = async (credits: number) => {
stepCreditsUsed += credits
agentState.creditsUsed += credits
agentState.directCreditsUsed += credits
}
const iterationNum = agentState.messageHistory.length
const systemTokens = countTokensJson(system)
let cacheDebugCorrelation: ReturnType<typeof createCacheDebugSnapshot> | undefined
if (CACHE_DEBUG_FULL_LOGGING) {
try {
cacheDebugCorrelation = createCacheDebugSnapshot({
agentType: String(agentType),
system,
toolDefinitions: params.tools
? Object.fromEntries(
Object.entries(params.tools).map(([name, tool]) => [
name,
{
description: tool.description,
inputSchema: tool.inputSchema as {},
},
]),
)
: {},
messages: [systemMessage(system), ...agentState.messageHistory],
logger,
projectRoot: fileContext.projectRoot,
runId: agentState.runId,
userInputId,
agentStepId,
model,
})
} catch (err) {
logger.warn({ error: err }, '[Cache Debug] Failed to create snapshot')
}
}
const onCacheDebugProviderRequestBuilt =
cacheDebugCorrelation
? ({
provider,
rawBody,
normalizedBody,
}: {
provider: string
rawBody: unknown
normalizedBody?: unknown
}) => {
enrichCacheDebugSnapshotWithProviderRequest({
correlation: cacheDebugCorrelation,
provider,
rawBody,
normalized: normalizedBody ?? rawBody,
logger,
})
}
: undefined
const onCacheDebugUsageReceived =
cacheDebugCorrelation
? (usage: CacheDebugUsageData) => {
enrichCacheDebugSnapshotWithUsage({
correlation: cacheDebugCorrelation,
usage,
logger,
})
}
: undefined
logger.debug(
{
iteration: iterationNum,
runId: agentState.runId,
model,
duration: Date.now() - startTime,
contextTokenCount: agentState.contextTokenCount,
agentMessages: agentState.messageHistory.concat().reverse(),
system,
prompt,
params: spawnParams,
agentContext,
systemTokens,
agentTemplate,
tools: params.tools,
},
`Start agent ${agentType} step ${iterationNum} (${userInputId}${prompt ? ` - Prompt: ${prompt.slice(0, 20)}` : ''})`,
)
// Handle n parameter for generating multiple responses
if (params.n !== undefined) {
const result = await promptAiSdk({
...params,
messages: agentState.messageHistory,
model,
n: params.n,
onCostCalculated,
cacheDebugCorrelation: cacheDebugCorrelation
? serializeCacheDebugCorrelation(cacheDebugCorrelation)
: undefined,
onCacheDebugProviderRequestBuilt,
onCacheDebugUsageReceived,
})
if (result.aborted) {
return {
agentState,
fullResponse: '',
shouldEndTurn: true,
messageId: null,
nResponses: undefined,
}
}
const responsesString = result.value
let nResponses: string[]
try {
nResponses = JSON.parse(responsesString) as string[]
if (!Array.isArray(nResponses)) {
if (params.n > 1) {
throw new Error(
`Expected JSON array response from LLM when n > 1, got non-array: ${responsesString.slice(0, 50)}`,
)
}
// If it parsed but isn't an array, treat as single response
nResponses = [responsesString]
}
} catch (e) {
if (params.n > 1) {
throw e
}
// If parsing fails, treat as single raw response (common for n=1)
nResponses = [responsesString]
}
return {
agentState,
fullResponse: responsesString,
shouldEndTurn: false,
messageId: null,
nResponses,
}
}
let fullResponse = ''
const toolResults: ToolMessage[] = []
// Raw stream from AI SDK
const stream = getAgentStreamFromTemplate({
...params,
agentId: agentState.parentId ? agentState.agentId : undefined,
costMode: params.costMode,
cacheDebugCorrelation: cacheDebugCorrelation
? serializeCacheDebugCorrelation(cacheDebugCorrelation)
: undefined,
includeCacheControl: supportsCacheControl(agentTemplate.model),
messages: [systemMessage(system), ...agentState.messageHistory],
onCacheDebugProviderRequestBuilt,
onCacheDebugUsageReceived,
template: agentTemplate,
onCostCalculated,
})
const {
fullResponse: fullResponseAfterStream,
fullResponseChunks,
hadToolCallError,
messageId,
toolCalls,
toolResults: newToolResults,
} = await processStream({
...params,
agentContext,
agentState,
agentStepId,
agentTemplate,
fullResponse,
messages: agentState.messageHistory,
repoId,
stream,
onCostCalculated,
})
toolResults.push(...newToolResults)
fullResponse = fullResponseAfterStream
agentState.messageHistory = expireMessages(
agentState.messageHistory,
'agentStep',
)
// Handle /compact command: replace message history with the summary
const wasCompacted =
prompt &&
(prompt.toLowerCase() === '/compact' || prompt.toLowerCase() === 'compact')
if (wasCompacted) {
agentState.messageHistory = [
userMessage(
withSystemTags(
`The following is a summary of the conversation between you and the user. The conversation continues after this summary:\n\n${fullResponse}`,
),
),
]
logger.debug({ summary: fullResponse }, 'Compacted messages')
}
const hasNoToolResults =
toolCalls.filter(
(call) => !TOOLS_WHICH_WONT_FORCE_NEXT_STEP.includes(call.toolName),
).length === 0 &&
toolResults.filter(
(result) => !TOOLS_WHICH_WONT_FORCE_NEXT_STEP.includes(result.toolName),
).length === 0 &&
!hadToolCallError // Tool call errors should also force another step so the agent can retry
const hasTaskCompleted = toolCalls.some(
(call) =>
call.toolName === 'task_completed' || call.toolName === 'end_turn',
)
// If the response is only <think>...</think> tags with no other non-whitespace content,
// the model was just thinking and should continue rather than end its turn.
const responseWithoutThinkTags = fullResponse
.replace(/<think>[\s\S]*?<\/think>/g, '')
.replace(/<think>[\s\S]*$/, '')
.trim()
const isThinkOnly =
hasNoToolResults &&
responseWithoutThinkTags.length === 0 &&
fullResponse.trim().length > 0
// If the agent has the task_completed tool, it must be called to end its turn.
const requiresExplicitCompletion =
agentTemplate.toolNames.includes('task_completed')
let shouldEndTurn: boolean
if (requiresExplicitCompletion) {
// For models requiring explicit completion, only end turn when:
// - task_completed is called, OR
// - end_turn is called (backward compatibility)
shouldEndTurn = hasTaskCompleted
} else {
// For other models, also end turn when there are no tool calls
// Exception: if the response is only <think> tags, continue the turn
shouldEndTurn = hasTaskCompleted || (hasNoToolResults && !isThinkOnly)
}
agentState = {
...agentState,
stepsRemaining: agentState.stepsRemaining - 1,
agentContext,
}
logger.debug(
{
iteration: iterationNum,
agentId: agentState.agentId,
model,
prompt,
shouldEndTurn,
duration: Date.now() - startTime,
fullResponse,
finalMessageHistoryWithToolResults: agentState.messageHistory.concat().reverse(),
toolCalls,
toolResults,
agentContext,
fullResponseChunks,
stepCreditsUsed,
},
`End agent ${agentType} step ${iterationNum} (${userInputId}${prompt ? ` - Prompt: ${prompt.slice(0, 20)}` : ''})`,
)
return {
agentState,
fullResponse,
shouldEndTurn,
messageId,
nResponses: undefined,
}
}
export async function loopAgentSteps(
params: {
addAgentStep: AddAgentStepFn
agentState: AgentState
agentType: string
clearUserPromptMessagesAfterResponse?: boolean
clientSessionId: string
content?: Array<TextPart | ImagePart>
costMode?: string
fileContext: ProjectFileContext
finishAgentRun: FinishAgentRunFn
localAgentTemplates: Record<string, AgentTemplate>
logger: Logger
parentSystemPrompt?: string
parentTools?: ToolSet
prompt: string | undefined
signal: AbortSignal
spawnParams: Record<string, any> | undefined
startAgentRun: StartAgentRunFn
userId: string | undefined
userInputId: string
agentTemplate?: AgentTemplate
} & ParamsExcluding<typeof additionalToolDefinitions, 'agentTemplate'> &
ParamsExcluding<
typeof runProgrammaticStep,
| 'agentState'
| 'onCostCalculated'
| 'prompt'
| 'runId'
| 'stepNumber'
| 'stepsComplete'
| 'system'
| 'template'
| 'toolCallParams'
| 'tools'
> &
ParamsExcluding<typeof getAgentTemplate, 'agentId'> &
ParamsExcluding<
typeof getAgentPrompt,
| 'agentTemplate'
| 'promptType'
| 'agentTemplates'
| 'additionalToolDefinitions'
> &
ParamsExcluding<
typeof getMCPToolData,
'toolNames' | 'mcpServers' | 'writeTo'
> &
ParamsExcluding<StartAgentRunFn, 'agentId' | 'ancestorRunIds'> &
ParamsExcluding<
FinishAgentRunFn,
'runId' | 'status' | 'totalSteps' | 'directCredits' | 'totalCredits'
> &
ParamsExcluding<
typeof runAgentStep,
| 'additionalToolDefinitions'
| 'agentState'
| 'agentTemplate'
| 'prompt'
| 'runId'
| 'spawnParams'
| 'system'
| 'tools'
> &
ParamsExcluding<
AddAgentStepFn,
| 'agentRunId'
| 'stepNumber'
| 'credits'
| 'childRunIds'
| 'messageId'
| 'status'
| 'startTime'
>,
): Promise<{
agentState: AgentState
output: AgentOutput
}> {
const {
addAgentStep,
agentState: initialAgentState,
agentType,
clearUserPromptMessagesAfterResponse = true,
clientSessionId,
content,
fileContext,
finishAgentRun,
localAgentTemplates,
logger,
parentSystemPrompt,
parentTools,
prompt,
signal,
spawnParams,
startAgentRun,
userId,
userInputId,
clientEnv,
ciEnv,
} = params
let agentTemplate = params.agentTemplate
if (!agentTemplate) {
agentTemplate =
(await getAgentTemplate({
...params,
agentId: agentType,
})) ?? undefined
}
if (!agentTemplate) {
throw new Error(`Agent template not found for type: ${agentType}`)
}
if (signal.aborted) {
return {
agentState: initialAgentState,
output: {
type: 'error',
message: 'Run cancelled by user',
},
}
}
const runId = await startAgentRun({
...params,
agentId: agentTemplate.id,
ancestorRunIds: initialAgentState.ancestorRunIds,
})
if (!runId) {
throw new Error('Failed to start agent run')
}
initialAgentState.runId = runId
let cachedAdditionalToolDefinitions: CustomToolDefinitions | undefined
// Use parent's tools for prompt caching when inheritParentSystemPrompt is true
const useParentTools =
agentTemplate.inheritParentSystemPrompt && parentTools !== undefined
// Initialize message history with user prompt and instructions on first iteration
const instructionsPrompt = await getAgentPrompt({
...params,
agentTemplate,
promptType: { type: 'instructionsPrompt' },
agentTemplates: localAgentTemplates,
useParentTools,
additionalToolDefinitions: async () => {
if (!cachedAdditionalToolDefinitions) {
cachedAdditionalToolDefinitions = await additionalToolDefinitions({
...params,
agentTemplate,
})
}
return cachedAdditionalToolDefinitions
},
})
// Build the initial message history with user prompt and instructions
// Generate system prompt once, using parent's if inheritParentSystemPrompt is true
let system: string
if (agentTemplate.inheritParentSystemPrompt && parentSystemPrompt) {
system = parentSystemPrompt
} else {
const systemPrompt = await getAgentPrompt({
...params,
agentTemplate,
promptType: { type: 'systemPrompt' },
agentTemplates: localAgentTemplates,
additionalToolDefinitions: async () => {
if (!cachedAdditionalToolDefinitions) {
cachedAdditionalToolDefinitions = await additionalToolDefinitions({
...params,
agentTemplate,
})
}
return cachedAdditionalToolDefinitions
},
})
system = systemPrompt ?? ''
}
// Build agent tools (agents as direct tool calls) for non-inherited tools
const agentTools = useParentTools
? {}
: await buildAgentToolSet({
...params,
spawnableAgents: agentTemplate.spawnableAgents,
agentTemplates: localAgentTemplates,
})
const tools = useParentTools
? parentTools
: await getToolSet({
toolNames: agentTemplate.toolNames,
additionalToolDefinitions: async () => {
if (!cachedAdditionalToolDefinitions) {
cachedAdditionalToolDefinitions = await additionalToolDefinitions({
...params,
agentTemplate,
})
}
return cachedAdditionalToolDefinitions
},
agentTools,
skills: fileContext.skills ?? {},
})
const hasUserMessage = Boolean(
prompt ||
(spawnParams && Object.keys(spawnParams).length > 0) ||
(content && content.length > 0),
)
const initialMessages = buildArray<Message>(
...initialAgentState.messageHistory,
hasUserMessage && [
{
// Actual user message!
role: 'user' as const,
content: buildUserMessageContent(prompt, spawnParams, content),
tags: ['USER_PROMPT'],
sentAt: Date.now(),
// James: Deprecate the below, only use tags, which are not prescriptive.
keepDuringTruncation: true,
},
prompt &&
prompt in additionalSystemPrompts &&
userMessage(
withSystemInstructionTags(
additionalSystemPrompts[
prompt as keyof typeof additionalSystemPrompts
],
),
),
,
],
instructionsPrompt &&
userMessage({
content: instructionsPrompt,
tags: ['INSTRUCTIONS_PROMPT'],
// James: Deprecate the below, only use tags, which are not prescriptive.
keepLastTags: ['INSTRUCTIONS_PROMPT'],
}),
)
// Convert tools to a serializable format for context-pruner token counting
const toolDefinitions = mapValues(tools, (tool) => ({
description: tool.description,
inputSchema: tool.inputSchema as {},
}))
const additionalToolDefinitionsWithCache = async () => {
if (!cachedAdditionalToolDefinitions) {
cachedAdditionalToolDefinitions = await additionalToolDefinitions({
...params,
agentTemplate,
})
}
return cachedAdditionalToolDefinitions
}
let currentAgentState: AgentState = {
...initialAgentState,
messageHistory: initialMessages,
systemPrompt: system,
toolDefinitions,
}
// Convert tool definitions to Anthropic format for accurate token counting
// Tool definitions are stored as { [name]: { description, inputSchema } }
// Anthropic count_tokens API expects [{ name, description, input_schema }]
const toolsForTokenCount = Object.entries(toolDefinitions).map(
([name, def]) => ({
name,
...(def.description && { description: def.description }),
...(def.inputSchema && { input_schema: def.inputSchema }),
}),
)
let shouldEndTurn = false
let hasRetriedOutputSchema = false
let currentPrompt = prompt
let currentParams = spawnParams
let totalSteps = 0
let nResponses: string[] | undefined = undefined
try {
while (true) {
totalSteps++
if (signal.aborted) {
throw new AbortError()
}
const startTime = new Date()
const stepPrompt = await getAgentPrompt({
...params,
agentTemplate,
promptType: { type: 'stepPrompt' },
fileContext,
agentState: currentAgentState,
agentTemplates: localAgentTemplates,
logger,
additionalToolDefinitions: additionalToolDefinitionsWithCache,
})
const messagesWithStepPrompt = buildArray(
...currentAgentState.messageHistory,
stepPrompt &&
userMessage({
content: stepPrompt,
}),
)
// Check context token count via Anthropic API
const tokenCountResult = await callTokenCountAPI({
messages: messagesWithStepPrompt,
system,
model: agentTemplate.model,
tools: toolsForTokenCount,
fetch,
logger,
env: { clientEnv, ciEnv },
})
if (tokenCountResult.inputTokens !== undefined) {
currentAgentState.contextTokenCount = tokenCountResult.inputTokens
} else if (tokenCountResult.error) {
logger.warn(
{ error: tokenCountResult.error },
'Failed to get token count from Anthropic API',
)
// Fall back to local estimate
const estimatedTokens =
countTokensJson(currentAgentState.messageHistory) +
countTokensJson(system) +
countTokensJson(toolDefinitions)
currentAgentState.contextTokenCount = estimatedTokens
}
// 1. Run programmatic step first if it exists
let n: number | undefined = undefined
if (agentTemplate.handleSteps) {
const programmaticResult = await runProgrammaticStep({
...params,
agentState: currentAgentState,
localAgentTemplates,
nResponses,
onCostCalculated: async (credits: number) => {
currentAgentState.creditsUsed += credits
currentAgentState.directCreditsUsed += credits
},
prompt: currentPrompt,
runId,
stepNumber: totalSteps,
stepsComplete: shouldEndTurn,
system,
tools,
template: agentTemplate,
toolCallParams: currentParams,
})
const {
agentState: programmaticAgentState,
endTurn,
stepNumber,
generateN,
} = programmaticResult
n = generateN
currentAgentState = programmaticAgentState
totalSteps = stepNumber
shouldEndTurn = endTurn
}
// Check if output is required but missing
if (
agentTemplate.outputSchema &&
currentAgentState.output === undefined &&
shouldEndTurn &&
!hasRetriedOutputSchema
) {
hasRetriedOutputSchema = true
logger.warn(
{
agentType,
agentId: currentAgentState.agentId,
runId,
},
'Agent finished without setting required output, restarting loop',
)
// Add system message instructing to use set_output
const outputSchemaMessage = withSystemTags(
`You must use the "set_output" tool to provide a result that matches the output schema before ending your turn. The output schema is required for this agent.`,
)
currentAgentState.messageHistory = [
...currentAgentState.messageHistory,
userMessage({
content: outputSchemaMessage,
keepDuringTruncation: true,
}),
]
// Reset shouldEndTurn to continue the loop
shouldEndTurn = false
}
// End turn if programmatic step ended turn, or if the previous runAgentStep ended turn
if (shouldEndTurn) {
break
}
const creditsBefore = currentAgentState.directCreditsUsed
const childrenBefore = currentAgentState.childRunIds.length
const {
agentState: newAgentState,
shouldEndTurn: llmShouldEndTurn,
messageId,
nResponses: generatedResponses,
} = await runAgentStep({
...params,
agentState: currentAgentState,
agentTemplate,
n,
prompt: currentPrompt,
runId,
spawnParams: currentParams,
system,
tools,
additionalToolDefinitions: additionalToolDefinitionsWithCache,
})
if (newAgentState.runId) {
await addAgentStep({
...params,
agentRunId: newAgentState.runId,
stepNumber: totalSteps,
credits: newAgentState.directCreditsUsed - creditsBefore,
childRunIds: newAgentState.childRunIds.slice(childrenBefore),
messageId,
status: 'completed',
startTime,
})
} else {
logger.error('No runId found for agent state after finishing agent run')
}
currentAgentState = newAgentState
shouldEndTurn = llmShouldEndTurn
nResponses = generatedResponses
currentPrompt = undefined
currentParams = undefined
}
if (clearUserPromptMessagesAfterResponse) {