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

byteplus.test.ts

810 lines27.5 KB

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