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 'imagen-4.0-ultra-generate-001': {
386 return generateImage({
387 threadId: 'media-image',
388 adapter: geminiI('imagen-4.0-ultra-generate-001'),
389 prompt: asTextPrompt(data.prompt),
390 numberOfImages: 1,
391 size: '1024x1024',
392 })
393 }
394 case 'imagen-4.0-generate-001': {
395 return generateImage({
396 threadId: 'media-image',
397 adapter: geminiI('imagen-4.0-generate-001'),
398 prompt: asTextPrompt(data.prompt),
399 numberOfImages: 1,
400 size: '1024x1024',
401 })
402 }
403 case 'imagen-4.0-fast-generate-001': {
404 return generateImage({
405 threadId: 'media-image',
406 adapter: geminiI('imagen-4.0-fast-generate-001'),
407 prompt: asTextPrompt(data.prompt),
408 numberOfImages: 1,
409 size: '1024x1024',
410 })
411 }
412 case 'dola-seedream-5-0-pro-260628': {
413 // BytePlus Seedream via ModelArk (ARK_API_KEY). `size` is either a
414 // 1K/2K/4K token or an explicit WIDTHxHEIGHT string — never both.
415 // Seedream models accept reference images, so image prompt parts are
416 // passed straight through.
417 return generateImage({
418 threadId: 'media-image',
419 adapter: byteplusI('dola-seedream-5-0-pro-260628'),
420 prompt: asImagePrompt(data.prompt),
421 numberOfImages: 1,
422 size: '2K',
423 })
424 }
425 default:
426 throw new Error(`Unknown model: ${data.model}`)
427 }
428 })
429
430/** What the browser sends for one video generation. */
431interface VideoRequest {
432 prompt: MediaPrompt
433 model: string
434 /**
435 * Gemini Omni Flash conversational editing: the jobId (interaction id)
436 * of a prior Omni generation to refine. Ignored by other models.
437 */
438 previousInteractionId?: string
439 /**
440 * Gemini Omni Flash generation controls (ignored by other models):
441 * clip duration in seconds (3-10, fractional OK, default 10), output
442 * aspect ratio, and an optional task-mode pin — omit `task` to let
443 * the model infer the mode from the prompt and attachments.
444 */
445 omniOptions?: {
446 duration?: number
447 aspectRatio?: '16:9' | '9:16'
448 task?: OmniTaskMode
449 }
450}
451
452/**
453 * The full create → poll → complete lifecycle for one model, as a chunk
454 * stream. `stream: true` is what moves the polling loop to the server: the
455 * browser's `useGenerateVideo` reads job id, status and result off these
456 * chunks instead of running its own timer.
457 */
458async function videoStreamForModel(
459 data: VideoRequest,
460): Promise<AsyncIterable<StreamChunk>> {
461 // Image-to-video models receive the start frame as a prompt part
462 // (role: 'start_frame') — the fal adapter routes it to the endpoint's
463 // start-image field. Text-to-video models take the text prompt only.
464 // `duration` is typed per endpoint ('5' | '10' on Kling 2.6, '3'…'15' on
465 // Kling 3, '4s' | '6s' | '8s' on Veo 3.1); `snapDuration(seconds)` picks the
466 // nearest supported value so a UI slider never has to know the literal.
467 switch (data.model) {
468 // Text-to-video models
469 case 'fal-ai/kling-video/v3/pro/text-to-video': {
470 const adapter = falV('fal-ai/kling-video/v3/pro/text-to-video')
471 return generateVideo({
472 threadId: 'media-video',
473 stream: true,
474 pollingInterval: VIDEO_POLL_INTERVAL_MS,
475 adapter,
476 prompt: asTextPrompt(data.prompt),
477 size: '16:9',
478 duration: adapter.snapDuration(5),
479 })
480 }
481 case 'fal-ai/veo3.1': {
482 const adapter = falV('fal-ai/veo3.1')
483 return generateVideo({
484 threadId: 'media-video',
485 stream: true,
486 pollingInterval: VIDEO_POLL_INTERVAL_MS,
487 adapter,
488 prompt: asTextPrompt(data.prompt),
489 size: '16:9_1080p',
490 duration: adapter.snapDuration(4),
491 })
492 }
493 case 'xai/grok-imagine-video/text-to-video': {
494 return generateVideo({
495 threadId: 'media-video',
496 stream: true,
497 pollingInterval: VIDEO_POLL_INTERVAL_MS,
498 adapter: falV('xai/grok-imagine-video/text-to-video'),
499 prompt: asTextPrompt(data.prompt),
500 size: '16:9_720p',
501 duration: 5,
502 })
503 }
504 case 'grok-imagine-video': {
505 // Direct xAI Imagine API (XAI_API_KEY) — no fal in between. The base
506 // grok-imagine-video (v1.0) supports text-to-video; durations are
507 // 1-15 integer seconds. Completed jobs report usage.billed
508 // ({ quantity, unit: 'seconds' }) and usage.cost (exact USD).
509 return generateVideo({
510 threadId: 'media-video',
511 stream: true,
512 pollingInterval: VIDEO_POLL_INTERVAL_MS,
513 adapter: grokV('grok-imagine-video'),
514 prompt: asTextPrompt(data.prompt),
515 size: '16:9_720p',
516 duration: 5,
517 })
518 }
519 case 'grok-imagine-video-1.5': {
520 // Direct xAI Imagine API — grok-imagine-video-1.5 is xAI's recommended
521 // default and supports text-to-video with native 1080p.
522 return generateVideo({
523 threadId: 'media-video',
524 stream: true,
525 pollingInterval: VIDEO_POLL_INTERVAL_MS,
526 adapter: grokV('grok-imagine-video-1.5'),
527 prompt: asTextPrompt(data.prompt),
528 size: '16:9_1080p',
529 duration: 5,
530 })
531 }
532 case 'dreamina-seedance-2-0-260128': {
533 // BytePlus Seedance via ModelArk (ARK_API_KEY). `size` is a "ratio" or
534 // "ratio_resolution" template; durations are 4-15 integer seconds.
535 // Seedance option applicability is per model and Ark 400s on an
536 // inapplicable field, so no service_tier/frames/camera_fixed here —
537 // the 2.0 family rejects all three.
538 return generateVideo({
539 threadId: 'media-video',
540 stream: true,
541 pollingInterval: VIDEO_POLL_INTERVAL_MS,
542 adapter: byteplusV('dreamina-seedance-2-0-260128'),
543 prompt: asTextPrompt(data.prompt),
544 size: '16:9_720p',
545 duration: 5,
546 })
547 }
548 case 'fal-ai/ltx-2.3/text-to-video/fast': {
549 const adapter = falV('fal-ai/ltx-2.3/text-to-video/fast')
550 return generateVideo({
551 threadId: 'media-video',
552 stream: true,
553 pollingInterval: VIDEO_POLL_INTERVAL_MS,
554 adapter,
555 prompt: asTextPrompt(data.prompt),
556 size: '16:9_2160p',
557 duration: adapter.snapDuration(6),
558 })
559 }
560 // Image-to-video models. The start frame is uploaded once to fal storage
561 // via the Files API (`falF()`) and referenced by its storage-URL
562 // handle, instead of being inlined as a base64 data: URI on the request.
563 case 'fal-ai/kling-video/v3/pro/image-to-video': {
564 const adapter = falV('fal-ai/kling-video/v3/pro/image-to-video')
565 return generateVideo({
566 threadId: 'media-video',
567 stream: true,
568 pollingInterval: VIDEO_POLL_INTERVAL_MS,
569 adapter,
570 prompt: await uploadInlineImageInputs(
571 asImageToVideoPrompt(data.prompt),
572 falF(),
573 ),
574 duration: adapter.snapDuration(5),
575 modelOptions: {
576 generate_audio: true,
577 },
578 })
579 }
580 case 'fal-ai/veo3.1/image-to-video': {
581 const adapter = falV('fal-ai/veo3.1/image-to-video')
582 return generateVideo({
583 threadId: 'media-video',
584 stream: true,
585 pollingInterval: VIDEO_POLL_INTERVAL_MS,
586 adapter,
587 prompt: await uploadInlineImageInputs(
588 asImageToVideoPrompt(data.prompt),
589 falF(),
590 ),
591 size: '16:9_1080p',
592 duration: adapter.snapDuration(4),
593 })
594 }
595 case 'xai/grok-imagine-video/image-to-video': {
596 return generateVideo({
597 threadId: 'media-video',
598 stream: true,
599 pollingInterval: VIDEO_POLL_INTERVAL_MS,
600 adapter: falV('xai/grok-imagine-video/image-to-video'),
601 prompt: await uploadInlineImageInputs(
602 asImageToVideoPrompt(data.prompt),
603 falF(),
604 ),
605 size: '16:9_720p',
606 duration: 5,
607 })
608 }
609 case 'grok-imagine-video-1.5/image-to-video': {
610 // Direct xAI Imagine API. The starting frame is supplied as an image
611 // prompt part (asImageToVideoPrompt requires one); the grokVideo
612 // adapter forwards it to the Imagine endpoint as the start frame.
613 return generateVideo({
614 threadId: 'media-video',
615 stream: true,
616 pollingInterval: VIDEO_POLL_INTERVAL_MS,
617 adapter: grokV('grok-imagine-video-1.5'),
618 prompt: asImageToVideoPrompt(data.prompt),
619 size: '16:9_720p',
620 duration: 5,
621 })
622 }
623 case 'fal-ai/ltx-2.3/image-to-video/fast': {
624 const adapter = falV('fal-ai/ltx-2.3/image-to-video/fast')
625 return generateVideo({
626 threadId: 'media-video',
627 stream: true,
628 pollingInterval: VIDEO_POLL_INTERVAL_MS,
629 adapter,
630 prompt: await uploadInlineImageInputs(
631 asImageToVideoPrompt(data.prompt),
632 falF(),
633 ),
634 size: '16:9_2160p',
635 duration: adapter.snapDuration(6),
636 })
637 }
638 // Gemini Omni Flash (Interactions API, GEMINI_API_KEY). One model
639 // serves both UI entries; it accepts text, image, AND video prompt
640 // parts (sent as interaction content blocks: images, then videos,
641 // then text). Clips are 3–10s (default 10s when `duration` is
642 // omitted); `size` is the output aspect ratio. Passing
643 // `previous_interaction_id` chains a prompt onto a prior generation
644 // for conversational editing.
645 case 'gemini-omni-1.1-flash':
646 case 'gemini-omni-1.1-flash/image-to-video': {
647 const prompt = asOmniPrompt(data.prompt)
648 if (
649 data.model.endsWith('/image-to-video') &&
650 !data.previousInteractionId &&
651 (typeof prompt === 'string' ||
652 !prompt.some((part) => part.type === 'image'))
653 ) {
654 throw new Error('Start image is required for image-to-video')
655 }
656 const { duration, aspectRatio, task } = data.omniOptions ?? {}
657 return generateVideo({
658 threadId: 'media-video',
659 stream: true,
660 pollingInterval: VIDEO_POLL_INTERVAL_MS,
661 adapter: geminiV('gemini-omni-1.1-flash'),
662 prompt,
663 size: aspectRatio ?? '16:9',
664 ...(duration !== undefined ? { duration } : {}),
665 ...(data.previousInteractionId || task
666 ? {
667 modelOptions: {
668 ...(data.previousInteractionId
669 ? { previous_interaction_id: data.previousInteractionId }
670 : {}),
671 ...(task
672 ? { generation_config: { video_config: { task } } }
673 : {}),
674 },
675 }
676 : {}),
677 })
678 }
679 // OpenRouter's dedicated async video API (`POST /api/v1/videos`). Like
680 // fal, it types the top-level `duration` per model and exposes
681 // `snapDuration()` to coerce a raw UI seconds value to the model's
682 // nearest supported duration.
683 case 'bytedance/seedance-2.0': {
684 const adapter = openRouterV('bytedance/seedance-2.0')
685 return generateVideo({
686 threadId: 'media-video',
687 stream: true,
688 pollingInterval: VIDEO_POLL_INTERVAL_MS,
689 adapter,
690 prompt: asTextPrompt(data.prompt),
691 size: '1280x720',
692 duration: adapter.snapDuration(7),
693 modelOptions: { aspectRatio: '16:9' },
694 })
695 }
696 case 'google/veo-3.1': {
697 const adapter = openRouterV('google/veo-3.1')
698 return generateVideo({
699 threadId: 'media-video',
700 stream: true,
701 pollingInterval: VIDEO_POLL_INTERVAL_MS,
702 adapter,
703 prompt: asImageToVideoPrompt(data.prompt),
704 size: '1280x720',
705 duration: adapter.snapDuration(7),
706 })
707 }
708 default:
709 throw new Error(`Unknown video model: ${data.model}`)
710 }
711}
712
713/**
714 * Streams one video generation as Server-Sent Events. `useGenerateVideo`
715 * takes this straight as its `fetcher`: the client parses the SSE body it
716 * returns, so the job id, every status update and the final url all arrive on
717 * the one request — no client-side polling loop and no job ids to thread
718 * through the UI.
719 */
720export const generateVideoFn = createServerFn({ method: 'POST' })
721 .inputValidator((data: VideoRequest) => {
722 if (!hasPromptContent(data.prompt)) throw new Error('Prompt is required')
723 if (!data.model) throw new Error('Model is required')
724 return data
725 })
726 // A rejected model / missing start frame throws out of `videoStreamForModel`
727 // before any stream exists, which surfaces as a plain server-function error
728 // (the hook reports it through `error`) rather than a stream that opens only
729 // to fail.
730 .handler(async ({ data }) =>
731 toServerSentEventsResponse(await videoStreamForModel(data)),
732 )
733
734// ============================================================================
735// Seedance Studio — BytePlus ModelArk direct (ARK_API_KEY, server-side only)
736// ============================================================================
737
738/**
739 * The tiers a model accepts. `resolveBytePlusVideoResolution` is the package's
740 * exported gate for exactly this decision — it throws on a tier the model does
741 * not offer — so probing it keeps one source of truth for a matrix that is
742 * neither uniform nor guessable (there is no 2K tier anywhere, and 4k exists
743 * only on `dreamina-seedance-2-0-260128`).
744 */
745function acceptedResolutions(
746 model: BytePlusVideoModel,
747): Array<BytePlusVideoResolution> {
748 const accepted = SEEDANCE_RESOLUTION_TIERS.filter((tier) => {
749 try {
750 resolveBytePlusVideoResolution(model, tier)
751 return true
752 } catch {
753 return false
754 }
755 })
756
757 // Using a throw as the predicate means *any* change to that function's
758 // contract reads as "no tier is supported". Every Seedance model offers at
759 // least 480p and 720p, so an empty list is drift, not a real answer —
760 // without this the Studio would silently fall back to a hardcoded '720p'
761 // and build requests on a guess. The route has an errorComponent for
762 // exactly this.
763 if (accepted.length === 0) {
764 throw new Error(
765 `Seedance capability probe returned no resolution tiers for "${model}". ` +
766 `resolveBytePlusVideoResolution's contract has probably changed — the ` +
767 `Studio's controls cannot be built from this.`,
768 )
769 }
770 return accepted
771}
772
773/**
774 * Per-model capability table for the Seedance Studio, read out of the adapter
775 * package on the server. No API key is involved: these are static metadata
776 * lookups, not calls to Ark.
777 */
778export const getSeedanceCapabilitiesFn = createServerFn({
779 method: 'GET',
780}).handler(
781 (): Array<SeedanceCapability> =>
782 BYTEPLUS_VIDEO_MODELS.map((model) => {
783 const durations = getBytePlusVideoDurationOptions(model)
784 if (durations.kind !== 'range') {
785 throw new Error(
786 `Expected a duration range for ${model}, got "${durations.kind}"`,
787 )
788 }
789 return {
790 model,
791 resolutions: acceptedResolutions(model),
792 duration: {
793 min: durations.min,
794 max: durations.max,
795 step: durations.step ?? 1,
796 },
797 supportsLastFrame: supportsLastFrame(model),
798 supportsReferenceMedia: supportsReferenceMedia(model),
799 }
800 }),
801)
802
803/** What the studio sends for one Seedance generation. */
804interface SeedanceRequest {
805 prompt: MediaPrompt
806 // Open by design: the studio's advanced field takes an id this package
807 // has no metadata for, which the adapter forwards ungated for Ark to judge.
808 model: BytePlusVideoModelOrString
809 options?: SeedanceJobOptions
810}
811
812/**
813 * Ceiling on how long the server will sit on a Seedance task. Generous
814 * because the flex tier is an offline batch queue where a task routinely
815 * waits many minutes before it even starts.
816 */
817const SEEDANCE_MAX_DURATION_MS = 30 * 60_000
818/** Seedance tasks are slow; polling faster only burns Ark quota. */
819const SEEDANCE_POLL_INTERVAL_MS = 5000
820
821/** The create → poll → complete lifecycle for one Seedance task. */
822function seedanceStream(data: SeedanceRequest): AsyncIterable<StreamChunk> {
823 const options = data.options ?? {}
824
825 // The studio's camelCase controls map one-to-one onto the provider's own
826 // request fields. Applicability is per model and Ark 400s on a field the
827 // model doesn't take (it does not ignore it), so the client only sends
828 // what the selected model accepts — see `SEEDANCE_MODELS` in lib/seedance.
829 //
830 // `ratio` / `resolution` are typed against the tiers this package knows,
831 // so a custom model id sends its sizing through the generic `size`
832 // template instead (see `SeedanceJobOptions.size`).
833 const modelOptions: BytePlusVideoProviderOptions = {
834 ...(options.size === undefined &&
835 options.ratio !== undefined && { ratio: options.ratio }),
836 ...(options.size === undefined &&
837 options.resolution !== undefined && {
838 resolution: options.resolution,
839 }),
840 // `-1` (let the model choose the length) is only reachable through
841 // provider options: the generic `duration` gets snapped into range.
842 ...(options.duration === -1 && { duration: -1 }),
843 ...(options.frames !== undefined && { frames: options.frames }),
844 ...(options.seed !== undefined && { seed: options.seed }),
845 ...(options.watermark !== undefined && { watermark: options.watermark }),
846 ...(options.generateAudio !== undefined && {
847 generate_audio: options.generateAudio,
848 }),
849 ...(options.cameraFixed !== undefined && {
850 camera_fixed: options.cameraFixed,
851 }),
852 ...(options.serviceTier !== undefined && {
853 service_tier: options.serviceTier,
854 }),
855 ...(options.draft !== undefined && { draft: options.draft }),
856 ...(options.priority !== undefined && { priority: options.priority }),
857 }
858
859 // `frames` takes precedence over `duration` server-side, so never send
860 // both; `-1` already went through modelOptions above.
861 const duration =
862 options.frames === undefined &&
863 options.duration !== undefined &&
864 options.duration > 0
865 ? options.duration
866 : undefined
867
868 return generateVideo({
869 threadId: 'media-seedance',
870 // For a model this package knows, the adapter snaps `duration` into its
871 // range and validates the resolution tier, prompt roles and
872 // frame/reference exclusivity before anything reaches Ark. For a custom
873 // id every one of those guards is off by design: the duration goes
874 // through verbatim and Ark is the authority.
875 adapter: byteplusV(data.model),
876 // Passed through un-narrowed, unlike the other generators: Seedance's
877 // reference mode takes video and audio parts as well as images (the
878 // template presets send both), and which of them a given model allows is
879 // the adapter's call — its error names the model and the part.
880 prompt: data.prompt,
881 ...(options.size !== undefined && { size: options.size }),
882 ...(duration !== undefined && { duration }),
883 modelOptions,
884 stream: true,
885 pollingInterval: SEEDANCE_POLL_INTERVAL_MS,
886 maxDuration: SEEDANCE_MAX_DURATION_MS,
887 })
888}
889
890/**
891 * Streams one Seedance task as Server-Sent Events, for the studio's
892 * `useGenerateVideo`. The browser never sees ARK_API_KEY or a job id it has
893 * to poll with — the server does the waiting and reports status on the wire.
894 */
895export const generateSeedanceVideoFn = createServerFn({ method: 'POST' })
896 .inputValidator((data: SeedanceRequest) => {
897 if (!hasPromptContent(data.prompt)) throw new Error('Prompt is required')
898 if (!data.model) throw new Error('Model is required')
899 return data
900 })
901 .handler(({ data }) => toServerSentEventsResponse(seedanceStream(data)))
902
903interface LiveVideoRequest {
904 prompt: string
905 model: LiveVideoModelId
906 resolution: LiveVideoResolution
907}
908
909/**
910 * Mints a live-video session. The browser then connects with the provider
911 * client (`@reactor-team/js-sdk` or `@fal-ai/client`). There is no job URL.
912 */
913export const generateLiveVideoFn = createServerFn({ method: 'POST' })
914 .inputValidator((data: LiveVideoRequest) => {
915 if (typeof data.prompt !== 'string' || data.prompt.trim().length === 0) {
916 throw new Error('Prompt is required')
917 }
918 if (!isLiveVideoModelId(data.model)) {
919 throw new Error(`Unknown live video model: ${data.model}`)
920 }
921 return data
922 })
923 .handler(async ({ data }) => {
924 const prompt = data.prompt.trim()
925 const provider = liveVideoProvider(data.model)
926 const live = isFalLiveVideoModel(data.model)
927 ? await generateLiveVideo({
928 threadId: 'media-live-video',
929 adapter: falL(data.model),
930 prompt,
931 debug: false,
932 })
933 : await generateLiveVideo({
934 threadId: 'media-live-video',
935 adapter: reactorV(data.model),
936 prompt,
937 ...(data.resolution === '1080p' ||
938 data.resolution === '2k' ||
939 data.resolution === '4k'
940 ? { modelOptions: { resolution: data.resolution } }
941 : {}),
942 debug: false,
943 })
944 return {
945 token: live.token,
946 model: live.model,
947 prompt: live.prompt,
948 expiresAt: live.expiresAt,
949 provider,
950 }
951 })
952
953interface WorldSeedImage {
954 dataBase64: string
955 extension?: string
956}
957
958interface WorldRequest {
959 prompt: string
960 model: WorldModelId
961 resolution: WorldResolution
962 seedImages?: Array<WorldSeedImage>
963}
964
965const WORLDLABS_MAX_SEED_IMAGES = 4
966
967function isWorldSeedImage(value: unknown): value is WorldSeedImage {
968 if (typeof value !== 'object' || value === null) return false
969 if (!('dataBase64' in value) || typeof value.dataBase64 !== 'string') {
970 return false
971 }
972 if (value.dataBase64.length === 0) return false
973 if (
974 'extension' in value &&
975 value.extension !== undefined &&
976 typeof value.extension !== 'string'
977 ) {
978 return false
979 }
980 return true
981}
982
983const WORLDLABS_TIMEOUT_MS = 12 * 60 * 1000
984
985/**
986 * Reactor mints a session token for a live stream. World Labs starts a job
987 * and waits until the Marble world is ready (about 5 minutes).
988 */
989export const generateWorldFn = createServerFn({ method: 'POST' })
990 .inputValidator((data: WorldRequest) => {
991 if (typeof data.prompt !== 'string' || data.prompt.trim().length === 0) {
992 throw new Error('Prompt is required')
993 }
994 if (isWorldLabsWorldModel(data.model)) {
995 if (data.seedImages !== undefined) {
996 if (
997 !Array.isArray(data.seedImages) ||
998 data.seedImages.length > WORLDLABS_MAX_SEED_IMAGES ||
999 !data.seedImages.every(isWorldSeedImage)
1000 ) {
1001 throw new Error(
1002 `World Labs accepts at most ${WORLDLABS_MAX_SEED_IMAGES} seed images`,
1003 )
1004 }
1005 }
1006 return data
1007 }
1008 if (!isReactorWorldModel(data.model)) {
1009 throw new Error(`Unknown world model: ${data.model}`)
1010 }
1011 if (!isWorldResolution(data.resolution)) {
1012 throw new Error(`Unknown resolution: ${data.resolution}`)
1013 }
1014 return data
1015 })
1016 .handler(async ({ data }) => {
1017 if (isWorldLabsWorldModel(data.model)) {
1018 const seedImages = data.seedImages ?? []
1019 const [firstSeed, ...restSeeds] = seedImages
1020 const world = await generateWorld({
1021 threadId: 'media-world',
1022 adapter: worldlabsW(data.model),
1023 prompt: data.prompt.trim(),
1024 timeout: WORLDLABS_TIMEOUT_MS,
1025 debug: false,
1026 ...(firstSeed && restSeeds.length === 0
1027 ? {
1028 modelOptions: {
1029 image: firstSeed,
1030 isPano: 'auto' as const,
1031 },
1032 }
1033 : seedImages.length > 1
1034 ? { modelOptions: { images: seedImages } }
1035 : {}),
1036 })
1037 if (typeof world.url !== 'string' || world.url.length === 0) {
1038 throw new Error('World Labs did not return a viewer URL')
1039 }
1040 return {
1041 kind: 'worldlabs' as const,
1042 url: world.url,
1043 worldId: world.worldId,
1044 model: world.model,
1045 prompt: world.prompt,
1046 status: world.status,
1047 thumbnailUrl: world.assets?.thumbnailUrl,
1048 caption: world.assets?.caption,
1049 splatUrl: pickSplatUrl(world.assets?.splats?.spzUrls),
1050 metricScaleFactor: world.assets?.splats?.metricScaleFactor,
1051 groundPlaneOffset: world.assets?.splats?.groundPlaneOffset,
1052 panoUrl: world.assets?.imagery?.panoUrl,
1053 meshUrl: world.assets?.mesh?.colliderMeshUrl,
1054 }
1055 }
1056
1057 const world = await generateWorld({
1058 threadId: 'media-world',
1059 adapter: reactorW(data.model),
1060 prompt: data.prompt.trim(),
1061 modelOptions: { resolution: data.resolution },
1062 debug: false,
1063 })
1064 if (typeof world.token !== 'string' || world.token.length === 0) {
1065 throw new Error('Reactor did not return a session token')
1066 }
1067 return {
1068 kind: 'reactor' as const,
1069 token: world.token,
1070 model: world.model,
1071 prompt: world.prompt,
1072 expiresAt: world.expiresAt,
1073 resolution: data.resolution,
1074 }
1075 })