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

server-functions.ts

1,042 lines35.9 KB

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