Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import {
3 SESSION_ID_EVENT,
4 toolNameForItem,
5 translateThreadEvents,
6} from '../src/stream/translate'
7import type { TranslateContext } from '../src/stream/translate'
8import type { CodexThreadEvent } from '../src/stream/sdk-types'
9import type { AdapterYieldChunk } from '@tanstack/ai'
10
11function makeCtx(overrides: Partial<TranslateContext> = {}): TranslateContext {
12 let id = 0
13 return {
14 model: 'gpt-5.1-codex',
15 runId: 'run-1',
16 threadId: 'thread-1',
17 genId: () => `gen-${++id}`,
18 ...overrides,
19 }
20}
21
22async function* fromArray(
23 events: Array<CodexThreadEvent>,
24): AsyncIterable<CodexThreadEvent> {
25 for (const event of events) yield event
26}
27
28async function collect(
29 events: Array<CodexThreadEvent>,
30 ctx: TranslateContext = makeCtx(),
31): Promise<Array<AdapterYieldChunk>> {
32 const chunks: Array<AdapterYieldChunk> = []
33 for await (const chunk of translateThreadEvents(fromArray(events), ctx)) {
34 chunks.push(chunk)
35 }
36 return chunks
37}
38
39function structuredComplete(chunks: Array<AdapterYieldChunk>) {
40 return chunks.find(
41 (c) => c.type === 'CUSTOM' && c.name === 'structured-output.complete',
42 )
43}
44
45function textDeltas(chunks: Array<AdapterYieldChunk>): string {
46 return chunks
47 .filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
48 .map((c) => ('delta' in c ? c.delta : ''))
49 .join('')
50}
51
52function expectStructuredObject(
53 chunks: Array<AdapterYieldChunk>,
54 object: Record<string, unknown>,
55) {
56 const complete = structuredComplete(chunks)
57 expect(complete).toBeDefined()
58 if (complete?.type === 'CUSTOM') {
59 expect(complete.value).toEqual(expect.objectContaining({ object }))
60 }
61}
62
63const started: CodexThreadEvent = {
64 type: 'thread.started',
65 thread_id: 'sess-1',
66}
67
68const completedTurn: CodexThreadEvent = {
69 type: 'turn.completed',
70 usage: {
71 input_tokens: 100,
72 cached_input_tokens: 40,
73 output_tokens: 20,
74 reasoning_output_tokens: 5,
75 },
76}
77
78describe('translateThreadEvents', () => {
79 it('translates a simple text turn', async () => {
80 const chunks = await collect([
81 started,
82 { type: 'turn.started' },
83 {
84 type: 'item.completed',
85 item: { id: 'item-1', type: 'agent_message', text: 'hi there' },
86 },
87 completedTurn,
88 ])
89
90 expect(chunks.map((c) => c.type)).toEqual([
91 'RUN_STARTED',
92 'CUSTOM',
93 'TEXT_MESSAGE_START',
94 'TEXT_MESSAGE_CONTENT',
95 'TEXT_MESSAGE_END',
96 'RUN_FINISHED',
97 ])
98 expect(chunks[1]).toMatchObject({
99 name: SESSION_ID_EVENT,
100 value: { sessionId: 'sess-1' },
101 })
102 expect(chunks[3]).toMatchObject({ delta: 'hi there', content: 'hi there' })
103 expect(chunks.at(-1)).toMatchObject({ finishReason: 'stop' })
104 })
105
106 it('reports usage with cache and reasoning details', async () => {
107 const chunks = await collect([started, completedTurn])
108 const finished = chunks.at(-1) as unknown as {
109 usage: Record<string, unknown>
110 }
111 expect(finished.usage).toMatchObject({
112 promptTokens: 100,
113 completionTokens: 20,
114 totalTokens: 120,
115 promptTokensDetails: { cachedTokens: 40 },
116 completionTokensDetails: { reasoningTokens: 5 },
117 })
118 })
119
120 it('notifies onSessionId and forwards raw events to onThreadEvent', async () => {
121 const sessionIds: Array<string> = []
122 const raw: Array<string> = []
123 await collect(
124 [started, completedTurn],
125 makeCtx({
126 onSessionId: (id) => sessionIds.push(id),
127 onThreadEvent: (event) => raw.push(event.type),
128 }),
129 )
130 expect(sessionIds).toEqual(['sess-1'])
131 expect(raw).toEqual(['thread.started', 'turn.completed'])
132 })
133
134 it('starts the run without a session event on resumed threads', async () => {
135 const chunks = await collect([
136 { type: 'turn.started' },
137 {
138 type: 'item.completed',
139 item: { id: 'item-1', type: 'agent_message', text: 'resumed' },
140 },
141 completedTurn,
142 ])
143 expect(chunks[0]).toMatchObject({ type: 'RUN_STARTED' })
144 expect(chunks.some((c) => c.type === 'CUSTOM')).toBe(false)
145 })
146
147 it('translates reasoning items into a reasoning burst', async () => {
148 const chunks = await collect([
149 started,
150 {
151 type: 'item.completed',
152 item: { id: 'item-r', type: 'reasoning', text: 'thinking...' },
153 },
154 completedTurn,
155 ])
156 expect(chunks.map((c) => c.type)).toEqual([
157 'RUN_STARTED',
158 'CUSTOM',
159 'REASONING_START',
160 'REASONING_MESSAGE_START',
161 'REASONING_MESSAGE_CONTENT',
162 'REASONING_MESSAGE_END',
163 'REASONING_END',
164 'RUN_FINISHED',
165 ])
166 })
167
168 it('pairs command executions across item.started and item.completed', async () => {
169 const chunks = await collect([
170 started,
171 {
172 type: 'item.started',
173 item: {
174 id: 'cmd-1',
175 type: 'command_execution',
176 command: 'ls -la',
177 status: 'in_progress',
178 },
179 },
180 {
181 type: 'item.completed',
182 item: {
183 id: 'cmd-1',
184 type: 'command_execution',
185 command: 'ls -la',
186 aggregated_output: 'file.txt',
187 exit_code: 0,
188 status: 'completed',
189 },
190 },
191 completedTurn,
192 ])
193
194 expect(chunks.map((c) => c.type)).toEqual([
195 'RUN_STARTED',
196 'CUSTOM',
197 'TOOL_CALL_START',
198 'TOOL_CALL_ARGS',
199 'TOOL_CALL_END',
200 'TOOL_CALL_RESULT',
201 'RUN_FINISHED',
202 ])
203 expect(chunks[2]).toMatchObject({
204 toolCallId: 'cmd-1',
205 toolCallName: 'command_execution',
206 })
207 expect(chunks[3]).toMatchObject({
208 args: JSON.stringify({ command: 'ls -la' }),
209 })
210 const result = chunks[5] as { content: string; state?: string }
211 expect(JSON.parse(result.content)).toMatchObject({
212 aggregated_output: 'file.txt',
213 exit_code: 0,
214 status: 'completed',
215 })
216 expect(result.state).toBeUndefined()
217 })
218
219 it('marks failed command executions as output-error', async () => {
220 const chunks = await collect([
221 started,
222 {
223 type: 'item.completed',
224 item: {
225 id: 'cmd-2',
226 type: 'command_execution',
227 command: 'false',
228 aggregated_output: '',
229 exit_code: 1,
230 status: 'failed',
231 },
232 },
233 completedTurn,
234 ])
235 const result = chunks.find((c) => c.type === 'TOOL_CALL_RESULT')
236 expect(result).toMatchObject({ state: 'output-error' })
237 })
238
239 it('emits a full tool pair when item.completed arrives without item.started', async () => {
240 const chunks = await collect([
241 started,
242 {
243 type: 'item.completed',
244 item: {
245 id: 'fc-1',
246 type: 'file_change',
247 changes: [{ path: 'a.ts', kind: 'update' }],
248 status: 'completed',
249 },
250 },
251 completedTurn,
252 ])
253 expect(chunks.map((c) => c.type)).toEqual([
254 'RUN_STARTED',
255 'CUSTOM',
256 'TOOL_CALL_START',
257 'TOOL_CALL_ARGS',
258 'TOOL_CALL_END',
259 'TOOL_CALL_RESULT',
260 'RUN_FINISHED',
261 ])
262 expect(chunks[2]).toMatchObject({ toolCallName: 'file_change' })
263 })
264
265 it('does not duplicate START events when both started and completed fire', async () => {
266 const chunks = await collect([
267 started,
268 {
269 type: 'item.started',
270 item: {
271 id: 'ws-1',
272 type: 'web_search',
273 query: 'tanstack ai',
274 },
275 },
276 {
277 type: 'item.completed',
278 item: { id: 'ws-1', type: 'web_search', query: 'tanstack ai' },
279 },
280 completedTurn,
281 ])
282 const startEvents = chunks.filter((c) => c.type === 'TOOL_CALL_START')
283 expect(startEvents).toHaveLength(1)
284 })
285
286 it('strips the tanstack server prefix from bridged MCP tool calls', async () => {
287 const chunks = await collect([
288 started,
289 {
290 type: 'item.completed',
291 item: {
292 id: 'mcp-1',
293 type: 'mcp_tool_call',
294 server: 'tanstack',
295 tool: 'lookup_user',
296 arguments: { userId: '7' },
297 result: { content: [{ type: 'text', text: '{"name":"Ada"}' }] },
298 status: 'completed',
299 },
300 },
301 completedTurn,
302 ])
303 expect(chunks.find((c) => c.type === 'TOOL_CALL_START')).toMatchObject({
304 toolCallName: 'lookup_user',
305 })
306 expect(chunks.find((c) => c.type === 'TOOL_CALL_RESULT')).toMatchObject({
307 content: '{"name":"Ada"}',
308 })
309 })
310
311 it('namespaces foreign MCP tool calls as mcp__server__tool', async () => {
312 expect(
313 toolNameForItem({
314 id: 'x',
315 type: 'mcp_tool_call',
316 server: 'github',
317 tool: 'create_issue',
318 status: 'completed',
319 }),
320 ).toBe('mcp__github__create_issue')
321 })
322
323 it('surfaces MCP tool errors as output-error results', async () => {
324 const chunks = await collect([
325 started,
326 {
327 type: 'item.completed',
328 item: {
329 id: 'mcp-2',
330 type: 'mcp_tool_call',
331 server: 'tanstack',
332 tool: 'boom',
333 error: { message: 'kaboom' },
334 status: 'failed',
335 },
336 },
337 completedTurn,
338 ])
339 expect(chunks.find((c) => c.type === 'TOOL_CALL_RESULT')).toMatchObject({
340 content: 'kaboom',
341 state: 'output-error',
342 })
343 })
344
345 it('ignores item.updated events', async () => {
346 const chunks = await collect([
347 started,
348 {
349 type: 'item.started',
350 item: {
351 id: 'todo-1',
352 type: 'todo_list',
353 items: [{ text: 'step 1', completed: false }],
354 },
355 },
356 {
357 type: 'item.updated',
358 item: {
359 id: 'todo-1',
360 type: 'todo_list',
361 items: [{ text: 'step 1', completed: true }],
362 },
363 },
364 {
365 type: 'item.completed',
366 item: {
367 id: 'todo-1',
368 type: 'todo_list',
369 items: [{ text: 'step 1', completed: true }],
370 },
371 },
372 completedTurn,
373 ])
374 expect(chunks.filter((c) => c.type === 'TOOL_CALL_ARGS')).toHaveLength(1)
375 expect(chunks.filter((c) => c.type === 'TOOL_CALL_RESULT')).toHaveLength(1)
376 })
377
378 it('synthesizes interrupted results for unresolved tool calls on turn.completed', async () => {
379 const chunks = await collect([
380 started,
381 {
382 type: 'item.started',
383 item: {
384 id: 'cmd-9',
385 type: 'command_execution',
386 command: 'sleep 100',
387 status: 'in_progress',
388 },
389 },
390 completedTurn,
391 ])
392 const result = chunks.find((c) => c.type === 'TOOL_CALL_RESULT')
393 expect(result).toMatchObject({
394 toolCallId: 'cmd-9',
395 content: JSON.stringify({ status: 'interrupted' }),
396 })
397 expect(chunks.at(-1)).toMatchObject({ type: 'RUN_FINISHED' })
398 })
399
400 it('maps turn.failed to RUN_ERROR after synthesizing results', async () => {
401 const chunks = await collect([
402 started,
403 {
404 type: 'item.started',
405 item: {
406 id: 'cmd-8',
407 type: 'command_execution',
408 command: 'x',
409 status: 'in_progress',
410 },
411 },
412 { type: 'turn.failed', error: { message: 'model exploded' } },
413 ])
414 const types: Array<string> = chunks.map((c) => c.type)
415 expect(types.indexOf('TOOL_CALL_RESULT')).toBeLessThan(
416 types.indexOf('RUN_ERROR'),
417 )
418 expect(chunks.at(-1)).toMatchObject({
419 type: 'RUN_ERROR',
420 message: 'model exploded',
421 })
422 })
423
424 it('maps stream error events to RUN_ERROR', async () => {
425 const chunks = await collect([
426 started,
427 { type: 'error', message: 'stream broke' },
428 ])
429 expect(chunks.at(-1)).toMatchObject({
430 type: 'RUN_ERROR',
431 message: 'stream broke',
432 })
433 })
434
435 it('synthesizes results then rethrows when the source stream throws', async () => {
436 async function* failing(): AsyncIterable<CodexThreadEvent> {
437 yield started
438 yield {
439 type: 'item.started',
440 item: {
441 id: 'cmd-7',
442 type: 'command_execution',
443 command: 'x',
444 status: 'in_progress',
445 },
446 }
447 throw new Error('aborted')
448 }
449
450 const chunks: Array<AdapterYieldChunk> = []
451 await expect(async () => {
452 for await (const chunk of translateThreadEvents(failing(), makeCtx())) {
453 chunks.push(chunk)
454 }
455 }).rejects.toThrow('aborted')
456 expect(chunks.at(-1)).toMatchObject({
457 type: 'TOOL_CALL_RESULT',
458 toolCallId: 'cmd-7',
459 content: JSON.stringify({ status: 'interrupted' }),
460 })
461 })
462
463 it('ignores non-fatal error items', async () => {
464 const chunks = await collect([
465 started,
466 {
467 type: 'item.completed',
468 item: { id: 'err-1', type: 'error', message: 'transient hiccup' },
469 },
470 completedTurn,
471 ])
472 expect(chunks.map((c) => c.type)).toEqual([
473 'RUN_STARTED',
474 'CUSTOM',
475 'RUN_FINISHED',
476 ])
477 })
478
479 it('emits structured-output events from the last agent_message when expected', async () => {
480 const chunks = await collect(
481 [
482 started,
483 {
484 type: 'item.completed',
485 item: { id: 'item-1', type: 'agent_message', text: '{"ok":true}' },
486 },
487 completedTurn,
488 ],
489 makeCtx({ expectStructuredOutput: true }),
490 )
491 expect(
492 chunks.some(
493 (c) => c.type === 'CUSTOM' && c.name === 'structured-output.start',
494 ),
495 ).toBe(true)
496 const complete = structuredComplete(chunks)
497 expect(complete).toBeDefined()
498 if (complete?.type === 'CUSTOM') {
499 expect(complete.value).toEqual(
500 expect.objectContaining({ object: { ok: true }, raw: '{"ok":true}' }),
501 )
502 }
503 expect(textDeltas(chunks)).toBe('{"ok":true}')
504 })
505
506 it('keeps earlier agent_message text when only the last item is structured', async () => {
507 const chunks = await collect(
508 [
509 started,
510 {
511 type: 'item.completed',
512 item: { id: 'item-1', type: 'agent_message', text: 'working' },
513 },
514 {
515 type: 'item.completed',
516 item: { id: 'item-2', type: 'agent_message', text: '{"ok":true}' },
517 },
518 completedTurn,
519 ],
520 makeCtx({ expectStructuredOutput: true }),
521 )
522 expect(textDeltas(chunks)).toContain('working')
523 expectStructuredObject(chunks, { ok: true })
524 })
525
526 it('emits RUN_ERROR when the last agent_message is not JSON', async () => {
527 const chunks = await collect(
528 [
529 started,
530 {
531 type: 'item.completed',
532 item: { id: 'item-1', type: 'agent_message', text: 'not json' },
533 },
534 completedTurn,
535 ],
536 makeCtx({ expectStructuredOutput: true }),
537 )
538 expect(chunks.find((c) => c.type === 'RUN_ERROR')).toMatchObject({
539 type: 'RUN_ERROR',
540 code: 'structured-output-parse-failed',
541 message: expect.stringMatching(/not json/),
542 })
543 })
544
545 it('parses fenced JSON from the last agent_message', async () => {
546 const chunks = await collect(
547 [
548 started,
549 {
550 type: 'item.completed',
551 item: {
552 id: 'item-1',
553 type: 'agent_message',
554 text: '```json\n{"ok":true}\n```',
555 },
556 },
557 completedTurn,
558 ],
559 makeCtx({ expectStructuredOutput: true }),
560 )
561 expectStructuredObject(chunks, { ok: true })
562 expect(chunks.some((c) => c.type === 'RUN_ERROR')).toBe(false)
563 })
564
565 it('emits earlier agent_message text before the last structured item arrives', async () => {
566 const chunks = await collect(
567 [
568 started,
569 {
570 type: 'item.completed',
571 item: { id: 'item-1', type: 'agent_message', text: 'working' },
572 },
573 {
574 type: 'item.started',
575 item: {
576 id: 'cmd-1',
577 type: 'command_execution',
578 command: 'ls',
579 status: 'in_progress',
580 },
581 },
582 {
583 type: 'item.completed',
584 item: {
585 id: 'cmd-1',
586 type: 'command_execution',
587 command: 'ls',
588 aggregated_output: 'ok',
589 status: 'completed',
590 },
591 },
592 {
593 type: 'item.completed',
594 item: { id: 'item-2', type: 'agent_message', text: '{"ok":true}' },
595 },
596 completedTurn,
597 ],
598 makeCtx({ expectStructuredOutput: true }),
599 )
600 const types = chunks.map((c) =>
601 c.type === 'CUSTOM' ? `CUSTOM:${c.name}` : c.type,
602 )
603 const workingIdx = chunks.findIndex(
604 (c) => c.type === 'TEXT_MESSAGE_CONTENT' && c.delta === 'working',
605 )
606 const toolStartIdx = types.indexOf('TOOL_CALL_START')
607 const completeIdx = types.indexOf('CUSTOM:structured-output.complete')
608 const finishedIdx = types.indexOf('RUN_FINISHED')
609 expect(workingIdx).toBeGreaterThan(-1)
610 expect(toolStartIdx).toBeGreaterThan(workingIdx)
611 expect(completeIdx).toBeGreaterThan(toolStartIdx)
612 expect(completeIdx).toBeLessThan(finishedIdx)
613 })
614
615 it('keeps a JSON agent_message as structured output when a started tool completes after it', async () => {
616 const chunks = await collect(
617 [
618 started,
619 {
620 type: 'item.started',
621 item: {
622 id: 'cmd-1',
623 type: 'command_execution',
624 command: 'ls',
625 status: 'in_progress',
626 },
627 },
628 {
629 type: 'item.completed',
630 item: { id: 'item-1', type: 'agent_message', text: '{"ok":true}' },
631 },
632 {
633 type: 'item.completed',
634 item: {
635 id: 'cmd-1',
636 type: 'command_execution',
637 command: 'ls',
638 aggregated_output: 'ok',
639 status: 'completed',
640 },
641 },
642 completedTurn,
643 ],
644 makeCtx({ expectStructuredOutput: true }),
645 )
646 expectStructuredObject(chunks, { ok: true })
647 const types = chunks.map((c) =>
648 c.type === 'CUSTOM' ? `CUSTOM:${c.name}` : c.type,
649 )
650 expect(types.indexOf('TOOL_CALL_START')).toBeLessThan(
651 types.indexOf('CUSTOM:structured-output.complete'),
652 )
653 expect(types.indexOf('TOOL_CALL_RESULT')).toBeLessThan(
654 types.indexOf('CUSTOM:structured-output.complete'),
655 )
656 })
657
658 it('keeps a JSON agent_message as structured output when tools follow it', async () => {
659 const chunks = await collect(
660 [
661 started,
662 {
663 type: 'item.completed',
664 item: { id: 'item-1', type: 'agent_message', text: '{"ok":true}' },
665 },
666 {
667 type: 'item.started',
668 item: {
669 id: 'cmd-1',
670 type: 'command_execution',
671 command: 'ls',
672 status: 'in_progress',
673 },
674 },
675 {
676 type: 'item.completed',
677 item: {
678 id: 'cmd-1',
679 type: 'command_execution',
680 command: 'ls',
681 aggregated_output: 'ok',
682 status: 'completed',
683 },
684 },
685 completedTurn,
686 ],
687 makeCtx({ expectStructuredOutput: true }),
688 )
689 expectStructuredObject(chunks, { ok: true })
690 })
691
692 it('streams agent_message text from item.updated deltas', async () => {
693 const chunks = await collect([
694 started,
695 {
696 type: 'item.started',
697 item: { id: 'item-1', type: 'agent_message', text: 'Hel' },
698 },
699 {
700 type: 'item.updated',
701 item: { id: 'item-1', type: 'agent_message', text: 'Hello' },
702 },
703 {
704 type: 'item.updated',
705 item: { id: 'item-1', type: 'agent_message', text: 'Hello world' },
706 },
707 {
708 type: 'item.completed',
709 item: { id: 'item-1', type: 'agent_message', text: 'Hello world' },
710 },
711 completedTurn,
712 ])
713 const deltas = chunks
714 .filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
715 .map((c) => ('delta' in c ? c.delta : ''))
716 expect(deltas).toEqual(['Hel', 'lo', ' world'])
717 })
718
719 it('does not drop the last agent_message when the stream ends without turn.completed', async () => {
720 const chunks = await collect(
721 [
722 started,
723 {
724 type: 'item.completed',
725 item: { id: 'item-1', type: 'agent_message', text: '{"ok":true}' },
726 },
727 ],
728 makeCtx({ expectStructuredOutput: true }),
729 )
730 expectStructuredObject(chunks, { ok: true })
731 })
732})