Repository navigation
Expand file tree
/
Copy pathrun-agent-step-tools.test.ts
More file actions
569 lines (508 loc) · 18.3 KB
/
Copy pathrun-agent-step-tools.test.ts
File metadata and controls
569 lines (508 loc) · 18.3 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
import * as analytics from '@codebuff/common/analytics'
import { TEST_USER_ID } from '@codebuff/common/old-constants'
import { TEST_AGENT_RUNTIME_IMPL } from '@codebuff/common/testing/impl/agent-runtime'
import {
createMockDbOperations,
setupDbSpies,
} from '@codebuff/common/testing/mocks/database'
import { getInitialSessionState } from '@codebuff/common/types/session-state'
import { promptSuccess } from '@codebuff/common/util/error'
import { assistantMessage, userMessage } from '@codebuff/common/util/messages'
import {
afterAll,
afterEach,
beforeEach,
describe,
expect,
it,
mock,
spyOn,
} from 'bun:test'
import { runAgentStep } from '../run-agent-step'
import { clearAgentGeneratorCache } from '../run-programmatic-step'
import { createToolCallChunk } from './test-utils'
import { asUserMessage } from '../util/messages'
import type { AgentTemplate } from '../templates/types'
import type { DbSpies } from '@codebuff/common/testing/mocks/database'
import type {
AgentRuntimeDeps,
AgentRuntimeScopedDeps,
} from '@codebuff/common/types/contracts/agent-runtime'
import type { ParamsExcluding } from '@codebuff/common/types/function-params'
import type { ProjectFileContext } from '@codebuff/common/util/file'
describe('runAgentStep - set_output tool', () => {
let testAgent: AgentTemplate
let agentRuntimeImpl: AgentRuntimeDeps & AgentRuntimeScopedDeps
let runAgentStepBaseParams: ParamsExcluding<
typeof runAgentStep,
| 'agentType'
| 'prompt'
| 'localAgentTemplates'
| 'agentState'
| 'agentTemplate'
>
let dbSpies: DbSpies
beforeEach(async () => {
agentRuntimeImpl = { ...TEST_AGENT_RUNTIME_IMPL, sendAction: () => {} }
// Create a test agent that supports set_output
testAgent = {
id: 'test-set-output-agent',
displayName: 'Test Set Output Agent',
spawnerPrompt: 'Testing set_output functionality',
model: 'claude-3-5-sonnet-20241022',
inputSchema: {},
outputMode: 'structured_output' as const,
includeMessageHistory: true,
inheritParentSystemPrompt: false,
mcpServers: {},
toolNames: ['set_output', 'end_turn'],
spawnableAgents: [],
systemPrompt: 'Test system prompt',
instructionsPrompt: 'Test instructions prompt',
stepPrompt: 'Test agent step prompt',
}
// Setup spies for database operations using typed helper
dbSpies = setupDbSpies(createMockDbOperations())
// Mock analytics
spyOn(analytics, 'trackEvent').mockImplementation(() => {})
agentRuntimeImpl.requestFiles = async ({ filePaths }) => {
const results: Record<string, string | null> = {}
filePaths.forEach((p) => {
if (p === 'src/auth.ts') {
results[p] = 'export function authenticate() { return true; }'
} else if (p === 'src/user.ts') {
results[p] = 'export interface User { id: string; name: string; }'
} else {
results[p] = null
}
})
return results
}
agentRuntimeImpl.requestOptionalFile = async ({ filePath }) => {
if (filePath === 'src/auth.ts') {
return 'export function authenticate() { return true; }'
} else if (filePath === 'src/user.ts') {
return 'export interface User { id: string; name: string; }'
}
return null
}
// Don't mock requestToolCall for integration test - let real tool execution happen
// Mock LLM APIs
agentRuntimeImpl.promptAiSdk = async function () {
return promptSuccess('Test response')
}
clearAgentGeneratorCache(agentRuntimeImpl)
runAgentStepBaseParams = {
...agentRuntimeImpl,
additionalToolDefinitions: () => Promise.resolve({}),
ancestorRunIds: [],
clientSessionId: 'test-session',
fileContext: mockFileContext,
fingerprintId: 'test-fingerprint',
onResponseChunk: () => {},
repoId: undefined,
repoUrl: undefined,
runId: 'test-run-id',
signal: new AbortController().signal,
spawnParams: undefined,
system: 'Test system prompt',
tools: {},
userId: TEST_USER_ID,
userInputId: 'test-input',
}
})
afterEach(() => {
dbSpies.restore()
mock.restore()
})
afterAll(() => {
clearAgentGeneratorCache(agentRuntimeImpl)
})
const mockFileContext: ProjectFileContext = {
projectRoot: '/test',
cwd: '/test',
fileTree: [],
fileTokenScores: {},
knowledgeFiles: {},
gitChanges: {
status: '',
diff: '',
diffCached: '',
lastCommitMessages: '',
},
changesSinceLastChat: {},
shellConfigFiles: {},
systemInfo: {
platform: 'test',
shell: 'test',
nodeVersion: 'test',
arch: 'test',
homedir: '/home/test',
cpus: 1,
chromeAvailable: false,
},
agentTemplates: {},
customToolDefinitions: {},
}
it('should set output with simple key-value pair', async () => {
runAgentStepBaseParams.promptAiSdkStream = async function* ({}) {
yield createToolCallChunk('set_output', { message: 'Hi' })
yield { type: 'text' as const, text: '\n\n' }
yield createToolCallChunk('end_turn', {})
return promptSuccess('mock-message-id')
}
const sessionState = getInitialSessionState(mockFileContext)
const agentState = sessionState.mainAgentState
const localAgentTemplates = {
'test-set-output-agent': testAgent,
}
const result = await runAgentStep({
...runAgentStepBaseParams,
agentType: 'test-set-output-agent',
localAgentTemplates,
agentTemplate: testAgent,
agentState,
prompt: 'Analyze the codebase',
})
expect(result.agentState.output).toEqual({
message: 'Hi',
})
expect(result.shouldEndTurn).toBe(true)
})
it('should set output with complex data', async () => {
runAgentStepBaseParams.promptAiSdkStream = async function* ({}) {
yield createToolCallChunk('set_output', {
message: 'Analysis complete',
status: 'success',
findings: ['Bug in auth.ts', 'Missing validation'],
})
yield createToolCallChunk('end_turn', {})
return promptSuccess('mock-message-id')
}
const sessionState = getInitialSessionState(mockFileContext)
const agentState = sessionState.mainAgentState
const localAgentTemplates = {
'test-set-output-agent': testAgent,
}
const result = await runAgentStep({
...runAgentStepBaseParams,
agentType: 'test-set-output-agent',
localAgentTemplates,
agentTemplate: testAgent,
agentState,
prompt: 'Analyze the codebase',
})
expect(result.agentState.output).toEqual({
message: 'Analysis complete',
status: 'success',
findings: ['Bug in auth.ts', 'Missing validation'],
})
expect(result.shouldEndTurn).toBe(true)
})
it('should replace existing output data', async () => {
runAgentStepBaseParams.promptAiSdkStream = async function* ({}) {
yield createToolCallChunk('set_output', {
newField: 'new value',
existingField: 'updated value',
})
yield createToolCallChunk('end_turn', {})
return promptSuccess('mock-message-id')
}
const sessionState = getInitialSessionState(mockFileContext)
const agentState = sessionState.mainAgentState
// Pre-populate the output with existing data
agentState.output = {
existingField: 'original value',
anotherField: 'unchanged',
}
const localAgentTemplates = {
'test-set-output-agent': testAgent,
}
const result = await runAgentStep({
...runAgentStepBaseParams,
localAgentTemplates,
agentTemplate: testAgent,
agentState,
prompt: 'Update the output',
agentType: 'test-set-output-agent',
})
expect(result.agentState.output).toEqual({
newField: 'new value',
existingField: 'updated value',
})
})
it('should handle empty output parameter', async () => {
runAgentStepBaseParams.promptAiSdkStream = async function* ({}) {
yield createToolCallChunk('set_output', {})
yield createToolCallChunk('end_turn', {})
return promptSuccess('mock-message-id')
}
const sessionState = getInitialSessionState(mockFileContext)
const agentState = sessionState.mainAgentState
agentState.output = { existingField: 'value' }
const localAgentTemplates = {
'test-set-output-agent': testAgent,
}
const result = await runAgentStep({
...runAgentStepBaseParams,
localAgentTemplates,
agentTemplate: testAgent,
agentState,
agentType: 'test-set-output-agent',
prompt: 'Update with empty object',
})
// Should replace with empty object
expect(result.agentState.output).toEqual({})
})
it('should handle handleSteps with one tool call and STEP_ALL', async () => {
// Create a mock agent template with handleSteps
const mockAgentTemplate: AgentTemplate = {
id: 'test-handlesteps-agent',
displayName: 'Test HandleSteps Agent',
spawnerPrompt: 'Testing handleSteps functionality',
model: 'claude-3-5-sonnet-20241022',
inputSchema: {},
outputMode: 'structured_output' as const,
includeMessageHistory: true,
inheritParentSystemPrompt: false,
mcpServers: {},
toolNames: ['read_files', 'end_turn'],
spawnableAgents: [],
systemPrompt: 'Test system prompt',
instructionsPrompt: 'Test instructions prompt',
stepPrompt: 'Test agent step prompt',
handleSteps: function* ({ agentState, prompt, params }) {
// Yield one tool call
yield {
toolName: 'read_files',
input: { paths: ['src/test.ts'] },
}
// Then yield STEP_ALL to continue processing
yield 'STEP_ALL'
},
}
// Mock the agent registry to include our test agent
const mockAgentRegistry = {
'test-handlesteps-agent': mockAgentTemplate,
}
// Mock requestFiles to return test file content
runAgentStepBaseParams.requestFiles = async ({ filePaths }) => {
const results: Record<string, string | null> = {}
filePaths.forEach((p) => {
if (p === 'src/test.ts') {
results[p] = 'export function testFunction() { return "test"; }'
} else {
results[p] = null
}
})
return results
}
// Mock the LLM stream to return a response that doesn't end the turn
runAgentStepBaseParams.promptAiSdkStream = async function* ({}) {
yield { type: 'text' as const, text: 'Continuing with the analysis...' } // Non-empty response, no tool calls
return promptSuccess('mock-message-id')
}
const sessionState = getInitialSessionState(mockFileContext)
const agentState = sessionState.mainAgentState
// Add the user prompt and instructions that would normally be added by loopAgentSteps
agentState.messageHistory = [
...agentState.messageHistory,
userMessage({
content: asUserMessage('Test the handleSteps functionality'),
keepDuringTruncation: true,
}),
userMessage({
content: 'Test instructions prompt',
timeToLive: 'userPrompt' as const,
keepDuringTruncation: true,
}),
]
const initialMessageCount = agentState.messageHistory.length
const result = await runAgentStep({
...runAgentStepBaseParams,
agentType: 'test-handlesteps-agent',
localAgentTemplates: mockAgentRegistry,
agentTemplate: mockAgentTemplate,
agentState,
prompt: 'Test the handleSteps functionality',
})
// Should end turn because toolCalls.length === 0 && toolResults.length === 0 from LLM processing
// (The programmatic step tool results don't count toward this calculation)
expect(result.shouldEndTurn).toBe(true)
const finalMessages = result.agentState.messageHistory
// Verify the exact sequence of messages in the final message history
const newMessages = finalMessages.slice(initialMessageCount)
// Check that we have the user prompt in the full message history
expect(
finalMessages.some(
(m) =>
m.role === 'user' &&
m.content[0].type === 'text' &&
m.content[0].text.includes('Test the handleSteps functionality'),
),
).toBe(true)
// The test should verify that the LLM response is correctly processed
expect(
newMessages.some(
(m) =>
m.role === 'assistant' &&
m.content[0].type === 'text' &&
m.content[0].text === 'Continuing with the analysis...',
),
).toBe(true)
})
it('should spawn agent inline that deletes last two assistant messages', async () => {
// Create a mock inline agent template that deletes messages
const mockInlineAgentTemplate: AgentTemplate = {
id: 'message-deleter-agent',
displayName: 'Message Deleter Agent',
spawnerPrompt: 'Deletes assistant messages',
model: 'claude-3-5-sonnet-20241022',
inputSchema: {},
outputMode: 'structured_output' as const,
includeMessageHistory: true,
inheritParentSystemPrompt: false,
mcpServers: {},
toolNames: ['set_messages', 'end_turn'],
spawnableAgents: [],
systemPrompt: 'Delete messages system prompt',
instructionsPrompt: 'Delete messages instructions prompt',
stepPrompt: 'Delete messages step prompt',
handleSteps: function* ({ agentState, prompt, params }) {
// Delete the last two assistant messages by doing two iterations
const messages = [...agentState.messageHistory]
// First iteration: find and remove the last assistant message, which is the tool call to this agent
for (let i = messages.length - 1; i >= 0; i--) {
if (messages[i].role === 'assistant') {
messages.splice(i, 1)
break
}
}
// Second iteration: find and remove the next-to-last assistant message
for (let i = messages.length - 1; i >= 0; i--) {
if (messages[i].role === 'assistant') {
messages.splice(i, 1)
break
}
}
// Third iteration: find and remove the third assistant message
for (let i = messages.length - 1; i >= 0; i--) {
if (messages[i].role === 'assistant') {
messages.splice(i, 1)
break
}
}
// Set the updated messages
yield {
toolName: 'set_messages',
input: { messages },
}
},
}
// Create a parent agent template that can spawn the inline agent
const mockParentAgentTemplate: AgentTemplate = {
id: 'parent-agent',
displayName: 'Parent Agent',
spawnerPrompt: 'Parent agent that spawns inline agents',
model: 'claude-3-5-sonnet-20241022',
inputSchema: {},
outputMode: 'structured_output' as const,
includeMessageHistory: true,
inheritParentSystemPrompt: false,
mcpServers: {},
toolNames: ['spawn_agent_inline', 'end_turn'],
spawnableAgents: ['message-deleter-agent'],
systemPrompt: 'Parent system prompt',
instructionsPrompt: 'Parent instructions prompt',
stepPrompt: 'Parent step prompt',
}
// Mock the agent registry to include both agents
const mockAgentRegistry = {
'parent-agent': mockParentAgentTemplate,
'message-deleter-agent': mockInlineAgentTemplate,
}
// Mock the LLM stream to spawn the inline agent
runAgentStepBaseParams.promptAiSdkStream = async function* ({}) {
yield createToolCallChunk('spawn_agent_inline', {
agent_type: 'message-deleter-agent',
prompt: 'Delete the last two assistant messages',
})
return promptSuccess('mock-message-id')
}
const sessionState = getInitialSessionState(mockFileContext)
const agentState = sessionState.mainAgentState
// Add some initial messages including assistant messages to delete
agentState.messageHistory = [
userMessage('Hello'),
assistantMessage('Hi there!'),
userMessage('How are you?'),
assistantMessage('I am doing well, thank you!'),
userMessage('Can you help me?'),
assistantMessage('Of course, I would be happy to help!'),
// Add the user prompt and instructions that would normally be added by loopAgentSteps
userMessage({
content: 'Spawn an inline agent to clean up messages',
keepDuringTruncation: true,
}),
userMessage({
content: 'Parent instructions prompt',
timeToLive: 'userPrompt' as const,
keepDuringTruncation: true,
}),
]
const result = await runAgentStep({
...runAgentStepBaseParams,
agentType: 'parent-agent',
localAgentTemplates: mockAgentRegistry,
agentTemplate: mockParentAgentTemplate,
agentState,
prompt: 'Spawn an inline agent to clean up messages',
})
const finalMessages = result.agentState.messageHistory
// This integration test demonstrates that spawn_agent_inline tool calls are executed successfully!
// The inline agent runs its handleSteps function and executes tool calls
// Verify that the inline agent executed and messages were properly deleted
// After refactoring, the execution flow may be different but the end result should be the same
// Check that some assistant messages were deleted (we started with 3, should have fewer now)
const assistantMessagesCount = finalMessages.filter(
(m) => m.role === 'assistant',
).length
expect(assistantMessagesCount).toBeLessThan(3) // We should have deleted some assistant messages
// Check that we have the user prompt that triggered the inline agent
expect(
finalMessages.some(
(m) =>
m.role === 'user' &&
m.content[0].type === 'text' &&
m.content[0].text.includes(
'Spawn an inline agent to clean up messages',
),
),
).toBe(true)
// The final messages should still contain the core conversation structure
expect(
finalMessages.some(
(m) =>
m.role === 'user' &&
m.content[0].type === 'text' &&
m.content[0].text === 'Hello',
),
).toBe(true)
expect(
finalMessages.some(
(m) =>
m.role === 'user' &&
m.content[0].type === 'text' &&
m.content[0].text === 'How are you?',
),
).toBe(true)
expect(
finalMessages.some(
(m) =>
m.role === 'user' &&
m.content[0].type === 'text' &&
m.content[0].text === 'Can you help me?',
),
).toBe(true)
})
})