-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathtool-executor.ts
More file actions
643 lines (579 loc) · 19.6 KB
/
Copy pathtool-executor.ts
File metadata and controls
643 lines (579 loc) · 19.6 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
import { endsAgentStepParam, toolNames } from '@codebuff/common/tools/constants'
import { toolParams } from '@codebuff/common/tools/list'
import { generateCompactId } from '@codebuff/common/util/string'
import { cloneDeep } from 'lodash'
import { getMCPToolData } from '../mcp'
import { MCP_TOOL_SEPARATOR } from '../mcp-constants'
import { getAgentShortName, getAgentToolName } from '../templates/prompts'
import { formatValueForError } from '../util/format-value'
import { codebuffToolHandlers } from './handlers/list'
import { getMatchingSpawn } from './handlers/tool/spawn-agent-utils'
import { getAgentTemplate } from '../templates/agent-registry'
import { ensureZodSchema } from './prompts'
import type { AgentTemplate } from '../templates/types'
import type { CodebuffToolHandlerFunction } from './handlers/handler-function-type'
import type { FileProcessingState } from './handlers/tool/write-file'
import type { ToolName } from '@codebuff/common/tools/constants'
import type {
ClientToolCall,
ClientToolName,
CodebuffToolCall,
CodebuffToolOutput,
} from '@codebuff/common/tools/list'
import type {
AgentRuntimeDeps,
AgentRuntimeScopedDeps,
} from '@codebuff/common/types/contracts/agent-runtime'
import type { Logger } from '@codebuff/common/types/contracts/logger'
import type { ToolMessage } from '@codebuff/common/types/messages/codebuff-message'
import type { ToolResultOutput } from '@codebuff/common/types/messages/content-part'
import type { PrintModeEvent } from '@codebuff/common/types/print-mode'
import type {
AgentTemplateType,
AgentState,
Subgoal,
} from '@codebuff/common/types/session-state'
import type {
CustomToolDefinitions,
ProjectFileContext,
} from '@codebuff/common/util/file'
import type { ToolCallPart, ToolSet } from 'ai'
export type CustomToolCall = {
toolName: string
input: Record<string, unknown>
} & Omit<ToolCallPart, 'type'>
export type ToolCallError = {
toolName?: string
input: Record<string, unknown>
error: string
} & Pick<CodebuffToolCall, 'toolCallId'>
function stringInputError(toolName: string, toolCallId: string): ToolCallError {
return {
toolName,
toolCallId,
input: {},
error: `Invalid parameters for ${toolName}: tool arguments were a string, not a JSON object. This usually means the model emitted malformed JSON (e.g. unescaped newlines or quotes inside a string value). Re-issue the tool call with properly escaped JSON.`,
}
}
export function parseRawToolCall<T extends ToolName = ToolName>(params: {
rawToolCall: {
toolName: T
toolCallId: string
input: Record<string, unknown>
}
}): CodebuffToolCall<T> | ToolCallError {
const { rawToolCall } = params
const toolName = rawToolCall.toolName
const processedParameters = rawToolCall.input
const paramsSchema = toolParams[toolName].inputSchema
if (typeof processedParameters === 'string') {
return stringInputError(toolName, rawToolCall.toolCallId)
}
const result = paramsSchema.safeParse(processedParameters)
if (!result.success) {
return {
toolName,
toolCallId: rawToolCall.toolCallId,
input: rawToolCall.input,
error: `Invalid parameters for ${toolName}: ${JSON.stringify(
result.error.issues,
null,
2,
)}`,
}
}
if (endsAgentStepParam in result.data) {
delete result.data[endsAgentStepParam]
}
return {
toolName,
input: result.data,
toolCallId: rawToolCall.toolCallId,
} as CodebuffToolCall<T>
}
export type ExecuteToolCallParams<T extends string = ToolName> = {
toolName: T
input: Record<string, unknown>
autoInsertEndStepParam?: boolean
excludeToolFromMessageHistory?: boolean
agentContext: Record<string, Subgoal>
agentState: AgentState
agentStepId: string
ancestorRunIds: string[]
agentTemplate: AgentTemplate
clientSessionId: string
fileContext: ProjectFileContext
fileProcessingState: FileProcessingState
fingerprintId: string
fromHandleSteps?: boolean
fullResponse: string
localAgentTemplates: Record<string, AgentTemplate>
logger: Logger
previousToolCallFinished: Promise<void>
prompt: string | undefined
repoId: string | undefined
repoUrl: string | undefined
runId: string
signal: AbortSignal
system: string
tools: ToolSet
toolCallId: string | undefined
toolCalls: (CodebuffToolCall | CustomToolCall)[]
toolCallsToAddToMessageHistory: (CodebuffToolCall | CustomToolCall)[]
toolResults: ToolMessage[]
toolResultsToAddToMessageHistory: ToolMessage[]
userId: string | undefined
userInputId: string
fetch: typeof globalThis.fetch
onCostCalculated: (credits: number) => Promise<void>
onResponseChunk: (chunk: string | PrintModeEvent) => void
} & AgentRuntimeDeps &
AgentRuntimeScopedDeps
export async function executeToolCall<T extends ToolName>(
params: ExecuteToolCallParams<T>,
): Promise<void> {
const {
toolName,
input,
excludeToolFromMessageHistory = false,
fromHandleSteps = false,
agentState,
agentTemplate,
logger,
previousToolCallFinished,
toolCalls,
toolCallsToAddToMessageHistory,
toolResults,
toolResultsToAddToMessageHistory,
userInputId,
onCostCalculated,
onResponseChunk,
requestToolCall,
} = params
const toolCallId = params.toolCallId ?? generateCompactId()
const toolCall: CodebuffToolCall<T> | ToolCallError = parseRawToolCall<T>({
rawToolCall: {
toolName,
toolCallId,
input,
},
})
// Filter out restricted tools - emit error instead of tool call/result
// This prevents the CLI from showing tool calls that the agent doesn't have permission to use
if (
toolCall.toolName &&
!agentTemplate.toolNames.includes(toolCall.toolName) &&
!fromHandleSteps
) {
// Emit an error event instead of tool call/result pair
// The stream parser will convert this to a user message for proper API compliance
onResponseChunk({
type: 'error',
message: `Tool \`${toolName}\` is not currently available. Make sure to only use tools provided at the start of the conversation AND that you most recently have permission to use.`,
})
return previousToolCallFinished
}
if ('error' in toolCall) {
const formattedInput = formatValueForError(input)
onResponseChunk({
type: 'error',
message: `${toolCall.error}\n\nOriginal tool call input:\n${formattedInput}`,
})
logger.debug(
{ toolCall, error: toolCall.error },
`${toolName} error: ${toolCall.error}`,
)
return previousToolCallFinished
}
// TODO: Allow tools to provide a validation function, and move this logic into the spawn_agents validation function.
// Pre-validate spawn_agents to filter out non-existent agents before streaming
let effectiveInput = input
if (toolName === 'spawn_agents') {
const agents = (input as Record<string, unknown>).agents
if (Array.isArray(agents)) {
const BASE_AGENTS = ['base', 'base-free', 'base-max', 'base-experimental']
const isBaseAgent = BASE_AGENTS.includes(agentTemplate.id)
const validationResults = await Promise.allSettled(
agents.map(async (agent) => {
if (!agent || typeof agent !== 'object') {
return { valid: false as const, error: 'Invalid agent entry' }
}
const agentTypeStr = (agent as Record<string, unknown>).agent_type
if (typeof agentTypeStr !== 'string' || !agentTypeStr) {
return {
valid: false as const,
error: 'Agent entry missing agent_type',
}
}
if (!isBaseAgent) {
const matchingSpawn = getMatchingSpawn(
agentTemplate.spawnableAgents,
agentTypeStr,
)
if (!matchingSpawn) {
if (toolNames.includes(agentTypeStr as ToolName)) {
return {
valid: false as const,
error: `"${agentTypeStr}" is a tool, not an agent. Call it directly as a tool instead of wrapping it in spawn_agents.`,
}
}
return {
valid: false as const,
error: `Agent "${agentTypeStr}" is not available to spawn`,
}
}
}
try {
const template = await getAgentTemplate({
agentId: agentTypeStr,
localAgentTemplates: params.localAgentTemplates,
fetchAgentFromDatabase: params.fetchAgentFromDatabase,
databaseAgentCache: params.databaseAgentCache,
logger,
apiKey: params.apiKey,
})
if (!template) {
if (toolNames.includes(agentTypeStr as ToolName)) {
return {
valid: false as const,
error: `"${agentTypeStr}" is a tool, not an agent. Call it directly as a tool instead of wrapping it in spawn_agents.`,
}
}
return {
valid: false as const,
error: `Agent "${agentTypeStr}" does not exist`,
}
}
} catch {
return {
valid: false as const,
error: `Agent "${agentTypeStr}" could not be loaded`,
}
}
return { valid: true as const, agent }
}),
)
const validAgents: unknown[] = []
const errors: string[] = []
for (const result of validationResults) {
if (result.status === 'rejected') {
errors.push('Agent validation failed unexpectedly')
} else if (result.value.valid) {
validAgents.push(result.value.agent)
} else {
errors.push(result.value.error)
}
}
if (errors.length > 0) {
if (validAgents.length === 0) {
const errorMsg = `Failed to spawn agents: ${errors.join('; ')}`
onResponseChunk({ type: 'error', message: errorMsg })
logger.debug(
{ toolName, errors },
'All agents in spawn_agents are invalid, not streaming tool call',
)
return previousToolCallFinished
}
const errorMsg = `Some agents could not be spawned: ${errors.join('; ')}. Proceeding with valid agents only.`
onResponseChunk({ type: 'error', message: errorMsg })
effectiveInput = { ...input, agents: validAgents }
}
}
}
// Only emit tool_call event after permission check passes
onResponseChunk({
type: 'tool_call',
toolCallId,
toolName,
input: effectiveInput,
agentId: agentState.agentId,
parentAgentId: agentState.parentId,
includeToolCall: !excludeToolFromMessageHistory,
})
// Cast to any to avoid type errors
const handler = codebuffToolHandlers[
toolName
] as unknown as CodebuffToolHandlerFunction<T>
// Use effective input for spawn_agents so the handler receives the correct agent types
const finalToolCall =
toolName === 'spawn_agents'
? { ...toolCall, input: effectiveInput }
: toolCall
toolCalls.push(finalToolCall)
if (!excludeToolFromMessageHistory) {
toolCallsToAddToMessageHistory.push(finalToolCall)
}
const toolResultPromise = handler({
...params,
toolCall: finalToolCall,
previousToolCallFinished,
writeToClient: onResponseChunk,
requestClientToolCall: (async (
clientToolCall: ClientToolCall<T extends ClientToolName ? T : never>,
) => {
if (params.signal.aborted) {
return []
}
const clientToolResult = await requestToolCall({
userInputId,
toolName: clientToolCall.toolName,
input: clientToolCall.input,
})
return clientToolResult.output as CodebuffToolOutput<T>
}) as any,
})
return toolResultPromise.then(async ({ output, creditsUsed }) => {
const toolResult: ToolMessage = {
role: 'tool',
toolName,
toolCallId: toolCall.toolCallId,
content: output,
}
onResponseChunk({
type: 'tool_result',
toolCallId: toolResult.toolCallId,
toolName: toolResult.toolName,
output: toolResult.content,
})
toolResults.push(toolResult)
if (!excludeToolFromMessageHistory) {
toolResultsToAddToMessageHistory.push(toolResult)
}
// After tool completes, resolve any pending creditsUsed promise
if (creditsUsed) {
onCostCalculated(creditsUsed)
logger.debug(
{ credits: creditsUsed, totalCredits: agentState.creditsUsed },
`Added ${creditsUsed} credits from ${toolName} to agent state`,
)
}
})
}
export function parseRawCustomToolCall(params: {
customToolDefs: CustomToolDefinitions
rawToolCall: {
toolName: string
toolCallId: string
input: Record<string, unknown>
}
autoInsertEndStepParam?: boolean
}): CustomToolCall | ToolCallError {
const { customToolDefs, rawToolCall, autoInsertEndStepParam = false } = params
const toolName = rawToolCall.toolName
if (
!(customToolDefs && toolName in customToolDefs) &&
!toolName.includes(MCP_TOOL_SEPARATOR)
) {
return {
toolName,
toolCallId: rawToolCall.toolCallId,
input: rawToolCall.input,
error: `Tool ${toolName} not found`,
}
}
if (typeof rawToolCall.input === 'string') {
return stringInputError(toolName, rawToolCall.toolCallId)
}
const processedParameters: Record<string, any> = {}
for (const [param, val] of Object.entries(rawToolCall.input ?? {})) {
processedParameters[param] = val
}
// Add the required codebuff_end_step parameter with the correct value for this tool if requested
if (autoInsertEndStepParam) {
processedParameters[endsAgentStepParam] =
customToolDefs?.[toolName]?.endsAgentStep
}
const rawSchema = customToolDefs?.[toolName]?.inputSchema
if (rawSchema) {
const paramsSchema = ensureZodSchema(rawSchema)
const result = paramsSchema.safeParse(processedParameters)
if (!result.success) {
return {
toolName: toolName,
toolCallId: rawToolCall.toolCallId,
input: rawToolCall.input,
error: `Invalid parameters for ${toolName}: ${JSON.stringify(
result.error.issues,
null,
2,
)}`,
}
}
}
const input = JSON.parse(JSON.stringify(rawToolCall.input))
if (endsAgentStepParam in input) {
delete input[endsAgentStepParam]
}
return {
toolName: toolName,
input,
toolCallId: rawToolCall.toolCallId,
}
}
export async function executeCustomToolCall(
params: ExecuteToolCallParams<string>,
): Promise<void> {
const {
toolName,
input,
autoInsertEndStepParam = false,
excludeToolFromMessageHistory = false,
fromHandleSteps = false,
agentState,
agentTemplate,
fileContext,
logger,
onResponseChunk,
previousToolCallFinished,
requestToolCall,
toolCallId,
toolCalls,
toolCallsToAddToMessageHistory,
toolResults,
toolResultsToAddToMessageHistory,
userInputId,
} = params
const toolCall: CustomToolCall | ToolCallError = parseRawCustomToolCall({
customToolDefs: await getMCPToolData({
...params,
toolNames: agentTemplate.toolNames,
mcpServers: agentTemplate.mcpServers,
writeTo: cloneDeep(fileContext.customToolDefinitions),
}),
rawToolCall: {
toolName,
toolCallId: toolCallId ?? generateCompactId(),
input,
},
autoInsertEndStepParam,
})
// Filter out restricted tools - emit error instead of tool call/result
// This prevents the CLI from showing tool calls that the agent doesn't have permission to use
if (
toolCall.toolName &&
!(agentTemplate.toolNames as string[]).includes(toolCall.toolName) &&
!fromHandleSteps &&
!(
toolCall.toolName.includes(MCP_TOOL_SEPARATOR) &&
toolCall.toolName.split(MCP_TOOL_SEPARATOR)[0] in agentTemplate.mcpServers
)
) {
// Emit an error event instead of tool call/result pair
// The stream parser will convert this to a user message for proper API compliance
onResponseChunk({
type: 'error',
message: `Tool \`${toolName}\` is not currently available. Make sure to only use tools listed in the system instructions.`,
})
return previousToolCallFinished
}
if ('error' in toolCall) {
const formattedInput = formatValueForError(input)
onResponseChunk({
type: 'error',
message: `${toolCall.error}\n\nOriginal tool call input:\n${formattedInput}`,
})
logger.debug(
{ toolCall, error: toolCall.error },
`${toolName} error: ${toolCall.error}`,
)
return previousToolCallFinished
}
// Only emit tool_call event after permission check passes
onResponseChunk({
type: 'tool_call',
toolCallId: toolCall.toolCallId,
toolName,
input: toolCall.input,
// Only include agentId for subagents (agents with a parent)
...(agentState?.parentId && { agentId: agentState.agentId }),
// Include includeToolCall flag if explicitly set to false
...(excludeToolFromMessageHistory && { includeToolCall: false }),
})
toolCalls.push(toolCall)
if (!excludeToolFromMessageHistory) {
toolCallsToAddToMessageHistory.push(toolCall)
}
return previousToolCallFinished
.then(async () => {
if (params.signal.aborted) {
return null
}
const toolName = toolCall.toolName.includes(MCP_TOOL_SEPARATOR)
? toolCall.toolName
.split(MCP_TOOL_SEPARATOR)
.slice(1)
.join(MCP_TOOL_SEPARATOR)
: toolCall.toolName
const clientToolResult = await requestToolCall({
userInputId,
toolName,
input: toolCall.input,
mcpConfig: toolCall.toolName.includes(MCP_TOOL_SEPARATOR)
? agentTemplate.mcpServers[
toolCall.toolName.split(MCP_TOOL_SEPARATOR)[0]
]
: undefined,
})
return clientToolResult.output satisfies ToolResultOutput[]
})
.then((result) => {
if (!result) {
return
}
const toolResult = {
role: 'tool',
toolName,
toolCallId: toolCall.toolCallId,
content: result,
} satisfies ToolMessage
logger.debug(
{ input, toolResult },
`${toolName} custom tool call & result (${toolResult.toolCallId})`,
)
onResponseChunk({
type: 'tool_result',
toolName: toolResult.toolName,
toolCallId: toolResult.toolCallId,
output: toolResult.content,
})
toolResults.push(toolResult)
if (!excludeToolFromMessageHistory) {
toolResultsToAddToMessageHistory.push(toolResult)
}
return
})
}
/**
* Checks if a tool name matches a spawnable agent and returns the transformed
* spawn_agents input if so. Returns null if not an agent tool call.
*/
export function tryTransformAgentToolCall(params: {
toolName: string
input: Record<string, unknown>
spawnableAgents: AgentTemplateType[]
}): { toolName: 'spawn_agents'; input: Record<string, unknown> } | null {
const { toolName, input, spawnableAgents } = params
const matchesAgentToolName = (agentType: AgentTemplateType) =>
getAgentToolName(agentType) === toolName ||
getAgentShortName(agentType) === toolName
// Find the full agent type for this direct-call alias.
const fullAgentType = spawnableAgents.find(matchesAgentToolName)
if (!fullAgentType) {
return null
}
// Convert to spawn_agents call - input already has prompt and params as top-level fields
// (consistent with spawn_agents schema)
const agentEntry: Record<string, unknown> = {
agent_type: fullAgentType,
}
if (typeof input.prompt === 'string') {
agentEntry.prompt = input.prompt
}
if (input.params && typeof input.params === 'object') {
agentEntry.params = input.params
}
const spawnAgentsInput = {
agents: [agentEntry],
}
return { toolName: 'spawn_agents', input: spawnAgentsInput }
}