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

live.ts

212 lines6.6 KB

1import { BaseLiveVideoAdapter } from '@tanstack/ai/adapters'
2import { generateId } from '@tanstack/ai-utils'
3import { getFalApiKeyFromEnv } from '../utils/client'
4import type {
5 LiveVideoGenerationOptions,
6 LiveVideoGenerationResult,
7} from '@tanstack/ai'
8import type { FalClientConfig } from '../utils/client'
9​
10const DEFAULT_FAL_TOKEN_URL = 'https://rest.fal.ai/tokens/'
11const DEFAULT_TOKEN_DURATION_SECONDS = 300
12​
13export const FAL_LIVE_VIDEO_MODELS = ['minimax/h3-max/director'] as const
14​
15export type FalLiveVideoModel = (typeof FAL_LIVE_VIDEO_MODELS)[number]
16​
17/**
18 * WMA / token app id for each public live model. Director's AsyncAPI lives at
19 * `fal-ai/minimax-h3-max-director`. `wma()` and `/tokens/` must use this id:
20 * `minimax/h3-max/director` parses as alias `h3-max`.
21 */
22export const FAL_LIVE_VIDEO_APP = {
23 'minimax/h3-max/director': 'fal-ai/minimax-h3-max-director',
24} as const satisfies Record<FalLiveVideoModel, string>
25​
26export function isFalLiveVideoModel(model: string): model is FalLiveVideoModel {
27 return (FAL_LIVE_VIDEO_MODELS as ReadonlyArray<string>).includes(model)
29​
30const WMA_PROXY_PATHS = new Set(['/ice', '/session', '/session/heartbeat'])
31​
32/**
33 * URLs a Director live proxy may forward. WMA talks to `wma.fal.run`
34 * (`/ice`, `/session`, `/session/heartbeat`). ICE can fall back to
35 * `fal.run/<app>/ice`. Anything else, including `queue.fal.run`, is
36 * rejected so the proxy cannot run arbitrary fal apps.
37 */
38export function allowedFalLiveVideoProxyTarget(raw: string): URL | null {
39 let url: URL
40 try {
41 url = new URL(raw)
42 } catch {
43 return null
44 }
45 if (url.protocol !== 'https:') return null
46 if (url.username || url.password || url.port || url.search || url.hash) {
47 return null
48 }
49 const path = url.pathname.replace(/\/$/, '') || '/'
50 if (url.hostname === 'wma.fal.run') {
51 return WMA_PROXY_PATHS.has(path) ? url : null
52 }
53 if (url.hostname === 'fal.run') {
54 for (const app of Object.values(FAL_LIVE_VIDEO_APP)) {
55 if (path === `/${app}/ice`) return url
56 }
57 }
58 return null
60​
61/**
62 * Provider options for fal live sessions. The browser applies resolution and
63 * aspect ratio on the WMA `configure` message. `tokenDuration` is the only
64 * server-side field: it sets how long the minted JWT lasts.
65 */
66export interface FalLiveVideoProviderOptions {
67 /** JWT lifetime in seconds. Defaults to 300. */
68 tokenDuration?: number
70​
71export type FalLiveVideoModelProviderOptionsByName = {
72 [M in FalLiveVideoModel]: FalLiveVideoProviderOptions
74​
75function resolveFalLiveApiKey(config?: FalClientConfig): string {
76 return config?.apiKey ?? getFalApiKeyFromEnv()
78​
79function readFalToken(body: unknown): string {
80 if (typeof body === 'string' && body.length > 0) return body
81 if (typeof body === 'object' && body !== null && 'token' in body) {
82 const token = body.token
83 if (typeof token === 'string' && token.length > 0) return token
84 }
85 throw new Error('fal token response did not include a token.')
87​
88/**
89 * fal live-video adapter. Mints a scoped JWT and returns the WMA app id on
90 * `result.model`. Open with `fal.realtime.open(wma(live.model))` through a
91 * server proxy that attaches `FAL_KEY`. WMA rejects the JWT as Key
92 * credentials.
93 *
94 * @example
95 * ```ts
96 * import { generateLiveVideo } from '@tanstack/ai'
97 * import { falLiveVideo } from '@tanstack/ai-fal'
98 *
99 * const live = await generateLiveVideo({
100 * adapter: falLiveVideo('minimax/h3-max/director'),
101 * prompt: 'A chef tosses noodles in a steel wok, flames leaping',
102 * })
103 * // live.model is 'fal-ai/minimax-h3-max-director'
104 * ```
105 */
106export class FalLiveVideoAdapter<
107 TModel extends FalLiveVideoModel,
108> extends BaseLiveVideoAdapter<TModel, FalLiveVideoProviderOptions> {
109 readonly name = 'fal' as const
110 private readonly clientConfig: FalClientConfig | undefined
111 private readonly apiKey: string
112​
113 constructor(model: TModel, config?: FalClientConfig) {
114 super(model, {})
115 this.apiKey = resolveFalLiveApiKey(config)
116 this.clientConfig = config
117 }
118​
119 async createLiveVideo(
120 options: LiveVideoGenerationOptions<FalLiveVideoProviderOptions>,
121 ): Promise<LiveVideoGenerationResult> {
122 const { logger, prompt, abortSignal, modelOptions } = options
123 const tokenDuration =
124 modelOptions?.tokenDuration ?? DEFAULT_TOKEN_DURATION_SECONDS
125 const fetchImpl = this.clientConfig?.fetch ?? globalThis.fetch
126​
127 logger.request(
128 `activity=generateLiveVideo provider=fal model=${this.model}`,
129 {
130 provider: 'fal',
131 model: this.model,
132 },
133 )
134​
135 if (typeof fetchImpl !== 'function') {
136 throw new Error(
137 'global fetch is not available. Pass `fetch` in the fal adapter config.',
138 )
139 }
140​
141 try {
142 const response = await fetchImpl(DEFAULT_FAL_TOKEN_URL, {
143 method: 'POST',
144 headers: {
145 Authorization: `Key ${this.apiKey}`,
146 'Content-Type': 'application/json',
147 },
148 body: JSON.stringify({
149 allowed_apps: [FAL_LIVE_VIDEO_APP[this.model]],
150 token_expiration: tokenDuration,
151 }),
152 ...(abortSignal ? { signal: abortSignal } : {}),
153 })
154​
155 if (!response.ok) {
156 const detail = await response.text().catch(() => '')
157 throw new Error(
158 `fal token request failed (${response.status}${
159 response.statusText ? ` ${response.statusText}` : ''
160 })${detail ? `: ${detail}` : ''}`,
161 )
162 }
163​
164 const token = readFalToken(await response.json())
165 const result: LiveVideoGenerationResult = {
166 id: generateId('liveVideo'),
167 model: FAL_LIVE_VIDEO_APP[this.model],
168 token,
169 expiresAt: Date.now() + tokenDuration * 1000,
170 prompt,
171 status: 'ready',
172 }
173​
174 logger.output(
175 `activity=generateLiveVideo provider=fal model=${this.model}`,
176 {
177 model: this.model,
178 status: result.status,
179 },
180 )
181​
182 return result
183 } catch (error) {
184 logger.errors('fal.createLiveVideo failed', {
185 error,
186 source: 'fal.createLiveVideo',
187 })
188 throw error
189 }
190 }
192​
193/**
194 * Create a fal live-video adapter. Reads `FAL_KEY` when `apiKey` is omitted.
195 */
196export function falLiveVideo<TModel extends FalLiveVideoModel>(
197 model: TModel,
198 config?: FalClientConfig,
199): FalLiveVideoAdapter<TModel> {
200 return new FalLiveVideoAdapter(model, config)
202​
203/**
204 * Create a fal live-video adapter with an explicit API key.
205 */
206export function createFalLiveVideo<TModel extends FalLiveVideoModel>(
207 model: TModel,
208 apiKey: string,
209 config?: Omit<FalClientConfig, 'apiKey'>,
210): FalLiveVideoAdapter<TModel> {
211 return new FalLiveVideoAdapter(model, { ...config, apiKey })