Open History to see the last commit
1import {
2 afterEach,
3 beforeEach,
4 describe,
5 expect,
6 it,
7 vi,
8 type Mock,
9} from 'vitest'
10import { EventType, StreamProcessor, chat } from '@tanstack/ai'
11import { resolveDebugOption } from '@tanstack/ai/adapter-internals'
12import {
13 createBytePlusText as _realCreateBytePlusText,
14 byteplusText as _realBytePlusText,
15} from '../src/adapters/text'
16import {
17 BYTEPLUS_CHAT_MODELS,
18 BYTEPLUS_STRUCTURED_OUTPUT_CHAT_MODELS,
19 BYTEPLUS_THINKING_SUMMARY_MODELS,
20} from '../src/model-meta'
21import type {
22 AdapterYieldChunk,
23 ContentPart,
24 ModelMessage,
25 Tool,
26} from '@tanstack/ai'
27import type { BytePlusTextProviderOptions } from '../src/index'
28
29// Silent logger for adapter calls under test.
30const testLogger = resolveDebugOption(false)
31
32// Stub the OpenAI SDK so constructing an adapter never opens a real network
33// handle. The per-test mock client is injected post-construction through the
34// wrapped factories below (the ai-groq / ai-grok pattern) rather than by
35// stubbing globals — the built openai-base dist resolves `openai`
36// independently, so vi.mock alone would not intercept it.
37vi.mock('openai', () => {
38 return {
39 default: class {
40 chat = {
41 completions: {
42 create: vi.fn(),
43 },
44 }
45 },
46 }
47})
48
49function createAsyncIterable<T>(chunks: Array<T>): AsyncIterable<T> {
50 return {
51 [Symbol.asyncIterator]() {
52 let index = 0
53 return {
54 async next() {
55 if (index < chunks.length) {
56 return { value: chunks[index++]!, done: false }
57 }
58 return { value: undefined as T, done: true }
59 },
60 }
61 },
62 }
63}
64
65let pendingMockCreate: Mock<(...args: Array<unknown>) => unknown> | undefined
66
67function setupMockSdkClient(
68 streamChunks: Array<Record<string, unknown>>,
69 nonStreamResponse?: Record<string, unknown>,
70): Mock<(...args: Array<unknown>) => unknown> {
71 pendingMockCreate = vi.fn().mockImplementation((params) => {
72 if (params.stream) {
73 return Promise.resolve(createAsyncIterable(streamChunks))
74 }
75 return Promise.resolve(nonStreamResponse)
76 })
77 return pendingMockCreate
78}
79
80function applyPendingMock<T extends object>(adapter: T): T {
81 if (pendingMockCreate) {
82 ;(adapter as any).client = {
83 chat: { completions: { create: pendingMockCreate } },
84 }
85 pendingMockCreate = undefined
86 }
87 return adapter
88}
89
90const createBytePlusText: typeof _realCreateBytePlusText = (
91 model,
92 apiKey,
93 config,
94) => applyPendingMock(_realCreateBytePlusText(model, apiKey, config))
95const byteplusText: typeof _realBytePlusText = (model, config) =>
96 applyPendingMock(_realBytePlusText(model, config))
97
98// Models are picked off the exported metadata rather than hard-coded so these
99// tests keep testing the *behaviour* (gating, echoing) if the underlying
100// capability lists are corrected.
101const THINKING_SUMMARY_MODEL = BYTEPLUS_THINKING_SUMMARY_MODELS[0]
102const PLAIN_MODEL = BYTEPLUS_CHAT_MODELS.find(
103 (model) =>
104 !(BYTEPLUS_THINKING_SUMMARY_MODELS as ReadonlyArray<string>).includes(
105 model,
106 ),
107)!
108const STRUCTURED_MODEL = BYTEPLUS_STRUCTURED_OUTPUT_CHAT_MODELS[0]
109const UNSTRUCTURED_MODEL = BYTEPLUS_CHAT_MODELS.find(
110 (model) =>
111 !(BYTEPLUS_STRUCTURED_OUTPUT_CHAT_MODELS as ReadonlyArray<string>).includes(
112 model,
113 ),
114)!
115
116const ENCRYPTED_BLOB = 'ENC-eyJhbGciOiJzaWduZWQifQ.reasoning-signature'
117
118const weatherTool: Tool = {
119 name: 'lookup_weather',
120 description: 'Return the forecast for a location',
121}
122
123/** A minimal plain-text completion: one content delta, then a finish chunk. */
124function textStreamChunks(model: string): Array<Record<string, unknown>> {
125 return [
126 {
127 id: 'chatcmpl-text',
128 model,
129 choices: [{ index: 0, delta: { content: 'Hello!' } }],
130 },
131 {
132 id: 'chatcmpl-text',
133 model,
134 choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
135 usage: { prompt_tokens: 12, completion_tokens: 7, total_tokens: 19 },
136 },
137 ]
138}
139
140/**
141 * The chunk sequence a thinking-summary model produces, as captured live:
142 * reasoning deltas → one dedicated encrypted_content chunk → content deltas →
143 * a finish chunk → a usage-only chunk with empty `choices`.
144 */
145function thinkingStreamChunks(model: string): Array<Record<string, unknown>> {
146 return [
147 {
148 id: 'chatcmpl-think',
149 model,
150 choices: [{ index: 0, delta: { reasoning_content: 'The user ' } }],
151 },
152 {
153 id: 'chatcmpl-think',
154 model,
155 choices: [
156 { index: 0, delta: { reasoning_content: 'wants a greeting.' } },
157 ],
158 },
159 {
160 id: 'chatcmpl-think',
161 model,
162 choices: [
163 {
164 index: 0,
165 delta: {
166 content: '',
167 reasoning_content: '',
168 encrypted_content: ENCRYPTED_BLOB,
169 },
170 },
171 ],
172 },
173 {
174 id: 'chatcmpl-think',
175 model,
176 choices: [{ index: 0, delta: { content: 'Hello' } }],
177 },
178 {
179 id: 'chatcmpl-think',
180 model,
181 choices: [{ index: 0, delta: { content: '!' }, finish_reason: 'stop' }],
182 },
183 {
184 id: 'chatcmpl-think',
185 model,
186 choices: [],
187 usage: {
188 prompt_tokens: 12,
189 completion_tokens: 7,
190 total_tokens: 19,
191 completion_tokens_details: { reasoning_tokens: 4 },
192 },
193 },
194 ]
195}
196
197async function collect(
198 stream: AsyncIterable<AdapterYieldChunk>,
199): Promise<Array<AdapterYieldChunk>> {
200 const chunks: Array<AdapterYieldChunk> = []
201 for await (const chunk of stream) chunks.push(chunk)
202 return chunks
203}
204
205describe('BytePlus text adapter', () => {
206 beforeEach(() => {
207 pendingMockCreate = undefined
208 })
209
210 afterEach(() => {
211 vi.unstubAllEnvs()
212 })
213
214 describe('construction', () => {
215 it('creates an adapter with an explicit API key', () => {
216 const adapter = createBytePlusText('seed-2-0-lite-260428', 'ark-test-key')
217
218 expect(adapter.kind).toBe('text')
219 expect(adapter.name).toBe('byteplus')
220 expect(adapter.model).toBe('seed-2-0-lite-260428')
221 })
222
223 it('creates an adapter from ARK_API_KEY', () => {
224 vi.stubEnv('ARK_API_KEY', 'env-ark-key')
225
226 const adapter = byteplusText('seed-1-6-250915')
227
228 expect(adapter.model).toBe('seed-1-6-250915')
229 })
230
231 it('throws when ARK_API_KEY is missing', () => {
232 vi.stubEnv('ARK_API_KEY', '')
233
234 expect(() => byteplusText('seed-2-0-lite-260428')).toThrow('ARK_API_KEY')
235 })
236
237 it('accepts a baseURL override (EU endpoint)', () => {
238 const adapter = createBytePlusText(
239 'seed-2-0-lite-260428',
240 'ark-test-key',
241 { baseURL: 'https://ark.eu-west.bytepluses.com/api/v3' },
242 )
243
244 expect(adapter).toBeDefined()
245 })
246 })
247
248 describe('streaming', () => {
249 it('emits reasoning, then text, then usage for a thinking stream', async () => {
250 setupMockSdkClient(thinkingStreamChunks(THINKING_SUMMARY_MODEL))
251 const adapter = createBytePlusText(THINKING_SUMMARY_MODEL, 'ark-test-key')
252
253 const chunks = await collect(
254 adapter.chatStream({
255 model: THINKING_SUMMARY_MODEL,
256 messages: [{ role: 'user', content: 'Say hi' }],
257 logger: testLogger,
258 }),
259 )
260
261 const types = chunks.map((c) => c.type)
262 expect(types[0]).toBe(EventType.RUN_STARTED)
263 expect(types).toContain(EventType.REASONING_MESSAGE_START)
264 expect(types).toContain(EventType.TEXT_MESSAGE_START)
265 expect(types.indexOf(EventType.REASONING_END)).toBeLessThan(
266 types.indexOf(EventType.TEXT_MESSAGE_START),
267 )
268
269 const reasoning = chunks
270 .filter((c) => c.type === EventType.REASONING_MESSAGE_CONTENT)
271 .map((c) => c.delta)
272 .join('')
273 expect(reasoning).toBe('The user wants a greeting.')
274
275 const text = chunks
276 .filter((c) => c.type === EventType.TEXT_MESSAGE_CONTENT)
277 .map((c) => c.delta)
278 .join('')
279 expect(text).toBe('Hello!')
280
281 const runFinished = chunks.find((c) => c.type === EventType.RUN_FINISHED)
282 expect(
283 runFinished?.type === EventType.RUN_FINISHED && runFinished.usage,
284 ).toMatchObject({
285 promptTokens: 12,
286 completionTokens: 7,
287 totalTokens: 19,
288 })
289 })
290
291 it('ties encrypted_content to the reasoning message', async () => {
292 setupMockSdkClient(thinkingStreamChunks(THINKING_SUMMARY_MODEL))
293
294 const chunks = []
295 for await (const chunk of chat({
296 adapter: createBytePlusText(THINKING_SUMMARY_MODEL, 'ark-test-key'),
297 messages: [{ role: 'user', content: 'Say hi' }],
298 })) {
299 chunks.push(chunk)
300 }
301
302 const reasoningIds = chunks.flatMap((c) =>
303 c.type === EventType.REASONING_MESSAGE_START ? [c.messageId] : [],
304 )
305 const values = chunks.flatMap((c) =>
306 c.type === EventType.REASONING_ENCRYPTED_VALUE ? [c] : [],
307 )
308 expect(values.map((v) => v.encryptedValue)).toEqual([ENCRYPTED_BLOB])
309 // An AG-UI client attaches the value to the message with this id.
310 expect(values.map((v) => v.entityId)).toEqual(reasoningIds)
311 })
312
313 it('does not treat the encrypted chunk as reasoning text', async () => {
314 setupMockSdkClient([
315 {
316 id: 'chatcmpl-enc-only',
317 model: THINKING_SUMMARY_MODEL,
318 choices: [
319 {
320 index: 0,
321 delta: {
322 content: '',
323 reasoning_content: '',
324 encrypted_content: ENCRYPTED_BLOB,
325 },
326 },
327 ],
328 },
329 {
330 id: 'chatcmpl-enc-only',
331 model: THINKING_SUMMARY_MODEL,
332 choices: [
333 { index: 0, delta: { content: 'Hi' }, finish_reason: 'stop' },
334 ],
335 },
336 ])
337 const adapter = createBytePlusText(THINKING_SUMMARY_MODEL, 'ark-test-key')
338
339 const chunks = await collect(
340 adapter.chatStream({
341 model: THINKING_SUMMARY_MODEL,
342 messages: [{ role: 'user', content: 'Say hi' }],
343 logger: testLogger,
344 }),
345 )
346
347 expect(
348 chunks.some((c) => c.type === EventType.REASONING_MESSAGE_CONTENT),
349 ).toBe(false)
350
351 // Pinning the consequence, not endorsing it: with no reasoning deltas
352 // the base never opens a reasoning lifecycle, so there is no
353 // STEP_FINISHED to stamp and the blob is silently dropped. Live Ark
354 // always sends the encrypted chunk *after* reasoning deltas, but that
355 // ordering is observed behaviour rather than a documented contract — if
356 // this assertion ever fails because a STEP_FINISHED appeared, the
357 // capture path needs revisiting, not this expectation.
358 expect(chunks.some((c) => c.type === EventType.STEP_FINISHED)).toBe(false)
359 })
360
361 it('emits AG-UI tool-call events with the OpenAI tool shape', async () => {
362 const mockCreate = setupMockSdkClient([
363 {
364 id: 'chatcmpl-tool',
365 model: 'seed-2-0-lite-260428',
366 choices: [
367 {
368 index: 0,
369 delta: {
370 tool_calls: [
371 {
372 index: 0,
373 id: 'call_1',
374 type: 'function',
375 function: {
376 name: 'lookup_weather',
377 arguments: '{"location":',
378 },
379 },
380 ],
381 },
382 },
383 ],
384 },
385 {
386 id: 'chatcmpl-tool',
387 model: 'seed-2-0-lite-260428',
388 choices: [
389 {
390 index: 0,
391 delta: {
392 tool_calls: [
393 { index: 0, function: { arguments: '"Berlin"}' } },
394 ],
395 },
396 finish_reason: 'tool_calls',
397 },
398 ],
399 },
400 ])
401 const adapter = createBytePlusText('seed-2-0-lite-260428', 'ark-test-key')
402
403 const chunks = await collect(
404 adapter.chatStream({
405 model: 'seed-2-0-lite-260428',
406 messages: [{ role: 'user', content: 'Weather in Berlin?' }],
407 tools: [weatherTool],
408 logger: testLogger,
409 }),
410 )
411
412 // Ark accepts (and requires) `type: 'function'` — the docs' claimed
413 // `'function_call'` value is rejected with 400 InvalidParameter.
414 expect(mockCreate.mock.calls[0]?.[0]).toMatchObject({
415 tools: [{ type: 'function', function: { name: 'lookup_weather' } }],
416 })
417
418 const toolEnd = chunks.find((c) => c.type === EventType.TOOL_CALL_END)
419 expect(
420 toolEnd?.type === EventType.TOOL_CALL_END && toolEnd.input,
421 ).toEqual({ location: 'Berlin' })
422 })
423 })
424
425 describe('encrypted_content round-trip', () => {
426 const assistantWithSignature: ModelMessage = {
427 role: 'assistant',
428 content: 'Hello!',
429 thinking: [
430 { content: 'The user wants a greeting.', signature: ENCRYPTED_BLOB },
431 ],
432 }
433
434 async function requestBodyFor(
435 model: (typeof BYTEPLUS_CHAT_MODELS)[number],
436 messages: Array<ModelMessage>,
437 ): Promise<any> {
438 const mockCreate = setupMockSdkClient([
439 {
440 id: 'chatcmpl-echo',
441 model,
442 choices: [
443 { index: 0, delta: { content: 'ok' }, finish_reason: 'stop' },
444 ],
445 },
446 ])
447 const adapter = createBytePlusText(model, 'ark-test-key')
448 await collect(adapter.chatStream({ model, messages, logger: testLogger }))
449 return mockCreate.mock.calls[0]?.[0]
450 }
451
452 it('echoes the blob verbatim on the outgoing assistant message', async () => {
453 const body = await requestBodyFor(THINKING_SUMMARY_MODEL, [
454 { role: 'user', content: 'Say hi' },
455 assistantWithSignature,
456 { role: 'user', content: 'Again?' },
457 ])
458
459 expect(body.messages[1]).toMatchObject({
460 role: 'assistant',
461 content: 'Hello!',
462 encrypted_content: ENCRYPTED_BLOB,
463 })
464 })
465
466 it('omits the field when the assistant message carries no signature', async () => {
467 const body = await requestBodyFor(THINKING_SUMMARY_MODEL, [
468 { role: 'user', content: 'Say hi' },
469 { role: 'assistant', content: 'Hello!' },
470 { role: 'user', content: 'Again?' },
471 ])
472
473 expect(body.messages[1]).not.toHaveProperty('encrypted_content')
474 })
475
476 it('never forwards a signature on a model that does not emit the blob', async () => {
477 const body = await requestBodyFor(PLAIN_MODEL, [
478 { role: 'user', content: 'Say hi' },
479 assistantWithSignature,
480 { role: 'user', content: 'Again?' },
481 ])
482
483 expect(body.messages[1]).not.toHaveProperty('encrypted_content')
484 })
485
486 it('echoes the last signature when several thinking steps carry one', async () => {
487 const body = await requestBodyFor(THINKING_SUMMARY_MODEL, [
488 { role: 'user', content: 'Say hi' },
489 {
490 role: 'assistant',
491 content: 'Hello!',
492 thinking: [
493 { content: 'first', signature: 'ENC-first' },
494 { content: 'second', signature: 'ENC-second' },
495 ],
496 },
497 { role: 'user', content: 'Again?' },
498 ])
499
500 expect(body.messages[1].encrypted_content).toBe('ENC-second')
501 })
502 })
503
504 describe('provider options', () => {
505 it('forwards Ark-only options, sampling options, and chat({ reasoning })', async () => {
506 const mockCreate = setupMockSdkClient([
507 {
508 id: 'chatcmpl-opts',
509 model: 'seed-2-0-lite-260428',
510 choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
511 },
512 ])
513 const adapter = createBytePlusText('seed-2-0-lite-260428', 'ark-test-key')
514
515 const modelOptions: BytePlusTextProviderOptions = {
516 repetition_penalty: 1.05,
517 service_tier: 'flex',
518 temperature: 0.4,
519 max_tokens: 256,
520 }
521
522 await collect(
523 adapter.chatStream({
524 model: 'seed-2-0-lite-260428',
525 messages: [{ role: 'user', content: 'Hello' }],
526 modelOptions,
527 reasoning: { level: 'high', summary: true },
528 logger: testLogger,
529 }),
530 )
531
532 expect(mockCreate.mock.calls[0]?.[0]).toMatchObject({
533 thinking: { type: 'enabled' },
534 reasoning_effort: 'high',
535 repetition_penalty: 1.05,
536 service_tier: 'flex',
537 temperature: 0.4,
538 max_tokens: 256,
539 stream: true,
540 stream_options: { include_usage: true },
541 })
542 })
543 })
544
545 describe('chat({ reasoning })', () => {
546 async function requestFor(
547 model: 'glm-4-7-251222' | 'glm-5-2-260617',
548 level: 'off' | 'high',
549 ) {
550 const mockCreate = setupMockSdkClient([
551 {
552 id: 'chatcmpl-reasoning',
553 model,
554 choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
555 },
556 ])
557 await collect(
558 createBytePlusText(model, 'ark-test-key').chatStream({
559 model,
560 messages: [{ role: 'user', content: 'Hello' }],
561 reasoning: { level, summary: true },
562 logger: testLogger,
563 }),
564 )
565 return mockCreate.mock.calls[0]?.[0] as Record<string, unknown>
566 }
567
568 it('off sends thinking disabled and no effort', async () => {
569 const body = await requestFor('glm-5-2-260617', 'off')
570 expect(body.thinking).toEqual({ type: 'disabled' })
571 expect(body).not.toHaveProperty('reasoning_effort')
572 })
573
574 it('an on/off model sends thinking enabled and no effort', async () => {
575 const body = await requestFor('glm-4-7-251222', 'high')
576 expect(body.thinking).toEqual({ type: 'enabled' })
577 expect(body).not.toHaveProperty('reasoning_effort')
578 })
579 })
580
581 describe('multimodal content parts', () => {
582 async function contentPartsFor(parts: Array<ContentPart>): Promise<any> {
583 const mockCreate = setupMockSdkClient([
584 {
585 id: 'chatcmpl-mm',
586 model: 'seed-2-0-lite-260428',
587 choices: [
588 { index: 0, delta: { content: 'ok' }, finish_reason: 'stop' },
589 ],
590 },
591 ])
592 const adapter = createBytePlusText('seed-2-0-lite-260428', 'ark-test-key')
593 await collect(
594 adapter.chatStream({
595 model: 'seed-2-0-lite-260428',
596 messages: [{ role: 'user', content: parts }],
597 logger: testLogger,
598 }),
599 )
600 const body: any = mockCreate.mock.calls[0]?.[0]
601 return body.messages[0].content
602 }
603
604 it('sends image parts with Ark detail and pixel bounds', async () => {
605 const content = await contentPartsFor([
606 { type: 'text', content: 'What is this?' },
607 {
608 type: 'image',
609 source: { type: 'url', value: 'https://example.com/cat.png' },
610 metadata: {
611 detail: 'xhigh',
612 image_pixel_limit: { max_pixels: 1_000_000 },
613 },
614 },
615 ])
616
617 expect(content).toContainEqual({
618 type: 'image_url',
619 image_url: {
620 url: 'https://example.com/cat.png',
621 detail: 'xhigh',
622 image_pixel_limit: { max_pixels: 1_000_000 },
623 },
624 })
625 })
626
627 it('wraps inline base64 image data in a data: URI', async () => {
628 const content = await contentPartsFor([
629 { type: 'text', content: 'What is this?' },
630 {
631 type: 'image',
632 source: { type: 'data', value: 'QUJD', mimeType: 'image/png' },
633 },
634 ])
635
636 expect(content).toContainEqual({
637 type: 'image_url',
638 image_url: { url: 'data:image/png;base64,QUJD', detail: 'auto' },
639 })
640 })
641
642 it('passes an already-encoded image data URI through untouched', async () => {
643 const content = await contentPartsFor([
644 { type: 'text', content: 'What is this?' },
645 {
646 type: 'image',
647 source: {
648 type: 'data',
649 value: 'data:image/png;base64,QUJD',
650 mimeType: 'image/png',
651 },
652 },
653 ])
654
655 expect(content).toContainEqual({
656 type: 'image_url',
657 image_url: { url: 'data:image/png;base64,QUJD', detail: 'auto' },
658 })
659 })
660
661 it('sends video parts as video_url', async () => {
662 const content = await contentPartsFor([
663 { type: 'text', content: 'Describe this' },
664 {
665 type: 'video',
666 source: { type: 'url', value: 'https://example.com/clip.mp4' },
667 metadata: { fps: 2 },
668 },
669 ])
670
671 expect(content).toContainEqual({
672 type: 'video_url',
673 video_url: { url: 'https://example.com/clip.mp4', fps: 2 },
674 })
675 })
676
677 it('sends URL audio as input_audio.url and inline audio as data + format', async () => {
678 const urlContent = await contentPartsFor([
679 { type: 'text', content: 'Transcribe' },
680 {
681 type: 'audio',
682 source: { type: 'url', value: 'https://example.com/clip.mp3' },
683 },
684 ])
685 expect(urlContent).toContainEqual({
686 type: 'input_audio',
687 input_audio: { url: 'https://example.com/clip.mp3' },
688 })
689
690 const dataContent = await contentPartsFor([
691 { type: 'text', content: 'Transcribe' },
692 {
693 type: 'audio',
694 source: { type: 'data', value: 'QUJD', mimeType: 'audio/mpeg' },
695 },
696 ])
697 expect(dataContent).toContainEqual({
698 type: 'input_audio',
699 input_audio: { data: 'QUJD', format: 'mp3' },
700 })
701 })
702
703 it('strips a data: prefix from inline audio — Ark takes bare base64', async () => {
704 const content = await contentPartsFor([
705 { type: 'text', content: 'Transcribe' },
706 {
707 type: 'audio',
708 source: {
709 type: 'data',
710 value: 'data:audio/wav;base64,QUJD',
711 mimeType: 'audio/wav',
712 },
713 },
714 ])
715
716 expect(content).toContainEqual({
717 type: 'input_audio',
718 input_audio: { data: 'QUJD', format: 'wav' },
719 })
720 })
721
722 it('honours an explicit metadata.format over the mimeType', async () => {
723 const content = await contentPartsFor([
724 { type: 'text', content: 'Transcribe' },
725 {
726 type: 'audio',
727 source: {
728 type: 'data',
729 value: 'QUJD',
730 mimeType: 'application/octet-stream',
731 },
732 metadata: { format: 'flac' },
733 },
734 ])
735
736 expect(content).toContainEqual({
737 type: 'input_audio',
738 input_audio: { data: 'QUJD', format: 'flac' },
739 })
740 })
741
742 it('fails loud on inline audio with an unrecognised mimeType', async () => {
743 const chunks = await collect(
744 createBytePlusText('seed-2-0-lite-260428', 'ark-test-key').chatStream({
745 model: 'seed-2-0-lite-260428',
746 messages: [
747 {
748 role: 'user',
749 content: [
750 { type: 'text', content: 'Transcribe' },
751 {
752 type: 'audio',
753 source: {
754 type: 'data',
755 value: 'QUJD',
756 mimeType: 'audio/weird-codec',
757 },
758 },
759 ],
760 },
761 ],
762 logger: testLogger,
763 }),
764 )
765
766 const runError = chunks.find((c) => c.type === EventType.RUN_ERROR)
767 expect(
768 runError?.type === EventType.RUN_ERROR && runError.message,
769 ).toContain('unrecognised mimeType')
770 })
771 })
772
773 describe('structured-output gating', () => {
774 it('opts into the native combined tools + schema path only on supported models', () => {
775 expect(
776 createBytePlusText(
777 STRUCTURED_MODEL,
778 'ark-test-key',
779 ).supportsCombinedToolsAndSchema(),
780 ).toBe(true)
781 expect(
782 createBytePlusText(
783 UNSTRUCTURED_MODEL,
784 'ark-test-key',
785 ).supportsCombinedToolsAndSchema(),
786 ).toBe(false)
787 })
788
789 it('throws from structuredOutput on a model Ark rejects json_schema for', async () => {
790 const adapter = createBytePlusText(UNSTRUCTURED_MODEL, 'ark-test-key')
791
792 await expect(
793 adapter.structuredOutput({
794 chatOptions: {
795 model: UNSTRUCTURED_MODEL,
796 messages: [{ role: 'user', content: 'Hi' }],
797 logger: testLogger,
798 },
799 outputSchema: { type: 'object', properties: {} },
800 }),
801 ).rejects.toThrow('does not support structured output')
802 })
803
804 // The two tests above assert the hook's return value and the
805 // structuredOutput* entry points in isolation. This one drives the whole
806 // chat() activity, which is where `supportsCombinedToolsAndSchema()` is
807 // actually consumed (`nativeCombined`, twice, in chat()'s activity), and
808 // pins the end-to-end consequence: on a rejecting model the guard fires
809 // *before* any request, so no schema Ark would 400 on ever leaves the
810 // process. Every structured E2E overrides to a supporting model, so this
811 // path ran nowhere.
812 it('fails before issuing a request when the model rejects json_schema', async () => {
813 const mockCreate = setupMockSdkClient(
814 textStreamChunks(UNSTRUCTURED_MODEL),
815 )
816 const adapter = createBytePlusText(UNSTRUCTURED_MODEL, 'ark-test-key')
817
818 const chunks: Array<AdapterYieldChunk> = []
819 for await (const chunk of chat({
820 adapter,
821 messages: [{ role: 'user', content: 'Say hi' }],
822 outputSchema: { type: 'object', properties: {} },
823 stream: true,
824 })) {
825 chunks.push(chunk)
826 }
827
828 // Ark has no json_object fallback, so there is nothing to downgrade to.
829 // The request is never made rather than being made without the schema.
830 expect(mockCreate).not.toHaveBeenCalled()
831
832 // And it surfaces as a named RUN_ERROR, not a raw 400 or silent prose.
833 const runError = chunks.find((c) => c.type === EventType.RUN_ERROR)
834 expect(
835 runError?.type === EventType.RUN_ERROR && runError.message,
836 ).toContain('does not support structured output')
837 })
838
839 it('does forward response_format into the streaming turns on a supported model', async () => {
840 const mockCreate = setupMockSdkClient(textStreamChunks(STRUCTURED_MODEL))
841 const adapter = createBytePlusText(STRUCTURED_MODEL, 'ark-test-key')
842
843 for await (const _ of chat({
844 adapter,
845 messages: [{ role: 'user', content: 'Say hi' }],
846 outputSchema: { type: 'object', properties: {} },
847 stream: true,
848 })) {
849 // consume
850 }
851
852 const request = mockCreate.mock.calls[0]?.[0] as Record<string, unknown>
853 expect(request.response_format).toMatchObject({ type: 'json_schema' })
854 })
855
856 it('emits RUN_ERROR (not a throw) from structuredOutputStream on those models', async () => {
857 const adapter = createBytePlusText(UNSTRUCTURED_MODEL, 'ark-test-key')
858
859 const chunks = await collect(
860 adapter.structuredOutputStream({
861 chatOptions: {
862 model: UNSTRUCTURED_MODEL,
863 messages: [{ role: 'user', content: 'Hi' }],
864 logger: testLogger,
865 },
866 outputSchema: { type: 'object', properties: {} },
867 }),
868 )
869
870 expect(chunks[0]?.type).toBe(EventType.RUN_STARTED)
871 const runError = chunks.find((c) => c.type === EventType.RUN_ERROR)
872 expect(runError?.type === EventType.RUN_ERROR && runError.code).toBe(
873 'unsupported-structured-output',
874 )
875 })
876
877 it('sends response_format json_schema on a supported model', async () => {
878 const mockCreate = setupMockSdkClient([], {
879 choices: [{ message: { content: '{"city":"Paris"}' } }],
880 })
881 const adapter = createBytePlusText(STRUCTURED_MODEL, 'ark-test-key')
882
883 const result = await adapter.structuredOutput({
884 chatOptions: {
885 model: STRUCTURED_MODEL,
886 messages: [{ role: 'user', content: 'Where is the Eiffel tower?' }],
887 logger: testLogger,
888 },
889 outputSchema: {
890 type: 'object',
891 properties: { city: { type: 'string' } },
892 required: ['city'],
893 },
894 })
895
896 expect(result.data).toEqual({ city: 'Paris' })
897 expect(mockCreate.mock.calls[0]?.[0]).toMatchObject({
898 stream: false,
899 response_format: { type: 'json_schema' },
900 })
901 })
902
903 it('streams structured output on a supported model', async () => {
904 setupMockSdkClient([
905 {
906 id: 'chatcmpl-sos',
907 model: STRUCTURED_MODEL,
908 choices: [{ index: 0, delta: { content: '{"city":' } }],
909 },
910 {
911 id: 'chatcmpl-sos',
912 model: STRUCTURED_MODEL,
913 choices: [
914 {
915 index: 0,
916 delta: { content: '"Paris"}' },
917 finish_reason: 'stop',
918 },
919 ],
920 },
921 ])
922 const adapter = createBytePlusText(STRUCTURED_MODEL, 'ark-test-key')
923
924 const chunks = await collect(
925 adapter.structuredOutputStream({
926 chatOptions: {
927 model: STRUCTURED_MODEL,
928 messages: [{ role: 'user', content: 'Where is the Eiffel tower?' }],
929 logger: testLogger,
930 },
931 outputSchema: {
932 type: 'object',
933 properties: { city: { type: 'string' } },
934 required: ['city'],
935 },
936 }),
937 )
938
939 expect(chunks.some((c) => c.type === EventType.RUN_ERROR)).toBe(false)
940 const complete = chunks.find(
941 (c) =>
942 c.type === EventType.CUSTOM &&
943 c.name === 'structured-output.complete',
944 )
945 expect(
946 complete?.type === EventType.CUSTOM &&
947 (complete.value as { object: unknown }).object,
948 ).toEqual({ city: 'Paris' })
949 })
950 })
951})
952
953/**
954 * The blob is only useful if it survives the whole round-trip through the
955 * chat engine, not just the adapter's own event stream: the server agent loop
956 * builds the continuation message itself, and it reads thinking from a
957 * different field than the client StreamProcessor does. These tests drive the
958 * real `chat()` agent loop so a regression in that hand-off is caught here
959 * rather than against live Ark.
960 */
961describe('encrypted_content through the chat() agent loop', () => {
962 beforeEach(() => {
963 pendingMockCreate = undefined
964 })
965
966 const lookupWeather: Tool = {
967 name: 'lookup_weather',
968 description: 'Look up the weather for a city',
969 inputSchema: {
970 type: 'object',
971 properties: { city: { type: 'string' } },
972 required: ['city'],
973 },
974 execute: async () => ({ conditions: 'sunny' }),
975 }
976
977 /**
978 * Turn 1: reasoning deltas → the dedicated encrypted chunk → a tool call.
979 * `text` controls whether the assistant also produces content, which selects
980 * between the finish_reason path and the drain path in the base.
981 */
982 function toolCallTurn(
983 model: string,
984 options: { text: boolean },
985 ): Array<Record<string, unknown>> {
986 return [
987 {
988 id: 'chatcmpl-loop',
989 model,
990 choices: [{ index: 0, delta: { reasoning_content: 'Need the tool.' } }],
991 },
992 {
993 id: 'chatcmpl-loop',
994 model,
995 choices: [
996 {
997 index: 0,
998 delta: {
999 content: '',
1000 reasoning_content: '',
1001 encrypted_content: ENCRYPTED_BLOB,
1002 },
1003 },
1004 ],
1005 },
1006 ...(options.text
1007 ? [
1008 {
1009 id: 'chatcmpl-loop',
1010 model,
1011 choices: [{ index: 0, delta: { content: 'Checking.' } }],
1012 },
1013 ]
1014 : []),
1015 {
1016 id: 'chatcmpl-loop',
1017 model,
1018 choices: [
1019 {
1020 index: 0,
1021 delta: {
1022 tool_calls: [
1023 {
1024 index: 0,
1025 id: 'call_loop_1',
1026 type: 'function',
1027 function: {
1028 name: 'lookup_weather',
1029 arguments: '{"city":"Berlin"}',
1030 },
1031 },
1032 ],
1033 },
1034 finish_reason: 'tool_calls',
1035 },
1036 ],
1037 },
1038 ]
1039 }
1040
1041 function finalTurn(model: string): Array<Record<string, unknown>> {
1042 return [
1043 {
1044 id: 'chatcmpl-loop-2',
1045 model,
1046 choices: [
1047 {
1048 index: 0,
1049 delta: { content: 'It is sunny in Berlin.' },
1050 finish_reason: 'stop',
1051 },
1052 ],
1053 },
1054 ]
1055 }
1056
1057 /**
1058 * Runs a two-request agent loop and returns the request body of the
1059 * continuation call.
1060 */
1061 async function continuationRequest(options: { text: boolean }): Promise<any> {
1062 const model = THINKING_SUMMARY_MODEL
1063 const turns = [
1064 toolCallTurn(model, { text: options.text }),
1065 finalTurn(model),
1066 ]
1067 let call = 0
1068 const mockCreate = vi.fn().mockImplementation(() => {
1069 const chunks = turns[Math.min(call++, turns.length - 1)]!
1070 return Promise.resolve(createAsyncIterable(chunks))
1071 })
1072
1073 const adapter = _realCreateBytePlusText(model, 'ark-test-key')
1074 ;(adapter as any).client = {
1075 chat: { completions: { create: mockCreate } },
1076 }
1077
1078 for await (const _ of chat({
1079 adapter,
1080 messages: [{ role: 'user', content: 'Weather in Berlin?' }],
1081 tools: [lookupWeather],
1082 })) {
1083 // consume the stream
1084 }
1085
1086 expect(mockCreate).toHaveBeenCalledTimes(2)
1087 return mockCreate.mock.calls[1]?.[0]
1088 }
1089
1090 it('echoes encrypted_content on the continuation request', async () => {
1091 const body = await continuationRequest({ text: true })
1092
1093 const assistant = body.messages.find(
1094 (m: any) => m.role === 'assistant' && m.tool_calls,
1095 )
1096 expect(assistant).toBeDefined()
1097 expect(assistant.encrypted_content).toBe(ENCRYPTED_BLOB)
1098 expect(assistant.tool_calls[0].function.name).toBe('lookup_weather')
1099 // The tool result must be there too — otherwise the loop didn't actually
1100 // continue and the assertion above proves nothing about a real 2nd turn.
1101 expect(
1102 body.messages.some(
1103 (m: any) => m.role === 'tool' && m.tool_call_id === 'call_loop_1',
1104 ),
1105 ).toBe(true)
1106 })
1107
1108 it('echoes it on the drain path too (thinking + tool call, no text)', async () => {
1109 const body = await continuationRequest({ text: false })
1110
1111 const assistant = body.messages.find(
1112 (m: any) => m.role === 'assistant' && m.tool_calls,
1113 )
1114 expect(assistant.encrypted_content).toBe(ENCRYPTED_BLOB)
1115 // An assistant turn with only tool calls sends `content: null`, per the
1116 // Chat Completions contract the base implements.
1117 expect(assistant.content).toBeNull()
1118 })
1119})
1120
1121// The adapter stamps `delta` onto a STEP_FINISHED that already carries the
1122// same reasoning text via REASONING_MESSAGE_CONTENT, because chat()'s agent
1123// loop reads thinking only from STEP_FINISHED.delta and drops the whole step —
1124// signature included — when that accumulation is empty.
1125//
1126// Nothing double-counts today only because StreamProcessor short-circuits
1127// STEP_FINISHED content once it has seen reasoning events. That guarantee
1128// lives in @tanstack/ai, not here, so without this test a change over there
1129// would double every BytePlus reasoning block in the UI while this package
1130// stayed green.
1131describe('reasoning delta round-trip through StreamProcessor', () => {
1132 it('surfaces the thinking text once, with the signature attached', async () => {
1133 setupMockSdkClient(thinkingStreamChunks(THINKING_SUMMARY_MODEL))
1134 const adapter = createBytePlusText(THINKING_SUMMARY_MODEL, 'ark-test-key')
1135
1136 const processor = new StreamProcessor()
1137 for await (const chunk of adapter.chatStream({
1138 model: THINKING_SUMMARY_MODEL,
1139 messages: [{ role: 'user', content: 'Say hi' }],
1140 logger: testLogger,
1141 })) {
1142 processor.processChunk(chunk)
1143 }
1144
1145 const thinkingParts = processor
1146 .getMessages()
1147 .flatMap((message) => message.parts ?? [])
1148 .filter((part) => part.type === 'thinking')
1149
1150 expect(thinkingParts).toHaveLength(1)
1151 // Not 'The user wants a greeting.The user wants a greeting.' — the exact
1152 // failure the STEP_FINISHED short-circuit prevents.
1153 expect(thinkingParts[0]).toMatchObject({
1154 content: 'The user wants a greeting.',
1155 signature: ENCRYPTED_BLOB,
1156 })
1157 })
1158})