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

video.ts

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