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

video.ts

738 lines25.8 KB

1import {
2 isFileSource,
3 resolveMediaPrompt,
4 unsupportedFileSourceError,
5} from '@tanstack/ai'
6import { BaseVideoAdapter } from '@tanstack/ai/adapters'
7import { toRunErrorPayload } from '@tanstack/ai/adapter-internals'
8import {
9 bytePlusArkError,
10 bytePlusArkHeaders,
11 bytePlusTimeoutSignal,
12 getBytePlusArkApiKeyFromEnv,
13 readJsonBody,
14 toHeaderRecord,
15 withBytePlusArkDefaults,
16} from '../utils/client'
17import {
18 getBytePlusVideoDurationOptions,
19 isKnownBytePlusVideoModel,
20} from '../model-meta'
21import {
22 resolveBytePlusVideoResolution,
23 resolveBytePlusVideoSize,
24 supportsAudioOnlyReference,
25 supportsLastFrame,
26 supportsReferenceMedia,
27} from '../video/video-provider-options'
28import type { DurationOptions } from '@tanstack/ai/adapters'
29import type {
30 AudioPart,
31 ImagePart,
32 MediaInputMetadata,
33 TokenUsage,
34 VideoGenerationOptions,
35 VideoJobResult,
36 VideoPart,
37 VideoStatusResult,
38 VideoUrlResult,
39} from '@tanstack/ai'
40import type {
41 BytePlusVideoContentPart,
42 BytePlusVideoCreateRequest,
43 BytePlusVideoCreateResponse,
44 BytePlusVideoTask,
45 BytePlusVideoTaskStatus,
46 BytePlusVideoTaskUsage,
47} from '../video/wire-types'
48import type { BytePlusVideoProviderOptions } from '../video/video-provider-options'
49import type {
50 BytePlusVideoModelOrString,
51 ResolveBytePlusVideoInputModalities,
52 ResolveBytePlusVideoSize,
53} from '../model-meta'
54import type { BytePlusArkConfig } from '../utils/client'
55​
56/**
57 * Configuration for the BytePlus Seedance video adapter.
58 *
59 * @experimental Video generation is an experimental feature and may change.
60 */
61export interface BytePlusVideoConfig extends BytePlusArkConfig {}
62​
63/** Path of the Seedance task API, relative to the Ark base URL. */
64const TASKS_PATH = '/contents/generations/tasks'
65​
66/**
67 * `content.video_url` and `content.last_frame_url` are deleted 24 hours after
68 * the task produces them.
69 */
70const VIDEO_URL_TTL_MS = 24 * 60 * 60 * 1000
71​
72/**
73 * Converts a media prompt part into the URL string Seedance's `content[]`
74 * takes: public URLs pass through (BytePlus fetches them server-side), data
75 * sources become base64 data URIs.
76 */
77function mediaPartToUrl(
78 part:
79 | ImagePart<MediaInputMetadata>
80 | VideoPart<MediaInputMetadata>
81 | AudioPart<MediaInputMetadata>,
82): string {
83 const { source } = part
84 if (isFileSource(source)) throw unsupportedFileSourceError('byteplus')
85 if (source.type === 'url') return source.value
86 if (source.value.startsWith('data:')) return source.value
87 return `data:${source.mimeType.toLowerCase()};base64,${source.value}`
89​
90/** Coerces a usage count that the API types as a string but sends as a number. */
91function toTokenCount(value: number | string | undefined): number | undefined {
92 if (typeof value === 'number') return value
93 if (typeof value === 'string') {
94 const parsed = Number(value)
95 return Number.isFinite(parsed) ? parsed : undefined
96 }
97 return undefined
99​
100/**
101 * Maps a finished task's usage onto `TokenUsage`.
102 *
103 * Seedance bills output only. The API documents input tokens as always 0 and
104 * `total_tokens` as equal to `completion_tokens`, so `promptTokens` is 0 and
105 * the completion count is the billed quantity (`usage.billed` with
106 * `unit: 'tokens'`).
107 */
108function buildBytePlusVideoUsage(
109 usage: BytePlusVideoTaskUsage | undefined,
110): TokenUsage | undefined {
111 if (!usage) return undefined
112​
113 const completionTokens = toTokenCount(usage.completion_tokens)
114 const totalTokens = toTokenCount(usage.total_tokens)
115 if (completionTokens === undefined && totalTokens === undefined) {
116 return undefined
117 }
118​
119 const completion = completionTokens ?? totalTokens ?? 0
120 return {
121 promptTokens: 0,
122 completionTokens: completion,
123 totalTokens: totalTokens ?? completion,
124 billed: { quantity: completion, unit: 'tokens' },
125 }
127​
128/**
129 * Formats a terminal task's error detail for a status / failure message.
130 *
131 * Always returns a string. Core surfaces a failed job as
132 * `throw new Error(statusResult.error || 'Video generation failed')`, so
133 * returning `undefined` for a failure Ark reported without an `error` block
134 * would hand the caller an unattributable error. The final fallback is a
135 * snapshot of the identifying fields instead.
136 */
137function describeTaskFailure(task: BytePlusVideoTask): string {
138 const { code, message } = task.error ?? {}
139 if (code && message) return `${code}: ${message}`
140 if (message) return message
141 if (code) return code
142 // `expired` and `cancelled` are terminal without an `error` block.
143 if (task.status === 'expired') {
144 return 'Task expired before it finished (execution_expires_after elapsed).'
145 }
146 if (task.status === 'cancelled') return 'Task was cancelled.'
147 return (
148 `Task reported status "${task.status ?? 'unknown'}" with no error detail ` +
149 `(id=${task.id ?? 'unknown'}, model=${task.model ?? 'unknown'}).`
150 )
152​
153/**
154 * BytePlus Seedance video generation adapter.
155 *
156 * Drives Ark's asynchronous task API — `POST /contents/generations/tasks` to
157 * submit, `GET /contents/generations/tasks/{id}` to poll and to read the
158 * finished video URL. Core owns the polling loop; this adapter implements the
159 * three primitives plus the duration metadata.
160 *
161 * Prompt parts map onto Seedance's `content[]` roles, which the API sorts into
162 * mutually exclusive task types:
163 *
164 * - `'start_frame'` (or a single un-roled image) → `first_frame` — the frame
165 * the video opens on (`i2v`).
166 * - `'end_frame'` → `last_frame` — the frame it closes on (`flf2v`); Seedance
167 * requires a `first_frame` alongside it, and
168 * `seedance-1-0-pro-fast-251015` does not support it at all.
169 * - `'reference'` / `'character'` → `reference_image`, video parts →
170 * `reference_video`, audio parts → `reference_audio` — subject and style
171 * references the model draws on (`r2v`, Seedance 2.5 and 2.0 family).
172 * Seedance 2.5 also accepts audio-only reference input; 2.0 does not.
173 *
174 * Frame roles and reference roles cannot be combined in one request, so the
175 * adapter rejects a mix up front rather than surfacing a raw 400.
176 *
177 * @experimental Video generation is an experimental feature and may change.
178 *
179 * @example
180 * ```typescript
181 * const adapter = byteplusVideo('seedance-1-0-pro-fast-251015')
182 *
183 * const { jobId } = await generateVideo({
184 * adapter,
185 * prompt: 'a guitar being played in a store',
186 * size: '16:9_720p',
187 * duration: 4,
188 * modelOptions: { service_tier: 'flex' },
189 * })
190 * ```
191 */
192export class BytePlusVideoAdapter<
193 TModel extends BytePlusVideoModelOrString,
194> extends BaseVideoAdapter<
195 TModel,
196 BytePlusVideoProviderOptions,
197 Record<TModel, BytePlusVideoProviderOptions>,
198 Record<TModel, ResolveBytePlusVideoSize<TModel>>,
199 Record<TModel, ResolveBytePlusVideoInputModalities<TModel>>,
200 Record<TModel, number>
201> {
202 readonly name = 'byteplus' as const
203​
204 /** Config with the Ark base URL resolved and its trailing slashes trimmed. */
205 private readonly clientConfig: Omit<BytePlusVideoConfig, 'baseURL'> & {
206 baseURL: string
207 }
208​
209 constructor(config: BytePlusVideoConfig, model: TModel) {
210 super({}, model)
211 this.clientConfig = withBytePlusArkDefaults(config)
212 }
213​
214 private async request(
215 path: string,
216 init?: Omit<RequestInit, 'headers'>,
217 ): Promise<{ response: Response; body: unknown }> {
218 const fetchImpl = this.clientConfig.fetch ?? fetch
219 const signal = bytePlusTimeoutSignal(this.clientConfig.timeout)
220 const response = await fetchImpl(`${this.clientConfig.baseURL}${path}`, {
221 ...init,
222 ...(signal && { signal }),
223 headers: bytePlusArkHeaders(
224 this.clientConfig.apiKey,
225 toHeaderRecord(this.clientConfig.defaultHeaders),
226 ),
227 })
228 return { response, body: await readJsonBody(response) }
229 }
230​
231 /**
232 * Builds the `content[]` array from the resolved prompt, enforcing
233 * Seedance's role vocabulary and mode exclusivity.
234 */
235 private buildContent(
236 resolved: ReturnType<typeof resolveMediaPrompt>,
237 ): Array<BytePlusVideoContentPart> {
238 const model = this.model
239 const content: Array<BytePlusVideoContentPart> = []
240 if (resolved.text) content.push({ type: 'text', text: resolved.text })
241​
242 // Every rule below except the role vocabulary itself is a claim about a
243 // *specific* model's capabilities, drawn from the known Seedance catalog.
244 // None of it can be true of a model that does not exist yet, so for an
245 // unknown id the guards stand down and Ark rules — otherwise the escape
246 // hatch would block exactly the requests it exists to enable (see
247 // BytePlusVideoModelOrString). 'mask' / 'control' still throw: Seedance's
248 // wire format has no field to carry them on any model.
249 const gated = isKnownBytePlusVideoModel(model)
250​
251 let firstFrames = 0
252 let lastFrames = 0
253 // Audio counts as a reference for the mode-exclusivity check. On Seedance
254 // 2.0 it also needs a visual reference; 2.5 allows audio-only.
255 let visualReferences = 0
256 let audioReferences = 0
257​
258 for (const part of resolved.images) {
259 const role = part.metadata?.role
260 switch (role) {
261 case 'mask':
262 case 'control':
263 throw new Error(
264 `byteplus: Seedance has no '${role}' image input on model ${model}. ` +
265 `Use 'start_frame', 'end_frame' or 'reference'.`,
266 )
267 case 'end_frame': {
268 if (gated && !supportsLastFrame(model)) {
269 throw new Error(
270 `byteplus: ${model} does not support a closing frame — it does ` +
271 `text-to-video and first-frame image-to-video only. Drop the ` +
272 `'end_frame' image or switch to a model with first-and-last-frame support.`,
273 )
274 }
275 lastFrames++
276 content.push({
277 type: 'image_url',
278 image_url: { url: mediaPartToUrl(part) },
279 role: 'last_frame',
280 })
281 break
282 }
283 case 'reference':
284 case 'character': {
285 if (gated && !supportsReferenceMedia(model)) {
286 throw new Error(
287 `byteplus: ${model} does not support reference images. Reference ` +
288 `media is available on Seedance 2.5 and the 2.0 family; on this ` +
289 `model use 'start_frame' / 'end_frame' images instead.`,
290 )
291 }
292 visualReferences++
293 content.push({
294 type: 'image_url',
295 image_url: { url: mediaPartToUrl(part) },
296 role: 'reference_image',
297 })
298 break
299 }
300 // An un-roled image is the opening frame, matching the API's own
301 // default and the fal / Veo adapters' positional convention.
302 case 'start_frame':
303 case undefined: {
304 firstFrames++
305 content.push({
306 type: 'image_url',
307 image_url: { url: mediaPartToUrl(part) },
308 role: 'first_frame',
309 })
310 break
311 }
312 }
313 }
314​
315 // Video and audio parts only exist in reference mode: Seedance rejects an
316 // un-roled video with "reference media mode requires video role to be
317 // reference_video", and has no frame-style role for either modality.
318 for (const part of resolved.videos) {
319 if (gated && !supportsReferenceMedia(model)) {
320 throw new Error(
321 `byteplus: ${model} does not accept video prompt parts. Reference ` +
322 `video is available on Seedance 2.5 and the 2.0 family only.`,
323 )
324 }
325 visualReferences++
326 content.push({
327 type: 'video_url',
328 video_url: { url: mediaPartToUrl(part) },
329 role: 'reference_video',
330 })
331 }
332​
333 for (const part of resolved.audios) {
334 if (gated && !supportsReferenceMedia(model)) {
335 throw new Error(
336 `byteplus: ${model} does not accept audio prompt parts. Reference ` +
337 `audio is available on Seedance 2.5 and the 2.0 family only.`,
338 )
339 }
340 audioReferences++
341 content.push({
342 type: 'audio_url',
343 audio_url: { url: mediaPartToUrl(part) },
344 role: 'reference_audio',
345 })
346 }
347​
348 const frames = firstFrames + lastFrames
349 if (gated && frames > 0 && visualReferences + audioReferences > 0) {
350 throw new Error(
351 `byteplus: first/last frame inputs cannot be combined with reference ` +
352 `media on model ${model}. Use either frame roles ('start_frame', ` +
353 `'end_frame') or reference roles ('reference', 'character', video, ` +
354 `audio) — not both.`,
355 )
356 }
357​
358 if (gated && firstFrames > 1) {
359 throw new Error(
360 `byteplus: ${model} accepts at most one opening frame; received ` +
361 `${firstFrames} un-roled or 'start_frame' images. Use metadata.role ` +
362 `('end_frame', 'reference') to disambiguate the others.`,
363 )
364 }
365​
366 if (gated && lastFrames > 1) {
367 throw new Error(
368 `byteplus: ${model} accepts at most one closing frame; received ` +
369 `${lastFrames} 'end_frame' images.`,
370 )
371 }
372​
373 // Seedance treats a closing frame as the second half of first-and-last-
374 // frame mode: on its own it fails with "last frame image content cannot be
375 // mixed with first frame or reference image content".
376 if (gated && lastFrames > 0 && firstFrames === 0) {
377 throw new Error(
378 `byteplus: a closing frame needs an opening frame alongside it on ` +
379 `model ${model}. Add a 'start_frame' image, or drop the 'end_frame' role.`,
380 )
381 }
382​
383 if (
384 gated &&
385 audioReferences > 0 &&
386 visualReferences === 0 &&
387 !supportsAudioOnlyReference(model)
388 ) {
389 throw new Error(
390 `byteplus: a reference audio input cannot be the only reference on ` +
391 `model ${model}. Pair it with a reference image or video, or use ` +
392 `Seedance 2.5 which accepts audio-only reference input.`,
393 )
394 }
395​
396 if (content.length === 0) {
397 throw new Error(
398 `byteplus: a video prompt must carry text or at least one media input ` +
399 `(model: ${model}).`,
400 )
401 }
402​
403 return content
404 }
405​
406 async createVideoJob(
407 options: VideoGenerationOptions<
408 BytePlusVideoProviderOptions,
409 ResolveBytePlusVideoSize<TModel>,
410 number
411 >,
412 ): Promise<VideoJobResult> {
413 const { size, modelOptions, logger } = options
414 const model = this.model
415​
416 const content = this.buildContent(resolveMediaPrompt(options.prompt))
417​
418 // The generic `size` carries a "ratio_resolution" template and splits back
419 // into Seedance's separate fields. Explicit modelOptions win below.
420 const parsedSize =
421 size !== undefined ? resolveBytePlusVideoSize(model, size) : undefined
422​
423 // Coerce the requested duration into the model's range rather than letting
424 // the API reject it. `modelOptions.duration` is deliberately not snapped:
425 // it is the escape hatch for `-1` (model picks the length).
426 //
427 // An unknown model's duration goes through verbatim. Snapping it would
428 // mean clamping against the ranges today's models happen to have, so a
429 // future model's legitimate 20-second request would silently become 15 —
430 // corrupting the request instead of protecting it.
431 const duration =
432 options.duration !== undefined
433 ? isKnownBytePlusVideoModel(model)
434 ? this.snapDuration(options.duration)
435 : options.duration
436 : undefined
437​
438 const request: BytePlusVideoCreateRequest = {
439 ...(parsedSize && {
440 ratio: parsedSize.ratio,
441 ...(parsedSize.resolution !== undefined && {
442 resolution: parsedSize.resolution,
443 }),
444 }),
445 ...(duration !== undefined && { duration }),
446 // Explicit provider options win over everything derived above.
447 ...modelOptions,
448 model,
449 content,
450 }
451​
452 // Validate what actually ships, not just what `size` contributed: a
453 // `modelOptions.resolution` overriding an already-checked size would
454 // otherwise reach Ark unchecked.
455 if (request.resolution !== undefined) {
456 request.resolution = resolveBytePlusVideoResolution(
457 model,
458 request.resolution,
459 )
460 }
461​
462 try {
463 logger.request(
464 `activity=video.create provider=${this.name} model=${model} size=${size ?? 'default'} duration=${request.duration ?? 'default'}`,
465 { provider: this.name, model },
466 )
467​
468 const { response, body } = await this.request(TASKS_PATH, {
469 method: 'POST',
470 body: JSON.stringify(request),
471 })
472 if (!response.ok) {
473 throw bytePlusArkError(response.status, body, 'video task creation')
474 }
475​
476 const { id } = (body ?? {}) as BytePlusVideoCreateResponse
477 if (!id) {
478 throw new Error('byteplus: video task creation returned no task id.')
479 }
480​
481 return { jobId: id, model }
482 } catch (error: unknown) {
483 logger.errors(`${this.name}.createVideoJob fatal`, {
484 error: toRunErrorPayload(error, `${this.name}.createVideoJob failed`),
485 source: `${this.name}.createVideoJob`,
486 })
487 throw error
488 }
489 }
490​
491 /**
492 * Fetches a task, tagging the thrown error with the HTTP status.
493 *
494 * The 200 body is validated rather than cast. `readJsonBody` returns
495 * `undefined` for an empty body and the raw text for a non-JSON one — both
496 * documented failure modes of these hosts (an HTML error page from a proxy
497 * in front of the API). Casting either to `BytePlusVideoTask` yields a task
498 * whose `status` is `undefined`, which {@link mapStatus} would have to
499 * interpret; the honest answer is that the response was not a task at all,
500 * so say so while the body is still in hand.
501 */
502 private async retrieveTask(jobId: string): Promise<BytePlusVideoTask> {
503 const { response, body } = await this.request(
504 `${TASKS_PATH}/${encodeURIComponent(jobId)}`,
505 )
506 if (!response.ok) {
507 const error = bytePlusArkError(response.status, body, 'video task lookup')
508 ;(error as { status?: number }).status = response.status
509 throw error
510 }
511 if (typeof body !== 'object' || body === null) {
512 throw bytePlusArkError(
513 response.status,
514 body,
515 `video task lookup (job ${jobId}) returned a non-object body`,
516 )
517 }
518 return body as BytePlusVideoTask
519 }
520​
521 async getVideoStatus(jobId: string): Promise<VideoStatusResult> {
522 let task: BytePlusVideoTask
523 try {
524 task = await this.retrieveTask(jobId)
525 } catch (error) {
526 // A task record lives 7 days from creation; past that the id 404s. Keep
527 // Ark's own code/message: a 404 from a wrong baseURL, a proxy, or a
528 // region mismatch is not an expired job id, and collapsing them all to
529 // "Job not found" sends the caller hunting the wrong thing.
530 if ((error as { status?: number }).status === 404) {
531 return {
532 jobId,
533 status: 'failed',
534 error: `Job not found: ${jobId} (${(error as Error).message})`,
535 }
536 }
537 throw error
538 }
539​
540 const status = this.mapStatus(task.status)
541 const failure = status === 'failed' ? describeTaskFailure(task) : undefined
542 return {
543 jobId,
544 status,
545 ...(failure !== undefined && { error: failure }),
546 }
547 }
548​
549 override async getVideo(jobId: string): Promise<VideoUrlResult> {
550 let task: BytePlusVideoTask
551 try {
552 task = await this.retrieveTask(jobId)
553 } catch (error) {
554 // See getVideoStatus: Ark's detail distinguishes an expired id from a
555 // misrouted request.
556 if ((error as { status?: number }).status === 404) {
557 throw new Error(
558 `Video job not found: ${jobId} (${(error as Error).message})`,
559 )
560 }
561 throw error
562 }
563​
564 const status = this.mapStatus(task.status)
565 if (status === 'failed') {
566 throw new Error(
567 `Video generation failed: ${describeTaskFailure(task)}. Job ID: ${jobId}`,
568 )
569 }
570​
571 const url = task.content?.video_url
572 if (!url) {
573 throw new Error(
574 `Video is not ready for download. Check status first. Job ID: ${jobId}`,
575 )
576 }
577​
578 // The 24-hour window runs from when the output was produced, which is the
579 // last status change on a succeeded task — `created_at` anchors the
580 // separate 7-day retention of the task record itself, and can be far
581 // earlier (a live `flex` task sat queued ~15 minutes). Corroborated by the
582 // signed TOS link itself, which carries `X-Tos-Expires=86400` from an
583 // `X-Tos-Date` matching `updated_at`. Fall back to `created_at` only when
584 // `updated_at` is missing.
585 const anchorSeconds = task.updated_at ?? task.created_at
586 const expiresAt =
587 anchorSeconds !== undefined
588 ? new Date(anchorSeconds * 1000 + VIDEO_URL_TTL_MS)
589 : undefined
590​
591 const usage = buildBytePlusVideoUsage(task.usage)
592 return {
593 jobId,
594 url,
595 ...(expiresAt && { expiresAt }),
596 ...(usage && { usage }),
597 }
598 }
599​
600 /**
601 * Maps Seedance task states onto the generic video status set. `expired`
602 * (the task outlived `execution_expires_after`) and `cancelled` are
603 * terminal non-successes, so both report as failed.
604 *
605 * An unrecognized state throws rather than defaulting to `processing`.
606 * Core's poll loop treats `processing` as "keep waiting", so mapping an
607 * unknown state — a missing `status`, or a terminal one Ark adds later such
608 * as `rejected` — onto it means polling until `maxDuration` and then
609 * reporting a generic timeout, with the state Ark actually sent never
610 * reaching the caller. Failing here names it.
611 */
612 protected mapStatus(
613 apiStatus: BytePlusVideoTaskStatus | string | undefined,
614 ): VideoStatusResult['status'] {
615 switch (apiStatus) {
616 case 'queued':
617 return 'pending'
618 case 'running':
619 return 'processing'
620 case 'succeeded':
621 return 'completed'
622 case 'failed':
623 case 'expired':
624 case 'cancelled':
625 return 'failed'
626 case undefined:
627 default:
628 throw new Error(
629 `byteplus: unrecognized Seedance task status ` +
630 `${apiStatus === undefined ? '(missing)' : `"${apiStatus}"`}. ` +
631 `Known states: queued, running, succeeded, failed, expired, cancelled.`,
632 )
633 }
634 }
635​
636 /**
637 * Seedance accepts any whole second inside a per-model range: 4–15s on the
638 * 2.0 family, 4–12s on 1.5-pro, 2–12s on the 1.0 models. An unknown model
639 * reports the union of those ranges as a UI hint — see
640 * `BYTEPLUS_VIDEO_FALLBACK_DURATIONS`, which `createVideoJob` does not snap
641 * against.
642 */
643 override availableDurations(): DurationOptions<number> {
644 return getBytePlusVideoDurationOptions(this.model)
645 }
647​
648/**
649 * Creates a BytePlus Seedance video adapter with an explicit API key.
650 * Type resolution happens here at the call site.
651 *
652 * @experimental Video generation is an experimental feature and may change.
653 *
654 * @param model - The model name (e.g., 'seedance-1-0-pro-fast-251015')
655 * @param apiKey - Your BytePlus Ark API key
656 * @param config - Optional additional configuration
657 * @returns Configured BytePlus video adapter instance with resolved types
658 *
659 * @example
660 * ```typescript
661 * const adapter = createBytePlusVideo('seedance-1-5-pro-251215', 'ark-...')
662 *
663 * const { jobId } = await generateVideo({
664 * adapter,
665 * prompt: 'a guitar being played in a store',
666 * size: '16:9_1080p',
667 * duration: 5,
668 * })
669 * ```
670 */
671export function createBytePlusVideo<TModel extends BytePlusVideoModelOrString>(
672 model: TModel,
673 apiKey: string,
674 config?: Omit<BytePlusVideoConfig, 'apiKey'>,
675): BytePlusVideoAdapter<TModel> {
676 return new BytePlusVideoAdapter({ apiKey, ...config }, model)
678​
679/**
680 * Creates a BytePlus Seedance video adapter, reading `ARK_API_KEY` from the
681 * environment. Type resolution happens here at the call site.
682 *
683 * Note that Ark keys are region-isolated and Seedance is only served from the
684 * Asia-Pacific endpoint — an EU key will not work here.
685 *
686 * @experimental Video generation is an experimental feature and may change.
687 *
688 * @param model - The model name (e.g., 'dreamina-seedance-2-0-260128')
689 * @param config - Optional configuration (excluding apiKey, auto-detected)
690 * @returns Configured BytePlus video adapter instance with resolved types
691 * @throws Error if ARK_API_KEY is not found in environment
692 *
693 * @example
694 * ```typescript
695 * const adapter = byteplusVideo('dreamina-seedance-2-0-260128')
696 *
697 * // Image-to-video: an un-roled image is the opening frame.
698 * const { jobId } = await generateVideo({
699 * adapter,
700 * prompt: [
701 * { type: 'text', content: 'the guitarist starts playing' },
702 * { type: 'image', source: { type: 'url', value: 'https://example.com/shop.jpg' } },
703 * ],
704 * })
705 *
706 * const status = await getVideoJobStatus({ adapter, jobId })
707 * ```
708 *
709 * ## Models this package does not know yet
710 *
711 * `model` also accepts any string, so a Seedance id BytePlus publishes after
712 * this release works without upgrading. **Seedance 2.5 is the case this exists
713 * for**: `dreamina-seedance-2-5-260628` is real and reachable, but its
714 * capability cells could not be probed from this repo's account (Ark answers
715 * 404 `ModelNotOpen` until the model is activated in the Ark Console), so it
716 * is deliberately absent from the narrowed model tables. Passing it here works
717 * for an account that has activated it.
718 *
719 * An unknown id relaxes both halves of the adapter: the `size` type widens to
720 * any string, provider options are ungated, and the runtime guards that encode
721 * per-model capabilities — resolution tiers, closing-frame and reference-media
722 * support, frame cardinality and mode exclusivity, duration snapping — stand
723 * down so Ark decides. Known ids are unaffected. See
724 * {@link BytePlusVideoModelOrString} for how to discover and probe an id.
725 *
726 * @example
727 * ```typescript
728 * // Seedance 2.5, before this package ships probe-verified metadata for it:
729 * const adapter = byteplusVideo('dreamina-seedance-2-5-260628')
730 * ```
731 */
732export function byteplusVideo<TModel extends BytePlusVideoModelOrString>(
733 model: TModel,
734 config?: Omit<BytePlusVideoConfig, 'apiKey'>,
735): BytePlusVideoAdapter<TModel> {
736 const apiKey = getBytePlusArkApiKeyFromEnv()
737 return createBytePlusVideo(model, apiKey, config)