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 threadId: 'thread-1',
256 model: THINKING_SUMMARY_MODEL,
257 messages: [{ role: 'user', content: 'Say hi' }],
258 logger: testLogger,
259 }),
260 )
261
262 const types = chunks.map((c) => c.type)
263 expect(types[0]).toBe(EventType.RUN_STARTED)
264 expect(types).toContain(EventType.REASONING_MESSAGE_START)
265 expect(types).toContain(EventType.TEXT_MESSAGE_START)
266 expect(types.indexOf(EventType.REASONING_END)).toBeLessThan(
267 types.indexOf(EventType.TEXT_MESSAGE_START),
268 )
269
270 const reasoning = chunks
271 .filter((c) => c.type === EventType.REASONING_MESSAGE_CONTENT)
272 .map((c) => c.delta)
273 .join('')
274 expect(reasoning).toBe('The user wants a greeting.')
275
276 const text = chunks
277 .filter((c) => c.type === EventType.TEXT_MESSAGE_CONTENT)
278 .map((c) => c.delta)
279 .join('')
280 expect(text).toBe('Hello!')
281
282 const runFinished = chunks.find((c) => c.type === EventType.RUN_FINISHED)
283 expect(
284 runFinished?.type === EventType.RUN_FINISHED && runFinished.usage,
285 ).toMatchObject({
286 promptTokens: 12,
287 completionTokens: 7,
288 totalTokens: 19,
289 })
290 })
291
292 it('ties encrypted_content to the reasoning message', async () => {
293 setupMockSdkClient(thinkingStreamChunks(THINKING_SUMMARY_MODEL))
294
295 const chunks = []
296 for await (const chunk of chat({
297 threadId: 'thread-1',
298 adapter: createBytePlusText(THINKING_SUMMARY_MODEL, 'ark-test-key'),
299 messages: [{ role: 'user', content: 'Say hi' }],
300 })) {
301 chunks.push(chunk)
302 }
303
304 const reasoningIds = chunks.flatMap((c) =>
305 c.type === EventType.REASONING_MESSAGE_START ? [c.messageId] : [],
306 )
307 const values = chunks.flatMap((c) =>
308 c.type === EventType.REASONING_ENCRYPTED_VALUE ? [c] : [],
309 )
310 expect(values.map((v) => v.encryptedValue)).toEqual([ENCRYPTED_BLOB])
311 // An AG-UI client attaches the value to the message with this id.
312 expect(values.map((v) => v.entityId)).toEqual(reasoningIds)
313 })
314
315 it('does not treat the encrypted chunk as reasoning text', async () => {
316 setupMockSdkClient([
317 {
318 id: 'chatcmpl-enc-only',
319 model: THINKING_SUMMARY_MODEL,
320 choices: [
321 {
322 index: 0,
323 delta: {
324 content: '',
325 reasoning_content: '',
326 encrypted_content: ENCRYPTED_BLOB,
327 },
328 },
329 ],
330 },
331 {
332 id: 'chatcmpl-enc-only',
333 model: THINKING_SUMMARY_MODEL,
334 choices: [
335 { index: 0, delta: { content: 'Hi' }, finish_reason: 'stop' },
336 ],
337 },
338 ])
339 const adapter = createBytePlusText(THINKING_SUMMARY_MODEL, 'ark-test-key')
340
341 const chunks = await collect(
342 adapter.chatStream({
343 threadId: 'thread-1',
344 model: THINKING_SUMMARY_MODEL,
345 messages: [{ role: 'user', content: 'Say hi' }],
346 logger: testLogger,
347 }),
348 )
349
350 expect(
351 chunks.some((c) => c.type === EventType.REASONING_MESSAGE_CONTENT),
352 ).toBe(false)
353
354 // Pinning the consequence, not endorsing it: with no reasoning deltas
355 // the base never opens a reasoning lifecycle, so there is no
356 // REASONING_MESSAGE_END to attach to and the blob is silently dropped.
357 // Live Ark always sends the encrypted chunk *after* reasoning deltas, but
358 // that ordering is observed behaviour rather than a documented contract.
359 expect(
360 chunks.some((c) => c.type === EventType.REASONING_ENCRYPTED_VALUE),
361 ).toBe(false)
362 })
363
364 it('emits AG-UI tool-call events with the OpenAI tool shape', async () => {
365 const mockCreate = setupMockSdkClient([
366 {
367 id: 'chatcmpl-tool',
368 model: 'seed-2-0-lite-260428',
369 choices: [
370 {
371 index: 0,
372 delta: {
373 tool_calls: [
374 {
375 index: 0,
376 id: 'call_1',
377 type: 'function',
378 function: {
379 name: 'lookup_weather',
380 arguments: '{"location":',
381 },
382 },
383 ],
384 },
385 },
386 ],
387 },
388 {
389 id: 'chatcmpl-tool',
390 model: 'seed-2-0-lite-260428',
391 choices: [
392 {
393 index: 0,
394 delta: {
395 tool_calls: [
396 { index: 0, function: { arguments: '"Berlin"}' } },
397 ],
398 },
399 finish_reason: 'tool_calls',
400 },
401 ],
402 },
403 ])
404 const adapter = createBytePlusText('seed-2-0-lite-260428', 'ark-test-key')
405
406 const chunks = await collect(
407 adapter.chatStream({
408 threadId: 'thread-1',
409 model: 'seed-2-0-lite-260428',
410 messages: [{ role: 'user', content: 'Weather in Berlin?' }],
411 tools: [weatherTool],
412 logger: testLogger,
413 }),
414 )
415
416 // Ark accepts (and requires) `type: 'function'` — the docs' claimed
417 // `'function_call'` value is rejected with 400 InvalidParameter.
418 expect(mockCreate.mock.calls[0]?.[0]).toMatchObject({
419 tools: [{ type: 'function', function: { name: 'lookup_weather' } }],
420 })
421
422 const toolEnd = chunks.find((c) => c.type === EventType.TOOL_CALL_END)
423 expect(
424 toolEnd?.type === EventType.TOOL_CALL_END && toolEnd.input,
425 ).toEqual({ location: 'Berlin' })
426 })
427 })
428
429 describe('encrypted_content round-trip', () => {
430 const assistantWithSignature: ModelMessage = {
431 role: 'assistant',
432 content: 'Hello!',
433 thinking: [
434 { content: 'The user wants a greeting.', signature: ENCRYPTED_BLOB },
435 ],
436 }
437
438 async function requestBodyFor(
439 model: (typeof BYTEPLUS_CHAT_MODELS)[number],
440 messages: Array<ModelMessage>,
441 ): Promise<any> {
442 const mockCreate = setupMockSdkClient([
443 {
444 id: 'chatcmpl-echo',
445 model,
446 choices: [
447 { index: 0, delta: { content: 'ok' }, finish_reason: 'stop' },
448 ],
449 },
450 ])
451 const adapter = createBytePlusText(model, 'ark-test-key')
452 await collect(
453 adapter.chatStream({
454 threadId: 'thread-1',
455 model,
456 messages,
457 logger: testLogger,
458 }),
459 )
460 return mockCreate.mock.calls[0]?.[0]
461 }
462
463 it('echoes the blob verbatim on the outgoing assistant message', async () => {
464 const body = await requestBodyFor(THINKING_SUMMARY_MODEL, [
465 { role: 'user', content: 'Say hi' },
466 assistantWithSignature,
467 { role: 'user', content: 'Again?' },
468 ])
469
470 expect(body.messages[1]).toMatchObject({
471 role: 'assistant',
472 content: 'Hello!',
473 encrypted_content: ENCRYPTED_BLOB,
474 })
475 })
476
477 it('omits the field when the assistant message carries no signature', async () => {
478 const body = await requestBodyFor(THINKING_SUMMARY_MODEL, [
479 { role: 'user', content: 'Say hi' },
480 { role: 'assistant', content: 'Hello!' },
481 { role: 'user', content: 'Again?' },
482 ])
483
484 expect(body.messages[1]).not.toHaveProperty('encrypted_content')
485 })
486
487 it('never forwards a signature on a model that does not emit the blob', async () => {
488 const body = await requestBodyFor(PLAIN_MODEL, [
489 { role: 'user', content: 'Say hi' },
490 assistantWithSignature,
491 { role: 'user', content: 'Again?' },
492 ])
493
494 expect(body.messages[1]).not.toHaveProperty('encrypted_content')
495 })
496
497 it('echoes the last signature when several thinking steps carry one', async () => {
498 const body = await requestBodyFor(THINKING_SUMMARY_MODEL, [
499 { role: 'user', content: 'Say hi' },
500 {
501 role: 'assistant',
502 content: 'Hello!',
503 thinking: [
504 { content: 'first', signature: 'ENC-first' },
505 { content: 'second', signature: 'ENC-second' },
506 ],
507 },
508 { role: 'user', content: 'Again?' },
509 ])
510
511 expect(body.messages[1].encrypted_content).toBe('ENC-second')
512 })
513 })
514
515 describe('provider options', () => {
516 it('forwards Ark-only options, sampling options, and chat({ reasoning })', async () => {
517 const mockCreate = setupMockSdkClient([
518 {
519 id: 'chatcmpl-opts',
520 model: 'seed-2-0-lite-260428',
521 choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
522 },
523 ])
524 const adapter = createBytePlusText('seed-2-0-lite-260428', 'ark-test-key')
525
526 const modelOptions: BytePlusTextProviderOptions = {
527 repetition_penalty: 1.05,
528 service_tier: 'flex',
529 temperature: 0.4,
530 max_tokens: 256,
531 }
532
533 await collect(
534 adapter.chatStream({
535 threadId: 'thread-1',
536 model: 'seed-2-0-lite-260428',
537 messages: [{ role: 'user', content: 'Hello' }],
538 modelOptions,
539 reasoning: { level: 'high', summary: true },
540 logger: testLogger,
541 }),
542 )
543
544 expect(mockCreate.mock.calls[0]?.[0]).toMatchObject({
545 thinking: { type: 'enabled' },
546 reasoning_effort: 'high',
547 repetition_penalty: 1.05,
548 service_tier: 'flex',
549 temperature: 0.4,
550 max_tokens: 256,
551 stream: true,
552 stream_options: { include_usage: true },
553 })
554 })
555 })
556
557 describe('chat({ reasoning })', () => {
558 async function requestFor(
559 model: 'glm-4-7-251222' | 'glm-5-2-260617',
560 level: 'off' | 'high',
561 ) {
562 const mockCreate = setupMockSdkClient([
563 {
564 id: 'chatcmpl-reasoning',
565 model,
566 choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
567 },
568 ])
569 await collect(
570 createBytePlusText(model, 'ark-test-key').chatStream({
571 threadId: 'thread-1',
572 model,
573 messages: [{ role: 'user', content: 'Hello' }],
574 reasoning: { level, summary: true },
575 logger: testLogger,
576 }),
577 )
578 return mockCreate.mock.calls[0]?.[0] as Record<string, unknown>
579 }
580
581 it('off sends thinking disabled and no effort', async () => {
582 const body = await requestFor('glm-5-2-260617', 'off')
583 expect(body.thinking).toEqual({ type: 'disabled' })
584 expect(body).not.toHaveProperty('reasoning_effort')
585 })
586
587 it('an on/off model sends thinking enabled and no effort', async () => {
588 const body = await requestFor('glm-4-7-251222', 'high')
589 expect(body.thinking).toEqual({ type: 'enabled' })
590 expect(body).not.toHaveProperty('reasoning_effort')
591 })
592 })
593
594 describe('multimodal content parts', () => {
595 async function contentPartsFor(parts: Array<ContentPart>): Promise<any> {
596 const mockCreate = setupMockSdkClient([
597 {
598 id: 'chatcmpl-mm',
599 model: 'seed-2-0-lite-260428',
600 choices: [
601 { index: 0, delta: { content: 'ok' }, finish_reason: 'stop' },
602 ],
603 },
604 ])
605 const adapter = createBytePlusText('seed-2-0-lite-260428', 'ark-test-key')
606 await collect(
607 adapter.chatStream({
608 threadId: 'thread-1',
609 model: 'seed-2-0-lite-260428',
610 messages: [{ role: 'user', content: parts }],
611 logger: testLogger,
612 }),
613 )
614 const body: any = mockCreate.mock.calls[0]?.[0]
615 return body.messages[0].content
616 }
617
618 it('sends image parts with Ark detail and pixel bounds', async () => {
619 const content = await contentPartsFor([
620 { type: 'text', content: 'What is this?' },
621 {
622 type: 'image',
623 source: { type: 'url', value: 'https://example.com/cat.png' },
624 metadata: {
625 detail: 'xhigh',
626 image_pixel_limit: { max_pixels: 1_000_000 },
627 },
628 },
629 ])
630
631 expect(content).toContainEqual({
632 type: 'image_url',
633 image_url: {
634 url: 'https://example.com/cat.png',
635 detail: 'xhigh',
636 image_pixel_limit: { max_pixels: 1_000_000 },
637 },
638 })
639 })
640
641 it('wraps inline base64 image data in a data: URI', async () => {
642 const content = await contentPartsFor([
643 { type: 'text', content: 'What is this?' },
644 {
645 type: 'image',
646 source: { type: 'data', value: 'QUJD', mimeType: 'image/png' },
647 },
648 ])
649
650 expect(content).toContainEqual({
651 type: 'image_url',
652 image_url: { url: 'data:image/png;base64,QUJD', detail: 'auto' },
653 })
654 })
655
656 it('passes an already-encoded image data URI through untouched', async () => {
657 const content = await contentPartsFor([
658 { type: 'text', content: 'What is this?' },
659 {
660 type: 'image',
661 source: {
662 type: 'data',
663 value: 'data:image/png;base64,QUJD',
664 mimeType: 'image/png',
665 },
666 },
667 ])
668
669 expect(content).toContainEqual({
670 type: 'image_url',
671 image_url: { url: 'data:image/png;base64,QUJD', detail: 'auto' },
672 })
673 })
674
675 it('sends video parts as video_url', async () => {
676 const content = await contentPartsFor([
677 { type: 'text', content: 'Describe this' },
678 {
679 type: 'video',
680 source: { type: 'url', value: 'https://example.com/clip.mp4' },
681 metadata: { fps: 2 },
682 },
683 ])
684
685 expect(content).toContainEqual({
686 type: 'video_url',
687 video_url: { url: 'https://example.com/clip.mp4', fps: 2 },
688 })
689 })
690
691 it('sends URL audio as input_audio.url and inline audio as data + format', async () => {
692 const urlContent = await contentPartsFor([
693 { type: 'text', content: 'Transcribe' },
694 {
695 type: 'audio',
696 source: { type: 'url', value: 'https://example.com/clip.mp3' },
697 },
698 ])
699 expect(urlContent).toContainEqual({
700 type: 'input_audio',
701 input_audio: { url: 'https://example.com/clip.mp3' },
702 })
703
704 const dataContent = await contentPartsFor([
705 { type: 'text', content: 'Transcribe' },
706 {
707 type: 'audio',
708 source: { type: 'data', value: 'QUJD', mimeType: 'audio/mpeg' },
709 },
710 ])
711 expect(dataContent).toContainEqual({
712 type: 'input_audio',
713 input_audio: { data: 'QUJD', format: 'mp3' },
714 })
715 })
716
717 it('strips a data: prefix from inline audio — Ark takes bare base64', async () => {
718 const content = await contentPartsFor([
719 { type: 'text', content: 'Transcribe' },
720 {
721 type: 'audio',
722 source: {
723 type: 'data',
724 value: 'data:audio/wav;base64,QUJD',
725 mimeType: 'audio/wav',
726 },
727 },
728 ])
729
730 expect(content).toContainEqual({
731 type: 'input_audio',
732 input_audio: { data: 'QUJD', format: 'wav' },
733 })
734 })
735
736 it('honours an explicit metadata.format over the mimeType', async () => {
737 const content = await contentPartsFor([
738 { type: 'text', content: 'Transcribe' },
739 {
740 type: 'audio',
741 source: {
742 type: 'data',
743 value: 'QUJD',
744 mimeType: 'application/octet-stream',
745 },
746 metadata: { format: 'flac' },
747 },
748 ])
749
750 expect(content).toContainEqual({
751 type: 'input_audio',
752 input_audio: { data: 'QUJD', format: 'flac' },
753 })
754 })
755
756 it('fails loud on inline audio with an unrecognised mimeType', async () => {
757 const chunks = await collect(
758 createBytePlusText('seed-2-0-lite-260428', 'ark-test-key').chatStream({
759 threadId: 'thread-1',
760 model: 'seed-2-0-lite-260428',
761 messages: [
762 {
763 role: 'user',
764 content: [
765 { type: 'text', content: 'Transcribe' },
766 {
767 type: 'audio',
768 source: {
769 type: 'data',
770 value: 'QUJD',
771 mimeType: 'audio/weird-codec',
772 },
773 },
774 ],
775 },
776 ],
777 logger: testLogger,
778 }),
779 )
780
781 const runError = chunks.find((c) => c.type === EventType.RUN_ERROR)
782 expect(
783 runError?.type === EventType.RUN_ERROR && runError.message,
784 ).toContain('unrecognised mimeType')
785 })
786 })
787
788 describe('structured-output gating', () => {
789 it('opts into the native combined tools + schema path only on supported models', () => {
790 expect(
791 createBytePlusText(
792 STRUCTURED_MODEL,
793 'ark-test-key',
794 ).supportsCombinedToolsAndSchema(),
795 ).toBe(true)
796 expect(
797 createBytePlusText(
798 UNSTRUCTURED_MODEL,
799 'ark-test-key',
800 ).supportsCombinedToolsAndSchema(),
801 ).toBe(false)
802 })
803
804 it('throws from structuredOutput on a model Ark rejects json_schema for', async () => {
805 const adapter = createBytePlusText(UNSTRUCTURED_MODEL, 'ark-test-key')
806
807 await expect(
808 adapter.structuredOutput({
809 chatOptions: {
810 threadId: 'thread-1',
811 model: UNSTRUCTURED_MODEL,
812 messages: [{ role: 'user', content: 'Hi' }],
813 logger: testLogger,
814 },
815 outputSchema: { type: 'object', properties: {} },
816 }),
817 ).rejects.toThrow('does not support structured output')
818 })
819
820 // The two tests above assert the hook's return value and the
821 // structuredOutput* entry points in isolation. This one drives the whole
822 // chat() activity, which is where `supportsCombinedToolsAndSchema()` is
823 // actually consumed (`nativeCombined`, twice, in chat()'s activity), and
824 // pins the end-to-end consequence: on a rejecting model the guard fires
825 // *before* any request, so no schema Ark would 400 on ever leaves the
826 // process. Every structured E2E overrides to a supporting model, so this
827 // path ran nowhere.
828 it('fails before issuing a request when the model rejects json_schema', async () => {
829 const mockCreate = setupMockSdkClient(
830 textStreamChunks(UNSTRUCTURED_MODEL),
831 )
832 const adapter = createBytePlusText(UNSTRUCTURED_MODEL, 'ark-test-key')
833
834 const chunks: Array<AdapterYieldChunk> = []
835 for await (const chunk of chat({
836 threadId: 'thread-1',
837 adapter,
838 messages: [{ role: 'user', content: 'Say hi' }],
839 outputSchema: { type: 'object', properties: {} },
840 stream: true,
841 })) {
842 chunks.push(chunk)
843 }
844
845 // Ark has no json_object fallback, so there is nothing to downgrade to.
846 // The request is never made rather than being made without the schema.
847 expect(mockCreate).not.toHaveBeenCalled()
848
849 // And it surfaces as a named RUN_ERROR, not a raw 400 or silent prose.
850 const runError = chunks.find((c) => c.type === EventType.RUN_ERROR)
851 expect(
852 runError?.type === EventType.RUN_ERROR && runError.message,
853 ).toContain('does not support structured output')
854 })
855
856 it('does forward response_format into the streaming turns on a supported model', async () => {
857 const mockCreate = setupMockSdkClient(textStreamChunks(STRUCTURED_MODEL))
858 const adapter = createBytePlusText(STRUCTURED_MODEL, 'ark-test-key')
859
860 for await (const _ of chat({
861 threadId: 'thread-1',
862 adapter,
863 messages: [{ role: 'user', content: 'Say hi' }],
864 outputSchema: { type: 'object', properties: {} },
865 stream: true,
866 })) {
867 // consume
868 }
869
870 const request = mockCreate.mock.calls[0]?.[0] as Record<string, unknown>
871 expect(request.response_format).toMatchObject({ type: 'json_schema' })
872 })
873
874 it('emits RUN_ERROR (not a throw) from structuredOutputStream on those models', async () => {
875 const adapter = createBytePlusText(UNSTRUCTURED_MODEL, 'ark-test-key')
876
877 const chunks = await collect(
878 adapter.structuredOutputStream({
879 chatOptions: {
880 threadId: 'thread-1',
881 model: UNSTRUCTURED_MODEL,
882 messages: [{ role: 'user', content: 'Hi' }],
883 logger: testLogger,
884 },
885 outputSchema: { type: 'object', properties: {} },
886 }),
887 )
888
889 expect(chunks[0]?.type).toBe(EventType.RUN_STARTED)
890 const runError = chunks.find((c) => c.type === EventType.RUN_ERROR)
891 expect(runError?.type === EventType.RUN_ERROR && runError.code).toBe(
892 'unsupported-structured-output',
893 )
894 })
895
896 it('sends response_format json_schema on a supported model', async () => {
897 const mockCreate = setupMockSdkClient([], {
898 choices: [{ message: { content: '{"city":"Paris"}' } }],
899 })
900 const adapter = createBytePlusText(STRUCTURED_MODEL, 'ark-test-key')
901
902 const result = await adapter.structuredOutput({
903 chatOptions: {
904 threadId: 'thread-1',
905 model: STRUCTURED_MODEL,
906 messages: [{ role: 'user', content: 'Where is the Eiffel tower?' }],
907 logger: testLogger,
908 },
909 outputSchema: {
910 type: 'object',
911 properties: { city: { type: 'string' } },
912 required: ['city'],
913 },
914 })
915
916 expect(result.data).toEqual({ city: 'Paris' })
917 expect(mockCreate.mock.calls[0]?.[0]).toMatchObject({
918 stream: false,
919 response_format: { type: 'json_schema' },
920 })
921 })
922
923 it('streams structured output on a supported model', async () => {
924 setupMockSdkClient([
925 {
926 id: 'chatcmpl-sos',
927 model: STRUCTURED_MODEL,
928 choices: [{ index: 0, delta: { content: '{"city":' } }],
929 },
930 {
931 id: 'chatcmpl-sos',
932 model: STRUCTURED_MODEL,
933 choices: [
934 {
935 index: 0,
936 delta: { content: '"Paris"}' },
937 finish_reason: 'stop',
938 },
939 ],
940 },
941 ])
942 const adapter = createBytePlusText(STRUCTURED_MODEL, 'ark-test-key')
943
944 const chunks = await collect(
945 adapter.structuredOutputStream({
946 chatOptions: {
947 threadId: 'thread-1',
948 model: STRUCTURED_MODEL,
949 messages: [{ role: 'user', content: 'Where is the Eiffel tower?' }],
950 logger: testLogger,
951 },
952 outputSchema: {
953 type: 'object',
954 properties: { city: { type: 'string' } },
955 required: ['city'],
956 },
957 }),
958 )
959
960 expect(chunks.some((c) => c.type === EventType.RUN_ERROR)).toBe(false)
961 const complete = chunks.find(
962 (c) =>
963 c.type === EventType.CUSTOM &&
964 c.name === 'structured-output.complete',
965 )
966 expect(
967 complete?.type === EventType.CUSTOM &&
968 (complete.value as { object: unknown }).object,
969 ).toEqual({ city: 'Paris' })
970 })
971 })
972})
973
974/**
975 * The blob is only useful if it survives the whole round-trip through the
976 * chat engine, not just the adapter's own event stream: the server agent loop
977 * builds the continuation message itself, and it reads thinking from a
978 * different field than the client StreamProcessor does. These tests drive the
979 * real `chat()` agent loop so a regression in that hand-off is caught here
980 * rather than against live Ark.
981 */
982describe('encrypted_content through the chat() agent loop', () => {
983 beforeEach(() => {
984 pendingMockCreate = undefined
985 })
986
987 const lookupWeather: Tool = {
988 name: 'lookup_weather',
989 description: 'Look up the weather for a city',
990 inputSchema: {
991 type: 'object',
992 properties: { city: { type: 'string' } },
993 required: ['city'],
994 },
995 execute: async () => ({ conditions: 'sunny' }),
996 }
997
998 /**
999 * Turn 1: reasoning deltas → the dedicated encrypted chunk → a tool call.
1000 * `text` controls whether the assistant also produces content, which selects
1001 * between the finish_reason path and the drain path in the base.
1002 */
1003 function toolCallTurn(
1004 model: string,
1005 options: { text: boolean },
1006 ): Array<Record<string, unknown>> {
1007 return [
1008 {
1009 id: 'chatcmpl-loop',
1010 model,
1011 choices: [{ index: 0, delta: { reasoning_content: 'Need the tool.' } }],
1012 },
1013 {
1014 id: 'chatcmpl-loop',
1015 model,
1016 choices: [
1017 {
1018 index: 0,
1019 delta: {
1020 content: '',
1021 reasoning_content: '',
1022 encrypted_content: ENCRYPTED_BLOB,
1023 },
1024 },
1025 ],
1026 },
1027 ...(options.text
1028 ? [
1029 {
1030 id: 'chatcmpl-loop',
1031 model,
1032 choices: [{ index: 0, delta: { content: 'Checking.' } }],
1033 },
1034 ]
1035 : []),
1036 {
1037 id: 'chatcmpl-loop',
1038 model,
1039 choices: [
1040 {
1041 index: 0,
1042 delta: {
1043 tool_calls: [
1044 {
1045 index: 0,
1046 id: 'call_loop_1',
1047 type: 'function',
1048 function: {
1049 name: 'lookup_weather',
1050 arguments: '{"city":"Berlin"}',
1051 },
1052 },
1053 ],
1054 },
1055 finish_reason: 'tool_calls',
1056 },
1057 ],
1058 },
1059 ]
1060 }
1061
1062 function finalTurn(model: string): Array<Record<string, unknown>> {
1063 return [
1064 {
1065 id: 'chatcmpl-loop-2',
1066 model,
1067 choices: [
1068 {
1069 index: 0,
1070 delta: { content: 'It is sunny in Berlin.' },
1071 finish_reason: 'stop',
1072 },
1073 ],
1074 },
1075 ]
1076 }
1077
1078 /**
1079 * Runs a two-request agent loop and returns the request body of the
1080 * continuation call.
1081 */
1082 async function continuationRequest(options: { text: boolean }): Promise<any> {
1083 const model = THINKING_SUMMARY_MODEL
1084 const turns = [
1085 toolCallTurn(model, { text: options.text }),
1086 finalTurn(model),
1087 ]
1088 let call = 0
1089 const mockCreate = vi.fn().mockImplementation(() => {
1090 const chunks = turns[Math.min(call++, turns.length - 1)]!
1091 return Promise.resolve(createAsyncIterable(chunks))
1092 })
1093
1094 const adapter = _realCreateBytePlusText(model, 'ark-test-key')
1095 ;(adapter as any).client = {
1096 chat: { completions: { create: mockCreate } },
1097 }
1098
1099 for await (const _ of chat({
1100 threadId: 'thread-1',
1101 adapter,
1102 messages: [{ role: 'user', content: 'Weather in Berlin?' }],
1103 tools: [lookupWeather],
1104 })) {
1105 // consume the stream
1106 }
1107
1108 expect(mockCreate).toHaveBeenCalledTimes(2)
1109 return mockCreate.mock.calls[1]?.[0]
1110 }
1111
1112 it('echoes encrypted_content on the continuation request', async () => {
1113 const body = await continuationRequest({ text: true })
1114
1115 const assistant = body.messages.find(
1116 (m: any) => m.role === 'assistant' && m.tool_calls,
1117 )
1118 expect(assistant).toBeDefined()
1119 expect(assistant.encrypted_content).toBe(ENCRYPTED_BLOB)
1120 expect(assistant.tool_calls[0].function.name).toBe('lookup_weather')
1121 // The tool result must be there too — otherwise the loop didn't actually
1122 // continue and the assertion above proves nothing about a real 2nd turn.
1123 expect(
1124 body.messages.some(
1125 (m: any) => m.role === 'tool' && m.tool_call_id === 'call_loop_1',
1126 ),
1127 ).toBe(true)
1128 })
1129
1130 it('echoes it on the drain path too (thinking + tool call, no text)', async () => {
1131 const body = await continuationRequest({ text: false })
1132
1133 const assistant = body.messages.find(
1134 (m: any) => m.role === 'assistant' && m.tool_calls,
1135 )
1136 expect(assistant.encrypted_content).toBe(ENCRYPTED_BLOB)
1137 // An assistant turn with only tool calls sends `content: null`, per the
1138 // Chat Completions contract the base implements.
1139 expect(assistant.content).toBeNull()
1140 })
1141})
1142
1143// The thinking text arrives only through REASONING_MESSAGE_CONTENT, and the
1144// signature through REASONING_ENCRYPTED_VALUE. This test guards that
1145// StreamProcessor builds one thinking part with both.
1146describe('reasoning delta round-trip through StreamProcessor', () => {
1147 it('surfaces the thinking text once, with the signature attached', async () => {
1148 setupMockSdkClient(thinkingStreamChunks(THINKING_SUMMARY_MODEL))
1149 const adapter = createBytePlusText(THINKING_SUMMARY_MODEL, 'ark-test-key')
1150
1151 const processor = new StreamProcessor()
1152 for await (const chunk of adapter.chatStream({
1153 threadId: 'thread-1',
1154 model: THINKING_SUMMARY_MODEL,
1155 messages: [{ role: 'user', content: 'Say hi' }],
1156 logger: testLogger,
1157 })) {
1158 processor.processChunk(chunk)
1159 }
1160
1161 const thinkingParts = processor
1162 .getMessages()
1163 .flatMap((message) => message.parts ?? [])
1164 .filter((part) => part.type === 'thinking')
1165
1166 expect(thinkingParts).toHaveLength(1)
1167 // Not 'The user wants a greeting.The user wants a greeting.'
1168 expect(thinkingParts[0]).toMatchObject({
1169 content: 'The user wants a greeting.',
1170 signature: ENCRYPTED_BLOB,
1171 })
1172 })
1173})