Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

translate.test.ts

971 lines25.8 KB

1import { describe, expect, it } from 'vitest'
2import { translateSdkStream } from '../src/stream/translate'
3import type {
4 AgentSdkMessage,
5 SdkRawStreamEvent,
6} from '../src/stream/sdk-types'
7import type { AdapterYieldChunk } from '@tanstack/ai'
8​
9function makeContext() {
10 let id = 0
11 return {
12 model: 'claude-opus-4-6',
13 runId: 'run-1',
14 threadId: 'thread-1',
15 genId: () => `gen-${++id}`,
16 }
18​
19async function* fromArray(
20 messages: Array<AgentSdkMessage>,
21): AsyncIterable<AgentSdkMessage> {
22 for (const message of messages) {
23 yield message
24 }
26​
27async function collect(
28 messages: Array<AgentSdkMessage>,
29 context: ReturnType<typeof makeContext> & {
30 expectStructuredOutput?: boolean
31 } = makeContext(),
32): Promise<Array<AdapterYieldChunk>> {
33 const chunks: Array<AdapterYieldChunk> = []
34 for await (const chunk of translateSdkStream(fromArray(messages), context)) {
35 chunks.push(chunk)
36 }
37 return chunks
39​
40const init: AgentSdkMessage = {
41 type: 'system',
42 subtype: 'init',
43 session_id: 'sess-abc',
44 model: 'claude-opus-4-6',
45 tools: ['Bash', 'Read'],
46 skills: ['repo-search'],
47 cwd: '/tmp',
49​
50const usage = {
51 input_tokens: 100,
52 output_tokens: 50,
53 cache_read_input_tokens: 10,
54 cache_creation_input_tokens: 5,
56​
57function assistantText(text: string, messageId = 'msg-1'): AgentSdkMessage {
58 return {
59 type: 'assistant',
60 message: { id: messageId, content: [{ type: 'text', text }] },
61 parent_tool_use_id: null,
62 }
64​
65function streamEvent(event: SdkRawStreamEvent): AgentSdkMessage {
66 return { type: 'stream_event', event, parent_tool_use_id: null }
68​
69function messageStart(messageId = 'msg-1'): AgentSdkMessage {
70 return streamEvent({ type: 'message_start', message: { id: messageId } })
72​
73function toolStart(index: number, id: string, name: string): AgentSdkMessage {
74 return streamEvent({
75 type: 'content_block_start',
76 index,
77 content_block: { type: 'tool_use', id, name },
78 })
80​
81function toolArgs(index: number, partialJson: string): AgentSdkMessage {
82 return streamEvent({
83 type: 'content_block_delta',
84 index,
85 delta: { type: 'input_json_delta', partial_json: partialJson },
86 })
88​
89function blockStop(index: number): AgentSdkMessage {
90 return streamEvent({ type: 'content_block_stop', index })
92​
93function assistantTool(
94 id: string,
95 name: string,
96 input: unknown,
97 messageId = 'msg-1',
98): AgentSdkMessage {
99 return {
100 type: 'assistant',
101 message: {
102 id: messageId,
103 content: [{ type: 'tool_use', id, name, input }],
104 },
105 parent_tool_use_id: null,
106 }
108​
109function toolResult(id: string, content = 'done'): AgentSdkMessage {
110 return {
111 type: 'user',
112 message: {
113 role: 'user',
114 content: [{ type: 'tool_result', tool_use_id: id, content }],
115 },
116 parent_tool_use_id: null,
117 }
119​
120const resultSuccess: AgentSdkMessage = {
121 type: 'result',
122 subtype: 'success',
123 result: 'done',
124 usage,
125 total_cost_usd: 0.12,
127​
128describe('translateSdkStream', () => {
129 it('translates a simple text turn into RUN_STARTED → CUSTOM → TEXT_* → RUN_FINISHED(stop)', async () => {
130 const chunks = await collect([init, assistantText('Hello!'), resultSuccess])
131​
132 expect(chunks.map((c) => c.type)).toEqual([
133 'RUN_STARTED',
134 'CUSTOM',
135 'TEXT_MESSAGE_START',
136 'TEXT_MESSAGE_CONTENT',
137 'TEXT_MESSAGE_END',
138 'RUN_FINISHED',
139 ])
140​
141 expect(chunks[0]).toMatchObject({
142 type: 'RUN_STARTED',
143 runId: 'run-1',
144 threadId: 'thread-1',
145 model: 'claude-opus-4-6',
146 })
147 expect(chunks[3]).toMatchObject({
148 type: 'TEXT_MESSAGE_CONTENT',
149 delta: 'Hello!',
150 content: 'Hello!',
151 })
152 expect(chunks[5]).toMatchObject({
153 type: 'RUN_FINISHED',
154 finishReason: 'stop',
155 })
156 })
157​
158 it('surfaces the session id via a CUSTOM claude-code.session-id event', async () => {
159 const chunks = await collect([init, assistantText('hi'), resultSuccess])
160 const custom = chunks.find((c) => c.type === 'CUSTOM')
161 expect(custom).toMatchObject({
162 type: 'CUSTOM',
163 name: 'claude-code.session-id',
164 value: {
165 sessionId: 'sess-abc',
166 model: 'claude-opus-4-6',
167 tools: ['Bash', 'Read'],
168 skills: ['repo-search'],
169 },
170 })
171 })
172​
173 it('uses an empty skill list when the SDK init message omits skills', async () => {
174 const { skills: _skills, ...initWithoutSkills } = init
175 const chunks = await collect([
176 initWithoutSkills,
177 assistantText('hi'),
178 resultSuccess,
179 ])
180 const custom = chunks.find((c) => c.type === 'CUSTOM')
181 expect(custom).toMatchObject({ value: { skills: [] } })
182 })
183​
184 it('maps usage onto RUN_FINISHED including cache token details', async () => {
185 const chunks = await collect([init, assistantText('hi'), resultSuccess])
186 const finished = chunks.find((c) => c.type === 'RUN_FINISHED')
187 expect(finished).toMatchObject({
188 usage: {
189 promptTokens: 100,
190 completionTokens: 50,
191 totalTokens: 150,
192 promptTokensDetails: { cachedTokens: 10, cacheWriteTokens: 5 },
193 },
194 })
195 })
196​
197 it('emits resolved TOOL_CALL_* quadruples for harness tool activity and never finishes with tool_calls', async () => {
198 const messages: Array<AgentSdkMessage> = [
199 init,
200 {
201 type: 'assistant',
202 message: {
203 id: 'msg-1',
204 content: [
205 {
206 type: 'tool_use',
207 id: 'toolu_1',
208 name: 'Bash',
209 input: { command: 'ls' },
210 },
211 ],
212 },
213 parent_tool_use_id: null,
214 },
215 {
216 type: 'user',
217 message: {
218 role: 'user',
219 content: [
220 {
221 type: 'tool_result',
222 tool_use_id: 'toolu_1',
223 content: 'file-a\nfile-b',
224 },
225 ],
226 },
227 parent_tool_use_id: null,
228 },
229 assistantText('Found two files.', 'msg-2'),
230 resultSuccess,
231 ]
232​
233 const chunks = await collect(messages)
234 const types = chunks.map((c) => c.type)
235 expect(types).toEqual([
236 'RUN_STARTED',
237 'CUSTOM',
238 'TOOL_CALL_START',
239 'TOOL_CALL_ARGS',
240 'TOOL_CALL_END',
241 'TOOL_CALL_RESULT',
242 'TEXT_MESSAGE_START',
243 'TEXT_MESSAGE_CONTENT',
244 'TEXT_MESSAGE_END',
245 'RUN_FINISHED',
246 ])
247​
248 expect(chunks[2]).toMatchObject({
249 toolCallId: 'toolu_1',
250 toolCallName: 'Bash',
251 })
252 expect(chunks[3]).toMatchObject({
253 toolCallId: 'toolu_1',
254 delta: JSON.stringify({ command: 'ls' }),
255 })
256 expect(chunks[4]).toMatchObject({
257 toolCallId: 'toolu_1',
258 input: { command: 'ls' },
259 })
260 expect(chunks[5]).toMatchObject({
261 type: 'TOOL_CALL_RESULT',
262 toolCallId: 'toolu_1',
263 content: 'file-a\nfile-b',
264 })
265​
266 const finished = chunks.filter((c) => c.type === 'RUN_FINISHED')
267 expect(finished).toHaveLength(1)
268 expect(finished[0]).toMatchObject({ finishReason: 'stop' })
269 })
270​
271 it('strips the mcp__tanstack__ prefix from bridged tool names', async () => {
272 const chunks = await collect([
273 init,
274 {
275 type: 'assistant',
276 message: {
277 id: 'msg-1',
278 content: [
279 {
280 type: 'tool_use',
281 id: 'toolu_2',
282 name: 'mcp__tanstack__lookup_user',
283 input: { userId: 'u1' },
284 },
285 ],
286 },
287 parent_tool_use_id: null,
288 },
289 resultSuccess,
290 ])
291​
292 const start = chunks.find((c) => c.type === 'TOOL_CALL_START')
293 expect(start).toMatchObject({ toolCallName: 'lookup_user' })
294 })
295​
296 it('marks errored tool results with state output-error', async () => {
297 const chunks = await collect([
298 init,
299 {
300 type: 'assistant',
301 message: {
302 id: 'msg-1',
303 content: [
304 { type: 'tool_use', id: 'toolu_3', name: 'Bash', input: {} },
305 ],
306 },
307 parent_tool_use_id: null,
308 },
309 {
310 type: 'user',
311 message: {
312 role: 'user',
313 content: [
314 {
315 type: 'tool_result',
316 tool_use_id: 'toolu_3',
317 content: [{ type: 'text', text: 'command failed' }],
318 is_error: true,
319 },
320 ],
321 },
322 parent_tool_use_id: null,
323 },
324 resultSuccess,
325 ])
326​
327 const result = chunks.find((c) => c.type === 'TOOL_CALL_RESULT')
328 expect(result).toMatchObject({
329 toolCallId: 'toolu_3',
330 content: 'command failed',
331 state: 'output-error',
332 })
333 })
334​
335 it('synthesizes interrupted tool results for unresolved tool calls before RUN_FINISHED', async () => {
336 const chunks = await collect([
337 init,
338 {
339 type: 'assistant',
340 message: {
341 id: 'msg-1',
342 content: [
343 { type: 'tool_use', id: 'toolu_4', name: 'Bash', input: {} },
344 ],
345 },
346 parent_tool_use_id: null,
347 },
348 resultSuccess,
349 ])
350​
351 const types = chunks.map((c) => c.type as string)
352 expect(types.indexOf('TOOL_CALL_RESULT')).toBeGreaterThan(-1)
353 expect(types.indexOf('TOOL_CALL_RESULT')).toBeLessThan(
354 types.indexOf('RUN_FINISHED'),
355 )
356 expect(chunks.find((c) => c.type === 'TOOL_CALL_RESULT')).toMatchObject({
357 toolCallId: 'toolu_4',
358 content: JSON.stringify({ status: 'interrupted' }),
359 })
360 })
361​
362 it('translates thinking blocks into REASONING_* events', async () => {
363 const chunks = await collect([
364 init,
365 {
366 type: 'assistant',
367 message: {
368 id: 'msg-1',
369 content: [
370 { type: 'thinking', thinking: 'pondering...' },
371 { type: 'text', text: 'answer' },
372 ],
373 },
374 parent_tool_use_id: null,
375 },
376 resultSuccess,
377 ])
378​
379 expect(chunks.map((c) => c.type)).toEqual([
380 'RUN_STARTED',
381 'CUSTOM',
382 'REASONING_START',
383 'REASONING_MESSAGE_START',
384 'REASONING_MESSAGE_CONTENT',
385 'REASONING_MESSAGE_END',
386 'REASONING_END',
387 'TEXT_MESSAGE_START',
388 'TEXT_MESSAGE_CONTENT',
389 'TEXT_MESSAGE_END',
390 'RUN_FINISHED',
391 ])
392 expect(
393 chunks.find((c) => c.type === 'REASONING_MESSAGE_CONTENT'),
394 ).toMatchObject({ delta: 'pondering...' })
395 })
396​
397 it('maps error_max_turns to RUN_FINISHED(length)', async () => {
398 const chunks = await collect([
399 init,
400 assistantText('partial'),
401 {
402 type: 'result',
403 subtype: 'error_max_turns',
404 usage,
405 total_cost_usd: 0.5,
406 errors: [],
407 },
408 ])
409 expect(chunks.at(-1)).toMatchObject({
410 type: 'RUN_FINISHED',
411 finishReason: 'length',
412 })
413 })
414​
415 it('maps error_during_execution to RUN_ERROR', async () => {
416 const chunks = await collect([
417 init,
418 {
419 type: 'result',
420 subtype: 'error_during_execution',
421 usage,
422 total_cost_usd: 0,
423 errors: ['boom'],
424 },
425 ])
426 expect(chunks.at(-1)).toMatchObject({
427 type: 'RUN_ERROR',
428 message: 'boom',
429 code: 'error_during_execution',
430 })
431 })
432​
433 it('skips subagent messages (parent_tool_use_id set)', async () => {
434 const chunks = await collect([
435 init,
436 {
437 type: 'assistant',
438 message: { id: 'msg-sub', content: [{ type: 'text', text: 'inner' }] },
439 parent_tool_use_id: 'toolu_task',
440 },
441 assistantText('outer'),
442 resultSuccess,
443 ])
444​
445 const contents = chunks.filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
446 expect(contents).toHaveLength(1)
447 expect(contents[0]).toMatchObject({ delta: 'outer' })
448 })
449​
450 it('streams partial text deltas and dedupes the whole assistant message', async () => {
451 const chunks = await collect([
452 init,
453 {
454 type: 'stream_event',
455 event: { type: 'message_start', message: { id: 'msg-1' } },
456 parent_tool_use_id: null,
457 },
458 {
459 type: 'stream_event',
460 event: {
461 type: 'content_block_start',
462 index: 0,
463 content_block: { type: 'text' },
464 },
465 parent_tool_use_id: null,
466 },
467 {
468 type: 'stream_event',
469 event: {
470 type: 'content_block_delta',
471 index: 0,
472 delta: { type: 'text_delta', text: 'Hel' },
473 },
474 parent_tool_use_id: null,
475 },
476 {
477 type: 'stream_event',
478 event: {
479 type: 'content_block_delta',
480 index: 0,
481 delta: { type: 'text_delta', text: 'lo' },
482 },
483 parent_tool_use_id: null,
484 },
485 {
486 type: 'stream_event',
487 event: { type: 'content_block_stop', index: 0 },
488 parent_tool_use_id: null,
489 },
490 assistantText('Hello', 'msg-1'),
491 resultSuccess,
492 ])
493​
494 expect(chunks.map((c) => c.type)).toEqual([
495 'RUN_STARTED',
496 'CUSTOM',
497 'TEXT_MESSAGE_START',
498 'TEXT_MESSAGE_CONTENT',
499 'TEXT_MESSAGE_CONTENT',
500 'TEXT_MESSAGE_END',
501 'RUN_FINISHED',
502 ])
503 expect(chunks[3]).toMatchObject({ delta: 'Hel', content: 'Hel' })
504 expect(chunks[4]).toMatchObject({ delta: 'lo', content: 'Hello' })
505 })
506​
507 it('streams partial tool-call args and dedupes the complete assistant message', async () => {
508 const chunks = await collect([
509 init,
510 messageStart(),
511 toolStart(0, 'toolu_1', 'Read'),
512 toolArgs(0, '{"file":'),
513 toolArgs(0, '"a.ts"}'),
514 blockStop(0),
515 assistantTool('toolu_1', 'Read', { file: 'a.ts' }),
516 toolResult('toolu_1', 'file contents'),
517 resultSuccess,
518 ])
519​
520 expect(chunks.map((c) => c.type)).toEqual([
521 'RUN_STARTED',
522 'CUSTOM',
523 'TOOL_CALL_START',
524 'TOOL_CALL_ARGS',
525 'TOOL_CALL_ARGS',
526 'TOOL_CALL_END',
527 'TOOL_CALL_RESULT',
528 'RUN_FINISHED',
529 ])
530 expect(chunks[3]).toMatchObject({ delta: '{"file":' })
531 expect(chunks[4]).toMatchObject({ delta: '"a.ts"}' })
532 expect(chunks[3]).not.toHaveProperty('args')
533 expect(chunks[5]).toMatchObject({
534 type: 'TOOL_CALL_END',
535 toolCallId: 'toolu_1',
536 toolCallName: 'Read',
537 input: { file: 'a.ts' },
538 })
539 })
540​
541 it('fails instead of completing malformed streamed tool input as an empty object', async () => {
542 await expect(
543 collect([
544 init,
545 messageStart(),
546 toolStart(0, 'toolu_1', 'Read'),
547 toolArgs(0, '{"file":'),
548 blockStop(0),
549 ]),
550 ).rejects.toThrow()
551 })
552​
553 it('correlates interleaved tool-call deltas by block index', async () => {
554 const chunks = await collect([
555 init,
556 messageStart(),
557 toolStart(0, 'toolu_a', 'Read'),
558 toolStart(1, 'toolu_b', 'Bash'),
559 toolArgs(1, '{"cmd":'),
560 toolArgs(0, '{"file":'),
561 toolArgs(1, '"ls"}'),
562 toolArgs(0, '"a.ts"}'),
563 blockStop(1),
564 blockStop(0),
565 resultSuccess,
566 ])
567​
568 expect(
569 chunks
570 .filter((chunk) => chunk.type === 'TOOL_CALL_ARGS')
571 .map((chunk) => [chunk.toolCallId, chunk.delta]),
572 ).toEqual([
573 ['toolu_b', '{"cmd":'],
574 ['toolu_a', '{"file":'],
575 ['toolu_b', '"ls"}'],
576 ['toolu_a', '"a.ts"}'],
577 ])
578 expect(
579 chunks
580 .filter((chunk) => chunk.type === 'TOOL_CALL_END')
581 .map((chunk) => [chunk.toolCallId, chunk.input]),
582 ).toEqual([
583 ['toolu_b', { cmd: 'ls' }],
584 ['toolu_a', { file: 'a.ts' }],
585 ])
586 })
587​
588 it('ignores unsupported partial content blocks', async () => {
589 const chunks = await collect([
590 init,
591 messageStart(),
592 streamEvent({
593 type: 'content_block_start',
594 index: 0,
595 content_block: { type: 'redacted_thinking' },
596 }),
597 streamEvent({
598 type: 'content_block_delta',
599 index: 0,
600 delta: { type: 'signature_delta' },
601 }),
602 blockStop(0),
603 resultSuccess,
604 ])
605​
606 expect(chunks.some((chunk) => chunk.type.startsWith('TOOL_CALL_'))).toBe(
607 false,
608 )
609 })
610​
611 it('emits synthetic tool results then rethrows when the SDK stream throws mid-run', async () => {
612 async function* throwing(): AsyncIterable<AgentSdkMessage> {
613 yield init
614 yield {
615 type: 'assistant',
616 message: {
617 id: 'msg-1',
618 content: [
619 { type: 'tool_use', id: 'toolu_5', name: 'Bash', input: {} },
620 ],
621 },
622 parent_tool_use_id: null,
623 }
624 throw new Error('aborted')
625 }
626​
627 const chunks: Array<AdapterYieldChunk> = []
628 await expect(async () => {
629 for await (const chunk of translateSdkStream(throwing(), makeContext())) {
630 chunks.push(chunk)
631 }
632 }).rejects.toThrow('aborted')
633​
634 expect(chunks.find((c) => c.type === 'TOOL_CALL_RESULT')).toMatchObject({
635 toolCallId: 'toolu_5',
636 content: JSON.stringify({ status: 'interrupted' }),
637 })
638 })
639​
640 it('ignores unknown SDK message types', async () => {
641 const chunks = await collect([
642 init,
643 {
644 type: 'system',
645 subtype: 'status',
646 status: 'compacting',
647 } as unknown as AgentSdkMessage,
648 assistantText('hi'),
649 resultSuccess,
650 ])
651 expect(chunks.map((c) => c.type)).toEqual([
652 'RUN_STARTED',
653 'CUSTOM',
654 'TEXT_MESSAGE_START',
655 'TEXT_MESSAGE_CONTENT',
656 'TEXT_MESSAGE_END',
657 'RUN_FINISHED',
658 ])
659 })
660​
661 it('synthesizes an interrupted result when the stream throws mid partial tool-args', async () => {
662 async function* throwing(): AsyncIterable<AgentSdkMessage> {
663 yield init
664 yield messageStart()
665 yield toolStart(0, 'toolu_9', 'Read')
666 yield toolArgs(0, '{"file":')
667 throw new Error('aborted')
668 }
669​
670 const chunks: Array<AdapterYieldChunk> = []
671 await expect(async () => {
672 for await (const chunk of translateSdkStream(throwing(), makeContext())) {
673 chunks.push(chunk)
674 }
675 }).rejects.toThrow('aborted')
676​
677 expect(chunks.find((c) => c.type === 'TOOL_CALL_END')).toMatchObject({
678 toolCallId: 'toolu_9',
679 })
680 expect(chunks.find((c) => c.type === 'TOOL_CALL_RESULT')).toMatchObject({
681 toolCallId: 'toolu_9',
682 content: JSON.stringify({ status: 'interrupted' }),
683 })
684 })
685​
686 it('tags a streamed tool call with its parent message id', async () => {
687 const chunks = await collect([
688 init,
689 messageStart(),
690 toolStart(0, 'toolu_7', 'Read'),
691 toolArgs(0, '{"file":"a.ts"}'),
692 blockStop(0),
693 resultSuccess,
694 ])
695​
696 expect(chunks.find((c) => c.type === 'TOOL_CALL_START')).toMatchObject({
697 parentMessageId: 'msg-1',
698 })
699 })
700​
701 it('streams a zero-argument tool call as START → END with no args frame', async () => {
702 const chunks = await collect([
703 init,
704 messageStart(),
705 toolStart(0, 'toolu_z', 'Now'),
706 blockStop(0),
707 resultSuccess,
708 ])
709​
710 const toolTypes = chunks
711 .map((c) => c.type)
712 .filter((t) => t.startsWith('TOOL_CALL_'))
713 expect(toolTypes).toEqual([
714 'TOOL_CALL_START',
715 'TOOL_CALL_END',
716 'TOOL_CALL_RESULT',
717 ])
718 expect(chunks.find((c) => c.type === 'TOOL_CALL_END')).toMatchObject({
719 toolCallId: 'toolu_z',
720 input: {},
721 })
722 })
723​
724 it('emits structured-output events from result.structured_output when expected', async () => {
725 const resultWithObject: AgentSdkMessage = {
726 type: 'result',
727 subtype: 'success',
728 result: 'done',
729 usage,
730 structured_output: { summary: 'ok' },
731 }
732 const chunks = await collect(
733 [init, assistantText('Looking around.'), resultWithObject],
734 { ...makeContext(), expectStructuredOutput: true },
735 )
736 const start = chunks.find(
737 (c) => c.type === 'CUSTOM' && c.name === 'structured-output.start',
738 )
739 const complete = chunks.find(
740 (c) => c.type === 'CUSTOM' && c.name === 'structured-output.complete',
741 )
742 expect(start).toBeDefined()
743 expect(complete).toBeDefined()
744 if (complete?.type === 'CUSTOM') {
745 expect(complete.value).toEqual(
746 expect.objectContaining({
747 object: { summary: 'ok' },
748 raw: JSON.stringify({ summary: 'ok' }),
749 }),
750 )
751 }
752 expect(chunks.some((c) => c.type === 'TEXT_MESSAGE_CONTENT')).toBe(true)
753 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
754 })
755​
756 it('harvests StructuredOutput tool input when result.structured_output is missing', async () => {
757 const report = {
758 name: 'TanStack AI',
759 oneLiner: 'Type-safe AI SDK',
760 }
761 const chunks = await collect(
762 [
763 init,
764 assistantText('I have enough to compile the report.'),
765 {
766 type: 'assistant',
767 message: {
768 id: 'msg-so',
769 content: [
770 {
771 type: 'tool_use',
772 id: 'toolu_so',
773 name: 'StructuredOutput',
774 input: report,
775 },
776 ],
777 },
778 parent_tool_use_id: null,
779 },
780 {
781 type: 'user',
782 message: {
783 role: 'user',
784 content: [
785 {
786 type: 'tool_result',
787 tool_use_id: 'toolu_so',
788 content: 'ok',
789 },
790 ],
791 },
792 parent_tool_use_id: null,
793 },
794 resultSuccess,
795 ],
796 { ...makeContext(), expectStructuredOutput: true },
797 )
798​
799 const complete = chunks.find(
800 (c) => c.type === 'CUSTOM' && c.name === 'structured-output.complete',
801 )
802 expect(complete).toBeDefined()
803 if (complete?.type === 'CUSTOM') {
804 expect(complete.value).toEqual(
805 expect.objectContaining({
806 object: report,
807 raw: JSON.stringify(report),
808 }),
809 )
810 }
811 expect(
812 chunks.some(
813 (c) =>
814 c.type === 'TOOL_CALL_START' &&
815 'toolCallName' in c &&
816 c.toolCallName === 'StructuredOutput',
817 ),
818 ).toBe(false)
819 expect(chunks.some((c) => c.type === 'TOOL_CALL_RESULT')).toBe(false)
820 })
821​
822 it('does not let an empty StructuredOutput tool wipe a captured object', async () => {
823 const report = { name: 'TanStack AI', oneLiner: 'SDK' }
824 const chunks = await collect(
825 [
826 init,
827 {
828 type: 'assistant',
829 message: {
830 id: 'msg-so-1',
831 content: [
832 {
833 type: 'tool_use',
834 id: 'toolu_so_full',
835 name: 'StructuredOutput',
836 input: report,
837 },
838 ],
839 },
840 parent_tool_use_id: null,
841 },
842 {
843 type: 'assistant',
844 message: {
845 id: 'msg-so-2',
846 content: [
847 {
848 type: 'tool_use',
849 id: 'toolu_so_empty',
850 name: 'StructuredOutput',
851 input: {},
852 },
853 ],
854 },
855 parent_tool_use_id: null,
856 },
857 resultSuccess,
858 ],
859 { ...makeContext(), expectStructuredOutput: true },
860 )
861 const complete = chunks.find(
862 (c) => c.type === 'CUSTOM' && c.name === 'structured-output.complete',
863 )
864 expect(complete?.type === 'CUSTOM' && complete.value).toEqual(
865 expect.objectContaining({ object: report }),
866 )
867 })
868​
869 it('harvests StructuredOutput from streamed input_json_delta', async () => {
870 const report = { name: 'TanStack AI', oneLiner: 'SDK' }
871 const chunks = await collect(
872 [
873 init,
874 {
875 type: 'stream_event',
876 event: { type: 'message_start', message: { id: 'msg-p' } },
877 parent_tool_use_id: null,
878 },
879 {
880 type: 'stream_event',
881 event: {
882 type: 'content_block_start',
883 index: 0,
884 content_block: {
885 type: 'tool_use',
886 id: 'toolu_stream',
887 name: 'StructuredOutput',
888 input: {},
889 },
890 },
891 parent_tool_use_id: null,
892 },
893 {
894 type: 'stream_event',
895 event: {
896 type: 'content_block_delta',
897 index: 0,
898 delta: {
899 type: 'input_json_delta',
900 partial_json: JSON.stringify(report),
901 },
902 },
903 parent_tool_use_id: null,
904 },
905 {
906 type: 'stream_event',
907 event: { type: 'content_block_stop', index: 0 },
908 parent_tool_use_id: null,
909 },
910 resultSuccess,
911 ],
912 { ...makeContext(), expectStructuredOutput: true },
913 )
914 const complete = chunks.find(
915 (c) => c.type === 'CUSTOM' && c.name === 'structured-output.complete',
916 )
917 expect(complete?.type === 'CUSTOM' && complete.value).toEqual(
918 expect.objectContaining({ object: report }),
919 )
920 expect(chunks.some((c) => c.type.startsWith('TOOL_CALL_'))).toBe(false)
921 })
922​
923 it('parses JSON from assistant text when the StructuredOutput tool is missing', async () => {
924 const report = { name: 'TanStack AI', oneLiner: 'SDK' }
925 const chunks = await collect(
926 [init, assistantText(JSON.stringify(report)), resultSuccess],
927 { ...makeContext(), expectStructuredOutput: true },
928 )
929 const complete = chunks.find(
930 (c) => c.type === 'CUSTOM' && c.name === 'structured-output.complete',
931 )
932 expect(complete?.type === 'CUSTOM' && complete.value).toEqual(
933 expect.objectContaining({ object: report }),
934 )
935 })
936​
937 it('does not emit structured-output events when the flag is off', async () => {
938 const resultWithObject: AgentSdkMessage = {
939 type: 'result',
940 subtype: 'success',
941 result: 'done',
942 usage,
943 structured_output: { summary: 'ok' },
944 }
945 const chunks = await collect([
946 init,
947 assistantText('Looking around.'),
948 resultWithObject,
949 ])
950 expect(
951 chunks.some(
952 (c) => c.type === 'CUSTOM' && c.name === 'structured-output.complete',
953 ),
954 ).toBe(false)
955 })
956​
957 it('maps error_max_structured_output_retries to RUN_ERROR', async () => {
958 const failed: AgentSdkMessage = {
959 type: 'result',
960 subtype: 'error_max_structured_output_retries',
961 errors: ['schema retries exhausted'],
962 usage,
963 }
964 const chunks = await collect([init, failed])
965 const err = chunks.find((c) => c.type === 'RUN_ERROR')
966 expect(err).toBeDefined()
967 if (err?.type === 'RUN_ERROR') {
968 expect(err.message).toContain('schema retries exhausted')
969 }
970 })
971})