-
Notifications
You must be signed in to change notification settings - Fork 216
Expand file tree
/
Copy pathdurable-agent.test.ts
More file actions
2621 lines (2281 loc) · 77.1 KB
/
durable-agent.test.ts
File metadata and controls
2621 lines (2281 loc) · 77.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
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
/**
* Tests for DurableAgent
*
* These tests focus on error handling in tool execution,
* particularly for FatalError conversion to tool result errors,
* and verifying that messages are properly passed to tool execute functions.
*/
import type {
LanguageModelV3,
LanguageModelV3Prompt,
LanguageModelV3ToolCall,
LanguageModelV3ToolResult,
} from '@ai-sdk/provider';
import type { StepResult, ToolSet } from 'ai';
import { describe, expect, it, vi } from 'vitest';
import { z } from 'zod';
class FatalError extends Error {
constructor(message: string) {
super(message);
this.name = 'FatalError';
}
}
// Mock the streamTextIterator
vi.mock('./stream-text-iterator.js', () => ({
streamTextIterator: vi.fn(),
}));
// Import after mocking
const { DurableAgent } = await import('./durable-agent.js');
import type {
PrepareStepCallback,
ToolCallRepairFunction,
} from './durable-agent.js';
import type { StreamTextIteratorYieldValue } from './stream-text-iterator.js';
/**
* Creates a mock LanguageModelV3 for testing
*/
function createMockModel(): LanguageModelV3 {
return {
specificationVersion: 'v3' as const,
provider: 'test',
modelId: 'test-model',
doGenerate: vi.fn(),
doStream: vi.fn(),
supportedUrls: {},
};
}
/**
* Type for the mock iterator used in tests
*/
type MockIterator = AsyncGenerator<
StreamTextIteratorYieldValue,
LanguageModelV3Prompt,
LanguageModelV3ToolResult[]
>;
describe('DurableAgent', () => {
describe('tool execution error handling', () => {
it('should convert FatalError to tool error result', async () => {
const errorMessage = 'This is a fatal error';
const tools: ToolSet = {
testTool: {
description: 'A test tool',
inputSchema: z.object({}),
execute: async () => {
throw new FatalError(errorMessage);
},
},
};
// We need to test the executeTool function indirectly through the agent
// Create a mock model that will trigger tool calls
const mockModel = createMockModel();
const agent = new DurableAgent({
model: async () => mockModel,
tools,
});
// Create a mock writable stream
const mockWritable = new WritableStream({
write: vi.fn(),
close: vi.fn(),
});
// Mock the streamTextIterator to return tool calls and then complete
const { streamTextIterator } = await import('./stream-text-iterator.js');
const mockMessages: LanguageModelV3Prompt = [
{ role: 'user', content: [{ type: 'text', text: 'test' }] },
];
const mockIterator = {
next: vi
.fn()
.mockResolvedValueOnce({
done: false,
value: {
toolCalls: [
{
toolCallId: 'test-call-id',
toolName: 'testTool',
input: '{}',
} as LanguageModelV3ToolCall,
],
messages: mockMessages,
},
})
.mockResolvedValueOnce({ done: true, value: [] }),
};
vi.mocked(streamTextIterator).mockReturnValue(
mockIterator as unknown as MockIterator
);
// Execute the stream - this should not throw even though the tool throws FatalError
await expect(
agent.stream({
messages: [{ role: 'user', content: 'test' }],
writable: mockWritable,
})
).resolves.not.toThrow();
// Verify that the iterator was called with tool results including the error
expect(mockIterator.next).toHaveBeenCalledTimes(2);
const toolResultsCall = mockIterator.next.mock.calls[1][0];
expect(toolResultsCall).toBeDefined();
expect(toolResultsCall).toHaveLength(1);
expect(toolResultsCall[0]).toMatchObject({
type: 'tool-result',
toolCallId: 'test-call-id',
toolName: 'testTool',
output: {
type: 'error-text',
value: errorMessage,
},
});
});
it('should convert non-FatalError to tool error result', async () => {
const errorMessage = 'This is a generic error';
const tools: ToolSet = {
testTool: {
description: 'A test tool',
inputSchema: z.object({}),
execute: async () => {
throw new Error(errorMessage);
},
},
};
const mockModel = createMockModel();
const agent = new DurableAgent({
model: async () => mockModel,
tools,
});
const mockWritable = new WritableStream({
write: vi.fn(),
close: vi.fn(),
});
const { streamTextIterator } = await import('./stream-text-iterator.js');
const mockMessages: LanguageModelV3Prompt = [
{ role: 'user', content: [{ type: 'text', text: 'test' }] },
];
const mockIterator = {
next: vi
.fn()
.mockResolvedValueOnce({
done: false,
value: {
toolCalls: [
{
toolCallId: 'test-call-id',
toolName: 'testTool',
input: '{}',
} as LanguageModelV3ToolCall,
],
messages: mockMessages,
},
})
.mockResolvedValueOnce({ done: true, value: [] }),
};
vi.mocked(streamTextIterator).mockReturnValue(
mockIterator as unknown as MockIterator
);
// Non-FatalError should be converted to error-text, not re-thrown
await expect(
agent.stream({
messages: [{ role: 'user', content: 'test' }],
writable: mockWritable,
})
).resolves.not.toThrow();
// Verify the error was converted to a tool error result
expect(mockIterator.next).toHaveBeenCalledTimes(2);
const toolResultsCall = mockIterator.next.mock.calls[1][0];
expect(toolResultsCall).toBeDefined();
expect(toolResultsCall).toHaveLength(1);
expect(toolResultsCall[0]).toMatchObject({
type: 'tool-result',
toolCallId: 'test-call-id',
toolName: 'testTool',
output: {
type: 'error-text',
value: errorMessage,
},
});
});
it('should successfully execute tools that return normally', async () => {
const toolResult = { success: true, data: 'test result' };
const tools: ToolSet = {
testTool: {
description: 'A test tool',
inputSchema: z.object({}),
execute: async () => toolResult,
},
};
const mockModel = createMockModel();
const agent = new DurableAgent({
model: async () => mockModel,
tools,
});
const mockWritable = new WritableStream({
write: vi.fn(),
close: vi.fn(),
});
const { streamTextIterator } = await import('./stream-text-iterator.js');
const mockMessages: LanguageModelV3Prompt = [
{ role: 'user', content: [{ type: 'text', text: 'test' }] },
];
const mockIterator = {
next: vi
.fn()
.mockResolvedValueOnce({
done: false,
value: {
toolCalls: [
{
toolCallId: 'test-call-id',
toolName: 'testTool',
input: '{}',
} as LanguageModelV3ToolCall,
],
messages: mockMessages,
},
})
.mockResolvedValueOnce({ done: true, value: [] }),
};
vi.mocked(streamTextIterator).mockReturnValue(
mockIterator as unknown as MockIterator
);
await agent.stream({
messages: [{ role: 'user', content: 'test' }],
writable: mockWritable,
});
// Verify that the iterator was called with successful tool results
expect(mockIterator.next).toHaveBeenCalledTimes(2);
const toolResultsCall = mockIterator.next.mock.calls[1][0];
expect(toolResultsCall).toBeDefined();
expect(toolResultsCall).toHaveLength(1);
expect(toolResultsCall[0]).toMatchObject({
type: 'tool-result',
toolCallId: 'test-call-id',
toolName: 'testTool',
output: {
// Object results use 'json' type with raw value (not stringified)
type: 'json',
value: toolResult,
},
});
});
it('should pass through LanguageModelV3ToolResultOutput directly', async () => {
// Tool returns a pre-formatted content output (e.g., multimodal with images)
const contentOutput = {
type: 'content',
value: [
{ type: 'text', text: 'Here is the image' },
{
type: 'file-data',
data: 'base64data',
mediaType: 'image/jpeg',
},
],
};
const tools: ToolSet = {
visionTool: {
description: 'Returns multimodal content',
inputSchema: z.object({}),
execute: vi.fn().mockResolvedValue(contentOutput),
},
};
const mockModel = createMockModel();
const agent = new DurableAgent({
model: async () => mockModel,
tools,
});
const mockWritable = new WritableStream({
write: vi.fn(),
close: vi.fn(),
});
const mockMessages: LanguageModelV3Prompt = [
{ role: 'user', content: [{ type: 'text', text: 'test' }] },
];
const { streamTextIterator } = await import('./stream-text-iterator.js');
const mockIterator = {
next: vi
.fn()
.mockResolvedValueOnce({
done: false,
value: {
toolCalls: [
{
toolCallId: 'vision-call-id',
toolName: 'visionTool',
input: '{}',
} as LanguageModelV3ToolCall,
],
messages: mockMessages,
},
})
.mockResolvedValueOnce({ done: true, value: [] }),
};
vi.mocked(streamTextIterator).mockReturnValue(
mockIterator as unknown as MockIterator
);
await agent.stream({
messages: [{ role: 'user', content: 'test' }],
writable: mockWritable,
});
const toolResultsCall = mockIterator.next.mock.calls[1][0];
expect(toolResultsCall).toHaveLength(1);
expect(toolResultsCall[0]).toMatchObject({
type: 'tool-result',
toolCallId: 'vision-call-id',
toolName: 'visionTool',
output: contentOutput, // Passed through as-is, not wrapped in json
});
});
it('should pass through pre-formatted text output directly', async () => {
// Tool returns an already-formatted text output
const textOutput = { type: 'text', value: 'pre-formatted result' };
const tools: ToolSet = {
textTool: {
description: 'Returns pre-formatted text',
inputSchema: z.object({}),
execute: vi.fn().mockResolvedValue(textOutput),
},
};
const mockModel = createMockModel();
const agent = new DurableAgent({
model: async () => mockModel,
tools,
});
const mockWritable = new WritableStream({
write: vi.fn(),
close: vi.fn(),
});
const mockMessages: LanguageModelV3Prompt = [
{ role: 'user', content: [{ type: 'text', text: 'test' }] },
];
const { streamTextIterator } = await import('./stream-text-iterator.js');
const mockIterator = {
next: vi
.fn()
.mockResolvedValueOnce({
done: false,
value: {
toolCalls: [
{
toolCallId: 'text-call-id',
toolName: 'textTool',
input: '{}',
} as LanguageModelV3ToolCall,
],
messages: mockMessages,
},
})
.mockResolvedValueOnce({ done: true, value: [] }),
};
vi.mocked(streamTextIterator).mockReturnValue(
mockIterator as unknown as MockIterator
);
await agent.stream({
messages: [{ role: 'user', content: 'test' }],
writable: mockWritable,
});
const toolResultsCall = mockIterator.next.mock.calls[1][0];
expect(toolResultsCall[0]).toMatchObject({
type: 'tool-result',
output: textOutput, // Passed through, not re-wrapped
});
});
it('should skip local execution for provider-executed tools', async () => {
// This tool should NOT be called because the tool call is provider-executed
const executeFn = vi.fn();
const tools: ToolSet = {
// This is a local tool - should never be called for provider-executed calls
localTool: {
description: 'A local tool',
inputSchema: z.object({}),
execute: executeFn,
},
};
const mockModel = createMockModel();
const agent = new DurableAgent({
model: async () => mockModel,
tools,
});
const mockWritable = new WritableStream({
write: vi.fn(),
close: vi.fn(),
});
const { streamTextIterator } = await import('./stream-text-iterator.js');
const mockMessages: LanguageModelV3Prompt = [
{ role: 'user', content: [{ type: 'text', text: 'test' }] },
];
// Create a provider-executed tool result map
const providerExecutedToolResults = new Map();
providerExecutedToolResults.set('provider-call-id', {
toolCallId: 'provider-call-id',
toolName: 'WebSearch',
result: 'Search results for: test query',
isError: false,
});
const mockIterator = {
next: vi
.fn()
.mockResolvedValueOnce({
done: false,
value: {
toolCalls: [
{
toolCallId: 'provider-call-id',
toolName: 'WebSearch',
input: '{"query":"test query"}',
providerExecuted: true, // This is a provider-executed tool
} as LanguageModelV3ToolCall,
],
messages: mockMessages,
providerExecutedToolResults,
},
})
.mockResolvedValueOnce({ done: true, value: [] }),
};
vi.mocked(streamTextIterator).mockReturnValue(
mockIterator as unknown as MockIterator
);
await agent.stream({
messages: [{ role: 'user', content: 'test' }],
writable: mockWritable,
});
// The local tool execute function should NOT have been called
expect(executeFn).not.toHaveBeenCalled();
// Verify that the iterator was called with the provider-executed tool result
expect(mockIterator.next).toHaveBeenCalledTimes(2);
const toolResultsCall = mockIterator.next.mock.calls[1][0];
expect(toolResultsCall).toBeDefined();
expect(toolResultsCall).toHaveLength(1);
expect(toolResultsCall[0]).toMatchObject({
type: 'tool-result',
toolCallId: 'provider-call-id',
toolName: 'WebSearch',
output: {
// String results use 'text' type with raw value
type: 'text',
value: 'Search results for: test query',
},
});
});
it('should handle mixed provider-executed and local tools', async () => {
const localToolResult = { local: 'result' };
const localExecuteFn = vi.fn().mockResolvedValue(localToolResult);
const tools: ToolSet = {
localTool: {
description: 'A local tool',
inputSchema: z.object({}),
execute: localExecuteFn,
},
};
const mockModel = createMockModel();
const agent = new DurableAgent({
model: async () => mockModel,
tools,
});
const mockWritable = new WritableStream({
write: vi.fn(),
close: vi.fn(),
});
const { streamTextIterator } = await import('./stream-text-iterator.js');
const mockMessages: LanguageModelV3Prompt = [
{ role: 'user', content: [{ type: 'text', text: 'test' }] },
];
// Create a provider-executed tool result map
const providerExecutedToolResults = new Map();
providerExecutedToolResults.set('provider-call-id', {
toolCallId: 'provider-call-id',
toolName: 'WebSearch',
result: { searchResults: ['result1', 'result2'] },
isError: false,
});
const mockIterator = {
next: vi
.fn()
.mockResolvedValueOnce({
done: false,
value: {
toolCalls: [
// Local tool call - should be executed locally
{
toolCallId: 'local-call-id',
toolName: 'localTool',
input: '{}',
providerExecuted: false,
} as LanguageModelV3ToolCall,
// Provider-executed tool call - should use stream result
{
toolCallId: 'provider-call-id',
toolName: 'WebSearch',
input: '{"query":"test"}',
providerExecuted: true,
} as LanguageModelV3ToolCall,
],
messages: mockMessages,
providerExecutedToolResults,
},
})
.mockResolvedValueOnce({ done: true, value: [] }),
};
vi.mocked(streamTextIterator).mockReturnValue(
mockIterator as unknown as MockIterator
);
await agent.stream({
messages: [{ role: 'user', content: 'test' }],
writable: mockWritable,
});
// The local tool execute function SHOULD have been called
expect(localExecuteFn).toHaveBeenCalledTimes(1);
// Verify that the iterator was called with both tool results
expect(mockIterator.next).toHaveBeenCalledTimes(2);
const toolResultsCall = mockIterator.next.mock.calls[1][0];
expect(toolResultsCall).toBeDefined();
expect(toolResultsCall).toHaveLength(2);
// First result should be from local tool (object result uses 'json' type)
expect(toolResultsCall[0]).toMatchObject({
type: 'tool-result',
toolCallId: 'local-call-id',
toolName: 'localTool',
output: {
type: 'json',
value: localToolResult,
},
});
// Second result should be from provider-executed tool (object result uses 'json' type)
expect(toolResultsCall[1]).toMatchObject({
type: 'tool-result',
toolCallId: 'provider-call-id',
toolName: 'WebSearch',
output: {
type: 'json',
value: { searchResults: ['result1', 'result2'] },
},
});
});
it('should handle provider-executed tool errors with isError flag', async () => {
const mockModel = createMockModel();
const agent = new DurableAgent({
model: async () => mockModel,
tools: {},
});
const mockWritable = new WritableStream({
write: vi.fn(),
close: vi.fn(),
});
const { streamTextIterator } = await import('./stream-text-iterator.js');
const mockMessages: LanguageModelV3Prompt = [
{ role: 'user', content: [{ type: 'text', text: 'test' }] },
];
// Create a provider-executed tool result with isError: true
const providerExecutedToolResults = new Map();
providerExecutedToolResults.set('provider-call-id', {
toolCallId: 'provider-call-id',
toolName: 'WebSearch',
result: 'Search failed: Rate limit exceeded',
isError: true,
});
const mockIterator = {
next: vi
.fn()
.mockResolvedValueOnce({
done: false,
value: {
toolCalls: [
{
toolCallId: 'provider-call-id',
toolName: 'WebSearch',
input: '{"query":"test query"}',
providerExecuted: true,
} as LanguageModelV3ToolCall,
],
messages: mockMessages,
providerExecutedToolResults,
},
})
.mockResolvedValueOnce({ done: true, value: [] }),
};
vi.mocked(streamTextIterator).mockReturnValue(
mockIterator as unknown as MockIterator
);
await agent.stream({
messages: [{ role: 'user', content: 'test' }],
writable: mockWritable,
});
// Verify that the iterator was called with error-text output type
expect(mockIterator.next).toHaveBeenCalledTimes(2);
const toolResultsCall = mockIterator.next.mock.calls[1][0];
expect(toolResultsCall).toBeDefined();
expect(toolResultsCall).toHaveLength(1);
expect(toolResultsCall[0]).toMatchObject({
type: 'tool-result',
toolCallId: 'provider-call-id',
toolName: 'WebSearch',
output: {
// String error results use 'error-text' type with raw value
type: 'error-text',
value: 'Search failed: Rate limit exceeded',
},
});
});
it('should warn and return empty result when provider-executed tool result is missing', async () => {
const consoleWarnSpy = vi
.spyOn(console, 'warn')
.mockImplementation(() => {});
const mockModel = createMockModel();
const agent = new DurableAgent({
model: async () => mockModel,
tools: {},
});
const mockWritable = new WritableStream({
write: vi.fn(),
close: vi.fn(),
});
const { streamTextIterator } = await import('./stream-text-iterator.js');
const mockMessages: LanguageModelV3Prompt = [
{ role: 'user', content: [{ type: 'text', text: 'test' }] },
];
// Empty map - no provider results available
const providerExecutedToolResults = new Map();
const mockIterator = {
next: vi
.fn()
.mockResolvedValueOnce({
done: false,
value: {
toolCalls: [
{
toolCallId: 'missing-result-id',
toolName: 'WebSearch',
input: '{"query":"test query"}',
providerExecuted: true,
} as LanguageModelV3ToolCall,
],
messages: mockMessages,
providerExecutedToolResults,
},
})
.mockResolvedValueOnce({ done: true, value: [] }),
};
vi.mocked(streamTextIterator).mockReturnValue(
mockIterator as unknown as MockIterator
);
await agent.stream({
messages: [{ role: 'user', content: 'test' }],
writable: mockWritable,
});
// Verify warning was logged
expect(consoleWarnSpy).toHaveBeenCalledWith(
expect.stringContaining('Provider-executed tool "WebSearch"')
);
expect(consoleWarnSpy).toHaveBeenCalledWith(
expect.stringContaining('missing-result-id')
);
// Verify empty result was returned
const toolResultsCall = mockIterator.next.mock.calls[1][0];
expect(toolResultsCall).toBeDefined();
expect(toolResultsCall).toHaveLength(1);
expect(toolResultsCall[0]).toMatchObject({
type: 'tool-result',
toolCallId: 'missing-result-id',
toolName: 'WebSearch',
output: {
type: 'text',
value: '',
},
});
consoleWarnSpy.mockRestore();
});
});
describe('client-side tools (tools without execute)', () => {
it('should stop the loop and return unresolved toolCalls for tools without execute', async () => {
const tools: ToolSet = {
askUser: {
description: 'Ask the user a question',
inputSchema: z.object({ question: z.string() }),
// No execute function - this is a client-side tool
},
};
const mockModel = createMockModel();
const agent = new DurableAgent({
model: async () => mockModel,
tools,
});
const mockWritable = new WritableStream({
write: vi.fn(),
close: vi.fn(),
});
const { streamTextIterator } = await import('./stream-text-iterator.js');
const mockMessages: LanguageModelV3Prompt = [
{ role: 'user', content: [{ type: 'text', text: 'test' }] },
];
const mockIterator = {
next: vi.fn().mockResolvedValueOnce({
done: false,
value: {
toolCalls: [
{
toolCallId: 'ask-user-call-id',
toolName: 'askUser',
input: '{"question":"What is your name?"}',
providerExecuted: false,
} as LanguageModelV3ToolCall,
],
messages: mockMessages,
},
}),
// Note: no second call - the loop should stop before calling next again
};
vi.mocked(streamTextIterator).mockReturnValue(
mockIterator as unknown as MockIterator
);
const result = await agent.stream({
messages: [{ role: 'user', content: 'test' }],
writable: mockWritable,
});
// The loop should have stopped - iterator.next called only once
expect(mockIterator.next).toHaveBeenCalledTimes(1);
// toolCalls should contain the call (matches AI SDK convention)
expect(result.toolCalls).toHaveLength(1);
expect(result.toolCalls[0]).toEqual({
type: 'tool-call',
toolCallId: 'ask-user-call-id',
toolName: 'askUser',
input: { question: 'What is your name?' },
});
// toolResults should be empty (no execute function → not executed)
expect(result.toolResults).toHaveLength(0);
// Messages should include the conversation up to the tool call (from iterMessages),
// not just the original input messages, so callers can resume
expect(result.messages).toBe(mockMessages);
});
it('should handle mixed executable and client-side tools in the same step', async () => {
const localToolResult = { data: 'from-server' };
const localExecuteFn = vi.fn().mockResolvedValue(localToolResult);
const tools: ToolSet = {
serverTool: {
description: 'A server-side tool',
inputSchema: z.object({}),
execute: localExecuteFn,
},
clientTool: {
description: 'A client-side tool',
inputSchema: z.object({ prompt: z.string() }),
// No execute function
},
};
const mockModel = createMockModel();
const agent = new DurableAgent({
model: async () => mockModel,
tools,
});
const writtenChunks: unknown[] = [];
const mockWritable = new WritableStream({
write: (chunk) => {
writtenChunks.push(chunk);
},
close: vi.fn(),
});
const { streamTextIterator } = await import('./stream-text-iterator.js');
const mockMessages: LanguageModelV3Prompt = [
{ role: 'user', content: [{ type: 'text', text: 'test' }] },
];
const mockIterator = {
next: vi.fn().mockResolvedValueOnce({
done: false,
value: {
toolCalls: [
{
toolCallId: 'server-call-id',
toolName: 'serverTool',
input: '{}',
providerExecuted: false,
} as LanguageModelV3ToolCall,
{
toolCallId: 'client-call-id',
toolName: 'clientTool',
input: '{"prompt":"confirm action"}',
providerExecuted: false,
} as LanguageModelV3ToolCall,
],
messages: mockMessages,
},
}),
};
vi.mocked(streamTextIterator).mockReturnValue(
mockIterator as unknown as MockIterator
);
const result = await agent.stream({
messages: [{ role: 'user', content: 'test' }],
writable: mockWritable,
});
// Server tool should have been executed
expect(localExecuteFn).toHaveBeenCalledTimes(1);
// The resolved server tool result should have been written to UI
const toolOutputChunks = writtenChunks.filter(
(c: any) => c.type === 'tool-output-available'
);
expect(toolOutputChunks).toHaveLength(1);
expect((toolOutputChunks[0] as any).toolCallId).toBe('server-call-id');
// Loop should have stopped
expect(mockIterator.next).toHaveBeenCalledTimes(1);
// toolCalls should contain ALL tool calls from the step
expect(result.toolCalls).toHaveLength(2);
expect(result.toolCalls[0]).toMatchObject({
type: 'tool-call',
toolCallId: 'server-call-id',
toolName: 'serverTool',
});
expect(result.toolCalls[1]).toMatchObject({
type: 'tool-call',
toolCallId: 'client-call-id',
toolName: 'clientTool',
input: { prompt: 'confirm action' },
});
// toolResults should only contain the server-executed tool
expect(result.toolResults).toHaveLength(1);
expect(result.toolResults[0]).toMatchObject({
type: 'tool-result',
toolCallId: 'server-call-id',
toolName: 'serverTool',
output: localToolResult,
});
// Consumer can find unresolved calls by diffing (standard AI SDK pattern)
const unresolvedCalls = result.toolCalls.filter(
(tc) =>
!result.toolResults.some((tr) => tr.toolCallId === tc.toolCallId)
);
expect(unresolvedCalls).toHaveLength(1);
expect(unresolvedCalls[0].toolName).toBe('clientTool');
// Messages should include the conversation (from iterMessages) and
// a tool role message with the resolved server tool result
expect(result.messages).toBe(mockMessages);
});
it('should call onFinish when stopping for client-side tools', async () => {
const onFinish = vi.fn();
const tools: ToolSet = {
askUser: {
description: 'Ask the user a question',
inputSchema: z.object({ question: z.string() }),
},
};
const mockModel = createMockModel();
const agent = new DurableAgent({
model: async () => mockModel,
tools,
});
const mockWritable = new WritableStream({
write: vi.fn(),
close: vi.fn(),
});
const { streamTextIterator } = await import('./stream-text-iterator.js');
const mockMessages: LanguageModelV3Prompt = [
{ role: 'user', content: [{ type: 'text', text: 'test' }] },
];
const mockIterator = {
next: vi.fn().mockResolvedValueOnce({
done: false,
value: {
toolCalls: [
{
toolCallId: 'ask-id',
toolName: 'askUser',
input: '{"question":"confirm?"}',
providerExecuted: false,
} as LanguageModelV3ToolCall,
],
messages: mockMessages,
},
}),
};
vi.mocked(streamTextIterator).mockReturnValue(