-
Notifications
You must be signed in to change notification settings - Fork 518
Expand file tree
/
Copy pathtool-validation-error.test.ts
More file actions
356 lines (317 loc) · 12 KB
/
tool-validation-error.test.ts
File metadata and controls
356 lines (317 loc) · 12 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
import { TEST_AGENT_RUNTIME_IMPL } from '@codebuff/common/testing/impl/agent-runtime'
import { getInitialSessionState } from '@codebuff/common/types/session-state'
import { promptSuccess } from '@codebuff/common/util/error'
import { jsonToolResult } from '@codebuff/common/util/messages'
import { beforeEach, describe, expect, it } from 'bun:test'
import { mockFileContext } from './test-utils'
import { processStream } from '../tools/stream-parser'
import type { AgentTemplate } from '../templates/types'
import type {
AgentRuntimeDeps,
AgentRuntimeScopedDeps,
} from '@codebuff/common/types/contracts/agent-runtime'
import type { StreamChunk } from '@codebuff/common/types/contracts/llm'
import type {
AssistantMessage,
ToolMessage,
} from '@codebuff/common/types/messages/codebuff-message'
import type { PrintModeEvent } from '@codebuff/common/types/print-mode'
describe('tool validation error handling', () => {
let agentRuntimeImpl: AgentRuntimeDeps & AgentRuntimeScopedDeps
beforeEach(() => {
agentRuntimeImpl = { ...TEST_AGENT_RUNTIME_IMPL, sendAction: () => {} }
})
const testAgentTemplate: AgentTemplate = {
id: 'test-agent',
displayName: 'Test Agent',
spawnerPrompt: 'Test agent',
model: 'claude-3-5-sonnet-20241022',
inputSchema: {},
outputMode: 'structured_output',
includeMessageHistory: true,
inheritParentSystemPrompt: false,
mcpServers: {},
toolNames: ['spawn_agents', 'end_turn'],
spawnableAgents: [],
systemPrompt: 'Test system prompt',
instructionsPrompt: 'Test instructions',
stepPrompt: 'Test step prompt',
}
it('should emit error event instead of tool result when spawn_agents receives invalid parameters', async () => {
// This simulates what happens when the LLM passes a string instead of an array to spawn_agents
// The error from Anthropic was: "Invalid parameters for spawn_agents: expected array, received string"
const invalidToolCallChunk: StreamChunk = {
type: 'tool-call',
toolName: 'spawn_agents',
toolCallId: 'test-tool-call-id',
input: {
agents: 'this should be an array not a string', // Invalid - should be array
},
}
async function* mockStream() {
yield invalidToolCallChunk
return promptSuccess('mock-message-id')
}
const sessionState = getInitialSessionState(mockFileContext)
const agentState = sessionState.mainAgentState
const responseChunks: (string | PrintModeEvent)[] = []
const result = await processStream({
...agentRuntimeImpl,
agentContext: {},
agentState,
agentStepId: 'test-step-id',
agentTemplate: testAgentTemplate,
ancestorRunIds: [],
clientSessionId: 'test-session',
fileContext: mockFileContext,
fingerprintId: 'test-fingerprint',
fullResponse: '',
localAgentTemplates: { 'test-agent': testAgentTemplate },
messages: [],
prompt: 'test prompt',
repoId: undefined,
repoUrl: undefined,
runId: 'test-run-id',
signal: new AbortController().signal,
stream: mockStream(),
system: 'test system',
tools: {},
userId: 'test-user',
userInputId: 'test-input-id',
onCostCalculated: async () => {},
onResponseChunk: (chunk) => {
responseChunks.push(chunk)
},
})
// Verify an error event was emitted (not a tool result)
const errorEvents = responseChunks.filter(
(chunk): chunk is Extract<PrintModeEvent, { type: 'error' }> =>
typeof chunk !== 'string' && chunk.type === 'error',
)
expect(errorEvents.length).toBe(1)
expect(errorEvents[0].message).toContain('Invalid parameters for spawn_agents')
// Verify hadToolCallError is true so the agent loop continues
expect(result.hadToolCallError).toBe(true)
// Verify NO tool_call event was emitted (since validation failed before that point)
const toolCallEvents = responseChunks.filter(
(chunk): chunk is Extract<PrintModeEvent, { type: 'tool_call' }> =>
typeof chunk !== 'string' && chunk.type === 'tool_call',
)
expect(toolCallEvents.length).toBe(0)
// Verify NO tool_result event was emitted
const toolResultEvents = responseChunks.filter(
(chunk): chunk is Extract<PrintModeEvent, { type: 'tool_result' }> =>
typeof chunk !== 'string' && chunk.type === 'tool_result',
)
expect(toolResultEvents.length).toBe(0)
// Verify the message history doesn't contain orphan tool results
// It should NOT have any tool messages since no tool call was made
const toolMessages = agentState.messageHistory.filter(
(m) => m.role === 'tool',
)
const assistantToolCalls = agentState.messageHistory.filter(
(m) =>
m.role === 'assistant' &&
m.content.some((c) => c.type === 'tool-call'),
)
// There should be no tool messages at all (the key fix!)
expect(toolMessages.length).toBe(0)
// And no assistant tool calls either
expect(assistantToolCalls.length).toBe(0)
// Verify error message was added to message history for the LLM to see
const userMessages = agentState.messageHistory.filter(
(m) => m.role === 'user',
)
const errorUserMessage = userMessages.find((m) => {
const contentStr = Array.isArray(m.content)
? m.content.map((p) => ('text' in p ? p.text : '')).join('')
: typeof m.content === 'string' ? m.content : ''
return contentStr.includes('Error during tool call') && contentStr.includes('Invalid parameters for spawn_agents')
})
expect(errorUserMessage).toBeDefined()
})
it('should still emit tool_call and tool_result for valid tool calls', async () => {
// Create an agent that has read_files tool
const agentWithReadFiles: AgentTemplate = {
...testAgentTemplate,
toolNames: ['read_files', 'end_turn'],
}
const validToolCallChunk: StreamChunk = {
type: 'tool-call',
toolName: 'read_files',
toolCallId: 'valid-tool-call-id',
input: {
paths: ['test.ts'], // Valid array parameter
},
}
async function* mockStream() {
yield validToolCallChunk
return promptSuccess('mock-message-id')
}
const sessionState = getInitialSessionState(mockFileContext)
const agentState = sessionState.mainAgentState
// Mock requestFiles to return a file
agentRuntimeImpl.requestFiles = async () => ({
'test.ts': 'console.log("test")',
})
const responseChunks: (string | PrintModeEvent)[] = []
await processStream({
...agentRuntimeImpl,
agentContext: {},
agentState,
agentStepId: 'test-step-id',
agentTemplate: agentWithReadFiles,
ancestorRunIds: [],
clientSessionId: 'test-session',
fileContext: mockFileContext,
fingerprintId: 'test-fingerprint',
fullResponse: '',
localAgentTemplates: { 'test-agent': agentWithReadFiles },
messages: [],
prompt: 'test prompt',
repoId: undefined,
repoUrl: undefined,
runId: 'test-run-id',
signal: new AbortController().signal,
stream: mockStream(),
system: 'test system',
tools: {},
userId: 'test-user',
userInputId: 'test-input-id',
onCostCalculated: async () => {},
onResponseChunk: (chunk) => {
responseChunks.push(chunk)
},
})
// Verify tool_call event was emitted
const toolCallEvents = responseChunks.filter(
(chunk): chunk is Extract<PrintModeEvent, { type: 'tool_call' }> =>
typeof chunk !== 'string' && chunk.type === 'tool_call',
)
expect(toolCallEvents.length).toBe(1)
expect(toolCallEvents[0].toolName).toBe('read_files')
// Verify tool_result event was emitted
const toolResultEvents = responseChunks.filter(
(chunk): chunk is Extract<PrintModeEvent, { type: 'tool_result' }> =>
typeof chunk !== 'string' && chunk.type === 'tool_result',
)
expect(toolResultEvents.length).toBe(1)
// Verify NO error events
const errorEvents = responseChunks.filter(
(chunk): chunk is Extract<PrintModeEvent, { type: 'error' }> =>
typeof chunk !== 'string' && chunk.type === 'error',
)
expect(errorEvents.length).toBe(0)
})
it('should preserve tool_call/tool_result ordering when custom tool setup is async', async () => {
const toolName = 'delayed_custom_tool'
const agentWithCustomTool: AgentTemplate = {
...testAgentTemplate,
toolNames: [toolName, 'end_turn'],
}
const delayedToolCallChunk: StreamChunk = {
type: 'tool-call',
toolName,
toolCallId: 'delayed-custom-tool-call-id',
input: {
query: 'test',
},
}
async function* mockStream() {
yield delayedToolCallChunk
return promptSuccess('mock-message-id')
}
const fileContextWithCustomTool = {
...mockFileContext,
customToolDefinitions: {
[toolName]: {
inputSchema: {
type: 'object',
properties: {
query: { type: 'string' },
},
required: ['query'],
additionalProperties: false,
},
endsAgentStep: false,
description: 'A delayed custom tool for ordering tests',
},
},
}
const sessionState = getInitialSessionState(fileContextWithCustomTool)
const agentState = sessionState.mainAgentState
agentRuntimeImpl.requestMcpToolData = async () => {
// Force an async gap so tool_call emission happens after stream completion.
await new Promise((resolve) => setTimeout(resolve, 20))
return []
}
agentRuntimeImpl.requestToolCall = async () => ({
output: jsonToolResult({ ok: true }),
})
await processStream({
...agentRuntimeImpl,
agentContext: {},
agentState,
agentStepId: 'test-step-id',
agentTemplate: agentWithCustomTool,
ancestorRunIds: [],
clientSessionId: 'test-session',
fileContext: fileContextWithCustomTool,
fingerprintId: 'test-fingerprint',
fullResponse: '',
localAgentTemplates: { 'test-agent': agentWithCustomTool },
messages: [],
prompt: 'test prompt',
repoId: undefined,
repoUrl: undefined,
runId: 'test-run-id',
signal: new AbortController().signal,
stream: mockStream(),
system: 'test system',
tools: {},
userId: 'test-user',
userInputId: 'test-input-id',
onCostCalculated: async () => {},
onResponseChunk: () => {},
})
const assistantToolCallMessages = agentState.messageHistory.filter(
(m): m is AssistantMessage =>
m.role === 'assistant' &&
m.content.some((c) => c.type === 'tool-call' && c.toolName === toolName),
)
const toolMessages = agentState.messageHistory.filter(
(m): m is ToolMessage => m.role === 'tool' && m.toolName === toolName,
)
expect(assistantToolCallMessages.length).toBe(1)
expect(toolMessages.length).toBe(1)
const assistantToolCallPart = assistantToolCallMessages[0].content.find(
(
c,
): c is Extract<AssistantMessage['content'][number], { type: 'tool-call' }> =>
c.type === 'tool-call' && c.toolName === toolName,
)
expect(assistantToolCallPart).toBeDefined()
expect(toolMessages[0].toolCallId).toBe(assistantToolCallPart!.toolCallId)
const assistantIndex = agentState.messageHistory.indexOf(
assistantToolCallMessages[0],
)
const toolResultIndex = agentState.messageHistory.indexOf(toolMessages[0])
expect(assistantIndex).toBeGreaterThanOrEqual(0)
expect(toolResultIndex).toBeGreaterThan(assistantIndex)
const assistantToolCallIds = new Set(
agentState.messageHistory.flatMap((message) => {
if (message.role !== 'assistant') {
return []
}
return message.content.flatMap((part) =>
part.type === 'tool-call' ? [part.toolCallId] : [],
)
}),
)
const orphanToolResults = agentState.messageHistory.filter(
(message): message is ToolMessage =>
message.role === 'tool' && !assistantToolCallIds.has(message.toolCallId),
)
expect(orphanToolResults.length).toBe(0)
})
})