-
Notifications
You must be signed in to change notification settings - Fork 518
Expand file tree
/
Copy pathcost-aggregation.test.ts
More file actions
443 lines (387 loc) · 14.1 KB
/
cost-aggregation.test.ts
File metadata and controls
443 lines (387 loc) · 14.1 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
import { TEST_AGENT_RUNTIME_IMPL } from '@codebuff/common/testing/impl/agent-runtime'
import {
getInitialAgentState,
getInitialSessionState,
} from '@codebuff/common/types/session-state'
import {
spyOn,
beforeEach,
afterEach,
describe,
expect,
it,
mock,
} from 'bun:test'
import * as agentRegistry from '../templates/agent-registry'
import * as spawnAgentUtils from '../tools/handlers/tool/spawn-agent-utils'
import { handleSpawnAgents } from '../tools/handlers/tool/spawn-agents'
import type { AgentState } from '@codebuff/common/types/session-state'
import type { ProjectFileContext } from '@codebuff/common/util/file'
import type { WebSocket } from 'ws'
const mockFileContext: ProjectFileContext = {
projectRoot: '/test',
cwd: '/test',
fileTree: [],
fileTokenScores: {},
knowledgeFiles: {},
gitChanges: {
status: '',
diff: '',
diffCached: '',
lastCommitMessages: '',
},
changesSinceLastChat: {},
shellConfigFiles: {},
agentTemplates: {},
customToolDefinitions: {},
systemInfo: {
platform: 'test',
shell: 'test',
nodeVersion: 'test',
arch: 'test',
homedir: '/home/test',
cpus: 1,
},
}
class MockWebSocket {
send(msg: string) {}
close() {}
on(event: string, listener: (...args: any[]) => void) {}
removeListener(event: string, listener: (...args: any[]) => void) {}
}
describe('Cost Aggregation System', () => {
let mockAgentTemplate: any
let mockLocalAgentTemplates: Record<string, any>
beforeEach(() => {
// Setup mock agent template
mockAgentTemplate = {
id: 'test-agent',
displayName: 'Test Agent',
model: 'gpt-4o-mini',
toolNames: ['write_file'],
spawnableAgents: ['test-agent'],
systemPrompt: 'Test system prompt',
instructionsPrompt: 'Test instructions',
stepPrompt: 'Test step prompt',
includeMessageHistory: true,
inheritParentSystemPrompt: false,
outputMode: 'last_message',
inputSchema: {},
}
mockLocalAgentTemplates = {
'test-agent': mockAgentTemplate,
}
// Mock getAgentTemplate to return our mock template
spyOn(agentRegistry, 'getAgentTemplate').mockResolvedValue(
mockAgentTemplate,
)
// Mock getMatchingSpawn to return the agent type for spawnable validation
spyOn(spawnAgentUtils, 'getMatchingSpawn').mockReturnValue('test-agent')
})
afterEach(() => {
mock.restore()
})
describe('Single Agent Cost Tracking', () => {
it('should track credits used by a single agent', async () => {
const sessionState = getInitialSessionState(mockFileContext)
const agentState = sessionState.mainAgentState
expect(agentState.creditsUsed).toBe(0)
// Simulate adding credits directly to agent state
agentState.creditsUsed += 100
expect(agentState.creditsUsed).toBe(100)
})
it('should accumulate costs across multiple operations', async () => {
const sessionState = getInitialSessionState(mockFileContext)
const agentState = sessionState.mainAgentState
// Simulate agent making multiple operations that incur costs
agentState.creditsUsed += 50
agentState.creditsUsed += 75
agentState.creditsUsed += 25
expect(agentState.creditsUsed).toBe(150)
})
})
describe('Subagent Cost Aggregation', () => {
it('should aggregate costs from successful subagents', async () => {
const parentAgentState: AgentState = {
agentId: 'parent-agent',
agentType: 'test-agent',
agentContext: {},
ancestorRunIds: [],
subagents: [],
childRunIds: [],
messageHistory: [],
stepsRemaining: 10,
creditsUsed: 50, // Parent starts with some cost
directCreditsUsed: 50,
}
const mockValidatedState = {
ws: new MockWebSocket() as unknown as WebSocket,
fingerprintId: 'test-fingerprint',
userId: 'test-user',
agentTemplate: mockAgentTemplate,
localAgentTemplates: mockLocalAgentTemplates,
messages: [],
agentState: parentAgentState,
sendSubagentChunk: () => {},
system: 'Test system prompt',
}
// Mock executeAgent to return results with different credit costs
const mockExecuteAgent = spyOn(spawnAgentUtils, 'executeSubagent')
.mockResolvedValueOnce({
agentState: {
...getInitialAgentState(),
agentId: 'sub-agent-1',
agentType: 'test-agent',
stepsRemaining: 10,
creditsUsed: 75, // First subagent uses 75 credits
},
output: { type: 'lastMessage', value: 'Sub-agent 1 response' },
})
.mockResolvedValueOnce({
agentState: {
...getInitialAgentState(),
agentId: 'sub-agent-2',
agentType: 'test-agent',
stepsRemaining: 10,
creditsUsed: 100, // Second subagent uses 100 credits
},
output: { type: 'lastMessage', value: 'Sub-agent 2 response' },
})
const mockToolCall = {
toolName: 'spawn_agents' as const,
toolCallId: 'test-call',
input: {
agents: [
{ agent_type: 'test-agent', prompt: 'Task 1' },
{ agent_type: 'test-agent', prompt: 'Task 2' },
],
},
}
const result = handleSpawnAgents({
...TEST_AGENT_RUNTIME_IMPL,
previousToolCallFinished: Promise.resolve(),
toolCall: mockToolCall,
fileContext: mockFileContext,
clientSessionId: 'test-session',
userInputId: 'test-input',
writeToClient: () => {},
getLatestState: () => ({ messages: [] }),
state: mockValidatedState,
})
await result.result
// Parent should have aggregated costs: original 50 + subagent 75 + subagent 100 = 225
expect(parentAgentState.creditsUsed).toBe(225)
expect(mockExecuteAgent).toHaveBeenCalledTimes(2)
})
it('should aggregate partial costs from failed subagents', async () => {
const parentAgentState: AgentState = {
...getInitialAgentState(),
agentId: 'parent-agent',
agentType: 'test-agent',
stepsRemaining: 10,
creditsUsed: 10, // Parent starts with some cost
}
const mockValidatedState = {
ws: new MockWebSocket() as unknown as WebSocket,
fingerprintId: 'test-fingerprint',
userId: 'test-user',
agentTemplate: mockAgentTemplate,
localAgentTemplates: mockLocalAgentTemplates,
messages: [],
agentState: parentAgentState,
sendSubagentChunk: () => {},
system: 'Test system prompt',
}
// Mock executeAgent to return success and failure with partial costs
const mockExecuteAgent = spyOn(spawnAgentUtils, 'executeSubagent')
.mockResolvedValueOnce({
agentState: {
...getInitialAgentState(),
agentId: 'sub-agent-1',
agentType: 'test-agent',
stepsRemaining: 10,
creditsUsed: 50, // Successful agent
},
output: { type: 'lastMessage', value: 'Successful response' },
})
.mockRejectedValueOnce(
(() => {
const error = new Error('Agent failed') as any
error.agentState = {
agentId: 'sub-agent-2',
agentType: 'test-agent',
agentContext: {},
subagents: [],
messageHistory: [],
stepsRemaining: 10,
creditsUsed: 25, // Partial cost from failed agent
}
error.output = { type: 'error', message: 'Agent failed' }
return error
})(),
)
const mockToolCall = {
toolName: 'spawn_agents' as const,
toolCallId: 'test-call',
input: {
agents: [
{ agent_type: 'test-agent', prompt: 'Task 1' },
{ agent_type: 'test-agent', prompt: 'Task 2' },
],
},
}
const result = handleSpawnAgents({
...TEST_AGENT_RUNTIME_IMPL,
previousToolCallFinished: Promise.resolve(),
toolCall: mockToolCall,
fileContext: mockFileContext,
clientSessionId: 'test-session',
userInputId: 'test-input',
writeToClient: () => {},
getLatestState: () => ({ messages: [] }),
state: mockValidatedState,
})
await result.result
// Parent should aggregate costs: original 10 + successful subagent 50 + failed subagent 25 = 85
expect(parentAgentState.creditsUsed).toBe(85)
})
})
describe('Error Handling', () => {
it('should preserve costs when operations fail', async () => {
const sessionState = getInitialSessionState(mockFileContext)
const agentState = sessionState.mainAgentState
// Set up initial credits
agentState.creditsUsed = 50
// Simulate adding credits before an error occurs
agentState.creditsUsed += 100
// Simulate an error happening (but costs should be preserved)
try {
throw new Error('Operation failed')
} catch (error) {
// Error occurred, but credits should still be preserved
}
// Agent state should still have the credits that were accumulated
expect(agentState.creditsUsed).toBe(150) // 50 + 100
})
it('should preserve costs when complex operations fail', async () => {
const sessionState = getInitialSessionState(mockFileContext)
const agentState = sessionState.mainAgentState
// Set up initial credits
agentState.creditsUsed = 25
// Simulate multiple operations adding credits
agentState.creditsUsed += 30 // First operation
agentState.creditsUsed += 45 // Second operation
// Simulate a failure after credits were added
let failed = false
try {
throw new Error('Complex operation failed')
} catch (error) {
failed = true
}
// Verify failure occurred but credits were preserved
expect(failed).toBe(true)
expect(agentState.creditsUsed).toBe(100) // 25 + 30 + 45
})
})
describe('Basic Functionality', () => {
it('should initialize creditsUsed field to 0', () => {
const sessionState = getInitialSessionState(mockFileContext)
expect(sessionState.mainAgentState.creditsUsed).toBe(0)
})
it('should allow setting and retrieving creditsUsed field', () => {
const sessionState = getInitialSessionState(mockFileContext)
sessionState.mainAgentState.creditsUsed = 100
expect(sessionState.mainAgentState.creditsUsed).toBe(100)
})
it('should verify cost field exists in AgentState structure', () => {
const sessionState = getInitialSessionState(mockFileContext)
// Verify the structure includes creditsUsed field
expect(sessionState.mainAgentState).toHaveProperty('creditsUsed')
expect(typeof sessionState.mainAgentState.creditsUsed).toBe('number')
// Verify it can be set and retrieved
sessionState.mainAgentState.creditsUsed = 999
expect(sessionState.mainAgentState.creditsUsed).toBe(999)
})
})
describe('Data Integrity', () => {
it('should maintain consistent cost accounting across the agent hierarchy', async () => {
const sessionState = getInitialSessionState(mockFileContext)
const mainAgentState = sessionState.mainAgentState
// Simulate a known cost scenario
const baseAgentCost = 200 // Main agent direct cost
const subAgent1Cost = 150 // First subagent cost
const subAgent2Cost = 100 // Second subagent cost
const expectedTotal = baseAgentCost + subAgent1Cost + subAgent2Cost
// Set up main agent cost
mainAgentState.creditsUsed = baseAgentCost
// Mock subagent spawning that adds their costs
const mockValidatedState = {
ws: new MockWebSocket() as unknown as WebSocket,
fingerprintId: 'test-fingerprint',
userId: 'test-user',
agentTemplate: mockAgentTemplate,
localAgentTemplates: mockLocalAgentTemplates,
messages: [],
agentState: mainAgentState,
sendSubagentChunk: () => {},
system: 'Test system prompt',
}
const mockExecuteAgent = spyOn(spawnAgentUtils, 'executeSubagent')
.mockResolvedValueOnce({
agentState: {
...getInitialAgentState(),
agentId: 'sub-agent-1',
agentType: 'test-agent',
messageHistory: [
{ role: 'assistant', content: 'Sub-agent 1 response' },
],
stepsRemaining: 10,
creditsUsed: subAgent1Cost,
} as AgentState,
output: { type: 'lastMessage', value: 'Sub-agent 1 response' },
})
.mockResolvedValueOnce({
agentState: {
...getInitialAgentState(),
agentId: 'sub-agent-2',
agentType: 'test-agent',
messageHistory: [
{ role: 'assistant', content: 'Sub-agent 2 response' },
],
stepsRemaining: 10,
creditsUsed: subAgent2Cost,
} as AgentState,
output: { type: 'lastMessage', value: 'Sub-agent 2 response' },
})
const mockToolCall = {
toolName: 'spawn_agents' as const,
toolCallId: 'test-call',
input: {
agents: [
{ agent_type: 'test-agent', prompt: 'Task 1' },
{ agent_type: 'test-agent', prompt: 'Task 2' },
],
},
}
const result = handleSpawnAgents({
...TEST_AGENT_RUNTIME_IMPL,
previousToolCallFinished: Promise.resolve(),
toolCall: mockToolCall,
fileContext: mockFileContext,
clientSessionId: 'test-session',
userInputId: 'test-input',
writeToClient: () => {},
getLatestState: () => ({ messages: [] }),
state: mockValidatedState,
})
await result.result
// Verify exact cost accounting
expect(mainAgentState.creditsUsed).toBe(expectedTotal)
// Verify no negative balances or impossible values
expect(mainAgentState.creditsUsed).toBeGreaterThanOrEqual(0)
expect(mainAgentState.creditsUsed).toBe(
Math.floor(mainAgentState.creditsUsed),
) // Should be integer
})
})
})