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