Open History to see the last commit
1/**
2 * BytePlus chat prices from the ModelArk pricing page (issue #73). The page
3 * is a Lark document: `window._ROUTER_DATA` embeds `curDoc.Content`, and
4 * each table is an `aceTable` of a row zone plus a column zone. Cell text
5 * lives in a zone id `x{rowId}x{colId}`.
6 *
7 * Only the standard online-inference table is read (the one that quotes
8 * cache storage per hour). Flex and batch tables further down are half of
9 * standard and are not levers. Cache storage itself is per token-hour, not
10 * per request, so that column is ignored. A model quoted at off-peak and
11 * peak rates gets a card whose required `pricing_period` lever picks one
12 * (#411); the page states the windows, not the request. A dated catalog id uses an
13 * undated page row only when exactly one page id is its prefix
14 * (`dola-seed-2-1-turbo` → `dola-seed-2-1-turbo-260628`).
15 *
16 * Video (Seedance) and image (Seedream) tables are read too (issue #99):
17 * see `parseByteplusVideo` and `parseByteplusImages`. A page missing chat,
18 * video, or image rows throws. The model list's "also supports" note copies
19 * a published image, video, or pixel-tier price onto that alias when the
20 * pair is unambiguous (issue #117). This page has no speech table, so Seed
21 * Speech stays unpriced. Seedance estimates also read frame rate and
22 * output sizes from the video generation tutorial; if that page fails, the
23 * cards publish without an estimate rather than failing the lookup.
24 */
25import { compileTokenCard, compileUnitCard } from '@modelschemas/rate-card'
26import type {
27 Expr,
28 RateCard,
29 RateCardEstimate,
30 TokenRateTier,
31} from '@modelschemas/rate-card'
32
33import { errorMessage } from '#/server/errors.ts'
34
35import { tagDocsFacts } from './fact-sources.ts'
36import { parseByteplusServerTools } from './server-tools.ts'
37import {
38 assertParsed,
39 cachedDocs,
40 tryDocs,
41 unavailable,
42} from './model-facts.ts'
43import type { DocsRun } from './model-facts.ts'
44import { fetchByteplusDoc } from './byteplus-docs.ts'
45import { sha256Text } from './types.ts'
46import type { ModelInfo } from './types.ts'
47
48export const BYTEPLUS_PRICING_URL =
49 'https://docs.byteplus.com/en/docs/ModelArk/1544106'
50
51/** Seedance output sizes and frame rates (the token formula's inputs). */
52export const BYTEPLUS_VIDEO_GUIDE_URL =
53 'https://docs.byteplus.com/en/docs/modelark/video-generation-tutorial'
54
55/**
56 * seed-translation's own model page (#411). The pricing page has no row for
57 * it; this page's "Model Price" table quotes the one model it documents.
58 */
59export const BYTEPLUS_SEED_TRANSLATION_URL =
60 'https://docs.byteplus.com/en/docs/ModelArk/recommended-models-seed-translation'
61
62/** "also supports" aliases. Not a price source. */
63export const BYTEPLUS_MODEL_LIST_URL =
64 'https://docs.byteplus.com/en/docs/ModelArk/1330310'
65
66/** Header (unit stripped) → request lever. Cache storage is not one. */
67const LEVERS: Record<string, string> = {
68 'input (non-audio)': 'input_tokens',
69 'input (audio)': 'audio_tokens',
70 'cache-hit input (non-audio)': 'cache_read_tokens',
71 'cache-hit input (audio)': 'audio_cache_tokens',
72 output: 'output_tokens',
73}
74
75interface DocOp {
76 insert: string | { id?: string }
77 attributes?: { aceTable?: string; [key: string]: unknown }
78}
79
80interface DocZone {
81 ops?: Array<DocOp>
82 zoneType?: string
83 zoneId?: string
84}
85
86export interface ByteplusDoc {
87 data: Record<string, DocZone>
88}
89
90export interface ByteplusChatRates {
91 base: Record<string, number>
92 tiers: Array<TokenRateTier>
93}
94
95/**
96 * A model quoted at off-peak and peak rates (DeepSeek V4.1 Flash, #411).
97 * The page names the peak windows in UTC+8; the card takes the period as a
98 * required `pricing_period` lever, so neither rate is presented as the price.
99 */
100export interface ByteplusPeriodRates {
101 periods: { off_peak: Record<string, number>; peak: Record<string, number> }
102}
103
104export type ByteplusTokenRates = ByteplusChatRates | ByteplusPeriodRates
105
106const PERIOD_LABELS: Record<string, keyof ByteplusPeriodRates['periods']> = {
107 'off-peak hours': 'off_peak',
108 'peak hours': 'peak',
109}
110
111function zoneText(zone: DocZone | undefined): string {
112 return (zone?.ops ?? [])
113 .map((op) => (typeof op.insert === 'string' ? op.insert : ''))
114 .join('')
115 .split('\n')
116 .map((line) => line.replace(/^\*\s?/, '').trim())
117 .filter((line) => line !== '')
118 .join(' ')
119 .replace(/\s+/g, ' ')
120 .trim()
121}
122
123function headerKey(cell: string): string {
124 return (
125 cell
126 .toLowerCase()
127 // Drop the trailing unit ("(USD/M tokens)"), keep "(non-audio)".
128 .replace(/\s*\([^)]*\)\s*$/, '')
129 .replace(/\s+/g, ' ')
130 .trim()
131 )
132}
133
134/**
135 * `Prompt length [0, 128]` is the base. `(128, 256]` starts above 128K
136 * tokens. `-` is an untiered base row. Anything else (peak hours) refuses.
137 */
138function promptFloorK(label: string): number | null {
139 if (label === '-' || label === '') return 0
140 if (/^prompt length \[0,\s*[\d.]+\]$/i.test(label)) return 0
141 const next = label.match(/^prompt length \(([\d.]+),\s*[\d.]+\]$/i)
142 if (next?.[1]) return Number(next[1])
143 return null
144}
145
146/** USD per million tokens. `undefined` is a lever the cell does not price. */
147function usdPerMillion(cell: string): number | null | undefined {
148 if (cell === '-' || cell === '') return undefined
149 if (!/^[\d]+(?:\.[\d]+)?$/.test(cell)) return null
150 return Number(cell) / 1e6
151}
152
153function tableRows(
154 doc: ByteplusDoc,
155 spec: string,
156): Array<Array<string>> | null {
157 const [rowId, colId] = spec.split(' ')
158 const row = rowId ? doc.data[rowId] : undefined
159 const col = colId ? doc.data[colId] : undefined
160 if (!row || !col) return null
161 const cols = (col.ops ?? []).flatMap((op) =>
162 typeof op.insert === 'object' && op.insert.id ? [op.insert.id] : [],
163 )
164 return (row.ops ?? []).flatMap((op) => {
165 const rowCell = op.insert
166 if (typeof rowCell !== 'object' || !rowCell.id) return []
167 const cellId = rowCell.id
168 return [cols.map((column) => zoneText(doc.data[`x${cellId}x${column}`]))]
169 })
170}
171
172/** One row's lever rates; null when a cell is unreadable or input/output is missing. */
173function rowRates(
174 row: Array<string>,
175 levers: Record<string, number>,
176): Record<string, number> | null {
177 const rates: Record<string, number> = {}
178 for (const [key, lever] of Object.entries(LEVERS)) {
179 const at = levers[key]
180 if (at === undefined) continue
181 const value = usdPerMillion(row[at] ?? '')
182 if (value === null) return null
183 if (value !== undefined) rates[lever] = value
184 }
185 if (rates.input_tokens === undefined || rates.output_tokens === undefined) {
186 return null
187 }
188 return rates
189}
190
191/** Exactly one off-peak and one peak row, or null. */
192function periodsFromGroup(
193 rows: Array<Array<string>>,
194 columns: { tier: number; levers: Record<string, number> },
195): ByteplusPeriodRates | null {
196 if (rows.length !== 2) return null
197 const periods: Partial<ByteplusPeriodRates['periods']> = {}
198 for (const row of rows) {
199 const period = PERIOD_LABELS[(row[columns.tier] ?? '').toLowerCase()]
200 const rates = rowRates(row, columns.levers)
201 if (!period || !rates || periods[period]) return null
202 periods[period] = rates
203 }
204 const { off_peak, peak } = periods
205 return off_peak && peak ? { periods: { off_peak, peak } } : null
206}
207
208function ratesFromGroup(
209 rows: Array<Array<string>>,
210 columns: { tier: number; levers: Record<string, number> },
211): ByteplusTokenRates | null {
212 if (
213 rows.some((row) => (row[columns.tier] ?? '').toLowerCase() in PERIOD_LABELS)
214 ) {
215 return periodsFromGroup(rows, columns)
216 }
217 const base: Record<string, number> = {}
218 const tiers: Array<TokenRateTier> = []
219 for (const [index, row] of rows.entries()) {
220 const floor = promptFloorK(row[columns.tier] ?? '')
221 if (floor === null) return null
222 const rates = rowRates(row, columns.levers)
223 if (!rates) return null
224 if (index === 0) {
225 if (floor !== 0) return null
226 Object.assign(base, rates)
227 continue
228 }
229 if (floor <= 0) return null
230 // Prompt length is the request's input. Audio columns are re-quoted in
231 // the same bracket, so they count toward it when the card is compiled.
232 tiers.push({ minPromptTokens: floor * 1000, rates })
233 }
234 return Object.keys(base).length > 0 ? { base, tiers } : null
235}
236
237/** Every table whose header (units stripped) names all of `required`. */
238function tablesWith(
239 doc: ByteplusDoc,
240 required: Array<string>,
241): Array<{ keys: Array<string>; rows: Array<Array<string>> }> {
242 return (doc.data['0']?.ops ?? []).flatMap((op) => {
243 const spec = op.attributes?.aceTable
244 const rows = spec ? tableRows(doc, spec) : null
245 const keys = rows?.[0]?.map(headerKey)
246 if (!rows || !keys || !required.every((key) => keys.includes(key))) {
247 return []
248 }
249 return [{ keys, rows: rows.slice(1) }]
250 })
251}
252
253/** Page model id → standard online-inference rates. */
254export function parseByteplusPricing(
255 doc: ByteplusDoc,
256): Map<string, ByteplusTokenRates> {
257 const out = new Map<string, ByteplusTokenRates>()
258 const tables = tablesWith(doc, [
259 'model id',
260 'cache-storage',
261 'input (non-audio)',
262 'output',
263 ])
264 for (const { keys, rows } of tables) {
265 if (out.size > 0) break
266 const tier = keys.indexOf('pricing tiers')
267 const levers: Record<string, number> = {}
268 for (const key of Object.keys(LEVERS)) {
269 const at = keys.indexOf(key)
270 if (at >= 0) levers[key] = at
271 }
272 if (tier < 0 || levers['input (non-audio)'] === undefined) continue
273 let current: { id: string; rows: Array<Array<string>> } | null = null
274 const groups: Array<{ id: string; rows: Array<Array<string>> }> = []
275 for (const row of rows) {
276 const id = row[keys.indexOf('model id')] ?? ''
277 if (id !== '') {
278 if (current) groups.push(current)
279 current = { id, rows: [row] }
280 } else if (current) {
281 current.rows.push(row)
282 }
283 }
284 if (current) groups.push(current)
285 for (const group of groups) {
286 if (out.has(group.id) || /\s/.test(group.id)) continue
287 const rates = ratesFromGroup(group.rows, { tier, levers })
288 if (rates) out.set(group.id, rates)
289 }
290 }
291 return out
292}
293
294/**
295 * Token card priced by the caller-stated `pricing_period` (no default: the
296 * request carries no clock, so the card refuses rather than pick one).
297 */
298export function compilePeriodCard(
299 { periods }: ByteplusPeriodRates,
300 source: RateCard['source'],
301): RateCard {
302 const levers = [
303 ...new Set([
304 ...Object.keys(periods.off_peak),
305 ...Object.keys(periods.peak),
306 ]),
307 ]
308 return {
309 inputs: {
310 pricing_period: {
311 param: 'pricing_period',
312 bound: 'usage',
313 kind: 'enum',
314 values: ['off_peak', 'peak'],
315 },
316 ...Object.fromEntries(
317 levers.map((lever) => [
318 lever,
319 {
320 param: lever,
321 bound: 'usage',
322 kind: 'number',
323 ...(lever !== 'input_tokens' &&
324 lever !== 'output_tokens' && { default: 0 }),
325 },
326 ]),
327 ),
328 },
329 tables: { rate: periods },
330 price: {
331 '+': levers.map(
332 (lever): Expr => ({
333 if: [
334 { '>': [{ var: lever }, 0] },
335 {
336 '*': [
337 { var: lever },
338 {
339 lookup: {
340 table: 'rate',
341 keys: [{ var: 'pricing_period' }, lever],
342 },
343 },
344 ],
345 },
346 0,
347 ],
348 }),
349 ),
350 },
351 examples: [],
352 source,
353 }
354}
355
356/** Model-page price header (units kept: the cells have no parentheses). */
357const MODEL_PAGE_LEVERS: Record<string, string> = {
358 'input usd/m tokens': 'input_tokens',
359 'input hits cache usd/m tokens': 'cache_read_tokens',
360 'output unit price usd/m tokens': 'output_tokens',
361}
362
363/**
364 * The single price row of a one-model doc page. Throws unless exactly one
365 * table with one row quotes both input and output.
366 */
367export function parseByteplusModelPage(
368 doc: ByteplusDoc,
369): Record<string, number> {
370 const tables = tablesWith(doc, Object.keys(MODEL_PAGE_LEVERS))
371 const row = tables.length === 1 ? tables[0] : undefined
372 if (!row || row.rows.length !== 1) {
373 throw new Error(
374 `byteplus model page: expected one price table row, found ${String(tables.length)} tables`,
375 )
376 }
377 const rates: Record<string, number> = {}
378 for (const [key, lever] of Object.entries(MODEL_PAGE_LEVERS)) {
379 const cell = row.rows[0]?.[row.keys.indexOf(key)] ?? ''
380 const value = usdPerMillion(cell)
381 if (value === null) {
382 throw new Error(`byteplus model page: unreadable ${key} "${cell}"`)
383 }
384 if (value !== undefined) rates[lever] = value
385 }
386 if (rates.input_tokens === undefined || rates.output_tokens === undefined) {
387 throw new Error('byteplus model page: no input or output price')
388 }
389 return rates
390}
391
392/**
393 * Catalog id → page row. Exact id wins. Otherwise the undated page id the
394 * catalog id extends with a `-YYMMDD` date — never another suffix, so
395 * `seedance-1-0-pro-fast-…` cannot take an undated `seedance-1-0-pro` row.
396 */
397export function byteplusRatesFor<T>(
398 rawId: string,
399 rates: Map<string, T>,
400): T | undefined {
401 const exact = rates.get(rawId)
402 if (exact) return exact
403 const dated = rawId.match(/^(.+)-\d{6}$/)?.[1]
404 return dated === undefined ? undefined : rates.get(dated)
405}
406
407const ALSO_SUPPORTS =
408 /\b([a-z0-9]+(?:-[a-z0-9]+)+)\s*\(also supports:\s*([a-z0-9]+(?:-[a-z0-9]+)+)\s*\)/g
409
410/**
411 * Model-list "also supports" pairs. One id named with two different
412 * partners is dropped; the other pairs stay. Not a price.
413 */
414export function parseByteplusAliases(doc: ByteplusDoc): Map<string, string> {
415 const pairs = new Map<string, string>()
416 const dropped = new Set<string>()
417 const text = Object.values(doc.data).map(zoneText).join('\n')
418 for (const match of text.matchAll(ALSO_SUPPORTS)) {
419 const primary = match[1] ?? ''
420 const alias = match[2] ?? ''
421 if (primary === '' || primary === alias) continue
422 const previous = pairs.get(primary)
423 if (previous !== undefined && previous !== alias) {
424 dropped.add(primary)
425 continue
426 }
427 const claimed = [...pairs.entries()].some(
428 ([other, taken]) => other !== primary && taken === alias,
429 )
430 if (claimed) {
431 dropped.add(primary)
432 continue
433 }
434 pairs.set(primary, alias)
435 }
436 for (const id of dropped) pairs.delete(id)
437 return pairs
438}
439
440/**
441 * Copy a price onto the unpriced side of an alias pair. Both sides priced,
442 * or neither, stays as parsed. Chat rates are not passed here.
443 */
444export function sharePublishedAliases<T>(
445 rates: Map<string, T>,
446 aliases: Map<string, string>,
447): void {
448 for (const [primary, alias] of aliases) {
449 const left = rates.get(primary)
450 const right = rates.get(alias)
451 if (left !== undefined && right === undefined) rates.set(alias, left)
452 else if (right !== undefined && left === undefined)
453 rates.set(primary, right)
454 }
455}
456
457/**
458 * Seedance rates, USD per million tokens: service tier (`default` online,
459 * `flex` offline) → resolution (`*` when the row names none) → variant. A
460 * variant is `no_video`/`video` (does the input carry a video),
461 * `silent`/`audio` (`generate_audio`), or `all` when the model has one
462 * rate.
463 */
464export type ByteplusVideoRates = Record<
465 string,
466 Record<string, Record<string, number>>
467>
468
469const VIDEO_VARIANTS: Array<[RegExp, string]> = [
470 [/Input without video: (\d+(?:\.\d+)?)/i, 'no_video'],
471 [/Input with video: (\d+(?:\.\d+)?)/i, 'video'],
472 [/Video with audio: (\d+(?:\.\d+)?)/i, 'audio'],
473 [/Video without audio: (\d+(?:\.\d+)?)/i, 'silent'],
474]
475
476/** A plain positive decimal, or `null`. */
477function decimal(text: string): number | null {
478 const value = /^\d+(?:\.\d+)?$/.test(text) ? Number(text) : NaN
479 return Number.isFinite(value) && value > 0 ? value : null
480}
481
482/** Both halves of a split, or one flat rate — anything else refuses. */
483function variantRates(body: string): Record<string, number> | null {
484 const text = body.trim()
485 const flat = decimal(text)
486 if (flat !== null) return { all: flat }
487 if (/^[\d.]+$/.test(text)) return null
488 const rates: Record<string, number> = {}
489 let rest = text
490 for (const [pattern, variant] of VIDEO_VARIANTS) {
491 rest = rest.replace(pattern, (_, n: string) => {
492 rates[variant] = Number(n)
493 return ''
494 })
495 }
496 const pairs = [
497 ['no_video', 'video'],
498 ['silent', 'audio'],
499 ]
500 const paired = pairs.some(([a = '', b = '']) => {
501 const keys = Object.keys(rates).sort()
502 return keys.join() === [a, b].sort().join()
503 })
504 const usable = Object.values(rates).every((n) => Number.isFinite(n) && n > 0)
505 return rest.trim() === '' && paired && usable ? rates : null
506}
507
508/**
509 * One rate cell → resolution → variant. `undefined` is "Not supported yet";
510 * `null` is a cell this parser cannot read. Promo cells quote the list
511 * price as "(Original) 5.6 Time limited 25% off"; the list price is kept
512 * (the discount is enterprise-only and time-boxed). Promo text with no
513 * "(Original)" price beside it may be quoting the discounted rate, so it
514 * refuses.
515 */
516function videoCell(
517 cell: string,
518): Record<string, Record<string, number>> | null | undefined {
519 const promos = cell.match(/Time limited \d+% off/gi)?.length ?? 0
520 const originals = cell.match(/\(Original\)/gi)?.length ?? 0
521 if (promos !== originals) return null
522 const text = cell
523 .replace(/\(Original\)/gi, '')
524 .replace(/Time limited \d+% off/gi, '')
525 .replace(/\s+/g, ' ')
526 .trim()
527 if (/^not supported/i.test(text)) return undefined
528 // [lead, "480p and 720p", body, "1080p", body, …]
529 const parts = text.split(/For ([^:]+?) outputs?:/i)
530 const lead = parts[0]?.trim() ?? ''
531 // A rate with no "For … outputs" applies whatever the resolution.
532 if (lead && parts.length > 1) return null
533 const segments: Array<[Array<string>, string]> = lead ? [[['*'], lead]] : []
534 for (let at = 1; at < parts.length; at += 2) {
535 const named = parts[at]?.toLowerCase().match(/\d+p|4k/g) ?? []
536 segments.push([named, parts[at + 1] ?? ''])
537 }
538 if (segments.length === 0) return null
539 const out: Record<string, Record<string, number>> = {}
540 for (const [resolutions, body] of segments) {
541 const rates = variantRates(body)
542 if (!rates || resolutions.length === 0) return null
543 for (const resolution of resolutions) out[resolution] = rates
544 }
545 return out
546}
547
548/**
549 * Video table: `Model ID ‖ Online inference ‖ Offline inference`. The id
550 * cell trails a description ("… Pricing varies based on …"); its first word
551 * is the id. A model with any unreadable cell gets no rates (and a warning).
552 * Only the first matching table is read.
553 */
554export function parseByteplusVideo(
555 doc: ByteplusDoc,
556): Map<string, ByteplusVideoRates> {
557 const out = new Map<string, ByteplusVideoRates>()
558 const tables = tablesWith(doc, [
559 'model id',
560 'online inference',
561 'offline inference',
562 ])
563 const [table] = tables
564 if (!table) return out
565 const at = (key: string) => table.keys.indexOf(key)
566 for (const row of table.rows) {
567 const id = (row[at('model id')] ?? '').split(' ')[0] ?? ''
568 if (!/^[a-z0-9-]+$/.test(id)) continue
569 const online = videoCell(row[at('online inference')] ?? '')
570 const offline = videoCell(row[at('offline inference')] ?? '')
571 if (!online || offline === null) {
572 warnUnread('video', id, row)
573 continue
574 }
575 out.set(id, { default: online, ...(offline && { flex: offline }) })
576 }
577 return out
578}
579
580/**
581 * Image table: `Model ID ‖ Input image price ‖ Output image price`, USD per
582 * image. Only flat rows with free input images are read here; Seedream 5.0
583 * pro's pixel-tiered row is `parseByteplusPixelTiers`. Only the first
584 * matching table is read.
585 */
586export function parseByteplusImages(doc: ByteplusDoc): Map<string, number> {
587 const out = new Map<string, number>()
588 const tables = tablesWith(doc, [
589 'model id',
590 'input image price',
591 'output image price',
592 ])
593 const [table] = tables
594 if (!table) return out
595 const at = (key: string) => table.keys.indexOf(key)
596 for (const row of table.rows) {
597 const id = (row[at('model id')] ?? '').split(' ')[0] ?? ''
598 if (!/^[a-z0-9-]+$/.test(id)) continue
599 const input = (row[at('input image price')] ?? '').trim()
600 const output = decimal((row[at('output image price')] ?? '').trim())
601 if (!/^free$/i.test(input) || output === null) {
602 // Pixel-tiered rows belong to `parseByteplusPixelTiers`.
603 const tiered = pixelTierRates(input, row[at('output image price')] ?? '')
604 if (!tiered) warnUnread('image', id, row)
605 continue
606 }
607 out.set(id, output)
608 }
609 return out
610}
611
612/** A priced row this parser could not read: logged so drift is visible. */
613function warnUnread(table: string, id: string, row: Array<string>): void {
614 console.warn(
615 JSON.stringify({
616 job: 'byteplus-pricing',
617 skipped: id,
618 table,
619 cells: row,
620 }),
621 )
622}
623
624/**
625 * Output frame rate and pixel size per Seedance model, from the video
626 * generation tutorial. The page's token formula is
627 * `(input s + output s) × width × height × fps / 1024`; cards apply it to
628 * output seconds only, since a request with input video refuses the
629 * estimate (see `compileSeedanceCard`).
630 */
631export interface SeedanceGeometry {
632 fps: number
633 /** resolution → ratio → output pixels */
634 dims: Record<string, Record<string, { w: number; h: number }>>
635}
636
637/**
638 * A resolution cell's note, for one display name: `true` serves it,
639 * `false` does not, `null` is a note this parser cannot read. Known
640 * shapes: "X and Y do not support 1080p", "Only X supports 4K".
641 */
642function noteServes(note: string, name: string): boolean | null {
643 if (note === '') return true
644 const names = (list: string) =>
645 list.split(/,\s*|\s+and\s+/i).map((part) => part.trim().toLowerCase())
646 const excluded = note.match(/^(.+?) (?:do|does) not support\b/i)?.[1]
647 if (excluded) return !names(excluded).includes(name)
648 const only = note.match(/^Only (.+?) supports?\b/i)?.[1]
649 if (only) return names(only).includes(name)
650 return null
651}
652
653/**
654 * Two tables on the tutorial: the model table (`Model name` header row of
655 * display names, a `Model ID` row, a `Frame rate` row) and the pixel table
656 * (`Resolution ‖ Aspect ratio ‖ <model or "… series">…`). A pixel column
657 * names one display name, or a series every display name it prefixes; a
658 * model's own column beats its series. A resolution note ("… do not support
659 * 1080p") limits who gets that row, and a note it cannot read drops the row.
660 * Two columns of the same rank disagreeing on a size drops the model, as
661 * does a repeated display name. Models missing a fact get no geometry.
662 */
663export function parseSeedanceGeometry(
664 doc: ByteplusDoc,
665): Map<string, SeedanceGeometry> {
666 const out = new Map<string, SeedanceGeometry>()
667 const [models] = tablesWith(doc, ['model name'])
668 const [pixels] = tablesWith(doc, ['resolution', 'aspect ratio'])
669 if (!models || !pixels) return out
670 const row = (label: string) =>
671 models.rows.find((r) => r.some((c) => c.toLowerCase() === label))
672 const ids = row('model id')
673 const fpsRow = row('frame rate')
674 if (!ids || !fpsRow) return out
675
676 // Display name (lowercase) → model id and fps.
677 const byName = new Map<string, { id: string; fps: number }>()
678 const repeated = new Set<string>()
679 models.keys.forEach((name, column) => {
680 const id = ids[column] ?? ''
681 const fps = fpsRow[column]?.match(/^(\d+) fps$/i)?.[1]
682 if (!/^[a-z0-9-]+$/.test(id) || !fps) return
683 if (byName.has(name)) repeated.add(name)
684 byName.set(name, { id, fps: Number(fps) })
685 })
686 for (const name of repeated) byName.delete(name)
687
688 const at = (key: string) => pixels.keys.indexOf(key)
689 // id|resolution|ratio → rank of the column that set it (2 own, 1 series).
690 const rank = new Map<string, number>()
691 const conflicted = new Set<string>()
692 let resolution = ''
693 let note = ''
694 for (const cells of pixels.rows) {
695 const label = (cells[at('resolution')] ?? '').trim()
696 if (label) {
697 const [first = '', ...rest] = label.split(' ')
698 resolution = first.toLowerCase()
699 note = rest.join(' ')
700 }
701 const ratio = cells[at('aspect ratio')] ?? ''
702 if (!/^(\d+p|4k)$/.test(resolution) || !/^\d+:\d+$/.test(ratio)) continue
703 pixels.keys.forEach((column, index) => {
704 const size = cells[index]?.match(/^(\d+)×(\d+)$/)
705 if (!size) return
706 const series = column.replace(/ series$/, '')
707 for (const [name, model] of byName) {
708 const own = name === column
709 const inSeries =
710 series !== column &&
711 (name === series || name.startsWith(`${series} `))
712 if (!own && !inSeries) continue
713 if (noteServes(note, name) !== true) continue
714 const key = `${model.id}|${resolution}|${ratio}`
715 const level = own ? 2 : 1
716 const geometry = out.get(model.id) ?? { fps: model.fps, dims: {} }
717 const byRatio = (geometry.dims[resolution] ??= {})
718 const size2 = { w: Number(size[1]), h: Number(size[2]) }
719 const prior = rank.get(key) ?? 0
720 if (prior > level) continue
721 const held = byRatio[ratio]
722 if (
723 prior === level &&
724 held &&
725 (held.w !== size2.w || held.h !== size2.h)
726 ) {
727 conflicted.add(model.id)
728 }
729 byRatio[ratio] = size2
730 rank.set(key, level)
731 out.set(model.id, geometry)
732 }
733 })
734 }
735 for (const id of conflicted) out.delete(id)
736 return out
737}
738
739/** Seedream 5.0 pro: per-image output rates split at a pixel count. */
740export interface ByteplusPixelTiers {
741 /** USD per input image after the first (the first is free). */
742 extraInput: number
743 /** Tier boundary in pixels; at or below it is `low`. */
744 maxLowPixels: number
745 /** The largest `size` level the page puts in the low tier (`1.5K`). */
746 lowLevel: string
747 low: number
748 high: number
749}
750
751const PIXEL_TIER_INPUT = /^First image: Free From the 2nd image: ([\d.]+)$/i
752// Layer decomposition is not read: the page says one request's layers can
753// land in different tiers, so the card refuses that mode.
754const PIXEL_TIER_OUTPUT =
755 /^Single image generation: ≤ ([\d.]+) million pixels \(([\d.]+)K or lower\): ([\d.]+) > \1 million pixels \(higher than \2K\): ([\d.]+) Layer decomposition: /i
756
757/** One image-table row as pixel tiers, or null for any other wording. */
758function pixelTierRates(
759 input: string,
760 output: string,
761): ByteplusPixelTiers | null {
762 const inMatch = PIXEL_TIER_INPUT.exec(input)
763 const outMatch = PIXEL_TIER_OUTPUT.exec(output)
764 if (!inMatch || !outMatch) return null
765 const extraInput = decimal(inMatch[1] ?? '')
766 const millions = decimal(outMatch[1] ?? '')
767 const low = decimal(outMatch[3] ?? '')
768 const high = decimal(outMatch[4] ?? '')
769 if (extraInput === null || millions === null || low === null) return null
770 if (high === null) return null
771 const lowLevel = `${outMatch[2]}K`
772 return { extraInput, maxLowPixels: millions * 1e6, lowLevel, low, high }
773}
774
775/** The image table's pixel-tiered rows; only the first table is read. */
776export function parseByteplusPixelTiers(
777 doc: ByteplusDoc,
778): Map<string, ByteplusPixelTiers> {
779 const out = new Map<string, ByteplusPixelTiers>()
780 const [table] = tablesWith(doc, [
781 'model id',
782 'input image price',
783 'output image price',
784 ])
785 if (!table) return out
786 const at = (key: string) => table.keys.indexOf(key)
787 for (const row of table.rows) {
788 const id = (row[at('model id')] ?? '').split(' ')[0] ?? ''
789 const rates = pixelTierRates(
790 row[at('input image price')] ?? '',
791 row[at('output image price')] ?? '',
792 )
793 if (/^[a-z0-9-]+$/.test(id) && rates) out.set(id, rates)
794 }
795 return out
796}
797
798/**
799 * Ark's `size` levels for Seedream 5.0 pro image generation (Image
800 * generation API, docs.byteplus.com/en/docs/ModelArk/1541523; default
801 * `2K`). The model picks the pixels, but every size that API doc lists for
802 * a level sits on one side of 2.61 MP, as the pricing page's "(1.5K or
803 * lower)" says. `4K` and `auto` are not image-generation sizes.
804 */
805const SEEDREAM_PRO_LEVELS = ['1K', '1.5K', '2K']
806
807/**
808 * `usage.generated_images × tier rate + max(0, usage.input_images − 1) ×
809 * input fee`.
810 * `size` is a level (tier from the page's "(1.5K or lower)") or `WxH`
811 * (tier from its pixel count). `layer_decomposition: true` refuses: its
812 * layers are billed per layer at each one's own tier, which no request
813 * field fixes.
814 */
815export function compileSeedreamProCard(
816 rates: ByteplusPixelTiers,
817 source: RateCard['source'],
818): RateCard | null {
819 const levelNumber = (level: string) => Number(level.replace(/K$/, ''))
820 const boundary = levelNumber(rates.lowLevel)
821 if (!SEEDREAM_PRO_LEVELS.includes(rates.lowLevel)) return null
822 const levelTier: Array<Expr> = SEEDREAM_PRO_LEVELS.flatMap((level) => [
823 { '==': [{ var: 'size.level' }, level] },
824 levelNumber(level) <= boundary ? 'low' : 'high',
825 ])
826 const pixels = { '*': [{ var: 'size.width' }, { var: 'size.height' }] }
827 const tier: Expr = {
828 if: [
829 { missing: 'size.level' },
830 { if: [{ '<=': [pixels, rates.maxLowPixels] }, 'low', 'high'] },
831 { if: levelTier },
832 ],
833 }
834 const mode: Expr = {
835 if: [{ var: 'layer_decomposition' }, 'layer_decomposition', 'generation'],
836 }
837 return {
838 inputs: {
839 size: {
840 param: 'size',
841 kind: 'dimensions',
842 levels: SEEDREAM_PRO_LEVELS,
843 default: '2K',
844 },
845 layer_decomposition: {
846 param: 'layer_decomposition',
847 kind: 'boolean',
848 default: false,
849 },
850 // Ark's own count of the request's images: `image` is a string or a
851 // list, and the bill counts what Ark received. Live 2026-10-02: no
852 // image → 0, a string → 1, a list of 3 → 3.
853 input_images: { param: 'input_images', bound: 'usage', kind: 'number' },
854 generated_images: {
855 param: 'generated_images',
856 bound: 'usage',
857 kind: 'number',
858 },
859 },
860 tables: { output: { generation: { low: rates.low, high: rates.high } } },
861 price: {
862 '+': [
863 {
864 '*': [
865 { var: 'generated_images' },
866 { lookup: { table: 'output', keys: [mode, tier] } },
867 ],
868 },
869 {
870 '*': [
871 { max: [0, { '-': [{ var: 'input_images' }, 1] }] },
872 rates.extraInput,
873 ],
874 },
875 ],
876 },
877 examples: [],
878 source,
879 }
880}
881
882/**
883 * `rate × usage.completion_tokens / 1e6`. The page bills "Token unit price ×
884 * Token consumption" and says consumption is what `usage.completion_tokens`
885 * returns, so that is the price as billed.
886 *
887 * With `geometry`, an omitted `completion_tokens` is estimated by the
888 * page's own formula over the tutorial's published sizes, and the estimate
889 * endpoint labels it as such. The estimate refuses where the published
890 * method does not hold: draft renders, `ratio: adaptive`, and any
891 * resolution × ratio the tutorial does not list.
892 *
893 * When `videoMinimums` is set, an input video uses
894 * `max(input seconds, minimum input for that output length) + output`.
895 * The minimum input seconds are the Lark table's (output 4–15 for 2.0,
896 * 4–30 for 2.5): `output - floor((output - 3) / 3) - 1`. Every pasted
897 * minimum-token cell equals that length times the row's width, height,
898 * and 24 fps, divided by 1024 and rounded. The cron still cannot read
899 * the Lark base, so a duration the table does not list refuses.
900 *
901 * Draft refuses outright on resolution-priced models: the page bills a draft
902 * at a different resolution than the request names. Video input is not a
903 * request field Ark exposes as one value (it rides in `content`), so the
904 * caller states it as `usage.input_video`. Only models whose rates split on
905 * video input take it.
906 */
907/**
908 * Minimum input seconds for one output duration, from the Seedance 2.0 and
909 * 2.5 Lark tables. Same series on both: 3s in for 4s out, 4s in for 5s out,
910 * 20s in for 30s out.
911 */
912export function seedanceMinInputSeconds(output: number): number {
913 return output - Math.floor((output - 3) / 3) - 1
914}
915
916export function compileSeedanceCard(
917 rates: ByteplusVideoRates,
918 source: RateCard['source'],
919 geometry?: {
920 model: SeedanceGeometry
921 url: string
922 hash: string
923 /** Last output duration the Lark minimum-token table publishes. */
924 videoMinimumsThrough?: number
925 },
926): RateCard | null {
927 const online = rates.default
928 if (!online) return null
929 const resolutions = Object.keys(online)
930 const variants = Object.keys(online[resolutions[0] ?? ''] ?? {})
931 // Every tier prices the same resolutions, each with the same variants.
932 const shape = (tier: Record<string, Record<string, number>>) =>
933 Object.keys(tier).sort().join() === [...resolutions].sort().join() &&
934 Object.values(tier).every(
935 (v) => Object.keys(v).sort().join() === [...variants].sort().join(),
936 )
937 if (!Object.values(rates).every(shape)) return null
938
939 const inputs: RateCard['inputs'] = {
940 // Ark's own defaults: omitted means online inference, not a draft.
941 service_tier: {
942 param: 'service_tier',
943 kind: 'enum',
944 values: Object.keys(rates),
945 default: 'default',
946 },
947 draft: { param: 'draft', kind: 'boolean', default: false },
948 completion_tokens: {
949 param: 'completion_tokens',
950 bound: 'usage',
951 kind: 'number',
952 },
953 }
954 let resolution: Expr = '*'
955 if (!resolutions.includes('*')) {
956 inputs.resolution = {
957 param: 'resolution',
958 kind: 'enum',
959 values: resolutions,
960 }
961 resolution = { if: [{ var: 'draft' }, 'draft', { var: 'resolution' }] }
962 }
963 let variant: Expr = 'all'
964 let inputVideo: Expr = 'no_input_video'
965 if (variants.includes('video')) {
966 inputs.input_video = {
967 param: 'input_video',
968 bound: 'usage',
969 kind: 'boolean',
970 }
971 variant = { if: [{ var: 'input_video' }, 'video', 'no_video'] }
972 inputVideo = {
973 if: [{ var: 'input_video' }, 'input_video', 'no_input_video'],
974 }
975 } else if (variants.includes('audio')) {
976 inputs.generate_audio = { param: 'generate_audio', kind: 'boolean' }
977 variant = { if: [{ var: 'generate_audio' }, 'audio', 'silent'] }
978 }
979
980 const tables: RateCard['tables'] = { rate: rates }
981 if (geometry && inputs.completion_tokens?.kind === 'number') {
982 // A series column also lists resolutions a member does not serve
983 // ("2.0 Fast and Mini do not support 1080p"); the rate table is the
984 // model's own list.
985 const dims = inputs.resolution
986 ? Object.fromEntries(
987 Object.entries(geometry.model.dims).filter(([r]) =>
988 resolutions.includes(r),
989 ),
990 )
991 : geometry.model.dims
992 const ratios = [...new Set(Object.values(dims).flatMap(Object.keys))]
993 const through = geometry.videoMinimumsThrough
994 const minInput =
995 through === undefined || !variants.includes('video')
996 ? undefined
997 : Object.fromEntries(
998 Array.from({ length: through - 3 }, (_, i) => {
999 const output = i + 4
1000 return [String(output), seedanceMinInputSeconds(output)]
1001 }),
1002 )
1003 const estimateInputs: RateCardEstimate['inputs'] = {
1004 ratio: { param: 'ratio', kind: 'enum', values: ratios },
1005 duration: { param: 'duration', kind: 'number' },
1006 }
1007 if (minInput) {
1008 estimateInputs.input_video_duration = {
1009 param: 'input_video_duration',
1010 kind: 'number',
1011 default: 0,
1012 }
1013 }
1014 if (!inputs.resolution) {
1015 estimateInputs.resolution = {
1016 param: 'resolution',
1017 kind: 'enum',
1018 values: Object.keys(dims),
1019 }
1020 }
1021 const side = (key: 'w' | 'h'): Expr => ({
1022 lookup: {
1023 table: 'pixels',
1024 keys: [{ var: 'resolution' }, { var: 'ratio' }, key],
1025 },
1026 })
1027 tables.pixels = dims
1028 if (minInput) tables.min_input_seconds = minInput
1029 // Shapes the published method covers; any other key refuses.
1030 tables.estimate_supported = minInput
1031 ? { no_input_video: { not_draft: 1 }, input_video: { not_draft: 1 } }
1032 : { no_input_video: { not_draft: 1 } }
1033 const seconds: Expr = minInput
1034 ? {
1035 if: [
1036 { var: 'input_video' },
1037 {
1038 '+': [
1039 {
1040 max: [
1041 { var: 'input_video_duration' },
1042 {
1043 lookup: {
1044 table: 'min_input_seconds',
1045 keys: [{ var: 'duration' }],
1046 },
1047 },
1048 ],
1049 },
1050 { var: 'duration' },
1051 ],
1052 },
1053 { var: 'duration' },
1054 ],
1055 }
1056 : { var: 'duration' }
1057 inputs.completion_tokens.estimate = {
1058 inputs: estimateInputs,
1059 value: {
1060 '*': [
1061 {
1062 lookup: {
1063 table: 'estimate_supported',
1064 keys: [
1065 inputVideo,
1066 { if: [{ var: 'draft' }, 'draft', 'not_draft'] },
1067 ],
1068 },
1069 },
1070 {
1071 '/': [
1072 {
1073 '*': [seconds, side('w'), side('h'), geometry.model.fps],
1074 },
1075 1024,
1076 ],
1077 },
1078 ],
1079 },
1080 source: { url: geometry.url, hash: geometry.hash },
1081 }
1082 }
1083 return {
1084 inputs,
1085 tables,
1086 price: {
1087 '/': [
1088 {
1089 '*': [
1090 {
1091 lookup: {
1092 table: 'rate',
1093 keys: [{ var: 'service_tier' }, resolution, variant],
1094 },
1095 },
1096 { var: 'completion_tokens' },
1097 ],
1098 },
1099 1_000_000,
1100 ],
1101 },
1102 examples: [],
1103 source,
1104 }
1105}
1106
1107/** Standard-table rates from the pricing page HTML. */
1108export function parseByteplusPricingPage(
1109 html: string,
1110): Map<string, ByteplusTokenRates> {
1111 return parseByteplusPricing(JSON.parse(pricingContent(html)) as ByteplusDoc)
1112}
1113
1114/**
1115 * `curDoc.Content` only. The page shell around it reshuffles between
1116 * fetches, so hashing the HTML would mark unchanged prices as new.
1117 */
1118export function pricingContent(
1119 html: string,
1120 label = 'byteplus pricing page',
1121): string {
1122 const at = html.indexOf('window._ROUTER_DATA')
1123 const start = html.indexOf('{', at)
1124 const end = html.indexOf('</script>', start)
1125 if (at < 0 || start < 0 || end < 0) {
1126 throw new Error(`${label}: no _ROUTER_DATA`)
1127 }
1128 const router = JSON.parse(html.slice(start, end)) as {
1129 loaderData?: Record<string, { curDoc?: { Content?: string } } | null>
1130 }
1131 const content = Object.values(router.loaderData ?? {}).find(
1132 (entry) => typeof entry?.curDoc?.Content === 'string',
1133 )?.curDoc?.Content
1134 if (!content) throw new Error(`${label}: no curDoc.Content`)
1135 return content
1136}
1137
1138type PricedFacts = Pick<
1139 ModelInfo,
1140 'pricing' | 'factSources' | 'serverTools' | 'absent'
1141>
1142
1143interface CachedModelPage {
1144 rates: Record<string, number>
1145 hash: string
1146 extractedAt: string
1147}
1148
1149/** seed-translation's page, or null (counted in `run`) when it fails. */
1150function seedTranslationPage(
1151 run: DocsRun,
1152 kv?: KVNamespace,
1153): Promise<CachedModelPage | null> {
1154 return tryDocs(run, BYTEPLUS_SEED_TRANSLATION_URL, (cached) =>
1155 cached<CachedModelPage>(kv, BYTEPLUS_SEED_TRANSLATION_URL, async () => {
1156 const content = pricingContent(
1157 await fetchByteplusDoc(BYTEPLUS_SEED_TRANSLATION_URL),
1158 'byteplus seed-translation page',
1159 )
1160 return {
1161 rates: parseByteplusModelPage(JSON.parse(content) as ByteplusDoc),
1162 hash: await sha256Text(content),
1163 extractedAt: new Date().toISOString(),
1164 }
1165 }),
1166 )
1167}
1168
1169interface CachedPricing {
1170 rates: Record<string, ByteplusTokenRates>
1171 video: Record<string, ByteplusVideoRates>
1172 images: Record<string, number>
1173 // Absent on entries cached before #102.
1174 pixelTiers?: Record<string, ByteplusPixelTiers>
1175 serverTools?: Record<string, Array<string>>
1176 hash: string
1177 extractedAt: string
1178}
1179
1180interface CachedGuide {
1181 geometry: Record<string, SeedanceGeometry>
1182 hash: string
1183}
1184
1185/**
1186 * Tutorial geometry, or none: it only feeds the labelled estimate, so a
1187 * failed fetch or parse publishes billed-only cards rather than failing
1188 * every BytePlus price with it.
1189 */
1190async function seedanceGuide(kv?: KVNamespace): Promise<CachedGuide | null> {
1191 const label = 'byteplus video generation tutorial'
1192 try {
1193 return await cachedDocs<CachedGuide>(
1194 kv,
1195 BYTEPLUS_VIDEO_GUIDE_URL,
1196 async () => {
1197 const content = pricingContent(
1198 await fetchByteplusDoc(BYTEPLUS_VIDEO_GUIDE_URL),
1199 label,
1200 )
1201 const parsed = parseSeedanceGeometry(JSON.parse(content) as ByteplusDoc)
1202 assertParsed(parsed, label)
1203 return {
1204 geometry: Object.fromEntries(parsed),
1205 hash: await sha256Text(content),
1206 }
1207 },
1208 )
1209 } catch (error) {
1210 console.warn(
1211 JSON.stringify({
1212 job: 'byteplus-pricing',
1213 skipped: 'seedance estimates',
1214 error: errorMessage(error),
1215 }),
1216 )
1217 return null
1218 }
1219}
1220
1221/**
1222 * Model-list document, or none. It only names aliases for prices the
1223 * pricing page already published, so a failed fetch still prices those rows.
1224 */
1225async function modelListContent(): Promise<string | null> {
1226 const label = 'byteplus model list'
1227 try {
1228 return pricingContent(
1229 await fetchByteplusDoc(BYTEPLUS_MODEL_LIST_URL),
1230 label,
1231 )
1232 } catch (error) {
1233 console.warn(
1234 JSON.stringify({
1235 job: 'byteplus-pricing',
1236 skipped: 'model list aliases',
1237 error: errorMessage(error),
1238 }),
1239 )
1240 return null
1241 }
1242}
1243
1244/** Card lookup by catalog id. Ids no table prices get nothing. */
1245export async function byteplusModelPricing(
1246 run: DocsRun,
1247 kv?: KVNamespace,
1248): Promise<(rawId: string) => PricedFacts> {
1249 const doc = await cachedDocs<CachedPricing>(
1250 kv,
1251 BYTEPLUS_PRICING_URL,
1252 async () => {
1253 const html = await fetchByteplusDoc(BYTEPLUS_PRICING_URL)
1254 const content = pricingContent(html)
1255 const page = JSON.parse(content) as ByteplusDoc
1256 const parsed = parseByteplusPricing(page)
1257 const video = parseByteplusVideo(page)
1258 const images = parseByteplusImages(page)
1259 const pixelTiers = parseByteplusPixelTiers(page)
1260 assertParsed(parsed, 'byteplus pricing page')
1261 assertParsed(video, 'byteplus pricing page (video)')
1262 assertParsed(images, 'byteplus pricing page (images)')
1263 const listContent = await modelListContent()
1264 const aliases = listContent
1265 ? parseByteplusAliases(JSON.parse(listContent) as ByteplusDoc)
1266 : new Map<string, string>()
1267 // Alias notes are not chat prices. A dated snapshot with no row stays
1268 // unpriced; only the published "also supports" pair is copied.
1269 sharePublishedAliases(video, aliases)
1270 sharePublishedAliases(images, aliases)
1271 sharePublishedAliases(pixelTiers, aliases)
1272 return {
1273 rates: Object.fromEntries(parsed),
1274 video: Object.fromEntries(video),
1275 images: Object.fromEntries(images),
1276 pixelTiers: Object.fromEntries(pixelTiers),
1277 serverTools: Object.fromEntries(parseByteplusServerTools(html)),
1278 hash: await sha256Text(listContent ? content + listContent : content),
1279 extractedAt: new Date().toISOString(),
1280 }
1281 },
1282 )
1283 const guide = await seedanceGuide(kv)
1284 const translation = await seedTranslationPage(run, kv)
1285 const geometry = new Map(Object.entries(guide?.geometry ?? {}))
1286 const rates = new Map(Object.entries(doc.rates))
1287 const video = new Map(Object.entries(doc.video))
1288 const images = new Map(Object.entries(doc.images))
1289 const pixelTiers = new Map(Object.entries(doc.pixelTiers ?? {}))
1290 const source = {
1291 url: BYTEPLUS_PRICING_URL,
1292 hash: doc.hash,
1293 extractedAt: doc.extractedAt,
1294 }
1295 const card = (rawId: string): RateCard | null => {
1296 const chat = byteplusRatesFor(rawId, rates)
1297 if (chat && 'periods' in chat) return compilePeriodCard(chat, source)
1298 if (chat) {
1299 return compileTokenCard(chat.base, chat.tiers, source, {
1300 extraPromptLevers: ['audio_tokens', 'audio_cache_tokens'],
1301 })
1302 }
1303 const seedance = byteplusRatesFor(rawId, video)
1304 if (seedance) {
1305 const model = byteplusRatesFor(rawId, geometry)
1306 return compileSeedanceCard(
1307 seedance,
1308 source,
1309 model && guide
1310 ? {
1311 model,
1312 url: BYTEPLUS_VIDEO_GUIDE_URL,
1313 hash: guide.hash,
1314 // Lark minimum-token table: 2.5 publishes outputs 4–30,
1315 // 2.0 publishes 4–15. Other video models have no table.
1316 videoMinimumsThrough: rawId.includes('seedance-2-5')
1317 ? 30
1318 : rawId.includes('seedance-2-0')
1319 ? 15
1320 : undefined,
1321 }
1322 : undefined,
1323 )
1324 }
1325 const tiered = byteplusRatesFor(rawId, pixelTiers)
1326 if (tiered) return compileSeedreamProCard(tiered, source)
1327 const perImage = byteplusRatesFor(rawId, images)
1328 if (perImage === undefined) return null
1329 // Billed per image returned (usage.generated_images); group-image mode
1330 // returns a variable count, so the caller supplies it.
1331 return compileUnitCard(
1332 {
1333 quantity: { param: 'generated_images', bound: 'usage' },
1334 rates: perImage,
1335 },
1336 source,
1337 )
1338 }
1339 const translationIds = new Map([['seed-translation', true]])
1340 return (rawId) => {
1341 const tools = doc.serverTools?.[rawId]
1342 const isTranslation = byteplusRatesFor(rawId, translationIds) === true
1343 // Page failed this poll: keep the stored card (`tryDocs` counted it).
1344 const lost = isTranslation && !translation ? unavailable('pricing') : {}
1345 const page = isTranslation ? translation : null
1346 const pricing = page
1347 ? compileTokenCard(page.rates, [], {
1348 url: BYTEPLUS_SEED_TRANSLATION_URL,
1349 hash: page.hash,
1350 extractedAt: page.extractedAt,
1351 })
1352 : isTranslation
1353 ? null
1354 : card(rawId)
1355 const pricingFacts = !pricing
1356 ? {}
1357 : page
1358 ? tagDocsFacts({ pricing }, BYTEPLUS_SEED_TRANSLATION_URL, page.hash)
1359 : tagDocsFacts({ pricing }, BYTEPLUS_PRICING_URL, doc.hash)
1360 const toolFacts =
1361 tools && tools.length > 0
1362 ? tagDocsFacts({ serverTools: tools }, BYTEPLUS_PRICING_URL, doc.hash)
1363 : {}
1364 const factSources = { ...pricingFacts, ...toolFacts }
1365 if (!pricing && !tools) return lost
1366 return {
1367 ...lost,
1368 ...(pricing ? { pricing } : {}),
1369 ...(tools && tools.length > 0 ? { serverTools: tools } : {}),
1370 ...(Object.keys(factSources).length > 0 ? { factSources } : {}),
1371 }
1372 }
1373}