Open History to see the last commit
1import { createServerFn } from '@tanstack/react-start'
2import { getRequest } from '@tanstack/react-start/server'
3import {
4 falFiles,
5 falImage,
6 falLiveVideo,
7 falVideo,
8 isFalLiveVideoModel,
9} from '@tanstack/ai-fal'
10import {
11 createGeminiFiles,
12 createGeminiImage,
13 createGeminiVideo,
14} from '@tanstack/ai-gemini'
15import { createGrokImage, createGrokVideo } from '@tanstack/ai-grok'
16import { createOpenRouterVideo } from '@tanstack/ai-openrouter'
17import {
18 BYTEPLUS_VIDEO_MODELS,
19 createBytePlusImage,
20 createBytePlusVideo,
21 getBytePlusVideoDurationOptions,
22 resolveBytePlusVideoResolution,
23 supportsLastFrame,
24 supportsReferenceMedia,
25} from '@tanstack/ai-byteplus'
26import {
27 fileSourceFromHandle,
28 generateImage,
29 generateLiveVideo,
30 generateVideo,
31 generateWorld,
32 toServerSentEventsResponse,
33 uploadFile,
34} from '@tanstack/ai'
35import { byokMissing, getByokKey } from '@tanstack/ai/byok/server'
36import {
37 createReactorVideo,
38 createReactorWorld,
39 isReactorWorldModel,
40} from '@tanstack/ai-reactor'
41import { worldlabsWorld, isWorldLabsWorldModel } from '@tanstack/ai-worldlabs'
42import { pickSplatUrl } from '@/lib/marble-splat'
43import {
44 byteplusByok,
45 falByok,
46 geminiByok,
47 grokByok,
48 openrouterByok,
49 reactorByok,
50 worldlabsByok,
51} from '@/lib/byok'
52import type { ByokProvider } from '@tanstack/ai/byok'
53import type {
54 LiveVideoModelId,
55 LiveVideoResolution,
56 WorldModelId,
57 WorldResolution,
58} from './models'
59import {
60 isLiveVideoModelId,
61 liveVideoProvider,
62 WORLD_RESOLUTIONS,
63} from './models'
64
65import type { FilesAdapter, StreamChunk } from '@tanstack/ai'
66import type {
67 BytePlusVideoModel,
68 BytePlusVideoModelOrString,
69 BytePlusVideoProviderOptions,
70 BytePlusVideoResolution,
71} from '@tanstack/ai-byteplus'
72import type {
73 ImagePart,
74 MediaInputMetadata,
75 MediaPrompt,
76 TextPart,
77 VideoPart,
78} from '@tanstack/ai/client'
79import type { OmniTaskMode } from './models'
80import type { SeedanceCapability, SeedanceJobOptions } from './seedance'
81import { SEEDANCE_RESOLUTION_TIERS } from './seedance'
82
83/** A prompt restricted to text — accepted by every (incl. text-only) model. */
84type TextPrompt = string | Array<TextPart>
85/** A prompt of text + image parts — accepted by image-conditioned models. */
86type ImagePrompt = string | Array<TextPart | ImagePart<MediaInputMetadata>>
87/** A prompt of text + image + video parts — Gemini Omni Flash accepts all three. */
88type OmniPrompt =
89 | string
90 | Array<
91 TextPart | ImagePart<MediaInputMetadata> | VideoPart<MediaInputMetadata>
92 >
93
94/** True when the prompt carries text — a non-empty string or any prompt part. */
95function hasPromptContent(prompt: MediaPrompt): boolean {
96 return typeof prompt === 'string'
97 ? prompt.trim().length > 0
98 : prompt.length > 0
99}
100
101/**
102 * Narrows a wire `MediaPrompt` to a text + image prompt for image-conditioned
103 * models, throwing on any other part kind (video/audio) so unsupported inputs
104 * fail fast rather than being silently dropped.
105 */
106function asImagePrompt(prompt: MediaPrompt): ImagePrompt {
107 if (typeof prompt === 'string') return prompt
108 return prompt.map((part) => {
109 if (part.type === 'text' || part.type === 'image') return part
110 throw new Error(`Unsupported prompt part for image model: ${part.type}`)
111 })
112}
113
114/**
115 * Narrows a wire `MediaPrompt` to a text-only prompt, throwing if any image /
116 * video / audio part is present (text-to-image models can't accept inputs).
117 */
118function asTextPrompt(prompt: MediaPrompt): TextPrompt {
119 if (typeof prompt === 'string') return prompt
120 return prompt.map((part) => {
121 if (part.type === 'text') return part
122 throw new Error(
123 `Model does not support image inputs (received ${part.type} part)`,
124 )
125 })
126}
127
128/**
129 * Narrows a wire `MediaPrompt` for Gemini Omni Flash, which accepts text,
130 * image, and video prompt parts (audio would be the only rejected kind).
131 */
132function asOmniPrompt(prompt: MediaPrompt): OmniPrompt {
133 if (typeof prompt === 'string') return prompt
134 return prompt.map((part) => {
135 if (part.type === 'text' || part.type === 'image' || part.type === 'video')
136 return part
137 throw new Error(`Unsupported prompt part for Omni Flash: ${part.type}`)
138 })
139}
140
141/**
142 * Like `asImagePrompt`, but additionally requires at least one image part —
143 * image-to-video endpoints need a start frame.
144 */
145function asImageToVideoPrompt(
146 prompt: MediaPrompt,
147): Array<TextPart | ImagePart<MediaInputMetadata>> {
148 const narrowed = asImagePrompt(prompt)
149 if (
150 typeof narrowed === 'string' ||
151 !narrowed.some((part) => part.type === 'image')
152 ) {
153 throw new Error('Start image is required for image-to-video')
154 }
155 return narrowed
156}
157
158/**
159 * Upload each inline (base64 `data`) image input to the provider's Files API and
160 * swap in a `{ type: 'file' }` handle. A reference image / start frame is then
161 * uploaded once via the tree-shakeable files adapter (`geminiF()` /
162 * `falF()`, the BYOK-keyed wrappers below) instead of being re-sent inline
163 * as base64 on the generation
164 * request — the memory-safe path for large inputs. URL and already-uploaded
165 * sources pass through untouched.
166 */
167async function uploadInlineImageInputs(
168 prompt: string | Array<TextPart | ImagePart<MediaInputMetadata>>,
169 files: FilesAdapter,
170): Promise<string | Array<TextPart | ImagePart<MediaInputMetadata>>> {
171 if (typeof prompt === 'string') return prompt
172 return Promise.all(
173 prompt.map(async (part) => {
174 if (part.type !== 'image' || part.source.type !== 'data') return part
175 const handle = await uploadFile({
176 adapter: files,
177 input: { data: part.source.value, mimeType: part.source.mimeType },
178 })
179 return { ...part, source: fileSourceFromHandle(handle) }
180 }),
181 )
182}
183
184/**
185 * Poll cadence for the streamed video lifecycle. The server holds the request
186 * open and polls the provider itself, so this is the rate at which
187 * `video:status` events reach the browser's `useGenerateVideo`.
188 */
189const VIDEO_POLL_INTERVAL_MS = 4000
190
191function requireByok(provider: ByokProvider): string {
192 const apiKey = getByokKey(getRequest(), provider)
193 if (!apiKey) {
194 throw byokMissing(provider)
195 }
196 return apiKey
197}
198
199function falI(model: Parameters<typeof falImage>[0]) {
200 return falImage(model, { apiKey: requireByok(falByok) })
201}
202
203function falV(model: Parameters<typeof falVideo>[0]) {
204 return falVideo(model, { apiKey: requireByok(falByok) })
205}
206
207function falL(model: Parameters<typeof falLiveVideo>[0]) {
208 return falLiveVideo(model, { apiKey: requireByok(falByok) })
209}
210
211function falF() {
212 return falFiles({ apiKey: requireByok(falByok) })
213}
214
215function grokI(model: Parameters<typeof createGrokImage>[0]) {
216 return createGrokImage(model, requireByok(grokByok))
217}
218
219function grokV(model: Parameters<typeof createGrokVideo>[0]) {
220 return createGrokVideo(model, requireByok(grokByok))
221}
222
223function geminiI(model: Parameters<typeof createGeminiImage>[0]) {
224 return createGeminiImage(model, requireByok(geminiByok))
225}
226
227function geminiV(model: Parameters<typeof createGeminiVideo>[0]) {
228 return createGeminiVideo(model, requireByok(geminiByok))
229}
230
231function geminiF() {
232 return createGeminiFiles(requireByok(geminiByok))
233}
234
235function byteplusI(model: Parameters<typeof createBytePlusImage>[0]) {
236 return createBytePlusImage(model, requireByok(byteplusByok))
237}
238
239function byteplusV(model: Parameters<typeof createBytePlusVideo>[0]) {
240 return createBytePlusVideo(model, requireByok(byteplusByok))
241}
242
243function openRouterV(model: Parameters<typeof createOpenRouterVideo>[0]) {
244 return createOpenRouterVideo(model, requireByok(openrouterByok))
245}
246
247function reactorV(model: Parameters<typeof createReactorVideo>[0]) {
248 return createReactorVideo(model, requireByok(reactorByok))
249}
250
251function reactorW(model: Parameters<typeof createReactorWorld>[0]) {
252 return createReactorWorld(model, requireByok(reactorByok))
253}
254
255function worldlabsW(model: Parameters<typeof worldlabsWorld>[0]) {
256 return worldlabsWorld(model, { apiKey: requireByok(worldlabsByok) })
257}
258
259function isWorldResolution(value: string): value is WorldResolution {
260 return (WORLD_RESOLUTIONS as ReadonlyArray<string>).includes(value)
261}
262
263export const generateImageFn = createServerFn({ method: 'POST' })
264 .inputValidator((data: { prompt: MediaPrompt; model: string }) => {
265 if (!hasPromptContent(data.prompt)) throw new Error('Prompt is required')
266 if (!data.model) throw new Error('Model is required')
267 return data
268 })
269 .handler(async ({ data }) => {
270 // NOTE: Use string literals when instantiating adapters to preserve type safety
271 // The Fal adapater also accepts any string for very latest models which is why new models appear to accept any paramater
272 // Pass size information in modelOptions for the Fal adapter instead of size to be sure you are using the correct resolution
273
274 switch (data.model) {
275 case 'fal-ai/nano-banana-pro': {
276 return generateImage({
277 threadId: 'media-image',
278 adapter: falI('fal-ai/nano-banana-pro'),
279 prompt: asTextPrompt(data.prompt),
280 numberOfImages: 1,
281 size: '16:9_4K',
282 modelOptions: {
283 output_format: 'jpeg',
284 },
285 })
286 }
287 case 'xai/grok-imagine-image': {
288 // NOTE: fal's generated `size` type for this model only offers
289 // `16:9_1K` / `16:9_4K`, but the live API rejects those resolutions
290 // ("Input should be '1k' or '2k'") — fal's published enum is out of
291 // sync with its API, so `'16:9_4K'` type-checks yet 422s at runtime.
292 // Pass aspect_ratio via modelOptions and let the endpoint pick its
293 // default resolution, which both type-checks and works at runtime.
294 return generateImage({
295 threadId: 'media-image',
296 adapter: falI('xai/grok-imagine-image'),
297 prompt: asTextPrompt(data.prompt),
298 numberOfImages: 1,
299 modelOptions: { aspect_ratio: '16:9' },
300 })
301 }
302 case 'grok-imagine-image': {
303 // Direct xAI Imagine API (XAI_API_KEY) via the native grokImage
304 // adapter — no fal in between. The grok-imagine models accept image
305 // prompt parts for image-conditioned generation, so we narrow with
306 // asImagePrompt. Sizing uses the aspect-ratio template.
307 return generateImage({
308 threadId: 'media-image',
309 adapter: grokI('grok-imagine-image'),
310 prompt: asImagePrompt(data.prompt),
311 numberOfImages: 1,
312 size: '16:9',
313 })
314 }
315 case 'grok-imagine-image-2.0': {
316 // xAI's recommended Imagine model; `quality` is a 2.0-only option
317 // ('low' | 'medium', default 'medium').
318 return generateImage({
319 threadId: 'media-image',
320 adapter: grokI('grok-imagine-image-2.0'),
321 prompt: asImagePrompt(data.prompt),
322 numberOfImages: 1,
323 size: '16:9',
324 modelOptions: { quality: 'medium' },
325 })
326 }
327 case 'grok-imagine-image-quality': {
328 return generateImage({
329 threadId: 'media-image',
330 adapter: grokI('grok-imagine-image-quality'),
331 prompt: asImagePrompt(data.prompt),
332 numberOfImages: 1,
333 size: '16:9',
334 })
335 }
336 case 'fal-ai/flux-2/klein/9b': {
337 // NOTE: Newer models are untyped (at the moment)
338 return generateImage({
339 threadId: 'media-image',
340 adapter: falI('fal-ai/flux-2/klein/9b'),
341 prompt: asTextPrompt(data.prompt),
342 numberOfImages: 1,
343 size: 'landscape_16_9',
344 })
345 }
346 case 'fal-ai/z-image/turbo': {
347 return generateImage({
348 threadId: 'media-image',
349 adapter: falI('fal-ai/z-image/turbo'),
350 prompt: asTextPrompt(data.prompt),
351 numberOfImages: 1,
352 size: 'landscape_16_9',
353 modelOptions: {
354 acceleration: 'high',
355 enable_prompt_expansion: true,
356 },
357 })
358 }
359 case 'gemini-nano-banana-2.1': {
360 // Reference images are uploaded once via the Gemini Files API and
361 // referenced by handle (fileData.fileUri) rather than inlined as base64.
362 return generateImage({
363 threadId: 'media-image',
364 adapter: geminiI('gemini-nano-banana-2.1'),
365 prompt: await uploadInlineImageInputs(
366 asImagePrompt(data.prompt),
367 geminiF(),
368 ),
369 numberOfImages: 1,
370 size: '16:9_4K',
371 })
372 }
373 case 'gemini-3-pro-image': {
374 return generateImage({
375 threadId: 'media-image',
376 adapter: geminiI('gemini-3-pro-image'),
377 prompt: await uploadInlineImageInputs(
378 asImagePrompt(data.prompt),
379 geminiF(),
380 ),
381 numberOfImages: 1,
382 size: '16:9_4K',
383 })
384 }
385 case 'dola-seedream-5-0-pro-260628': {
386 // BytePlus Seedream via ModelArk (ARK_API_KEY). `size` is either a
387 // 1K/2K/4K token or an explicit WIDTHxHEIGHT string — never both.
388 // Seedream models accept reference images, so image prompt parts are
389 // passed straight through.
390 return generateImage({
391 threadId: 'media-image',
392 adapter: byteplusI('dola-seedream-5-0-pro-260628'),
393 prompt: asImagePrompt(data.prompt),
394 numberOfImages: 1,
395 size: '2K',
396 })
397 }
398 default:
399 throw new Error(`Unknown model: ${data.model}`)
400 }
401 })
402
403/** What the browser sends for one video generation. */
404interface VideoRequest {
405 prompt: MediaPrompt
406 model: string
407 /**
408 * Gemini Omni Flash conversational editing: the jobId (interaction id)
409 * of a prior Omni generation to refine. Ignored by other models.
410 */
411 previousInteractionId?: string
412 /**
413 * Gemini Omni Flash generation controls (ignored by other models):
414 * clip duration in seconds (3-10, fractional OK, default 10), output
415 * aspect ratio, and an optional task-mode pin — omit `task` to let
416 * the model infer the mode from the prompt and attachments.
417 */
418 omniOptions?: {
419 duration?: number
420 aspectRatio?: '16:9' | '9:16'
421 task?: OmniTaskMode
422 }
423}
424
425/**
426 * The full create → poll → complete lifecycle for one model, as a chunk
427 * stream. `stream: true` is what moves the polling loop to the server: the
428 * browser's `useGenerateVideo` reads job id, status and result off these
429 * chunks instead of running its own timer.
430 */
431async function videoStreamForModel(
432 data: VideoRequest,
433): Promise<AsyncIterable<StreamChunk>> {
434 // Image-to-video models receive the start frame as a prompt part
435 // (role: 'start_frame') — the fal adapter routes it to the endpoint's
436 // start-image field. Text-to-video models take the text prompt only.
437 // `duration` is typed per endpoint ('5' | '10' on Kling 2.6, '3'…'15' on
438 // Kling 3, '4s' | '6s' | '8s' on Veo 3.1); `snapDuration(seconds)` picks the
439 // nearest supported value so a UI slider never has to know the literal.
440 switch (data.model) {
441 // Text-to-video models
442 case 'fal-ai/kling-video/v3/pro/text-to-video': {
443 const adapter = falV('fal-ai/kling-video/v3/pro/text-to-video')
444 return generateVideo({
445 threadId: 'media-video',
446 stream: true,
447 pollingInterval: VIDEO_POLL_INTERVAL_MS,
448 adapter,
449 prompt: asTextPrompt(data.prompt),
450 size: '16:9',
451 duration: adapter.snapDuration(5),
452 })
453 }
454 case 'fal-ai/veo3.1': {
455 const adapter = falV('fal-ai/veo3.1')
456 return generateVideo({
457 threadId: 'media-video',
458 stream: true,
459 pollingInterval: VIDEO_POLL_INTERVAL_MS,
460 adapter,
461 prompt: asTextPrompt(data.prompt),
462 size: '16:9_1080p',
463 duration: adapter.snapDuration(4),
464 })
465 }
466 case 'xai/grok-imagine-video/text-to-video': {
467 return generateVideo({
468 threadId: 'media-video',
469 stream: true,
470 pollingInterval: VIDEO_POLL_INTERVAL_MS,
471 adapter: falV('xai/grok-imagine-video/text-to-video'),
472 prompt: asTextPrompt(data.prompt),
473 size: '16:9_720p',
474 duration: 5,
475 })
476 }
477 case 'grok-imagine-video': {
478 // Direct xAI Imagine API (XAI_API_KEY) — no fal in between. The base
479 // grok-imagine-video (v1.0) supports text-to-video; durations are
480 // 1-15 integer seconds. Completed jobs report usage.billed
481 // ({ quantity, unit: 'seconds' }) and usage.cost (exact USD).
482 return generateVideo({
483 threadId: 'media-video',
484 stream: true,
485 pollingInterval: VIDEO_POLL_INTERVAL_MS,
486 adapter: grokV('grok-imagine-video'),
487 prompt: asTextPrompt(data.prompt),
488 size: '16:9_720p',
489 duration: 5,
490 })
491 }
492 case 'grok-imagine-video-1.5': {
493 // Direct xAI Imagine API — grok-imagine-video-1.5 is xAI's recommended
494 // default and supports text-to-video with native 1080p.
495 return generateVideo({
496 threadId: 'media-video',
497 stream: true,
498 pollingInterval: VIDEO_POLL_INTERVAL_MS,
499 adapter: grokV('grok-imagine-video-1.5'),
500 prompt: asTextPrompt(data.prompt),
501 size: '16:9_1080p',
502 duration: 5,
503 })
504 }
505 case 'dreamina-seedance-2-0-260128': {
506 // BytePlus Seedance via ModelArk (ARK_API_KEY). `size` is a "ratio" or
507 // "ratio_resolution" template; durations are 4-15 integer seconds.
508 // Seedance option applicability is per model and Ark 400s on an
509 // inapplicable field, so no service_tier/frames/camera_fixed here —
510 // the 2.0 family rejects all three.
511 return generateVideo({
512 threadId: 'media-video',
513 stream: true,
514 pollingInterval: VIDEO_POLL_INTERVAL_MS,
515 adapter: byteplusV('dreamina-seedance-2-0-260128'),
516 prompt: asTextPrompt(data.prompt),
517 size: '16:9_720p',
518 duration: 5,
519 })
520 }
521 case 'fal-ai/ltx-2.3/text-to-video/fast': {
522 const adapter = falV('fal-ai/ltx-2.3/text-to-video/fast')
523 return generateVideo({
524 threadId: 'media-video',
525 stream: true,
526 pollingInterval: VIDEO_POLL_INTERVAL_MS,
527 adapter,
528 prompt: asTextPrompt(data.prompt),
529 size: '16:9_2160p',
530 duration: adapter.snapDuration(6),
531 })
532 }
533 // Image-to-video models. The start frame is uploaded once to fal storage
534 // via the Files API (`falF()`) and referenced by its storage-URL
535 // handle, instead of being inlined as a base64 data: URI on the request.
536 case 'fal-ai/kling-video/v3/pro/image-to-video': {
537 const adapter = falV('fal-ai/kling-video/v3/pro/image-to-video')
538 return generateVideo({
539 threadId: 'media-video',
540 stream: true,
541 pollingInterval: VIDEO_POLL_INTERVAL_MS,
542 adapter,
543 prompt: await uploadInlineImageInputs(
544 asImageToVideoPrompt(data.prompt),
545 falF(),
546 ),
547 duration: adapter.snapDuration(5),
548 modelOptions: {
549 generate_audio: true,
550 },
551 })
552 }
553 case 'fal-ai/veo3.1/image-to-video': {
554 const adapter = falV('fal-ai/veo3.1/image-to-video')
555 return generateVideo({
556 threadId: 'media-video',
557 stream: true,
558 pollingInterval: VIDEO_POLL_INTERVAL_MS,
559 adapter,
560 prompt: await uploadInlineImageInputs(
561 asImageToVideoPrompt(data.prompt),
562 falF(),
563 ),
564 size: '16:9_1080p',
565 duration: adapter.snapDuration(4),
566 })
567 }
568 case 'xai/grok-imagine-video/image-to-video': {
569 return generateVideo({
570 threadId: 'media-video',
571 stream: true,
572 pollingInterval: VIDEO_POLL_INTERVAL_MS,
573 adapter: falV('xai/grok-imagine-video/image-to-video'),
574 prompt: await uploadInlineImageInputs(
575 asImageToVideoPrompt(data.prompt),
576 falF(),
577 ),
578 size: '16:9_720p',
579 duration: 5,
580 })
581 }
582 case 'grok-imagine-video-1.5/image-to-video': {
583 // Direct xAI Imagine API. The starting frame is supplied as an image
584 // prompt part (asImageToVideoPrompt requires one); the grokVideo
585 // adapter forwards it to the Imagine endpoint as the start frame.
586 return generateVideo({
587 threadId: 'media-video',
588 stream: true,
589 pollingInterval: VIDEO_POLL_INTERVAL_MS,
590 adapter: grokV('grok-imagine-video-1.5'),
591 prompt: asImageToVideoPrompt(data.prompt),
592 size: '16:9_720p',
593 duration: 5,
594 })
595 }
596 case 'fal-ai/ltx-2.3/image-to-video/fast': {
597 const adapter = falV('fal-ai/ltx-2.3/image-to-video/fast')
598 return generateVideo({
599 threadId: 'media-video',
600 stream: true,
601 pollingInterval: VIDEO_POLL_INTERVAL_MS,
602 adapter,
603 prompt: await uploadInlineImageInputs(
604 asImageToVideoPrompt(data.prompt),
605 falF(),
606 ),
607 size: '16:9_2160p',
608 duration: adapter.snapDuration(6),
609 })
610 }
611 // Gemini Omni Flash (Interactions API, GEMINI_API_KEY). One model
612 // serves both UI entries; it accepts text, image, AND video prompt
613 // parts (sent as interaction content blocks: images, then videos,
614 // then text). Clips are 3–10s (default 10s when `duration` is
615 // omitted); `size` is the output aspect ratio. Passing
616 // `previous_interaction_id` chains a prompt onto a prior generation
617 // for conversational editing.
618 case 'gemini-omni-1.1-flash':
619 case 'gemini-omni-1.1-flash/image-to-video': {
620 const prompt = asOmniPrompt(data.prompt)
621 if (
622 data.model.endsWith('/image-to-video') &&
623 !data.previousInteractionId &&
624 (typeof prompt === 'string' ||
625 !prompt.some((part) => part.type === 'image'))
626 ) {
627 throw new Error('Start image is required for image-to-video')
628 }
629 const { duration, aspectRatio, task } = data.omniOptions ?? {}
630 return generateVideo({
631 threadId: 'media-video',
632 stream: true,
633 pollingInterval: VIDEO_POLL_INTERVAL_MS,
634 adapter: geminiV('gemini-omni-1.1-flash'),
635 prompt,
636 size: aspectRatio ?? '16:9',
637 ...(duration !== undefined ? { duration } : {}),
638 ...(data.previousInteractionId || task
639 ? {
640 modelOptions: {
641 ...(data.previousInteractionId
642 ? { previous_interaction_id: data.previousInteractionId }
643 : {}),
644 ...(task
645 ? { generation_config: { video_config: { task } } }
646 : {}),
647 },
648 }
649 : {}),
650 })
651 }
652 // OpenRouter's dedicated async video API (`POST /api/v1/videos`). Like
653 // fal, it types the top-level `duration` per model and exposes
654 // `snapDuration()` to coerce a raw UI seconds value to the model's
655 // nearest supported duration.
656 case 'bytedance/seedance-2.0': {
657 const adapter = openRouterV('bytedance/seedance-2.0')
658 return generateVideo({
659 threadId: 'media-video',
660 stream: true,
661 pollingInterval: VIDEO_POLL_INTERVAL_MS,
662 adapter,
663 prompt: asTextPrompt(data.prompt),
664 size: '1280x720',
665 duration: adapter.snapDuration(7),
666 modelOptions: { aspectRatio: '16:9' },
667 })
668 }
669 case 'google/veo-3.1': {
670 const adapter = openRouterV('google/veo-3.1')
671 return generateVideo({
672 threadId: 'media-video',
673 stream: true,
674 pollingInterval: VIDEO_POLL_INTERVAL_MS,
675 adapter,
676 prompt: asImageToVideoPrompt(data.prompt),
677 size: '1280x720',
678 duration: adapter.snapDuration(7),
679 })
680 }
681 default:
682 throw new Error(`Unknown video model: ${data.model}`)
683 }
684}
685
686/**
687 * Streams one video generation as Server-Sent Events. `useGenerateVideo`
688 * takes this straight as its `fetcher`: the client parses the SSE body it
689 * returns, so the job id, every status update and the final url all arrive on
690 * the one request — no client-side polling loop and no job ids to thread
691 * through the UI.
692 */
693export const generateVideoFn = createServerFn({ method: 'POST' })
694 .inputValidator((data: VideoRequest) => {
695 if (!hasPromptContent(data.prompt)) throw new Error('Prompt is required')
696 if (!data.model) throw new Error('Model is required')
697 return data
698 })
699 // A rejected model / missing start frame throws out of `videoStreamForModel`
700 // before any stream exists, which surfaces as a plain server-function error
701 // (the hook reports it through `error`) rather than a stream that opens only
702 // to fail.
703 .handler(async ({ data }) =>
704 toServerSentEventsResponse(await videoStreamForModel(data)),
705 )
706
707// ============================================================================
708// Seedance Studio — BytePlus ModelArk direct (ARK_API_KEY, server-side only)
709// ============================================================================
710
711/**
712 * The tiers a model accepts. `resolveBytePlusVideoResolution` is the package's
713 * exported gate for exactly this decision — it throws on a tier the model does
714 * not offer — so probing it keeps one source of truth for a matrix that is
715 * neither uniform nor guessable (there is no 2K tier anywhere, and 4k exists
716 * only on `dreamina-seedance-2-0-260128`).
717 */
718function acceptedResolutions(
719 model: BytePlusVideoModel,
720): Array<BytePlusVideoResolution> {
721 const accepted = SEEDANCE_RESOLUTION_TIERS.filter((tier) => {
722 try {
723 resolveBytePlusVideoResolution(model, tier)
724 return true
725 } catch {
726 return false
727 }
728 })
729
730 // Using a throw as the predicate means *any* change to that function's
731 // contract reads as "no tier is supported". Every Seedance model offers at
732 // least 480p and 720p, so an empty list is drift, not a real answer —
733 // without this the Studio would silently fall back to a hardcoded '720p'
734 // and build requests on a guess. The route has an errorComponent for
735 // exactly this.
736 if (accepted.length === 0) {
737 throw new Error(
738 `Seedance capability probe returned no resolution tiers for "${model}". ` +
739 `resolveBytePlusVideoResolution's contract has probably changed — the ` +
740 `Studio's controls cannot be built from this.`,
741 )
742 }
743 return accepted
744}
745
746/**
747 * Per-model capability table for the Seedance Studio, read out of the adapter
748 * package on the server. No API key is involved: these are static metadata
749 * lookups, not calls to Ark.
750 */
751export const getSeedanceCapabilitiesFn = createServerFn({
752 method: 'GET',
753}).handler(
754 (): Array<SeedanceCapability> =>
755 BYTEPLUS_VIDEO_MODELS.map((model) => {
756 const durations = getBytePlusVideoDurationOptions(model)
757 if (durations.kind !== 'range') {
758 throw new Error(
759 `Expected a duration range for ${model}, got "${durations.kind}"`,
760 )
761 }
762 return {
763 model,
764 resolutions: acceptedResolutions(model),
765 duration: {
766 min: durations.min,
767 max: durations.max,
768 step: durations.step ?? 1,
769 },
770 supportsLastFrame: supportsLastFrame(model),
771 supportsReferenceMedia: supportsReferenceMedia(model),
772 }
773 }),
774)
775
776/** What the studio sends for one Seedance generation. */
777interface SeedanceRequest {
778 prompt: MediaPrompt
779 // Open by design: the studio's advanced field takes an id this package
780 // has no metadata for, which the adapter forwards ungated for Ark to judge.
781 model: BytePlusVideoModelOrString
782 options?: SeedanceJobOptions
783}
784
785/**
786 * Ceiling on how long the server will sit on a Seedance task. Generous
787 * because the flex tier is an offline batch queue where a task routinely
788 * waits many minutes before it even starts.
789 */
790const SEEDANCE_MAX_DURATION_MS = 30 * 60_000
791/** Seedance tasks are slow; polling faster only burns Ark quota. */
792const SEEDANCE_POLL_INTERVAL_MS = 5000
793
794/** The create → poll → complete lifecycle for one Seedance task. */
795function seedanceStream(data: SeedanceRequest): AsyncIterable<StreamChunk> {
796 const options = data.options ?? {}
797
798 // The studio's camelCase controls map one-to-one onto the provider's own
799 // request fields. Applicability is per model and Ark 400s on a field the
800 // model doesn't take (it does not ignore it), so the client only sends
801 // what the selected model accepts — see `SEEDANCE_MODELS` in lib/seedance.
802 //
803 // `ratio` / `resolution` are typed against the tiers this package knows,
804 // so a custom model id sends its sizing through the generic `size`
805 // template instead (see `SeedanceJobOptions.size`).
806 const modelOptions: BytePlusVideoProviderOptions = {
807 ...(options.size === undefined &&
808 options.ratio !== undefined && { ratio: options.ratio }),
809 ...(options.size === undefined &&
810 options.resolution !== undefined && {
811 resolution: options.resolution,
812 }),
813 // `-1` (let the model choose the length) is only reachable through
814 // provider options: the generic `duration` gets snapped into range.
815 ...(options.duration === -1 && { duration: -1 }),
816 ...(options.frames !== undefined && { frames: options.frames }),
817 ...(options.seed !== undefined && { seed: options.seed }),
818 ...(options.watermark !== undefined && { watermark: options.watermark }),
819 ...(options.generateAudio !== undefined && {
820 generate_audio: options.generateAudio,
821 }),
822 ...(options.cameraFixed !== undefined && {
823 camera_fixed: options.cameraFixed,
824 }),
825 ...(options.serviceTier !== undefined && {
826 service_tier: options.serviceTier,
827 }),
828 ...(options.draft !== undefined && { draft: options.draft }),
829 ...(options.priority !== undefined && { priority: options.priority }),
830 }
831
832 // `frames` takes precedence over `duration` server-side, so never send
833 // both; `-1` already went through modelOptions above.
834 const duration =
835 options.frames === undefined &&
836 options.duration !== undefined &&
837 options.duration > 0
838 ? options.duration
839 : undefined
840
841 return generateVideo({
842 threadId: 'media-seedance',
843 // For a model this package knows, the adapter snaps `duration` into its
844 // range and validates the resolution tier, prompt roles and
845 // frame/reference exclusivity before anything reaches Ark. For a custom
846 // id every one of those guards is off by design: the duration goes
847 // through verbatim and Ark is the authority.
848 adapter: byteplusV(data.model),
849 // Passed through un-narrowed, unlike the other generators: Seedance's
850 // reference mode takes video and audio parts as well as images (the
851 // template presets send both), and which of them a given model allows is
852 // the adapter's call — its error names the model and the part.
853 prompt: data.prompt,
854 ...(options.size !== undefined && { size: options.size }),
855 ...(duration !== undefined && { duration }),
856 modelOptions,
857 stream: true,
858 pollingInterval: SEEDANCE_POLL_INTERVAL_MS,
859 maxDuration: SEEDANCE_MAX_DURATION_MS,
860 })
861}
862
863/**
864 * Streams one Seedance task as Server-Sent Events, for the studio's
865 * `useGenerateVideo`. The browser never sees ARK_API_KEY or a job id it has
866 * to poll with — the server does the waiting and reports status on the wire.
867 */
868export const generateSeedanceVideoFn = createServerFn({ method: 'POST' })
869 .inputValidator((data: SeedanceRequest) => {
870 if (!hasPromptContent(data.prompt)) throw new Error('Prompt is required')
871 if (!data.model) throw new Error('Model is required')
872 return data
873 })
874 .handler(({ data }) => toServerSentEventsResponse(seedanceStream(data)))
875
876interface LiveVideoRequest {
877 prompt: string
878 model: LiveVideoModelId
879 resolution: LiveVideoResolution
880}
881
882/**
883 * Mints a live-video session. The browser then connects with the provider
884 * client (`@reactor-team/js-sdk` or `@fal-ai/client`). There is no job URL.
885 */
886export const generateLiveVideoFn = createServerFn({ method: 'POST' })
887 .inputValidator((data: LiveVideoRequest) => {
888 if (typeof data.prompt !== 'string' || data.prompt.trim().length === 0) {
889 throw new Error('Prompt is required')
890 }
891 if (!isLiveVideoModelId(data.model)) {
892 throw new Error(`Unknown live video model: ${data.model}`)
893 }
894 return data
895 })
896 .handler(async ({ data }) => {
897 const prompt = data.prompt.trim()
898 const provider = liveVideoProvider(data.model)
899 const live = isFalLiveVideoModel(data.model)
900 ? await generateLiveVideo({
901 threadId: 'media-live-video',
902 adapter: falL(data.model),
903 prompt,
904 debug: false,
905 })
906 : await generateLiveVideo({
907 threadId: 'media-live-video',
908 adapter: reactorV(data.model),
909 prompt,
910 ...(data.resolution === '1080p' ||
911 data.resolution === '2k' ||
912 data.resolution === '4k'
913 ? { modelOptions: { resolution: data.resolution } }
914 : {}),
915 debug: false,
916 })
917 return {
918 token: live.token,
919 model: live.model,
920 prompt: live.prompt,
921 expiresAt: live.expiresAt,
922 provider,
923 }
924 })
925
926interface WorldSeedImage {
927 dataBase64: string
928 extension?: string
929}
930
931interface WorldRequest {
932 prompt: string
933 model: WorldModelId
934 resolution: WorldResolution
935 seedImages?: Array<WorldSeedImage>
936}
937
938const WORLDLABS_MAX_SEED_IMAGES = 4
939
940function isWorldSeedImage(value: unknown): value is WorldSeedImage {
941 if (typeof value !== 'object' || value === null) return false
942 if (!('dataBase64' in value) || typeof value.dataBase64 !== 'string') {
943 return false
944 }
945 if (value.dataBase64.length === 0) return false
946 if (
947 'extension' in value &&
948 value.extension !== undefined &&
949 typeof value.extension !== 'string'
950 ) {
951 return false
952 }
953 return true
954}
955
956const WORLDLABS_TIMEOUT_MS = 12 * 60 * 1000
957
958/**
959 * Reactor mints a session token for a live stream. World Labs starts a job
960 * and waits until the Marble world is ready (about 5 minutes).
961 */
962export const generateWorldFn = createServerFn({ method: 'POST' })
963 .inputValidator((data: WorldRequest) => {
964 if (typeof data.prompt !== 'string' || data.prompt.trim().length === 0) {
965 throw new Error('Prompt is required')
966 }
967 if (isWorldLabsWorldModel(data.model)) {
968 if (data.seedImages !== undefined) {
969 if (
970 !Array.isArray(data.seedImages) ||
971 data.seedImages.length > WORLDLABS_MAX_SEED_IMAGES ||
972 !data.seedImages.every(isWorldSeedImage)
973 ) {
974 throw new Error(
975 `World Labs accepts at most ${WORLDLABS_MAX_SEED_IMAGES} seed images`,
976 )
977 }
978 }
979 return data
980 }
981 if (!isReactorWorldModel(data.model)) {
982 throw new Error(`Unknown world model: ${data.model}`)
983 }
984 if (!isWorldResolution(data.resolution)) {
985 throw new Error(`Unknown resolution: ${data.resolution}`)
986 }
987 return data
988 })
989 .handler(async ({ data }) => {
990 if (isWorldLabsWorldModel(data.model)) {
991 const seedImages = data.seedImages ?? []
992 const [firstSeed, ...restSeeds] = seedImages
993 const world = await generateWorld({
994 threadId: 'media-world',
995 adapter: worldlabsW(data.model),
996 prompt: data.prompt.trim(),
997 timeout: WORLDLABS_TIMEOUT_MS,
998 debug: false,
999 ...(firstSeed && restSeeds.length === 0
1000 ? {
1001 modelOptions: {
1002 image: firstSeed,
1003 isPano: 'auto' as const,
1004 },
1005 }
1006 : seedImages.length > 1
1007 ? { modelOptions: { images: seedImages } }
1008 : {}),
1009 })
1010 if (typeof world.url !== 'string' || world.url.length === 0) {
1011 throw new Error('World Labs did not return a viewer URL')
1012 }
1013 return {
1014 kind: 'worldlabs' as const,
1015 url: world.url,
1016 worldId: world.worldId,
1017 model: world.model,
1018 prompt: world.prompt,
1019 status: world.status,
1020 thumbnailUrl: world.assets?.thumbnailUrl,
1021 caption: world.assets?.caption,
1022 splatUrl: pickSplatUrl(world.assets?.splats?.spzUrls),
1023 metricScaleFactor: world.assets?.splats?.metricScaleFactor,
1024 groundPlaneOffset: world.assets?.splats?.groundPlaneOffset,
1025 panoUrl: world.assets?.imagery?.panoUrl,
1026 meshUrl: world.assets?.mesh?.colliderMeshUrl,
1027 }
1028 }
1029
1030 const world = await generateWorld({
1031 threadId: 'media-world',
1032 adapter: reactorW(data.model),
1033 prompt: data.prompt.trim(),
1034 modelOptions: { resolution: data.resolution },
1035 debug: false,
1036 })
1037 if (typeof world.token !== 'string' || world.token.length === 0) {
1038 throw new Error('Reactor did not return a session token')
1039 }
1040 return {
1041 kind: 'reactor' as const,
1042 token: world.token,
1043 model: world.model,
1044 prompt: world.prompt,
1045 expiresAt: world.expiresAt,
1046 resolution: data.resolution,
1047 }
1048 })