Open History to see the last commit
1import { readFileSync } from 'node:fs'
2import { describe, expect, it, vi } from 'vitest'
3
4import { findDanglingRefs } from '#/server/ingest/bundle.ts'
5import {
6 runIngestScope,
7 takeIngestEvents,
8} from '#/server/ingest/ingest-signals.ts'
9import { classifyAndBundle } from '#/server/ingest/sync.ts'
10import { cardRequestParamsOk } from '#/server/rate-card.ts'
11import {
12 arkChatCapabilities,
13 arkTaskActivity,
14 byteplusProvider,
15} from './byteplus.ts'
16import {
17 BYTEPLUS_MODEL_LIST_URL,
18 BYTEPLUS_PRICING_URL,
19 BYTEPLUS_VIDEO_GUIDE_URL,
20 compileSeedreamProCard,
21 parseByteplusMakers,
22} from './byteplus-pricing.ts'
23import type { ByteplusDoc } from './byteplus-pricing.ts'
24import modelListProviders from './fixtures/byteplus-model-list-providers.json'
25import {
26 BYTEPLUS_ASR_PRICING_URL,
27 BYTEPLUS_AUDIO_API_URL,
28 BYTEPLUS_AUDIO_PRICING_URL,
29} from './byteplus-speech-pricing.ts'
30import { SEEDANCE_DURATION_DOCS } from './byteplus-video-duration.ts'
31import { BYTEPLUS_REASONING_URL } from './reasoning-config.ts'
32import { pricingDoc, routerHtml } from './fixtures/byteplus-pricing-doc.ts'
33import type { PricingTable } from './fixtures/byteplus-pricing-doc.ts'
34import { docFixtureHtml } from './fixtures/byteplus-doc.ts'
35
36/**
37 * One chat, video, and image row, enough for listModels to attach cards
38 * without fetching the live pricing page (that fetch races other tests'
39 * fetch stubs).
40 */
41function pricingFixtureHtml(): string {
42 return routerHtml(pricingDoc(PRICING_TABLES))
43}
44
45/** The tutorial's model and pixel tables, one Seedance 1.0 row each. */
46function guideFixtureHtml(): string {
47 return docFixtureHtml([
48 [
49 ['Model name', '', 'Seedance 1.0 Pro'],
50 ['Model ID', '', 'seedance-1-0-pro-250528'],
51 ['', 'Frame rate', '24 fps'],
52 ],
53 [
54 ['Resolution', 'Aspect ratio', 'Seedance 1.0 series'],
55 ['1080p', '16:9', '1920×1088'],
56 ],
57 ])
58}
59
60/** The thinking page: one effort list and one supported-models row. */
61function reasoningFixtureHtml(): string {
62 return docFixtureHtml([
63 '## Adjust chain-of-thought length',
64 'minimal',
65 'high',
66 [
67 ['Supported models', 'Default value'],
68 ['* seed-2-0-lite-260428', 'high'],
69 ],
70 '## Pass thinking content back',
71 ])
72}
73
74/** Model list alias for the lite Seedream row the pricing fixture names. */
75function modelListFixtureHtml(): string {
76 const data = {
77 '0': {
78 ops: [
79 {
80 insert:
81 'seedream-5-0-260128\n(also supports: seedream-5-0-lite-260128)\n',
82 },
83 ],
84 },
85 }
86 const router = {
87 loaderData: { page: { curDoc: { Content: JSON.stringify({ data }) } } },
88 }
89 return `<script>window._ROUTER_DATA = ${JSON.stringify(router)}</script>`
90}
91
92/** Pages the provider fetches besides the Ark listing, by URL. */
93const DOC_FIXTURES: Record<string, () => string> = {
94 [BYTEPLUS_PRICING_URL]: pricingFixtureHtml,
95 [BYTEPLUS_VIDEO_GUIDE_URL]: guideFixtureHtml,
96 [BYTEPLUS_REASONING_URL]: reasoningFixtureHtml,
97 [BYTEPLUS_MODEL_LIST_URL]: modelListFixtureHtml,
98 [BYTEPLUS_AUDIO_PRICING_URL]: () =>
99 docFixtureHtml([
100 [
101 ['Payment', 'Package', 'Fee (USD)', 'Unit', 'Valid Period'],
102 ['Pay-as-you-go', '-', '0.15', 'minute', '-'],
103 ],
104 ]),
105 [BYTEPLUS_AUDIO_API_URL]: () =>
106 docFixtureHtml([
107 'This is also the duration used for billing, with a maximum of 120s.',
108 ]),
109 [BYTEPLUS_ASR_PRICING_URL]: () =>
110 docFixtureHtml([
111 'Audio File ASR Fast Mode:',
112 [
113 ['Payment', 'Package', 'Fee (USD)', 'Unit', 'Valid Period'],
114 ['Pay-as-you-go', '-', '0.36', 'USD / Hour', '-'],
115 ],
116 ]),
117}
118
119const PRICING_TABLES: Array<PricingTable> = [
120 {
121 tab: 'Standard',
122 rows: [
123 [
124 'Provider',
125 'Model ID',
126 'Prompt length',
127 'Input',
128 'Cached input',
129 'Cache storage',
130 'Output',
131 ],
132 [
133 'ByteDance',
134 'seed-2-0-pro-260328',
135 'Not applicable',
136 '$0.50',
137 '$0.10',
138 '$0.0083',
139 '$3.00',
140 ],
141 ],
142 },
143 {
144 tab: 'Input without video',
145 rows: [
146 ['Model', 'Online inference', '', '', 'Offline inference'],
147 ['', '480p and 720p', '1080p', '4K', ''],
148 ['seedance-1-0-pro-250528', '$2.5', '', '', '$1.25'],
149 ],
150 merges: [
151 [[0], [1, 2, 3]],
152 [[2], [1, 2, 3]],
153 ],
154 },
155 {
156 rows: [
157 ['Model ID', 'Input image', 'Output image'],
158 ['seedream-5-0-lite-260128', 'Free', '$0.035'],
159 ['seedream-4-5-251128', 'Free', '$0.04'],
160 ['seedream-4-0-250828', 'Free', '$0.03'],
161 ],
162 },
163]
164
165/**
166 * Minimal stand-ins for the four `service/arkruntime/model` files fetchSpec
167 * pulls — enough Go to define every endpoint root and its closure.
168 */
169const GO_FIXTURES: Record<string, string> = {
170 'chat_completion.go': `
171type ThinkingType string
172const (
173 ThinkingTypeEnabled ThinkingType = "enabled"
174 ThinkingTypeDisabled ThinkingType = "disabled"
175)
176type Thinking struct {
177 Type ThinkingType \`json:"type"\`
178}
179type ChatCompletionMessage struct {
180 Role string \`json:"role"\`
181 Content string \`json:"content,omitempty"\`
182}
183type CreateChatCompletionRequest struct {
184 Model string \`json:"model"\`
185 Messages []*ChatCompletionMessage \`json:"messages"\`
186 MaxTokens *int \`json:"max_tokens,omitempty"\`
187 Thinking *Thinking \`json:"thinking,omitempty"\`
188 ServiceTier *string \`json:"service_tier,omitempty"\`
189}
190type ChatCompletionResponse struct {
191 ID string \`json:"id"\`
192 Model string \`json:"model"\`
193 Usage Usage \`json:"usage"\`
194}
195`,
196 'images.go': `
197type GenerateImagesRequest struct {
198 Model string \`json:"model"\`
199 Prompt string \`json:"prompt"\`
200 Image interface{} \`json:"image,omitempty"\`
201 Size *string \`json:"size,omitempty"\`
202 Watermark *bool \`json:"watermark,omitempty"\`
203}
204type ImagesResponse struct {
205 Model string \`json:"model"\`
206}
207`,
208 'content_generation.go': `
209type CreateContentGenerationContentItem struct {
210 Type string \`json:"type"\`
211 Text *string \`json:"text,omitempty"\`
212}
213type ExtraBody map[string]interface{}
214type CreateContentGenerationTaskRequest struct {
215 Model string \`json:"model"\`
216 Content []*CreateContentGenerationContentItem \`json:"content"\`
217 Resolution *string \`json:"resolution,omitempty"\`
218 ExtraBody \`json:"-"\`
219}
220type CreateContentGenerationTaskResponse struct {
221 ID string \`json:"id"\`
222}
223type GetContentGenerationTaskResponse struct {
224 ID string \`json:"id"\`
225 Status string \`json:"status"\`
226 Content Content \`json:"content"\`
227}
228type Content struct {
229 VideoURL string \`json:"video_url"\`
230}
231`,
232 'common.go': `
233type Usage struct {
234 PromptTokens int \`json:"prompt_tokens"\`
235 TotalTokens int \`json:"total_tokens"\`
236}
237`,
238}
239
240/** Serve the Go fixtures (or fail them) for the duration of `run`. */
241async function withGoSdk<T>(
242 mode: 'ok' | 'unreachable',
243 run: () => Promise<T>,
244): Promise<{
245 result: T
246 urls: Array<string>
247 authorizations: Array<string | null>
248}> {
249 const original = globalThis.fetch
250 const urls: Array<string> = []
251 const authorizations: Array<string | null> = []
252 globalThis.fetch = ((url: string, init?: RequestInit) => {
253 const href = String(url)
254 urls.push(href)
255 authorizations.push(new Headers(init?.headers).get('Authorization'))
256 if (mode === 'unreachable') return Promise.reject(new Error('network down'))
257 const file = Object.keys(GO_FIXTURES).find((f) => href.endsWith(f))
258 return Promise.resolve(
259 file
260 ? new Response(GO_FIXTURES[file])
261 : new Response('not found', { status: 404 }),
262 )
263 }) as typeof fetch
264 try {
265 return { result: await run(), urls, authorizations }
266 } finally {
267 globalThis.fetch = original
268 }
269}
270
271describe('byteplus spec generated from the Go SDK', () => {
272 it('classifies and bundles the generation endpoints without warnings', async () => {
273 const {
274 result: fetched,
275 urls,
276 authorizations,
277 } = await withGoSdk('ok', () => byteplusProvider.fetchSpec({}))
278 // All four model files come from the SDK's default branch.
279 expect(urls).toHaveLength(4)
280 for (const url of urls) {
281 expect(url).toMatch(
282 /^https:\/\/raw\.githubusercontent\.com\/byteplus-sdk\/byteplus-go-sdk-v2\/main\/service\/arkruntime\/model\/\w+\.go$/,
283 )
284 }
285 expect(fetched.warnings ?? []).toEqual([])
286 expect(fetched.specs).toHaveLength(2)
287 // Ark is provenanced to the SDK; Seed Speech stays on the docs URL.
288 expect(fetched.sources[0]?.url).toBe(
289 'https://github.com/byteplus-sdk/byteplus-go-sdk-v2/tree/main/service/arkruntime/model',
290 )
291 expect(fetched.sources[1]?.url).toMatch(/^https:\/\/docs\.byteplus\.com\//)
292 expect(authorizations).toEqual([null, null, null, null])
293 for (const source of fetched.sources) {
294 expect(source.hash).toMatch(/^[0-9a-f]{64}$/)
295 }
296
297 const { endpoints, warnings } = classifyAndBundle(byteplusProvider, fetched)
298 expect(warnings).toEqual([])
299 expect(
300 endpoints
301 .map((e): [string, string] => [e.dbId, e.activity])
302 .sort(([aId, aAct], [bId, bAct]) =>
303 aId < bId
304 ? -1
305 : aId > bId
306 ? 1
307 : aAct < bAct
308 ? -1
309 : aAct > bAct
310 ? 1
311 : 0,
312 ),
313 ).toEqual([
314 ['byteplus/auc/bigmodel/recognize/flash', 'audio'],
315 ['byteplus/chat/completions', 'chat'],
316 ['byteplus/contents/generations/tasks', 'video'],
317 ['byteplus/contents/generations/tasks/{id}', 'video'],
318 ['byteplus/contents/generations/tasks/{id}:delete', 'video'],
319 ['byteplus/images/generations', 'image'],
320 ['byteplus/tts/create', 'audio'],
321 ])
322
323 for (const endpoint of endpoints) {
324 expect(endpoint.input, endpoint.dbId).toBeDefined()
325 if (endpoint.method !== 'DELETE') {
326 expect(endpoint.output, endpoint.dbId).toBeDefined()
327 }
328 if (endpoint.input) expect(findDanglingRefs(endpoint.input)).toEqual([])
329 if (endpoint.output) expect(findDanglingRefs(endpoint.output)).toEqual([])
330 }
331
332 const chat = endpoints.find((e) => e.dbId === 'byteplus/chat/completions')
333 expect(chat?.input?.required).toEqual(['model', 'messages'])
334 const video = endpoints.find(
335 (e) => e.dbId === 'byteplus/contents/generations/tasks',
336 )
337 expect(video?.input?.required).toEqual(['model', 'content'])
338 const task = endpoints.find(
339 (e) => e.dbId === 'byteplus/contents/generations/tasks/{id}',
340 )
341 expect(task?.method).toBe('GET')
342 expect(task?.input?.required).toEqual(['id'])
343 const cancel = endpoints.find(
344 (e) => e.dbId === 'byteplus/contents/generations/tasks/{id}:delete',
345 )
346 expect(cancel?.method).toBe('DELETE')
347 expect(cancel?.input?.required).toEqual(['id'])
348 expect(cancel?.output).toBeUndefined()
349 const defs = task?.output?.$defs as
350 | Record<string, { properties?: Record<string, unknown> }>
351 | undefined
352 expect(defs?.Content?.properties?.video_url).toMatchObject({
353 type: 'string',
354 })
355 })
356
357 it('re-applies curated fields and descriptions the SDK omits', async () => {
358 const { result: fetched } = await withGoSdk('ok', () =>
359 byteplusProvider.fetchSpec({}),
360 )
361 const { endpoints } = classifyAndBundle(byteplusProvider, fetched)
362 const chat = endpoints.find((e) => e.dbId === 'byteplus/chat/completions')
363 const props = chat?.input?.properties as Record<
364 string,
365 Record<string, unknown>
366 >
367 // Present in the fixture, so straight from the SDK.
368 expect(props.thinking).toBeDefined()
369 // Absent from the SDK entirely — restored from the curated list.
370 expect(props.reasoning_effort).toMatchObject({ type: 'string' })
371 expect(props.top_k).toMatchObject({ type: 'integer' })
372 expect(props.seed).toMatchObject({ type: 'integer' })
373 // Curated prose beats the (here absent) Go doc comment.
374 expect(String(props.model?.description)).toContain('Ark model id')
375
376 const image = endpoints.find(
377 (e) => e.dbId === 'byteplus/images/generations',
378 )
379 const imageProps = image?.input?.properties as Record<
380 string,
381 Record<string, unknown>
382 >
383 expect(String(imageProps.watermark?.description)).toContain(
384 'DEFAULTS TO TRUE',
385 )
386 })
387
388 it('falls back to the embedded document when the SDK is unreachable', async () => {
389 const { result: fetched } = await withGoSdk('unreachable', () =>
390 byteplusProvider.fetchSpec({}),
391 )
392 expect(fetched.specs).toHaveLength(2)
393 expect(fetched.sources[0]?.url).toMatch(/^https:\/\/docs\.byteplus\.com\//)
394 expect(fetched.warnings?.[0]).toContain('served the embedded Ark document')
395
396 // Degraded freshness, not a degraded service: every endpoint survives.
397 const { endpoints, warnings } = classifyAndBundle(byteplusProvider, fetched)
398 expect(warnings).toEqual([])
399 expect(endpoints).toHaveLength(7)
400 })
401
402 it.each(['ok', 'unreachable'] as const)(
403 'images schema (%s SDK) carries every request field the Seedream 5.0 pro card reads',
404 async (mode) => {
405 const { result: fetched } = await withGoSdk(mode, () =>
406 byteplusProvider.fetchSpec({}),
407 )
408 const image = classifyAndBundle(byteplusProvider, fetched).endpoints.find(
409 (e) => e.dbId === 'byteplus/images/generations',
410 )
411 const props = Object.keys(image?.input?.properties ?? {})
412 const card = compileSeedreamProCard(
413 {
414 extraInput: 0.003,
415 maxLowPixels: 2.61e6,
416 lowLevel: '1.5K',
417 low: 0.045,
418 high: 0.09,
419 },
420 {
421 url: BYTEPLUS_PRICING_URL,
422 hash: 'a'.repeat(64),
423 extractedAt: '2026-10-02T00:00:00Z',
424 },
425 )
426 // The write gate refuses a card whose request param the schema lacks.
427 expect(card && cardRequestParamsOk(card, new Set(props))).toBe(true)
428 },
429 )
430
431 it('derives identical content hashes on every build (sync idempotence)', async () => {
432 const { result: a } = await withGoSdk('ok', () =>
433 byteplusProvider.fetchSpec({}),
434 )
435 const { result: b } = await withGoSdk('ok', () =>
436 byteplusProvider.fetchSpec({}),
437 )
438 expect(a.sources.map((s) => s.hash)).toEqual(b.sources.map((s) => s.hash))
439 })
440
441 it('does not send GITHUB_TOKEN to raw.githubusercontent.com', async () => {
442 const { urls, authorizations } = await withGoSdk('ok', () =>
443 byteplusProvider.fetchSpec({ GITHUB_TOKEN: 'ghp_test' }),
444 )
445 expect(urls).toHaveLength(4)
446 for (const url of urls) {
447 expect(url.startsWith('https://raw.githubusercontent.com/')).toBe(true)
448 }
449 expect(authorizations).toEqual([null, null, null, null])
450 })
451})
452
453/** Keyless listModels with each fixture page swapped by URL (`null`: 503). */
454async function listWith(pages: Record<string, (() => string) | null>) {
455 const original = globalThis.fetch
456 globalThis.fetch = ((url: string) => {
457 const href = String(url)
458 if (href in pages) {
459 const page = pages[href]
460 return Promise.resolve(
461 page ? new Response(page()) : new Response('down', { status: 503 }),
462 )
463 }
464 const doc = DOC_FIXTURES[href]
465 if (doc) return Promise.resolve(new Response(doc()))
466 throw new Error(`Unmocked native source in listWith: ${href}`)
467 }) as typeof fetch
468 const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
469 try {
470 return await byteplusProvider.listModels({})
471 } finally {
472 globalThis.fetch = original
473 warn.mockRestore()
474 }
475}
476
477describe('byteplus pricing pages failing', () => {
478 it('publishes billed-only Seedance cards when the tutorial is down', async () => {
479 const { models } = await listWith({
480 [BYTEPLUS_PRICING_URL]: pricingFixtureHtml,
481 [BYTEPLUS_VIDEO_GUIDE_URL]: null,
482 [BYTEPLUS_MODEL_LIST_URL]: modelListFixtureHtml,
483 })
484 const seedance = models.find((m) => m.rawId === 'seedance-1-0-pro-250528')
485 expect(seedance?.pricing).toMatchObject({
486 inputs: { completion_tokens: { bound: 'usage' } },
487 })
488 expect(seedance?.pricing).not.toMatchObject({
489 inputs: { completion_tokens: { estimate: expect.anything() as object } },
490 })
491 expect(
492 models.find((m) => m.rawId === 'seed-2-0-pro-260328')?.pricing,
493 ).toBeTruthy()
494 })
495
496 it('throws when the pricing page loses a table, keeping stored cards', async () => {
497 const withoutVideo = () =>
498 routerHtml(
499 pricingDoc(
500 PRICING_TABLES.filter((table) => table.rows[0]?.[0] !== 'Model'),
501 ),
502 )
503 await expect(
504 listWith({
505 [BYTEPLUS_PRICING_URL]: withoutVideo,
506 [BYTEPLUS_VIDEO_GUIDE_URL]: guideFixtureHtml,
507 [BYTEPLUS_MODEL_LIST_URL]: modelListFixtureHtml,
508 }),
509 ).rejects.toThrow(/video\): parsed 0/)
510 })
511})
512
513describe('byteplus maker (#710)', () => {
514 const doc = modelListProviders as ByteplusDoc
515
516 it('reads the merged Provider cells of the model list (2026-11-21)', () => {
517 const { makers, named } = parseByteplusMakers(doc)
518 expect(makers.get('seed-2-0-lite-260428')).toBe('ByteDance')
519 expect(makers.get('deepseek-v4-pro-ga-260813')).toBe('DeepSeek')
520 expect(makers.get('deepseek-v4-pro-260425')).toBe('DeepSeek')
521 expect(makers.get('glm-5-3-flash-260828')).toBe('Z.ai')
522 expect(makers.get('glm-5-2-260617')).toBe('Z.ai')
523 expect(makers.get('hitem3d-2-0-251223')).toBe('Hitem3D')
524 expect(makers.has('gpt-oss-120b-250805')).toBe(false)
525 // A Model ID column with no Provider names the id and no maker.
526 expect(makers.has('seedance-1-0-pro-250528')).toBe(false)
527 expect(named.has('seedance-1-0-pro-250528')).toBe(true)
528 // Absent from every table: the page says nothing about it.
529 expect(named.has('gpt-oss-120b-250805')).toBe(false)
530 })
531
532 it('throws on a list with no Provider table', () => {
533 expect(() => parseByteplusMakers({ data: { '0': { ops: [] } } })).toThrow(
534 /parsed 0 model rows/,
535 )
536 })
537
538 it('names the maker, says when a listed id has none, keeps it when down', async () => {
539 const pick = (models: Array<{ rawId: string; maker?: unknown }>) =>
540 Object.fromEntries(
541 models
542 .filter((m) =>
543 [
544 'glm-5-2-260617',
545 'gpt-oss-120b-250805',
546 'seedance-1-0-pro-250528',
547 ].includes(m.rawId),
548 )
549 .map((m) => [m.rawId, m]),
550 )
551 const read = pick(
552 (
553 await listWith({
554 [BYTEPLUS_MODEL_LIST_URL]: () => routerHtml(doc),
555 })
556 ).models,
557 )
558 expect(read['glm-5-2-260617']).toMatchObject({
559 maker: 'Z.ai',
560 factSources: {
561 maker: { sourceUrl: BYTEPLUS_MODEL_LIST_URL, path: 'Provider' },
562 },
563 })
564 expect(read['seedance-1-0-pro-250528']).toMatchObject({
565 maker: null,
566 factSources: { maker: { path: 'unstated' } },
567 })
568 // The list never names gpt-oss: no maker and no source either way.
569 expect(read['gpt-oss-120b-250805']?.maker).toBeUndefined()
570 expect(
571 (read['gpt-oss-120b-250805'] as { factSources?: { maker?: unknown } })
572 .factSources?.maker,
573 ).toBeUndefined()
574 const down = await listWith({ [BYTEPLUS_MODEL_LIST_URL]: null })
575 expect(
576 down.models.find((m) => m.rawId === 'glm-5-2-260617')?.absent,
577 ).toMatchObject({ maker: 'unavailable' })
578 })
579})
580
581describe('byteplus Seed Speech cards (#672)', () => {
582 it('prices both rows from the voice billing pages', async () => {
583 const { models } = await listWith({})
584 const audio = models.find((m) => m.rawId === 'seed-audio-1.0')
585 expect(audio?.absent?.pricing).toBeUndefined()
586 expect(audio?.pricing).toMatchObject({
587 inputs: {
588 original_duration: {
589 bound: 'usage',
590 estimate: { value: 120, source: { url: BYTEPLUS_AUDIO_API_URL } },
591 },
592 },
593 source: { url: BYTEPLUS_AUDIO_PRICING_URL },
594 })
595 expect(models.find((m) => m.rawId === 'seed-asr')?.pricing).toMatchObject({
596 inputs: { audio_seconds: { bound: 'usage' } },
597 source: { url: BYTEPLUS_ASR_PRICING_URL },
598 })
599 })
600
601 it('keeps the stored card and reports the page when one is down', async () => {
602 const { models, docsFailures } = await listWith({
603 [BYTEPLUS_AUDIO_API_URL]: null,
604 })
605 const audio = models.find((m) => m.rawId === 'seed-audio-1.0')
606 expect(audio?.pricing).toBeFalsy()
607 expect(audio?.absent?.pricing).toBe('unavailable')
608 expect(docsFailures?.first.map((f) => f.source)).toContain(
609 BYTEPLUS_AUDIO_API_URL,
610 )
611 expect(models.find((m) => m.rawId === 'seed-asr')?.pricing).toBeTruthy()
612 })
613})
614
615describe('byteplus ids the pricing page no longer names (#646)', () => {
616 // 2026-11-12: the page dropped its "Retiring models" tables. Eight listed
617 // ids (seed-1-8-251228, glm-4-7-251222, …) are named nowhere on it.
618 it('clears the price of an id the page does not name', async () => {
619 const { models } = await listWith({})
620 const row = (rawId: string) => models.find((m) => m.rawId === rawId)
621 expect(row('seed-1-8-251228')?.pricing).toBeFalsy()
622 expect(row('seed-1-8-251228')?.absent?.pricing).toBe('cleared')
623 expect(row('glm-4-7-251222')?.absent?.pricing).toBe('cleared')
624 // A priced row carries no reason.
625 expect(row('seed-2-0-pro-260328')?.absent?.pricing).toBeUndefined()
626 })
627
628 it('keeps the stored card of an id the page names but no table prices', async () => {
629 const unread = () =>
630 routerHtml(
631 pricingDoc([
632 ...PRICING_TABLES,
633 {
634 tab: 'Standard',
635 rows: [
636 PRICING_TABLES[0]?.rows[0] ?? [],
637 // A bracket this parser refuses, and an undated id.
638 ['', 'seed-1-8-251228', 'Peak', '$1', '$1', '$1', '$1'],
639 ['', 'glm-4-7', 'About 128', '$1', '$1', '$1', '$1'],
640 ],
641 },
642 ]),
643 )
644 const { models } = await listWith({ [BYTEPLUS_PRICING_URL]: unread })
645 for (const rawId of ['seed-1-8-251228', 'glm-4-7-251222']) {
646 const row = models.find((m) => m.rawId === rawId)
647 expect(row?.pricing).toBeFalsy()
648 expect(row?.absent?.pricing).toBeUndefined()
649 }
650 })
651})
652
653/** The doc center's client-render shell on the first fetch, then `page`. */
654function shellThen(page: () => string): () => string {
655 const shell = readFileSync(
656 new URL('./fixtures/byteplus-doc-shell.html.txt', import.meta.url),
657 'utf8',
658 )
659 let served = false
660 return () => {
661 if (served) return page()
662 served = true
663 return shell
664 }
665}
666
667describe('byteplus doc center shell', () => {
668 it('refetches each pricing doc that first comes back as the shell', async () => {
669 const { models } = await listWith({
670 [BYTEPLUS_PRICING_URL]: shellThen(pricingFixtureHtml),
671 [BYTEPLUS_VIDEO_GUIDE_URL]: shellThen(guideFixtureHtml),
672 [BYTEPLUS_MODEL_LIST_URL]: shellThen(modelListFixtureHtml),
673 })
674 const priced = (rawId: string) =>
675 models.find((m) => m.rawId === rawId)?.pricing
676 expect(priced('seed-2-0-pro-260328')).toBeTruthy()
677 expect(priced('seedance-1-0-pro-250528')).toMatchObject({
678 inputs: {
679 completion_tokens: {
680 estimate: { source: { url: BYTEPLUS_VIDEO_GUIDE_URL } },
681 },
682 },
683 })
684 expect(priced('seedream-5-0-260128')).toMatchObject({
685 inputs: { generated_images: { bound: 'usage' } },
686 })
687 })
688})
689
690describe('byteplus curated models (no ARK_API_KEY)', () => {
691 it('lists the ported @tanstack/ai-byteplus catalog with metadata', async () => {
692 const original = globalThis.fetch
693 globalThis.fetch = ((url: string, init?: RequestInit) => {
694 const doc = DOC_FIXTURES[String(url)]
695 if (doc) return Promise.resolve(new Response(doc()))
696 return original(url, init)
697 }) as typeof fetch
698 const { models, skipped, docsFailures } = await byteplusProvider
699 .listModels({})
700 .finally(() => {
701 globalThis.fetch = original
702 })
703 // Keyless is a supported mode, not a skip: the embedded catalog stands
704 // in, and the poll records the fallback so it is not a healthy poll.
705 expect(skipped).toBeUndefined()
706 // First, so a docs-page failure in the same poll does not hide it.
707 // `failed` may be higher when a docs source also fails.
708 expect(docsFailures?.failed).toBeGreaterThanOrEqual(1)
709 expect(docsFailures?.first[0]).toEqual({
710 source: 'https://ark.ap-southeast.bytepluses.com/api/v3/models',
711 error: 'ARK_API_KEY is unset; serving the embedded catalog',
712 elapsedMs: 0,
713 })
714 // 18 chat + 7 video + 5 image + 2 speech.
715 expect(models).toHaveLength(32)
716 expect(new Set(models.map((m) => m.rawId)).size).toBe(32)
717
718 const byActivity = new Map<string, number>()
719 for (const m of models) {
720 expect(m.activity, m.rawId).toBeTruthy()
721 byActivity.set(
722 m.activity ?? '',
723 (byActivity.get(m.activity ?? '') ?? 0) + 1,
724 )
725 }
726 expect(byActivity.get('chat')).toBe(18)
727 expect(byActivity.get('video')).toBe(7)
728 expect(byActivity.get('image')).toBe(5)
729 expect(byActivity.get('audio')).toBe(2)
730
731 const seedance = models.find((m) => m.rawId === 'seedance-1-5-pro-251215')
732 expect(seedance?.releasedAt).toBe(Date.parse('2025-12-15') / 1000)
733 // Video and image rows from the pricing page become cards.
734 const priced = (rawId: string) =>
735 models.find((m) => m.rawId === rawId)?.pricing
736 expect(priced('seedance-1-0-pro-250528')).toMatchObject({
737 inputs: {
738 completion_tokens: {
739 bound: 'usage',
740 estimate: { source: { url: BYTEPLUS_VIDEO_GUIDE_URL } },
741 },
742 },
743 })
744 expect(priced('seedream-4-5-251128')).toMatchObject({
745 inputs: { generated_images: { bound: 'usage' } },
746 })
747 // Model list: seedream-5-0-260128 also supports the priced lite row.
748 expect(priced('seedream-5-0-260128')).toMatchObject({
749 inputs: { generated_images: { bound: 'usage' } },
750 })
751 // Seed Speech is priced from the voice billing pages (#672).
752 expect(priced('seed-asr')).toBeTruthy()
753 expect(priced('seed-audio-1.0')).toBeTruthy()
754 // Undated Seed Speech ids keep their poll-time firstSeenAt.
755 const asr = models.find((m) => m.rawId === 'seed-asr')
756 expect(asr?.releasedAt).toBeNull()
757
758 const glm = models.find((m) => m.rawId === 'glm-5-2-260617')
759 expect(glm?.contextWindow).toBe(1_024_000)
760 expect(glm?.maxOutput).toBe(128_000)
761 })
762})
763
764describe('ark task_type → activity', () => {
765 it('prefers generation task types over the modality-input ones', () => {
766 // Chat models that accept audio input carry SpeechToText alongside
767 // TextGeneration; they are chat endpoints, not transcription ones.
768 expect(
769 arkTaskActivity([
770 'TextGeneration',
771 'VisualQuestionAnswering',
772 'SpeechToText',
773 ]),
774 ).toBe('chat')
775 expect(arkTaskActivity(['ImageToVideo', 'TextToVideo'])).toBe('video')
776 expect(arkTaskActivity(['text_to_video', 'image_to_video'])).toBe('video')
777 expect(arkTaskActivity(['MultimodalToVideo', 'VideoEditing'])).toBe('video')
778 expect(arkTaskActivity(['multimodal_to_video', 'video_editing'])).toBe(
779 'video',
780 )
781 expect(arkTaskActivity(['ImageToImage', 'TextToImage'])).toBe('image')
782 expect(arkTaskActivity(['text_to_image', 'image_to_image'])).toBe('image')
783 expect(
784 arkTaskActivity([
785 'ImageEmbedding',
786 'MultimodalEmbedding',
787 'TextEmbedding',
788 ]),
789 ).toBe('embeddings')
790 expect(arkTaskActivity(['image_embedding', 'text_embedding'])).toBe(
791 'embeddings',
792 )
793 expect(arkTaskActivity(['SpeechToText'])).toBe('audio')
794 expect(
795 arkTaskActivity([
796 'text_generation',
797 'visual_question_answering',
798 'speech_to_text',
799 ]),
800 ).toBe('chat')
801 // 3D-generation models report no task_type at all.
802 expect(arkTaskActivity([])).toBeNull()
803 expect(arkTaskActivity(undefined)).toBeNull()
804 expect(arkTaskActivity(['SomethingNew'])).toBeNull()
805 })
806})
807
808describe('byteplus live models (ARK_API_KEY set)', () => {
809 // Verbatim rows from Ark's GET /models, captured 2026-08-12.
810 const ARK_PAGE = {
811 data: [
812 {
813 id: 'seed-2-0-lite-260428',
814 name: 'seed-2-0-lite',
815 created: 1_778_162_292,
816 domain: 'VLM',
817 task_type: [
818 'TextGeneration',
819 'VisualQuestionAnswering',
820 'SpeechToText',
821 ],
822 modalities: {
823 input_modalities: ['text', 'image', 'video', 'audio'],
824 output_modalities: ['text'],
825 },
826 token_limits: {
827 context_window: 262_144,
828 max_output_token_length: 131_072,
829 max_reasoning_token_length: 131_072,
830 },
831 features: {
832 structured_outputs: { json_object: true, json_schema: true },
833 tools: { function_calling: true },
834 },
835 },
836 {
837 id: 'kimi-k2-250905',
838 name: 'kimi-k2',
839 created: 1_757_927_317,
840 status: 'Shutdown',
841 domain: 'LLM',
842 task_type: ['TextGeneration'],
843 modalities: { input_modalities: ['text'], output_modalities: ['text'] },
844 token_limits: {
845 context_window: 262_144,
846 max_output_token_length: 32_768,
847 },
848 features: {},
849 },
850 {
851 id: 'hitem3d-2-0-251223',
852 name: 'hitem3d-2-0',
853 created: 1_774_855_941,
854 domain: '3DGeneration',
855 modalities: {},
856 token_limits: {},
857 features: {},
858 },
859 ],
860 }
861
862 function withStubbedFetch<T>(body: unknown, run: () => Promise<T>) {
863 const original = globalThis.fetch
864 const calls: Array<{ url: string; auth: string | null }> = []
865 globalThis.fetch = ((url: string, init?: RequestInit) => {
866 const href = String(url)
867 calls.push({
868 url: href,
869 auth: new Headers(init?.headers).get('authorization'),
870 })
871 const doc = DOC_FIXTURES[href]
872 if (doc) return Promise.resolve(new Response(doc()))
873 if (!href.includes('/api/v3/models')) return original(url, init)
874 return Promise.resolve(new Response(JSON.stringify(body)))
875 }) as typeof fetch
876 return run()
877 .then((result) => ({ result, calls }))
878 .finally(() => {
879 globalThis.fetch = original
880 })
881 }
882
883 it('maps live rows and sends the bearer key', async () => {
884 const { result, calls } = await withStubbedFetch(ARK_PAGE, () =>
885 byteplusProvider.listModels({ ARK_API_KEY: 'ark-test' }),
886 )
887 const ark = calls.find((call) => call.url.includes('/api/v3/models'))
888 expect(ark?.url).toBe(
889 'https://ark.ap-southeast.bytepluses.com/api/v3/models',
890 )
891 expect(ark?.auth).toBe('Bearer ark-test')
892
893 const seed = result.models.find((m) => m.rawId === 'seed-2-0-lite-260428')
894 expect(seed?.activity).toBe('chat')
895 expect(seed?.displayName).toBe('seed-2-0-lite')
896 expect(seed?.contextWindow).toBe(262_144)
897 expect(seed?.maxOutput).toBe(131_072)
898 // Upstream `created` beats the id-suffix fallback.
899 expect(seed?.releasedAt).toBe(1_778_162_292)
900 expect(seed?.modalities).toEqual({
901 input: ['text', 'image', 'video', 'audio'],
902 output: ['text'],
903 })
904 expect(seed?.deprecated).toBe(false)
905
906 // Shutdown and Retiring both read as deprecated.
907 expect(
908 result.models.find((m) => m.rawId === 'kimi-k2-250905')?.deprecated,
909 ).toBe(true)
910 // 3D generation is outside our taxonomy.
911 expect(
912 result.models.find((m) => m.rawId === 'hitem3d-2-0-251223')?.activity,
913 ).toBeNull()
914 })
915
916 it('projects chat features onto the shared string[] vocabulary', async () => {
917 const { result } = await withStubbedFetch(ARK_PAGE, () =>
918 byteplusProvider.listModels({ ARK_API_KEY: 'ark-test' }),
919 )
920 // Ark advertises json_schema here, but a real request 400s: the probe
921 // verdict wins, so response_format stays and structured_outputs goes.
922 expect(
923 result.models.find((m) => m.rawId === 'seed-2-0-lite-260428')
924 ?.capabilities,
925 ).toEqual(['tools', 'tool_choice', 'reasoning', 'response_format'])
926 // Every chat row, curated gap-fillers included, is a string[].
927 for (const m of result.models.filter((row) => row.activity === 'chat')) {
928 expect(Array.isArray(m.capabilities)).toBe(true)
929 }
930 })
931
932 it('keeps json_object-only models off structured_outputs', () => {
933 expect(
934 arkChatCapabilities({
935 id: 'glm-5-3-flash-260828',
936 token_limits: { max_reasoning_token_length: 131_072 },
937 features: {
938 structured_outputs: { json_object: true, json_schema: false },
939 tools: { function_calling: true },
940 cache: { prefix_cache: true, session_cache: true },
941 },
942 }),
943 ).toEqual(['tools', 'tool_choice', 'reasoning', 'response_format'])
944 })
945
946 it.each([
947 ['an empty data array', { data: [] }],
948 ['no data field', {}],
949 ['a null body', null],
950 ['data that is not an array', { data: { id: 'seed-2-0-lite-260428' } }],
951 ])(
952 'throws when Ark returns %s, so the poll keeps the stored rows',
953 async (_label, body) => {
954 await expect(
955 withStubbedFetch(body, () =>
956 byteplusProvider.listModels({ ARK_API_KEY: 'ark-test' }),
957 ),
958 ).rejects.toThrow(/returned no models; refusing the embedded catalog/)
959 },
960 )
961
962 it('fills the gaps the listing omits from the curated catalog', async () => {
963 const { result } = await withStubbedFetch(ARK_PAGE, () =>
964 byteplusProvider.listModels({ ARK_API_KEY: 'ark-test' }),
965 )
966 const ids = result.models.map((m) => m.rawId)
967 expect(new Set(ids).size).toBe(ids.length)
968 // Seed Speech lives on another host and is in no Ark listing.
969 expect(ids).toContain('seed-audio-1.0')
970 expect(ids).toContain('seed-asr')
971 // Served by Ark but absent from its own listing.
972 expect(ids).toContain('seedream-5-0-lite-260128')
973 // A live row must not be duplicated by its curated twin.
974 expect(ids.filter((id) => id === 'seed-2-0-lite-260428')).toHaveLength(1)
975 })
976
977 it('links image and video rows the listing no longer classifies', async () => {
978 const { result } = await withStubbedFetch(
979 {
980 data: [
981 {
982 id: 'dreamina-seedance-2-0-260128',
983 domain: 'VideoGeneration',
984 task_type: ['text_to_video', 'image_to_video'],
985 modalities: {
986 input_modalities: ['text', 'image', 'video', 'audio'],
987 output_modalities: ['video'],
988 },
989 },
990 {
991 id: 'dola-seedream-5-5-261028',
992 domain: 'ImageGeneration',
993 modalities: {},
994 },
995 { id: 'seedance-1-0-pro-250528', modalities: {} },
996 { id: 'seedream-4-0-20260415' },
997 {
998 id: 'seed-2-0-lite-260428',
999 task_type: [
1000 'text_generation',
1001 'visual_question_answering',
1002 'speech_to_text',
1003 ],
1004 modalities: {
1005 input_modalities: ['text', 'image', 'video', 'audio'],
1006 output_modalities: ['text'],
1007 },
1008 features: { tools: { function_calling: true } },
1009 },
1010 ],
1011 },
1012 () => byteplusProvider.listModels({ ARK_API_KEY: 'ark-test' }),
1013 )
1014 const row = (rawId: string) => result.models.find((m) => m.rawId === rawId)
1015 expect(row('dreamina-seedance-2-0-260128')).toMatchObject({
1016 activity: 'video',
1017 modalities: {
1018 input: ['text', 'image', 'video', 'audio'],
1019 output: ['video'],
1020 },
1021 })
1022 // Domain states image generation; the listing states no modalities.
1023 expect(row('dola-seedream-5-5-261028')).toMatchObject({
1024 activity: 'image',
1025 modalities: { output: ['image'] },
1026 })
1027 expect(row('dola-seedream-5-5-261028')?.modalities).toEqual({
1028 output: ['image'],
1029 })
1030 // The curated catalog still names this id's input and output.
1031 expect(row('seedance-1-0-pro-250528')).toMatchObject({
1032 activity: 'video',
1033 modalities: { input: ['text', 'image'], output: ['video'] },
1034 })
1035 // No task type, domain, or modalities. The id is a Seedream model.
1036 expect(row('seedream-4-0-20260415')).toMatchObject({
1037 activity: 'image',
1038 modalities: { output: ['image'] },
1039 })
1040 expect(row('seedream-4-0-20260415')?.modalities).toEqual({
1041 output: ['image'],
1042 })
1043 const seed = row('seed-2-0-lite-260428')
1044 expect(seed?.activity).toBe('chat')
1045 expect(seed?.capabilities).toEqual(['tools', 'tool_choice'])
1046 })
1047
1048 it('reports a listed video id with no duration row and still returns it', async () => {
1049 await runIngestScope(async () => {
1050 const { result } = await withStubbedFetch(
1051 {
1052 data: [
1053 { id: 'dreamina-seedance-2-0-260128', domain: 'VideoGeneration' },
1054 {
1055 id: 'dreamina-not-in-the-duration-table',
1056 domain: 'VideoGeneration',
1057 },
1058 ],
1059 },
1060 () => byteplusProvider.listModels({ ARK_API_KEY: 'ark-test' }),
1061 )
1062 expect(
1063 result.models.find(
1064 (model) => model.rawId === 'dreamina-not-in-the-duration-table',
1065 )?.activity,
1066 ).toBe('video')
1067 expect(
1068 takeIngestEvents().filter((event) => event.event === 'ingest_failed'),
1069 ).toEqual([
1070 {
1071 event: 'ingest_failed',
1072 properties: {
1073 job: 'models-poll',
1074 providerId: 'byteplus',
1075 error: `no Seedance duration for dreamina-not-in-the-duration-table (${SEEDANCE_DURATION_DOCS})`,
1076 },
1077 },
1078 ])
1079 })
1080 })
1081})
1082
1083describe('byteplus schema provenance', () => {
1084 it('grades each endpoint by how its schema was arrived at', async () => {
1085 const { result: fetched } = await withGoSdk('ok', () =>
1086 byteplusProvider.fetchSpec({}),
1087 )
1088 const { endpoints } = classifyAndBundle(byteplusProvider, fetched)
1089 const by = new Map(
1090 endpoints.map((e) => [e.dbId, [e.derivation, e.verifiedAt] as const]),
1091 )
1092 // Ark is re-derived from the Go SDK every sync, so it self-heals and
1093 // carries no point-in-time claim.
1094 expect(by.get('byteplus/chat/completions')).toEqual(['generated', null])
1095 expect(by.get('byteplus/images/generations')).toEqual(['generated', null])
1096 expect(by.get('byteplus/contents/generations/tasks')).toEqual([
1097 'generated',
1098 null,
1099 ])
1100 expect(by.get('byteplus/contents/generations/tasks/{id}')).toEqual([
1101 'generated',
1102 null,
1103 ])
1104 expect(by.get('byteplus/contents/generations/tasks/{id}:delete')).toEqual([
1105 'generated',
1106 null,
1107 ])
1108 // Seed Speech is hand-written: TTS was exercised live, ASR never was.
1109 expect(by.get('byteplus/tts/create')).toEqual([
1110 'probe-verified',
1111 '2026-08-12',
1112 ])
1113 expect(by.get('byteplus/auc/bigmodel/recognize/flash')).toEqual([
1114 'docs-derived',
1115 null,
1116 ])
1117 })
1118
1119 it('downgrades Ark to a dated claim when it falls back to the embedded doc', async () => {
1120 const { result: fetched } = await withGoSdk('unreachable', () =>
1121 byteplusProvider.fetchSpec({}),
1122 )
1123 const { endpoints } = classifyAndBundle(byteplusProvider, fetched)
1124 const chat = endpoints.find((e) => e.dbId === 'byteplus/chat/completions')
1125 // No longer self-healing, and it says so.
1126 expect(chat?.derivation).toBe('probe-verified')
1127 expect(chat?.verifiedAt).toBe('2026-07-31')
1128 const cancel = endpoints.find(
1129 (e) => e.dbId === 'byteplus/contents/generations/tasks/{id}:delete',
1130 )
1131 expect(cancel?.derivation).toBe('docs-derived')
1132 expect(cancel?.verifiedAt).toBeNull()
1133 })
1134})