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

byteplus.test.ts

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