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

byteplus.test.ts

1,063 lines36.2 KB

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