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

byteplus.test.ts

771 lines26.3 KB

1import { describe, expect, it, vi } from 'vitest'
2​
3import { findDanglingRefs } from '#/server/ingest/bundle.ts'
4import { classifyAndBundle } from '#/server/ingest/sync.ts'
5import { cardRequestParamsOk } from '#/server/rate-card.ts'
6import {
7 arkChatCapabilities,
8 arkTaskActivity,
9 byteplusProvider,
10} from './byteplus.ts'
11import {
12 BYTEPLUS_MODEL_LIST_URL,
13 BYTEPLUS_PRICING_URL,
14 BYTEPLUS_VIDEO_GUIDE_URL,
15 compileSeedreamProCard,
16} from './byteplus-pricing.ts'
17import { BYTEPLUS_REASONING_URL } from './reasoning-config.ts'
18​
19/**
20 * One chat, video, and image row, enough for listModels to attach cards
21 * without fetching the live pricing page (that fetch races other tests'
22 * fetch stubs).
23 */
24function pricingFixtureHtml(): string {
25 return docFixtureHtml(PRICING_TABLES)
27​
28/** The tutorial's model and pixel tables, one Seedance 1.0 row each. */
29function guideFixtureHtml(): string {
30 return docFixtureHtml([
31 [
32 ['Model name', '', 'Seedance 1.0 Pro'],
33 ['Model ID', '', 'seedance-1-0-pro-250528'],
34 ['', 'Frame rate', '24 fps'],
35 ],
36 [
37 ['Resolution', 'Aspect ratio', 'Seedance 1.0 series'],
38 ['1080p', '16:9', '1920×1088'],
39 ],
40 ])
42​
43/** The thinking page: one effort list and one supported-models row. */
44function reasoningFixtureMarkdown(): string {
45 return [
46 '## Adjust chain-of-thought length',
47 '',
48 '* `minimal`: Turns off reasoning and answers directly.',
49 '* `high`: Deep analysis.',
50 '',
51 '|Supported models |Default value |',
52 '|---|---|',
53 '|* `seed-2-0-lite-260428` |`high` |',
54 '',
55 '## Pass thinking content back',
56 ].join('\n')
58​
59/** Model list alias for the lite Seedream row the pricing fixture names. */
60function modelListFixtureHtml(): string {
61 const data = {
62 '0': {
63 ops: [
64 {
65 insert:
66 'seedream-5-0-260128\n(also supports: seedream-5-0-lite-260128)\n',
67 },
68 ],
69 },
70 }
71 const router = {
72 loaderData: { page: { curDoc: { Content: JSON.stringify({ data }) } } },
73 }
74 return `<script>window._ROUTER_DATA = ${JSON.stringify(router)}</script>`
76​
77/** Pages the provider fetches besides the Ark listing, by URL. */
78const DOC_FIXTURES: Record<string, () => string> = {
79 [BYTEPLUS_PRICING_URL]: pricingFixtureHtml,
80 [BYTEPLUS_VIDEO_GUIDE_URL]: guideFixtureHtml,
81 [BYTEPLUS_REASONING_URL]: reasoningFixtureMarkdown,
82 [BYTEPLUS_MODEL_LIST_URL]: modelListFixtureHtml,
84​
85const PRICING_TABLES = (() => {
86 const chat = [
87 'Model ID',
88 'Pricing tiers (K tokens)',
89 'Input (non-audio) (USD/M tokens)',
90 'Input (audio) (USD/M tokens)',
91 'Cache-storage (USD/M tokens/Hour)',
92 'Cache-hit input (non-audio) (USD/M tokens)',
93 'Cache-hit input (audio) (USD/M tokens)',
94 'Output (USD/M tokens)',
95 ]
96 const tables: Array<Array<Array<string>>> = [
97 [
98 chat,
99 ['seed-2-0-pro-260328', '-', '0.50', '-', '0.0083', '0.10', '-', '3.00'],
100 ],
101 [
102 [
103 'Model ID',
104 'Online inference (USD / M tokens)',
105 'Offline inference (USD / M tokens)',
106 ],
107 ['seedance-1-0-pro-250528', '2.5', '1.25'],
108 ],
109 [
110 [
111 'Model ID',
112 'Input image price (USD / image)',
113 'Output image price (USD / image)',
114 ],
115 ['seedream-5-0-lite-260128', 'Free', '0.035'],
116 ['seedream-4-5-251128', 'Free', '0.04'],
117 ['seedream-4-0-250828', 'Free', '0.03'],
118 ],
119 ]
120 return tables
121})()
122​
123function docFixtureHtml(tables: Array<Array<Array<string>>>): string {
124 const data: Record<string, unknown> = {
125 '0': {
126 ops: tables.map((_, t) => ({
127 insert: '*',
128 attributes: { aceTable: `rows${t} cols${t}` },
129 })),
130 },
131 }
132 tables.forEach((body, t) => {
133 data[`rows${t}`] = {
134 ops: body.map((_, index) => ({ insert: { id: `t${t}r${index}` } })),
135 zoneType: 'R',
136 }
137 data[`cols${t}`] = {
138 ops: (body[0] ?? []).map((_, index) => ({
139 insert: { id: `t${t}c${index}` },
140 })),
141 zoneType: 'C',
142 }
143 body.forEach((cells, row) => {
144 cells.forEach((text, column) => {
145 data[`xt${t}r${row}xt${t}c${column}`] = {
146 ops: [
147 { insert: '*', attributes: { lmkr: '1' } },
148 { insert: `${text}\n` },
149 ],
150 }
151 })
152 })
153 })
154 const router = {
155 loaderData: { page: { curDoc: { Content: JSON.stringify({ data }) } } },
156 }
157 return `<script>window._ROUTER_DATA = ${JSON.stringify(router)}</script>`
159​
160/**
161 * Minimal stand-ins for the four `service/arkruntime/model` files fetchSpec
162 * pulls — enough Go to define every endpoint root and its closure.
163 */
164const GO_FIXTURES: Record<string, string> = {
165 'chat_completion.go': `
166type ThinkingType string
167const (
168 ThinkingTypeEnabled ThinkingType = "enabled"
169 ThinkingTypeDisabled ThinkingType = "disabled"
171type Thinking struct {
172 Type ThinkingType \`json:"type"\`
174type ChatCompletionMessage struct {
175 Role string \`json:"role"\`
176 Content string \`json:"content,omitempty"\`
178type CreateChatCompletionRequest struct {
179 Model string \`json:"model"\`
180 Messages []*ChatCompletionMessage \`json:"messages"\`
181 MaxTokens *int \`json:"max_tokens,omitempty"\`
182 Thinking *Thinking \`json:"thinking,omitempty"\`
183 ServiceTier *string \`json:"service_tier,omitempty"\`
185type ChatCompletionResponse struct {
186 ID string \`json:"id"\`
187 Model string \`json:"model"\`
188 Usage Usage \`json:"usage"\`
190`,
191 'images.go': `
192type GenerateImagesRequest struct {
193 Model string \`json:"model"\`
194 Prompt string \`json:"prompt"\`
195 Image interface{} \`json:"image,omitempty"\`
196 Size *string \`json:"size,omitempty"\`
197 Watermark *bool \`json:"watermark,omitempty"\`
199type ImagesResponse struct {
200 Model string \`json:"model"\`
202`,
203 'content_generation.go': `
204type CreateContentGenerationContentItem struct {
205 Type string \`json:"type"\`
206 Text *string \`json:"text,omitempty"\`
208type ExtraBody map[string]interface{}
209type CreateContentGenerationTaskRequest struct {
210 Model string \`json:"model"\`
211 Content []*CreateContentGenerationContentItem \`json:"content"\`
212 Resolution *string \`json:"resolution,omitempty"\`
213 ExtraBody \`json:"-"\`
215type CreateContentGenerationTaskResponse struct {
216 ID string \`json:"id"\`
218type GetContentGenerationTaskResponse struct {
219 ID string \`json:"id"\`
220 Status string \`json:"status"\`
221 Content Content \`json:"content"\`
223type Content struct {
224 VideoURL string \`json:"video_url"\`
226`,
227 'common.go': `
228type Usage struct {
229 PromptTokens int \`json:"prompt_tokens"\`
230 TotalTokens int \`json:"total_tokens"\`
232`,
234​
235/** Serve the Go fixtures (or fail them) for the duration of `run`. */
236async function withGoSdk<T>(
237 mode: 'ok' | 'unreachable',
238 run: () => Promise<T>,
239): Promise<{
240 result: T
241 urls: Array<string>
242 authorizations: Array<string | null>
243}> {
244 const original = globalThis.fetch
245 const urls: Array<string> = []
246 const authorizations: Array<string | null> = []
247 globalThis.fetch = ((url: string, init?: RequestInit) => {
248 const href = String(url)
249 urls.push(href)
250 authorizations.push(new Headers(init?.headers).get('Authorization'))
251 if (mode === 'unreachable') return Promise.reject(new Error('network down'))
252 const file = Object.keys(GO_FIXTURES).find((f) => href.endsWith(f))
253 return Promise.resolve(
254 file
255 ? new Response(GO_FIXTURES[file])
256 : new Response('not found', { status: 404 }),
257 )
258 }) as typeof fetch
259 try {
260 return { result: await run(), urls, authorizations }
261 } finally {
262 globalThis.fetch = original
263 }
265​
266describe('byteplus spec generated from the Go SDK', () => {
267 it('classifies and bundles the generation endpoints without warnings', async () => {
268 const {
269 result: fetched,
270 urls,
271 authorizations,
272 } = await withGoSdk('ok', () => byteplusProvider.fetchSpec({}))
273 // All four model files come from the SDK's default branch.
274 expect(urls).toHaveLength(4)
275 for (const url of urls) {
276 expect(url).toMatch(
277 /^https:\/\/raw\.githubusercontent\.com\/byteplus-sdk\/byteplus-go-sdk-v2\/main\/service\/arkruntime\/model\/\w+\.go$/,
278 )
279 }
280 expect(fetched.warnings ?? []).toEqual([])
281 expect(fetched.specs).toHaveLength(2)
282 // Ark is provenanced to the SDK; Seed Speech stays on the docs URL.
283 expect(fetched.sources[0]?.url).toBe(
284 'https://github.com/byteplus-sdk/byteplus-go-sdk-v2/tree/main/service/arkruntime/model',
285 )
286 expect(fetched.sources[1]?.url).toMatch(/^https:\/\/docs\.byteplus\.com\//)
287 expect(authorizations).toEqual([null, null, null, null])
288 for (const source of fetched.sources) {
289 expect(source.hash).toMatch(/^[0-9a-f]{64}$/)
290 }
291​
292 const { endpoints, warnings } = classifyAndBundle(byteplusProvider, fetched)
293 expect(warnings).toEqual([])
294 expect(endpoints.map((e) => [e.dbId, e.activity]).sort()).toEqual([
295 ['byteplus/auc/bigmodel/recognize/flash', 'audio'],
296 ['byteplus/chat/completions', 'chat'],
297 ['byteplus/contents/generations/tasks', 'video'],
298 ['byteplus/contents/generations/tasks/{id}', 'video'],
299 ['byteplus/images/generations', 'image'],
300 ['byteplus/tts/create', 'audio'],
301 ])
302​
303 for (const endpoint of endpoints) {
304 expect(endpoint.input, endpoint.dbId).toBeDefined()
305 expect(endpoint.output, endpoint.dbId).toBeDefined()
306 if (endpoint.input) expect(findDanglingRefs(endpoint.input)).toEqual([])
307 if (endpoint.output) expect(findDanglingRefs(endpoint.output)).toEqual([])
308 }
309​
310 const chat = endpoints.find((e) => e.dbId === 'byteplus/chat/completions')
311 expect(chat?.input?.required).toEqual(['model', 'messages'])
312 const video = endpoints.find(
313 (e) => e.dbId === 'byteplus/contents/generations/tasks',
314 )
315 expect(video?.input?.required).toEqual(['model', 'content'])
316 const task = endpoints.find(
317 (e) => e.dbId === 'byteplus/contents/generations/tasks/{id}',
318 )
319 expect(task?.method).toBe('GET')
320 expect(task?.input?.required).toEqual(['id'])
321 const defs = task?.output?.$defs as
322 | Record<string, { properties?: Record<string, unknown> }>
323 | undefined
324 expect(defs?.Content?.properties?.video_url).toMatchObject({
325 type: 'string',
326 })
327 })
328​
329 it('re-applies curated fields and descriptions the SDK omits', async () => {
330 const { result: fetched } = await withGoSdk('ok', () =>
331 byteplusProvider.fetchSpec({}),
332 )
333 const { endpoints } = classifyAndBundle(byteplusProvider, fetched)
334 const chat = endpoints.find((e) => e.dbId === 'byteplus/chat/completions')
335 const props = chat?.input?.properties as Record<
336 string,
337 Record<string, unknown>
338 >
339 // Present in the fixture, so straight from the SDK.
340 expect(props.thinking).toBeDefined()
341 // Absent from the SDK entirely — restored from the curated list.
342 expect(props.reasoning_effort).toMatchObject({ type: 'string' })
343 expect(props.top_k).toMatchObject({ type: 'integer' })
344 expect(props.seed).toMatchObject({ type: 'integer' })
345 // Curated prose beats the (here absent) Go doc comment.
346 expect(String(props.model?.description)).toContain('Ark model id')
347​
348 const image = endpoints.find(
349 (e) => e.dbId === 'byteplus/images/generations',
350 )
351 const imageProps = image?.input?.properties as Record<
352 string,
353 Record<string, unknown>
354 >
355 expect(String(imageProps.watermark?.description)).toContain(
356 'DEFAULTS TO TRUE',
357 )
358 })
359​
360 it('falls back to the embedded document when the SDK is unreachable', async () => {
361 const { result: fetched } = await withGoSdk('unreachable', () =>
362 byteplusProvider.fetchSpec({}),
363 )
364 expect(fetched.specs).toHaveLength(2)
365 expect(fetched.sources[0]?.url).toMatch(/^https:\/\/docs\.byteplus\.com\//)
366 expect(fetched.warnings?.[0]).toContain('served the embedded Ark document')
367​
368 // Degraded freshness, not a degraded service: all five endpoints survive.
369 const { endpoints, warnings } = classifyAndBundle(byteplusProvider, fetched)
370 expect(warnings).toEqual([])
371 expect(endpoints).toHaveLength(6)
372 })
373​
374 it.each(['ok', 'unreachable'] as const)(
375 'images schema (%s SDK) carries every request field the Seedream 5.0 pro card reads',
376 async (mode) => {
377 const { result: fetched } = await withGoSdk(mode, () =>
378 byteplusProvider.fetchSpec({}),
379 )
380 const image = classifyAndBundle(byteplusProvider, fetched).endpoints.find(
381 (e) => e.dbId === 'byteplus/images/generations',
382 )
383 const props = Object.keys(image?.input?.properties ?? {})
384 const card = compileSeedreamProCard(
385 {
386 extraInput: 0.003,
387 maxLowPixels: 2.61e6,
388 lowLevel: '1.5K',
389 low: 0.045,
390 high: 0.09,
391 },
392 {
393 url: BYTEPLUS_PRICING_URL,
394 hash: 'a'.repeat(64),
395 extractedAt: '2026-10-02T00:00:00Z',
396 },
397 )
398 // The write gate refuses a card whose request param the schema lacks.
399 expect(card && cardRequestParamsOk(card, new Set(props))).toBe(true)
400 },
401 )
402​
403 it('derives identical content hashes on every build (sync idempotence)', async () => {
404 const { result: a } = await withGoSdk('ok', () =>
405 byteplusProvider.fetchSpec({}),
406 )
407 const { result: b } = await withGoSdk('ok', () =>
408 byteplusProvider.fetchSpec({}),
409 )
410 expect(a.sources.map((s) => s.hash)).toEqual(b.sources.map((s) => s.hash))
411 })
412​
413 it('does not send GITHUB_TOKEN to raw.githubusercontent.com', async () => {
414 const { urls, authorizations } = await withGoSdk('ok', () =>
415 byteplusProvider.fetchSpec({ GITHUB_TOKEN: 'ghp_test' }),
416 )
417 expect(urls).toHaveLength(4)
418 for (const url of urls) {
419 expect(url.startsWith('https://raw.githubusercontent.com/')).toBe(true)
420 }
421 expect(authorizations).toEqual([null, null, null, null])
422 })
423})
424​
425/** Keyless listModels with each fixture page swapped by URL (`null`: 503). */
426async function listWith(pages: Record<string, (() => string) | null>) {
427 const original = globalThis.fetch
428 globalThis.fetch = ((url: string) => {
429 const href = String(url)
430 if (href in pages) {
431 const page = pages[href]
432 return Promise.resolve(
433 page ? new Response(page()) : new Response('down', { status: 503 }),
434 )
435 }
436 const doc = DOC_FIXTURES[href]
437 if (doc) return Promise.resolve(new Response(doc()))
438 throw new Error(`Unmocked native source in listWith: ${href}`)
439 }) as typeof fetch
440 const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
441 try {
442 return await byteplusProvider.listModels({})
443 } finally {
444 globalThis.fetch = original
445 warn.mockRestore()
446 }
448​
449describe('byteplus pricing pages failing', () => {
450 it('publishes billed-only Seedance cards when the tutorial is down', async () => {
451 const { models } = await listWith({
452 [BYTEPLUS_PRICING_URL]: pricingFixtureHtml,
453 [BYTEPLUS_VIDEO_GUIDE_URL]: null,
454 [BYTEPLUS_MODEL_LIST_URL]: modelListFixtureHtml,
455 })
456 const seedance = models.find((m) => m.rawId === 'seedance-1-0-pro-250528')
457 expect(seedance?.pricing).toMatchObject({
458 inputs: { completion_tokens: { bound: 'usage' } },
459 })
460 expect(seedance?.pricing).not.toMatchObject({
461 inputs: { completion_tokens: { estimate: expect.anything() as object } },
462 })
463 expect(
464 models.find((m) => m.rawId === 'seed-2-0-pro-260328')?.pricing,
465 ).toBeTruthy()
466 })
467​
468 it('throws when the pricing page loses a table, keeping stored cards', async () => {
469 const withoutVideo = () =>
470 docFixtureHtml(
471 PRICING_TABLES.filter(
472 (table) => !table[0]?.includes('Online inference (USD / M tokens)'),
473 ),
474 )
475 await expect(
476 listWith({
477 [BYTEPLUS_PRICING_URL]: withoutVideo,
478 [BYTEPLUS_VIDEO_GUIDE_URL]: guideFixtureHtml,
479 [BYTEPLUS_MODEL_LIST_URL]: modelListFixtureHtml,
480 }),
481 ).rejects.toThrow(/video\): parsed 0/)
482 })
483})
484​
485describe('byteplus curated models (no ARK_API_KEY)', () => {
486 it('lists the ported @tanstack/ai-byteplus catalog with metadata', async () => {
487 const original = globalThis.fetch
488 globalThis.fetch = ((url: string, init?: RequestInit) => {
489 const doc = DOC_FIXTURES[String(url)]
490 if (doc) return Promise.resolve(new Response(doc()))
491 return original(url, init)
492 }) as typeof fetch
493 const { models, skipped } = await byteplusProvider
494 .listModels({})
495 .finally(() => {
496 globalThis.fetch = original
497 })
498 // Keyless is a supported mode, not a skip: the embedded catalog stands in.
499 expect(skipped).toBeUndefined()
500 // 18 chat + 7 video + 5 image + 2 speech.
501 expect(models).toHaveLength(32)
502 expect(new Set(models.map((m) => m.rawId)).size).toBe(32)
503​
504 const byActivity = new Map<string, number>()
505 for (const m of models) {
506 expect(m.activity, m.rawId).toBeTruthy()
507 byActivity.set(
508 m.activity ?? '',
509 (byActivity.get(m.activity ?? '') ?? 0) + 1,
510 )
511 }
512 expect(byActivity.get('chat')).toBe(18)
513 expect(byActivity.get('video')).toBe(7)
514 expect(byActivity.get('image')).toBe(5)
515 expect(byActivity.get('audio')).toBe(2)
516​
517 const seedance = models.find((m) => m.rawId === 'seedance-1-5-pro-251215')
518 expect(seedance?.releasedAt).toBe(Date.parse('2025-12-15') / 1000)
519 // Video and image rows from the pricing page become cards.
520 const priced = (rawId: string) =>
521 models.find((m) => m.rawId === rawId)?.pricing
522 expect(priced('seedance-1-0-pro-250528')).toMatchObject({
523 inputs: {
524 completion_tokens: {
525 bound: 'usage',
526 estimate: { source: { url: BYTEPLUS_VIDEO_GUIDE_URL } },
527 },
528 },
529 })
530 expect(priced('seedream-4-5-251128')).toMatchObject({
531 inputs: { generated_images: { bound: 'usage' } },
532 })
533 // Model list: seedream-5-0-260128 also supports the priced lite row.
534 expect(priced('seedream-5-0-260128')).toMatchObject({
535 inputs: { generated_images: { bound: 'usage' } },
536 })
537 // No speech table on the ModelArk pricing page.
538 expect(priced('seed-asr')).toBeUndefined()
539 expect(priced('seed-audio-1.0')).toBeUndefined()
540 // Undated Seed Speech ids keep their poll-time firstSeenAt.
541 const asr = models.find((m) => m.rawId === 'seed-asr')
542 expect(asr?.releasedAt).toBeNull()
543​
544 const glm = models.find((m) => m.rawId === 'glm-5-2-260617')
545 expect(glm?.contextWindow).toBe(1_024_000)
546 expect(glm?.maxOutput).toBe(128_000)
547 })
548})
549​
550describe('ark task_type → activity', () => {
551 it('prefers generation task types over the modality-input ones', () => {
552 // Chat models that accept audio input carry SpeechToText alongside
553 // TextGeneration; they are chat endpoints, not transcription ones.
554 expect(
555 arkTaskActivity([
556 'TextGeneration',
557 'VisualQuestionAnswering',
558 'SpeechToText',
559 ]),
560 ).toBe('chat')
561 expect(arkTaskActivity(['ImageToVideo', 'TextToVideo'])).toBe('video')
562 expect(arkTaskActivity(['MultimodalToVideo', 'VideoEditing'])).toBe('video')
563 expect(arkTaskActivity(['ImageToImage', 'TextToImage'])).toBe('image')
564 expect(
565 arkTaskActivity([
566 'ImageEmbedding',
567 'MultimodalEmbedding',
568 'TextEmbedding',
569 ]),
570 ).toBe('embeddings')
571 expect(arkTaskActivity(['SpeechToText'])).toBe('audio')
572 // 3D-generation models report no task_type at all.
573 expect(arkTaskActivity([])).toBeNull()
574 expect(arkTaskActivity(undefined)).toBeNull()
575 expect(arkTaskActivity(['SomethingNew'])).toBeNull()
576 })
577})
578​
579describe('byteplus live models (ARK_API_KEY set)', () => {
580 // Verbatim rows from Ark's GET /models, captured 2026-08-12.
581 const ARK_PAGE = {
582 data: [
583 {
584 id: 'seed-2-0-lite-260428',
585 name: 'seed-2-0-lite',
586 created: 1_778_162_292,
587 domain: 'VLM',
588 task_type: [
589 'TextGeneration',
590 'VisualQuestionAnswering',
591 'SpeechToText',
592 ],
593 modalities: {
594 input_modalities: ['text', 'image', 'video', 'audio'],
595 output_modalities: ['text'],
596 },
597 token_limits: {
598 context_window: 262_144,
599 max_output_token_length: 131_072,
600 max_reasoning_token_length: 131_072,
601 },
602 features: {
603 structured_outputs: { json_object: true, json_schema: true },
604 tools: { function_calling: true },
605 },
606 },
607 {
608 id: 'kimi-k2-250905',
609 name: 'kimi-k2',
610 created: 1_757_927_317,
611 status: 'Shutdown',
612 domain: 'LLM',
613 task_type: ['TextGeneration'],
614 modalities: { input_modalities: ['text'], output_modalities: ['text'] },
615 token_limits: {
616 context_window: 262_144,
617 max_output_token_length: 32_768,
618 },
619 features: {},
620 },
621 {
622 id: 'hitem3d-2-0-251223',
623 name: 'hitem3d-2-0',
624 created: 1_774_855_941,
625 domain: '3DGeneration',
626 modalities: {},
627 token_limits: {},
628 features: {},
629 },
630 ],
631 }
632​
633 function withStubbedFetch<T>(body: unknown, run: () => Promise<T>) {
634 const original = globalThis.fetch
635 const calls: Array<{ url: string; auth: string | null }> = []
636 globalThis.fetch = ((url: string, init?: RequestInit) => {
637 const href = String(url)
638 calls.push({
639 url: href,
640 auth: new Headers(init?.headers).get('authorization'),
641 })
642 const doc = DOC_FIXTURES[href]
643 if (doc) return Promise.resolve(new Response(doc()))
644 if (!href.includes('/api/v3/models')) return original(url, init)
645 return Promise.resolve(new Response(JSON.stringify(body)))
646 }) as typeof fetch
647 return run()
648 .then((result) => ({ result, calls }))
649 .finally(() => {
650 globalThis.fetch = original
651 })
652 }
653​
654 it('maps live rows and sends the bearer key', async () => {
655 const { result, calls } = await withStubbedFetch(ARK_PAGE, () =>
656 byteplusProvider.listModels({ ARK_API_KEY: 'ark-test' }),
657 )
658 const ark = calls.find((call) => call.url.includes('/api/v3/models'))
659 expect(ark?.url).toBe(
660 'https://ark.ap-southeast.bytepluses.com/api/v3/models',
661 )
662 expect(ark?.auth).toBe('Bearer ark-test')
663​
664 const seed = result.models.find((m) => m.rawId === 'seed-2-0-lite-260428')
665 expect(seed?.activity).toBe('chat')
666 expect(seed?.displayName).toBe('seed-2-0-lite')
667 expect(seed?.contextWindow).toBe(262_144)
668 expect(seed?.maxOutput).toBe(131_072)
669 // Upstream `created` beats the id-suffix fallback.
670 expect(seed?.releasedAt).toBe(1_778_162_292)
671 expect(seed?.modalities).toEqual({
672 input: ['text', 'image', 'video', 'audio'],
673 output: ['text'],
674 })
675 expect(seed?.deprecated).toBe(false)
676​
677 // Shutdown and Retiring both read as deprecated.
678 expect(
679 result.models.find((m) => m.rawId === 'kimi-k2-250905')?.deprecated,
680 ).toBe(true)
681 // 3D generation is outside our taxonomy.
682 expect(
683 result.models.find((m) => m.rawId === 'hitem3d-2-0-251223')?.activity,
684 ).toBeNull()
685 })
686​
687 it('projects chat features onto the shared string[] vocabulary', async () => {
688 const { result } = await withStubbedFetch(ARK_PAGE, () =>
689 byteplusProvider.listModels({ ARK_API_KEY: 'ark-test' }),
690 )
691 // Ark advertises json_schema here, but a real request 400s: the probe
692 // verdict wins, so response_format stays and structured_outputs goes.
693 expect(
694 result.models.find((m) => m.rawId === 'seed-2-0-lite-260428')
695 ?.capabilities,
696 ).toEqual(['tools', 'tool_choice', 'reasoning', 'response_format'])
697 // Every chat row, curated gap-fillers included, is a string[].
698 for (const m of result.models.filter((row) => row.activity === 'chat')) {
699 expect(Array.isArray(m.capabilities)).toBe(true)
700 }
701 })
702​
703 it('keeps json_object-only models off structured_outputs', () => {
704 expect(
705 arkChatCapabilities({
706 id: 'glm-5-3-flash-260828',
707 token_limits: { max_reasoning_token_length: 131_072 },
708 features: {
709 structured_outputs: { json_object: true, json_schema: false },
710 tools: { function_calling: true },
711 cache: { prefix_cache: true, session_cache: true },
712 },
713 }),
714 ).toEqual(['tools', 'tool_choice', 'reasoning', 'response_format'])
715 })
716​
717 it('fills the gaps the listing omits from the curated catalog', async () => {
718 const { result } = await withStubbedFetch(ARK_PAGE, () =>
719 byteplusProvider.listModels({ ARK_API_KEY: 'ark-test' }),
720 )
721 const ids = result.models.map((m) => m.rawId)
722 expect(new Set(ids).size).toBe(ids.length)
723 // Seed Speech lives on another host and is in no Ark listing.
724 expect(ids).toContain('seed-audio-1.0')
725 expect(ids).toContain('seed-asr')
726 // Served by Ark but absent from its own listing.
727 expect(ids).toContain('seedream-5-0-lite-260128')
728 // A live row must not be duplicated by its curated twin.
729 expect(ids.filter((id) => id === 'seed-2-0-lite-260428')).toHaveLength(1)
730 })
731})
732​
733describe('byteplus schema provenance', () => {
734 it('grades each endpoint by how its schema was arrived at', async () => {
735 const { result: fetched } = await withGoSdk('ok', () =>
736 byteplusProvider.fetchSpec({}),
737 )
738 const { endpoints } = classifyAndBundle(byteplusProvider, fetched)
739 const by = new Map(
740 endpoints.map((e) => [e.dbId, [e.derivation, e.verifiedAt] as const]),
741 )
742 // Ark is re-derived from the Go SDK every sync, so it self-heals and
743 // carries no point-in-time claim.
744 expect(by.get('byteplus/chat/completions')).toEqual(['generated', null])
745 expect(by.get('byteplus/images/generations')).toEqual(['generated', null])
746 expect(by.get('byteplus/contents/generations/tasks')).toEqual([
747 'generated',
748 null,
749 ])
750 // Seed Speech is hand-written: TTS was exercised live, ASR never was.
751 expect(by.get('byteplus/tts/create')).toEqual([
752 'probe-verified',
753 '2026-08-12',
754 ])
755 expect(by.get('byteplus/auc/bigmodel/recognize/flash')).toEqual([
756 'docs-derived',
757 null,
758 ])
759 })
760​
761 it('downgrades Ark to a dated claim when it falls back to the embedded doc', async () => {
762 const { result: fetched } = await withGoSdk('unreachable', () =>
763 byteplusProvider.fetchSpec({}),
764 )
765 const { endpoints } = classifyAndBundle(byteplusProvider, fetched)
766 const chat = endpoints.find((e) => e.dbId === 'byteplus/chat/completions')
767 // No longer self-healing, and it says so.
768 expect(chat?.derivation).toBe('probe-verified')
769 expect(chat?.verifiedAt).toBe('2026-07-31')
770 })
771})