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

translate.test.ts

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