@devvibex/aiflow 1.9.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -97,20 +97,23 @@ to invalidate the cache.
97
97
  {
98
98
  appId: string,
99
99
  models: {
100
- chat: string[], // e.g. ["claude-sonnet-4-6", "gpt-4o", ...]
100
+ chat: string[], // version-less ids, e.g. ["claude-opus", "gpt", ...]
101
101
  image: string[],
102
102
  embed: string[],
103
103
  video: string[],
104
- audio: string[], // Lyria — e.g. ["lyria-3-clip-preview", ...]
105
- sfx: string[], // ElevenLabs — e.g. ["eleven_text_to_sound_v2"]
104
+ audio: string[], // Lyria 3.5 — ["lyria-pro"]
105
+ sfx: string[], // ElevenLabs — ["elevenlabs-sfx"]
106
106
  },
107
107
  defaults: { chat: string, image: string, embed: string, video: string, audio: string, sfx: string },
108
+ imageBackgroundModels: string[], // image models that honour `background`
109
+ audioImageInputModels: string[], // audio models that take `images`
108
110
  limits: {
109
111
  maxTokens: number,
110
112
  maxImageN: number,
111
113
  maxEmbedInputs: number,
112
114
  minSfxDurationSeconds: number,
113
115
  maxSfxDurationSeconds: number,
116
+ maxAudioInputImages: number,
114
117
  },
115
118
  creditValue: number,
116
119
  }
@@ -125,23 +128,185 @@ Returns `Promise<{ id, model, content, usage: { inputTokens, outputTokens, credi
125
128
  Async iterable of `{ delta: string, done: boolean }` chunks. The final chunk
126
129
  has `done: true` and carries the cumulative `usage` object.
127
130
 
128
- ### `aiflow.generateImage({ prompt, model?, size?, n?, image?, images?, system?, language?, signal? })`
131
+ ### `aiflow.generateImage({ prompt, model?, size?, n?, image?, images?, system?, language?, background?, signal? })`
129
132
 
130
133
  Returns `{ images: [{ url?, b64?, mimeType }], usage: { creditsUsed } }`.
131
134
  `url` is a short-lived signed URL (~1h). Pass `image`/`images` to edit an
132
- existing image (image-to-image) instead of generating from text.
135
+ existing image (image-to-image) instead of generating from text. `background`
136
+ (`'auto'` | `'transparent'` | `'opaque'`) is honoured only by the models in
137
+ `config.imageBackgroundModels`; `generateImageBatch` takes it top-level or per
138
+ page. The module default is set with `admin.updateConfig({ imageBackground })`.
133
139
 
134
140
  ### `aiflow.generateVideo({ prompt, model?, aspectRatio?, image?, video?, signal? })`
135
141
 
136
142
  Returns `{ videoUrl, usage: { creditsUsed } }`. Pass `image` for image-to-video
137
143
  or `video` for video-to-video; omit both for pure text-to-video.
138
144
 
139
- ### `aiflow.generateAudio({ prompt, model?, negativePrompt?, seed?, signal?, timeout? })`
145
+ The default model is **Gemini Omni**: one clip of ~10s, **with sound**, 16:9 or
146
+ 9:16 only, and no length parameter. For a longer or extendable video use
147
+ `generateLongVideo` / `createVideoSession` below — same model, so a single clip
148
+ and an extended one look and sound alike. Veo and Seedance are opt-in per module.
140
149
 
141
- Generate music / background audio from a text prompt (Google Vertex AI **Lyria**).
142
- Returns `{ audioUrl, model, durationSeconds, usage: { creditsUsed } }`. `audioUrl`
143
- is a hosted mp3/wav on the CDN. `prompt` should be a musical description (mood,
144
- genre, tempo/BPM, instrumentation). `negativePrompt`/`seed` apply to Lyria 2 only.
150
+ ### `aiflow.generateLongVideo({ prompt, durationSeconds, ... })` — long video from one prompt
151
+
152
+ One prompt plus a duration, one call, one finished video. The gateway splits your
153
+ prompt into a storyboard of ~10s beats, generates the opening clip, then extends
154
+ turn after turn — concatenating as it goes — until the timeline reaches the
155
+ length you asked for.
156
+
157
+ **Maximum 40 seconds.** A video is one Gemini Omni chain: an opening clip of up
158
+ to 10s (its default and its maximum) plus consecutive extends, 40s in total.
159
+ That is a model limit, not a setting — ask for more and you get 40s back with a
160
+ `warning` saying so. Past 40s, generate several videos and join them with
161
+ `mergeVideos` (below) — the joins are hard cuts.
162
+
163
+ ```js
164
+ const video = await aiflow.generateLongVideo({
165
+ prompt: 'A lighthouse keeper climbing the spiral stairs at dawn, then the lamp sweeping out over the water',
166
+ durationSeconds: 30, // 5-40
167
+ aspectRatio: '16:9',
168
+ onProgress: ({ segmentsDone, segmentsPlanned, durationSeconds, videoUrl }) => {
169
+ // videoUrl is ALREADY PLAYABLE — show the partial video, not a spinner
170
+ setStatus(`${segmentsDone}/${segmentsPlanned} — ${durationSeconds ?? 0}s`);
171
+ setPreview(videoUrl);
172
+ },
173
+ });
174
+
175
+ video.videoUrl; // the finished, concatenated video
176
+ video.durationSeconds; // the REAL length — read this, not what you requested
177
+ video.usage.creditsUsed;
178
+ video.warning; // set if it finished shorter than asked (still playable)
179
+ ```
180
+
181
+ The result is always ONE CONTINUOUS SHOT — each clip continues the last — and
182
+ `extendVideo` can lengthen it afterwards while it is still under 40s.
183
+
184
+ Design the UI around four facts:
185
+
186
+ - **Cap the duration control at 40s.** Preset chips (10s / 20s / 30s / 40s) say
187
+ it most clearly. Anything above is clamped, not honoured.
188
+ - **It takes a long time** — roughly 2.5–3 minutes per 10 seconds, so ~8 min for
189
+ a 30s video and ~10 for the full 40s. `onProgress` fires after each clip, so
190
+ show progress and the partial video, which is already playable.
191
+ - **The result is "at least" the requested length** (up to the 40s cap). Omni
192
+ cannot be asked for a clip length, so the timeline overshoots by up to one
193
+ segment.
194
+ - **A short build still resolves.** If a turn fails or credits run out mid-way,
195
+ you get the shorter video plus `warning` explaining why — show both; it is not
196
+ an error.
197
+
198
+ `resumeLongVideo(sessionId)` exists for the older **scene-based** long-form
199
+ builds (parallel scenes with hard cuts, `session.mode === 'scenes'`). No new
200
+ session is built that way while the 40s cap is in place; the method stays for
201
+ sessions created before it.
202
+
203
+ Cost scales with the finished length (Omni bills per delivered second), so show a
204
+ credit estimate before calling. A deployment can lower the cap below 40s
205
+ (`AIFLOW_VIDEO_MAX_TARGET_SECONDS`) but never raise it; either way a larger
206
+ request is clamped, not refused.
207
+
208
+ Under the hood this is a video session (below) that the gateway drives for you —
209
+ `sessionId` comes back on the result, so you can keep extending it manually
210
+ afterwards.
211
+
212
+ ### `aiflow.mergeVideos({ videos })` — join clips you already have
213
+
214
+ Pure assembly: no model runs, nothing is generated, **no AI credits are charged**,
215
+ and the clips need not have come from AIFlow.
216
+
217
+ ```js
218
+ const joined = await aiflow.mergeVideos({
219
+ videos: [clipA.videoUrl, clipB.videoUrl, uploadedDataUrl],
220
+ });
221
+ joined.videoUrl; // one joined video
222
+ joined.durationSeconds; // its measured length
223
+ ```
224
+
225
+ Clips are joined **in the order given**. The first one sets the output format —
226
+ every other clip is scaled and letterboxed (never cropped) to its frame size and
227
+ frame rate, so a mixed-resolution set produces one consistent video instead of
228
+ one that changes size halfway through. Silent clips get a silent audio track so
229
+ the join does not drop sound. Limits: 2–20 clips, 600s of output.
230
+
231
+ **Which long-video call do I want?**
232
+
233
+ | | `mergeVideos` | `generateLongVideo` |
234
+ | --- | --- | --- |
235
+ | What it joins | clips you already have | clips it generates for you |
236
+ | Between clips | a hard cut | one continuous shot |
237
+ | Speed | seconds | minutes (~2–3 per 10s) |
238
+ | AI cost | none | per generated second |
239
+ | Good for | montages, compilations, ads, joining user uploads | one flowing scene from one prompt |
240
+
241
+ They compose: generate several clips with `generateVideo` (fast, in parallel),
242
+ then `mergeVideos` them into a montage. Use `generateLongVideo` only when the
243
+ camera and subject must carry across the joins.
244
+
245
+ ### Stateful video sessions — extend and concatenate (Gemini Omni)
246
+
247
+ Gemini Omni has no "generate 40 seconds" mode and no concatenation endpoint. A
248
+ longer clip is built **turn by turn**: each turn appends 3–10s while the model
249
+ keeps the characters, motion and audio bed continuous, chaining on the previous
250
+ interaction it still holds server-side. The gateway concatenates the segments
251
+ and always hands back the whole timeline, so your app plays **one url** and
252
+ never stitches anything itself.
253
+
254
+ Runs on Gemini Omni — Veo and Seedance hold no context between calls. Leave
255
+ `model` unset: the gateway uses Omni even when the module's video model is Veo
256
+ or Seedance, and refuses only a non-Omni model you pass explicitly. Total length
257
+ is capped at **40 seconds**.
258
+
259
+ ```js
260
+ // 1. Open a session — generate the opening clip…
261
+ const { sessionId, jobId } = await aiflow.createVideoSession({
262
+ prompt: 'A lighthouse keeper climbing the spiral stairs at dawn',
263
+ aspectRatio: '16:9', // fixed for the whole session
264
+ });
265
+ const opening = await aiflow.getVideoJob(jobId); // poll until 'succeeded'
266
+
267
+ // …or seed it from a clip you already have — an upload, a generateVideo or a
268
+ // mergeVideos result (no jobId — ready on return). The WHOLE clip stays on the
269
+ // timeline and counts toward the 40s, so up to 37s; Omni continues from its end.
270
+ const { sessionId: seeded } = await aiflow.createVideoSession({
271
+ video: existingVideoUrlOrDataUrl,
272
+ });
273
+
274
+ // 2. Extend. Keep the prompt SIMPLE — terse continuation prompts extend best.
275
+ const turn = await aiflow.extendVideo(sessionId, {
276
+ prompt: 'he reaches the top and the lamp sweeps out over the water',
277
+ });
278
+ turn.videoUrl; // the WHOLE timeline, re-stitched
279
+ turn.segmentUrl; // just the new tail
280
+
281
+ // 3. Read the timeline at any time
282
+ const session = await aiflow.getVideoSession(sessionId);
283
+ session.videoUrl; // play this
284
+ session.durationSeconds; // measured length so far
285
+ session.remainingSeconds; // left before the 40s ceiling
286
+ session.canExtend; // gate your "Extend" button on THIS, nothing else
287
+ session.segments; // [{ url, durationSeconds, prompt, kind }, ...]
288
+
289
+ // 4. "My videos"
290
+ const { sessions } = await aiflow.listVideoSessions({ limit: 20 });
291
+ ```
292
+
293
+ `extendVideo` submits and polls to completion. For your own progress UI use
294
+ `submitVideoExtend(sessionId, { prompt })` → `getVideoJob(jobId)` instead; the
295
+ job's `videoUrl` is the timeline and `segmentUrl` the new tail.
296
+
297
+ Every turn is billed separately (Omni prices by output token), and
298
+ `session.usage.creditsUsed` is the running total for the whole session.
299
+
300
+ ### `aiflow.generateAudio({ prompt, model?, images?, signal?, timeout? })`
301
+
302
+ Generate music from a text prompt with Google **Lyria 3.5**. Returns
303
+ `{ audioUrl, model, durationSeconds, usage: { creditsUsed } }`; `audioUrl` is a
304
+ hosted mp3 on the CDN. `prompt` is a musical description (mood, genre,
305
+ tempo/BPM, instrumentation), and length or exclusions go in it too ("about 30
306
+ seconds, seamless loop", "no vocals"). `images` takes up to 10 https:// or
307
+ data: URLs for the music to be inspired by, on the models in
308
+ `config.audioImageInputModels`. `negativePrompt` / `seed` are still accepted
309
+ but ignored by Lyria 3.5.
145
310
 
146
311
  ### `aiflow.generateSfx({ prompt, model?, durationSeconds?, signal?, timeout? })`
147
312
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@devvibex/aiflow",
3
- "version": "1.9.0",
4
- "description": "First-party LLM gateway SDK for apps generated on the VibeX platform — chat, streaming, image, video, music (Lyria), sound effects (ElevenLabs), embeddings and real-time speech translation (Gemini Live) without shipping any third-party API key.",
3
+ "version": "1.14.0",
4
+ "description": "First-party LLM gateway SDK for apps generated on the VibeX platform — chat, streaming, image, video (including stateful multi-turn video extension with Gemini Omni), music (Lyria), sound effects (ElevenLabs), embeddings and real-time speech translation (Gemini Live) without shipping any third-party API key.",
5
5
  "keywords": [
6
6
  "ai",
7
7
  "llm",
@@ -9,6 +9,11 @@
9
9
  "claude",
10
10
  "gpt",
11
11
  "gemini",
12
+ "gemini-omni",
13
+ "video-generation",
14
+ "video-extension",
15
+ "long-video",
16
+ "video-merge",
12
17
  "lyria",
13
18
  "elevenlabs",
14
19
  "music-generation",
package/src/index.d.ts CHANGED
@@ -84,6 +84,9 @@ export interface ChatStreamChunk {
84
84
  [key: string]: unknown;
85
85
  }
86
86
 
87
+ /** Values for the image `background` option. */
88
+ export type ImageBackground = 'auto' | 'transparent' | 'opaque';
89
+
87
90
  export interface ImageRequest {
88
91
  prompt: string;
89
92
  model?: string;
@@ -102,6 +105,12 @@ export interface ImageRequest {
102
105
  * `{{language}}` placeholder in the system/user prompt server-side.
103
106
  */
104
107
  language?: string;
108
+ /**
109
+ * What sits behind the subject: 'auto' (model decides, the default),
110
+ * 'transparent' (alpha PNG) or 'opaque'. Honoured only by the models in
111
+ * `config.imageBackgroundModels`; other models ignore it.
112
+ */
113
+ background?: ImageBackground;
105
114
  signal?: AbortSignal;
106
115
  /** Per-call timeout (ms). Defaults to 180000 — image edits exceed the 60s client default. */
107
116
  timeout?: number;
@@ -135,6 +144,8 @@ export interface ImageBatchPage {
135
144
  images?: string[];
136
145
  system?: string;
137
146
  language?: string;
147
+ /** Per-page override of the shared `background`. */
148
+ background?: ImageBackground;
138
149
  }
139
150
 
140
151
  export interface ImageBatchRequest {
@@ -148,6 +159,8 @@ export interface ImageBatchRequest {
148
159
  size?: '512x512' | '1024x1024' | '1024x1792' | string;
149
160
  /** Max pages processed simultaneously (1–4, default 3 server-side). */
150
161
  concurrency?: number;
162
+ /** Shared `background` for every page — see {@link ImageRequest.background}. */
163
+ background?: ImageBackground;
151
164
  signal?: AbortSignal;
152
165
  /** Per-call timeout (ms). Defaults to 600000 (10 min). */
153
166
  timeout?: number;
@@ -173,25 +186,28 @@ export interface ImageBatchResponse {
173
186
  export interface VideoRequest {
174
187
  prompt: string;
175
188
  /**
176
- * Video model. Defaults to the app's configured default. Veo models
177
- * (`veo-*`) run on Google Vertex; Seedance/Dreamina
178
- * (`dreamina-seedance-*`) run on BytePlus Ark.
189
+ * Video model: `'gemini-omni'` | `'veo'` | `'seedance'`. Defaults to the
190
+ * app's configured model, which is Gemini Omni unless the module was pinned
191
+ * to another one. Omni clips always have sound and are the only ones that
192
+ * can be extended (see {@link AIFlowClient.createVideoSession}).
179
193
  */
180
194
  model?: string;
181
195
  /**
182
- * Output aspect ratio. Veo supports 16:9 / 9:16 / 1:1; Seedance also
183
- * accepts 4:3 / 3:4 / 21:9 (the server maps unsupported ratios to 16:9).
196
+ * Output aspect ratio. Gemini Omni supports 16:9 / 9:16 only; Veo also 1:1;
197
+ * Seedance also 1:1 / 4:3 / 3:4 / 21:9. An unsupported ratio is mapped to
198
+ * 16:9 by the server.
184
199
  */
185
200
  aspectRatio?: '16:9' | '9:16' | '1:1' | '4:3' | '3:4' | '21:9' | string;
186
201
  /**
187
- * Output resolution (Seedance/Dreamina only): '480p' | '720p' | '1080p'.
188
- * Lower resolution generates faster. Defaults to the app's server-side
189
- * default (720p) when omitted. Ignored by Veo.
202
+ * Output resolution: '720p' (default) | '1080p' on Gemini Omni and
203
+ * Seedance; Seedance also '480p' (Omni treats it as 720p). Lower generates
204
+ * faster and, on Omni, costs less. Ignored by Veo.
190
205
  */
191
206
  resolution?: '480p' | '720p' | '1080p' | string;
192
207
  /**
193
- * Clip length in seconds. Seedance 2.0 supports an integer 4–15 (clamped to
194
- * that range, default 5). Ignored by Veo, which uses a fixed length per mode.
208
+ * Clip length in seconds — Seedance only: an integer 4–15 (clamped to that
209
+ * range, default 5). Gemini Omni takes no length and returns a ~10s clip
210
+ * (longer: {@link AIFlowClient.generateLongVideo}); Veo uses a fixed length.
195
211
  */
196
212
  duration?: number;
197
213
  /** Burn the provider watermark into the output (Seedance only). */
@@ -239,17 +255,256 @@ export interface VideoJobStatusResponse {
239
255
  usage?: { creditsUsed: number };
240
256
  /** Present once status === 'failed'. */
241
257
  error?: string;
258
+ /**
259
+ * Session turns only (see {@link AIFlowClient.createVideoSession}). On
260
+ * success `videoUrl` is the WHOLE stitched timeline and `segmentUrl` the
261
+ * newly generated tail alone.
262
+ */
263
+ sessionId?: string;
264
+ segmentUrl?: string;
265
+ /** Measured length of the stitched `videoUrl` after this turn. */
266
+ durationSeconds?: number;
267
+ /** Auto-build progress; present while a build runs and once it finishes. */
268
+ segmentsDone?: number;
269
+ segmentsPlanned?: number;
270
+ /**
271
+ * A build SUCCEEDED but came up short of the requested length. There is a
272
+ * real playable video; this says why it is shorter. Distinct from `error`.
273
+ */
274
+ warning?: string;
275
+ }
276
+
277
+ // ─── Stateful video sessions (Gemini Omni `extend`) ─────────────────────────
278
+
279
+ /** One clip on a session's timeline, in play order. */
280
+ export interface VideoSegment {
281
+ /** CDN URL of THIS clip alone — not the stitched timeline. */
282
+ url: string;
283
+ thumbnailUrl?: string;
284
+ durationSeconds: number;
285
+ prompt?: string;
286
+ /**
287
+ * 'base' = generated opener, 'upload' = your seed clip, 'extension' = a
288
+ * chained turn, 'scene' = one clip of a LONG-FORM video (hard cut either
289
+ * side).
290
+ */
291
+ kind: 'base' | 'upload' | 'extension' | 'scene';
292
+ createdAt?: string;
293
+ }
294
+
295
+ /**
296
+ * A stateful video session: one growing timeline. Returned by session create,
297
+ * extend and read, so a client only ever renders one shape.
298
+ */
299
+ export interface VideoSession {
300
+ sessionId: string;
301
+ /** 'exhausted' once the 40s ceiling is reached — a state, not an error. */
302
+ status: 'active' | 'exhausted';
303
+ model: string;
304
+ aspectRatio?: string;
305
+ resolution?: string;
306
+ /**
307
+ * THE CONCATENATION — every segment stitched in play order. Play this.
308
+ * Empty while a session's opening clip is still generating, and a NEW url
309
+ * after every extend.
310
+ */
311
+ videoUrl: string;
312
+ thumbnailUrl?: string;
313
+ /** Measured length of `videoUrl`. */
314
+ durationSeconds: number;
315
+ /** Seconds left before Omni's 40s ceiling. */
316
+ remainingSeconds: number;
317
+ /**
318
+ * Whether another extend turn is possible. The ONLY flag a UI should gate
319
+ * its extend control on: false both while the opening clip is generating and
320
+ * once the ceiling is reached.
321
+ */
322
+ canExtend: boolean;
323
+ segments: VideoSegment[];
324
+ extendCount: number;
325
+ /** Credits charged across EVERY turn of this session so far. */
326
+ usage: { creditsUsed: number };
327
+ /** Length this session was auto-built to, when opened with a target. */
328
+ targetDurationSeconds?: number;
329
+ /** Ceiling `remainingSeconds` is measured against. */
330
+ maxDurationSeconds: number;
331
+ /** The per-segment beats an auto-build planned from the single prompt. */
332
+ storyboard?: string[];
333
+ /**
334
+ * `continuous` = one flowing shot built by chaining (up to ~2 min).
335
+ * `scenes` = LONG-FORM: independent scenes generated in parallel and merged
336
+ * with hard cuts — the only shape that reaches many minutes.
337
+ */
338
+ mode: 'continuous' | 'scenes';
339
+ /** Long-form progress. Absent for a continuous session. */
340
+ scenesTotal?: number;
341
+ scenesDone?: number;
342
+ /** A long-form build with scenes still missing can be resumed. */
343
+ canResume?: boolean;
344
+ }
345
+
346
+ export interface VideoSessionRequest {
347
+ /**
348
+ * What the opening clip shows. Required unless `video` seeds the session.
349
+ */
350
+ prompt?: string;
351
+ /**
352
+ * Leave unset. Sessions run on Gemini Omni — the only model with a stateful
353
+ * extend protocol — and the gateway picks it even when the module's video
354
+ * model is Veo or Seedance. A non-Omni model passed here is rejected.
355
+ */
356
+ model?: string;
357
+ /** Omni supports 16:9 and 9:16 only. Fixed for the whole session. */
358
+ aspectRatio?: '16:9' | '9:16';
359
+ /** Fixed for the whole session. Defaults to 720p. */
360
+ resolution?: '360p' | '720p' | '1080p' | '4k';
361
+ /** Still image to animate into the opening clip (image-to-video). */
362
+ image?: string;
363
+ /**
364
+ * A clip you already have — an upload, a `generateVideo` or a
365
+ * `mergeVideos` result — to seed the timeline with instead of generating an
366
+ * opener. An `https://` or `data:` URL. The WHOLE clip stays on the timeline
367
+ * and counts toward the 40s cap, so it may be at most 37s (longer is a 400);
368
+ * the model continues from its last ~10s (Omni's input limit).
369
+ */
370
+ video?: string;
371
+ description?: string;
372
+ /**
373
+ * AUTO-BUILD: how long the finished video should be. With this set the
374
+ * gateway storyboards the prompt and takes every turn itself until the
375
+ * timeline is this long — see {@link AIFlowClient.generateLongVideo}, which
376
+ * wraps create + poll into one call.
377
+ */
378
+ targetDurationSeconds?: number;
379
+ signal?: AbortSignal;
380
+ timeout?: number;
381
+ }
382
+
383
+ /** Progress of an auto-build, reported after each completed segment. */
384
+ export interface VideoBuildProgress {
385
+ segmentsDone: number;
386
+ segmentsPlanned?: number;
387
+ /** Length of the timeline so far. */
388
+ durationSeconds?: number;
389
+ /** ALREADY PLAYABLE — show it instead of a spinner. */
390
+ videoUrl?: string;
391
+ thumbnailUrl?: string;
392
+ }
393
+
394
+ export interface LongVideoRequest {
395
+ /** What the whole video shows. The gateway splits it into per-segment beats. */
396
+ prompt: string;
397
+ /**
398
+ * How long the finished video should be, in seconds — **5 to 40**.
399
+ *
400
+ * 40s is a model limit: a video is one Omni chain (an opening clip of up to
401
+ * 10s, then consecutive extends) and Google will not extend one past 40s.
402
+ * A larger number is CLAMPED to 40 and the result carries a `warning`.
403
+ *
404
+ * The result is "at least" this, up to the cap: Omni cannot be asked for a
405
+ * clip length, so the timeline overshoots by up to one ~10s segment.
406
+ */
407
+ durationSeconds: number;
408
+ /** Must be a Gemini Omni model; defaults to the module's video model. */
409
+ model?: string;
410
+ aspectRatio?: '16:9' | '9:16';
411
+ resolution?: '360p' | '720p' | '1080p' | '4k';
412
+ /** Still image to animate into the OPENING segment. */
413
+ image?: string;
414
+ description?: string;
415
+ /** Fires after each completed segment, with a playable partial video. */
416
+ onProgress?: (progress: VideoBuildProgress) => void;
417
+ signal?: AbortSignal;
418
+ /** Overall wait budget. Defaults to ~7 minutes per 10s requested. */
419
+ timeout?: number;
420
+ pollIntervalMs?: number;
421
+ }
422
+
423
+ export interface LongVideoResponse extends VideoResponse {
424
+ sessionId?: string;
425
+ /** Real measured length — read this, not what you requested. */
426
+ durationSeconds?: number;
427
+ segmentsDone?: number;
428
+ /**
429
+ * Set when the build came up short of `durationSeconds`, or when the request
430
+ * was clamped to the 40s maximum. The video is real and already paid for —
431
+ * show it, and the reason; do not treat it as an error.
432
+ */
433
+ warning?: string;
434
+ }
435
+
436
+ export interface VideoMergeRequest {
437
+ /**
438
+ * The clips to join, IN PLAY ORDER — `https://` URLs or `data:` URLs.
439
+ * The FIRST one sets the output frame size and frame rate; the rest are
440
+ * scaled and letterboxed to match. At least 2, at most 20.
441
+ */
442
+ videos: string[];
443
+ /** Fires as clips are fetched and prepared. */
444
+ onProgress?: (progress: VideoBuildProgress) => void;
445
+ signal?: AbortSignal;
446
+ /** Defaults to 2 minutes per clip (minimum 10 minutes). */
447
+ timeout?: number;
448
+ pollIntervalMs?: number;
449
+ }
450
+
451
+ export interface VideoMergeResponse extends VideoResponse {
452
+ /** Measured length of the joined video. */
453
+ durationSeconds?: number;
454
+ }
455
+
456
+ /** Returned by {@link AIFlowClient.createVideoSession}. */
457
+ export interface VideoSessionCreateResponse {
458
+ sessionId: string;
459
+ /** Present only when an opening clip is generating — poll it. */
460
+ jobId?: string;
461
+ /** Always present, so a client renders one shape either way. */
462
+ session: VideoSession;
463
+ }
464
+
465
+ export interface VideoExtendRequest {
466
+ /**
467
+ * What happens next. Keep it SIMPLE — terse continuation prompts extend
468
+ * best. Omitted, the gateway uses "Continue the scene."
469
+ */
470
+ prompt?: string;
471
+ description?: string;
472
+ signal?: AbortSignal;
473
+ timeout?: number;
474
+ pollIntervalMs?: number;
242
475
  }
243
476
 
244
- // ─── Audio (music — Lyria) ──────────────────────────────────────────────────
477
+ /** Result of one completed extend turn. */
478
+ export interface VideoExtendResponse extends VideoResponse {
479
+ /** The whole timeline is in `videoUrl`; this is the new tail alone. */
480
+ segmentUrl?: string;
481
+ durationSeconds?: number;
482
+ sessionId?: string;
483
+ }
484
+
485
+ /** Acknowledgement returned by {@link AIFlowClient.submitVideoExtend}. */
486
+ export interface VideoExtendSubmitResponse extends VideoJobSubmitResponse {
487
+ sessionId: string;
488
+ }
489
+
490
+ // ─── Audio (music — Lyria 3.5) ──────────────────────────────────────────────
245
491
 
246
492
  export interface AudioRequest {
247
- /** Musical description — mood, genre, tempo (BPM), instrumentation, texture. */
493
+ /**
494
+ * Musical description — mood, genre, tempo (BPM), instrumentation, texture,
495
+ * length ("about 30 seconds") and exclusions ("no vocals").
496
+ */
248
497
  prompt: string;
249
498
  model?: string;
250
- /** Things to steer away from. Lyria 2 only — ignored by Lyria 3. */
499
+ /**
500
+ * Up to `config.limits.maxAudioInputImages` (10) reference images — https://
501
+ * or data: URLs — that the music should be inspired by. Only for models in
502
+ * `config.audioImageInputModels`; the gateway answers 400 otherwise.
503
+ */
504
+ images?: string[];
505
+ /** Ignored by Lyria 3.5 — put exclusions in `prompt`. */
251
506
  negativePrompt?: string;
252
- /** Deterministic seed (Lyria 2 only). */
507
+ /** Ignored by Lyria 3.5. */
253
508
  seed?: number;
254
509
  signal?: AbortSignal;
255
510
  /** Per-call timeout (ms). Defaults to 180000 (3 min) — music gen is slow. */
@@ -587,12 +842,20 @@ export interface AiflowConfig {
587
842
  modelUserSelectable?: boolean;
588
843
  /** Per-feature form of `modelUserSelectable`. */
589
844
  userSelectable?: Record<string, boolean>;
845
+ /** Module default for the image `background` option. */
846
+ imageBackground?: ImageBackground;
847
+ /** Image models that honour `background`. */
848
+ imageBackgroundModels?: string[];
849
+ /** Audio models that accept reference `images` in `generateAudio`. */
850
+ audioImageInputModels?: string[];
590
851
  limits: {
591
852
  maxTokens: number;
592
853
  maxImageN: number;
593
854
  maxEmbedInputs: number;
594
855
  minSfxDurationSeconds: number;
595
856
  maxSfxDurationSeconds: number;
857
+ /** Reference images per `generateAudio` call. */
858
+ maxAudioInputImages?: number;
596
859
  };
597
860
  creditValue: number;
598
861
  /** Module-configured default system prompt, or null if none. */
@@ -615,6 +878,12 @@ export interface AiflowAdminModule {
615
878
  title: string | null;
616
879
  systemPrompt: string | null;
617
880
  defaults: Record<string, string>;
881
+ /** Per-feature "User Selection" flags, key-for-key with `defaults`. */
882
+ userSelectable?: Record<string, boolean>;
883
+ /** Stored default for the image `background` option. */
884
+ imageBackground?: ImageBackground;
885
+ /** Image models that honour `background`. */
886
+ imageBackgroundModels?: string[];
618
887
  models: string[];
619
888
  }
620
889
 
@@ -629,6 +898,8 @@ export interface AiflowAdminUpdateConfigInput {
629
898
  defaults?: Record<string, string>;
630
899
  /** Sugar: sets the chat default model (folded into `defaults.chat`). */
631
900
  defaultModel?: string;
901
+ /** Default image `background` for the module. Top-level — never inside `defaults`. */
902
+ imageBackground?: ImageBackground;
632
903
  }
633
904
 
634
905
  /**
@@ -727,6 +998,91 @@ export class AIFlowClient {
727
998
  jobId: string,
728
999
  options?: { signal?: AbortSignal; timeout?: number },
729
1000
  ): Promise<VideoJobStatusResponse>;
1001
+ /**
1002
+ * Open a stateful video session — one growing timeline built turn by turn
1003
+ * with Gemini Omni's `extend`.
1004
+ *
1005
+ * With `prompt`, the opening clip is generated and `jobId` is returned to
1006
+ * poll. With `video`, the timeline is seeded from your own clip and is ready
1007
+ * on return. The gateway keeps the concatenation, so the app always plays
1008
+ * `session.videoUrl` and never stitches anything itself.
1009
+ */
1010
+ createVideoSession(
1011
+ request: VideoSessionRequest,
1012
+ ): Promise<VideoSessionCreateResponse>;
1013
+ /**
1014
+ * Generate a LONG video from one prompt and a duration, in a single call:
1015
+ * the gateway storyboards the prompt into ~10s beats, generates them turn by
1016
+ * turn and concatenates them into one finished clip.
1017
+ *
1018
+ * **Maximum 40 seconds** — see {@link LongVideoRequest.durationSeconds}.
1019
+ * For anything longer, generate several videos and {@link mergeVideos} them;
1020
+ * the joins are hard cuts.
1021
+ *
1022
+ * Takes MINUTES (roughly two to three per 10s). `onProgress` fires after
1023
+ * every segment with a playable partial `videoUrl` — build the UI around
1024
+ * that, not a spinner.
1025
+ */
1026
+ generateLongVideo(request: LongVideoRequest): Promise<LongVideoResponse>;
1027
+ /**
1028
+ * Join clips you already have into one longer video — no model call, no AI
1029
+ * credits. Clips are joined in the order given, normalised to the first
1030
+ * one's format.
1031
+ *
1032
+ * Each join is a HARD CUT: right for a montage, wrong for one continuous
1033
+ * scene. Use {@link generateLongVideo} when the shot must flow.
1034
+ */
1035
+ mergeVideos(request: VideoMergeRequest): Promise<VideoMergeResponse>;
1036
+ /**
1037
+ * Resume a LONG-FORM build that stopped short — after a gateway restart, a
1038
+ * provider hiccup, or credits that have since been topped up. Only missing
1039
+ * scenes are generated; finished ones are already paid for and are never
1040
+ * regenerated. Resolves with the re-assembled video.
1041
+ *
1042
+ * Applies to SCENE-based sessions (`mode === 'scenes'`) only. None are
1043
+ * created while the 40s cap is in place — every new build is continuous and
1044
+ * is lengthened with {@link extendVideo} — so this serves sessions made
1045
+ * before it. A continuous session is rejected with a 400.
1046
+ */
1047
+ resumeLongVideo(
1048
+ sessionId: string,
1049
+ request?: {
1050
+ onProgress?: (progress: VideoBuildProgress) => void;
1051
+ signal?: AbortSignal;
1052
+ timeout?: number;
1053
+ pollIntervalMs?: number;
1054
+ },
1055
+ ): Promise<LongVideoResponse>;
1056
+ /** Submit a merge without waiting; poll it with {@link getVideoJob}. */
1057
+ submitVideoMerge(request: {
1058
+ videos: string[];
1059
+ signal?: AbortSignal;
1060
+ timeout?: number;
1061
+ }): Promise<VideoJobSubmitResponse>;
1062
+ /**
1063
+ * Append one 3–10s continuation to a session's timeline and wait for it.
1064
+ * Returns the re-stitched timeline in `videoUrl`.
1065
+ */
1066
+ extendVideo(
1067
+ sessionId: string,
1068
+ request?: VideoExtendRequest,
1069
+ ): Promise<VideoExtendResponse>;
1070
+ /** Submit an extend turn without waiting; poll it with {@link getVideoJob}. */
1071
+ submitVideoExtend(
1072
+ sessionId: string,
1073
+ request?: VideoExtendRequest,
1074
+ ): Promise<VideoExtendSubmitResponse>;
1075
+ /** Read a session's current timeline, segments and `canExtend` flag. */
1076
+ getVideoSession(
1077
+ sessionId: string,
1078
+ options?: { signal?: AbortSignal; timeout?: number },
1079
+ ): Promise<VideoSession>;
1080
+ /** The caller's own sessions, newest first — backs a "my videos" screen. */
1081
+ listVideoSessions(options?: {
1082
+ limit?: number;
1083
+ signal?: AbortSignal;
1084
+ timeout?: number;
1085
+ }): Promise<{ sessions: VideoSession[] }>;
730
1086
  generateAudio(request: AudioRequest): Promise<AudioResponse>;
731
1087
  generateSfx(request: SfxRequest): Promise<SfxResponse>;
732
1088
  embed(request: EmbedRequest): Promise<EmbedResponse>;
package/src/index.js CHANGED
@@ -10,6 +10,39 @@ const DEFAULT_TIMEOUT_MS = 60_000;
10
10
  const DEFAULT_MAX_RETRIES = 2;
11
11
  const RETRY_STATUSES = new Set([429, 500, 502, 503, 504]);
12
12
 
13
+ /**
14
+ * Above this many seconds the gateway builds a video as independent SCENES in
15
+ * PARALLEL (hard cuts) instead of chaining one continuous shot — chaining is
16
+ * sequential and cannot reach these lengths. Mirrors
17
+ * `AIFLOW_VIDEO_CONTINUOUS_MAX_DURATION` server-side; used here only to size the
18
+ * client's wait, so a drift between the two costs nothing.
19
+ */
20
+ const CONTINUOUS_MAX_SECONDS = 120;
21
+
22
+ /**
23
+ * How long to wait for a build of `seconds` of video.
24
+ *
25
+ * A segment takes ~2.5–3 minutes of model time. Continuous builds run those
26
+ * strictly one after another; long-form runs them a few at a time, so its wall
27
+ * clock grows far more slowly. Both get generous slack — the cost of waiting too
28
+ * long is a slightly late error, the cost of waiting too little is abandoning a
29
+ * video the customer has already been charged for.
30
+ */
31
+ function longVideoTimeoutMs(seconds) {
32
+ const segments = Math.max(1, Math.ceil(seconds / 10));
33
+ const perSegmentMs = 7 * 60_000;
34
+ if (seconds <= CONTINUOUS_MAX_SECONDS) {
35
+ return Math.max(600_000, segments * perSegmentMs);
36
+ }
37
+ // Long-form: assume only a modest amount of the server's concurrency, so a
38
+ // slow provider day does not time the client out mid-build.
39
+ const assumedConcurrency = 2;
40
+ return Math.max(
41
+ 1_800_000,
42
+ Math.ceil(segments / assumedConcurrency) * perSegmentMs,
43
+ );
44
+ }
45
+
13
46
  export class AIFlowError extends Error {
14
47
  constructor(message, { status, code, requestId, cause } = {}) {
15
48
  super(message);
@@ -370,6 +403,7 @@ export class AIFlowClient {
370
403
  images,
371
404
  system,
372
405
  language,
406
+ background,
373
407
  signal,
374
408
  timeout,
375
409
  } = {}) {
@@ -393,6 +427,9 @@ export class AIFlowClient {
393
427
  images,
394
428
  system: resolvedSystem,
395
429
  language,
430
+ // 'auto' | 'transparent' | 'opaque' — honoured only by the
431
+ // models in `config.imageBackgroundModels`.
432
+ background,
396
433
  },
397
434
  // Image edits (esp. document translation) routinely exceed the 60s
398
435
  // client default — a single 2K edit was observed at ~63s. Default
@@ -422,6 +459,7 @@ export class AIFlowClient {
422
459
  language,
423
460
  size,
424
461
  concurrency,
462
+ background,
425
463
  signal,
426
464
  timeout,
427
465
  } = {}) {
@@ -441,6 +479,7 @@ export class AIFlowClient {
441
479
  language,
442
480
  size,
443
481
  concurrency,
482
+ background,
444
483
  },
445
484
  // A batch of multi-minute edits needs far longer than a single
446
485
  // request — default to 10 minutes, matching the server socket.
@@ -536,9 +575,15 @@ export class AIFlowClient {
536
575
  /** Poll a video job to completion and normalise the success payload. */
537
576
  async _pollVideoJob(
538
577
  jobId,
539
- { signal, timeout = 600_000, pollIntervalMs = 3_000 } = {},
578
+ {
579
+ signal,
580
+ timeout = 600_000,
581
+ pollIntervalMs = 3_000,
582
+ onProgress,
583
+ } = {},
540
584
  ) {
541
585
  const deadline = Date.now() + timeout;
586
+ let lastProgress = -1;
542
587
  // eslint-disable-next-line no-constant-condition
543
588
  while (true) {
544
589
  if (signal?.aborted) {
@@ -547,12 +592,49 @@ export class AIFlowClient {
547
592
  });
548
593
  }
549
594
  const job = await this.getVideoJob(jobId, { signal });
595
+ // Fired only when a SEGMENT actually landed, not on every poll — a
596
+ // progress callback that runs every 5s with identical numbers just
597
+ // re-renders the UI for nothing.
598
+ if (
599
+ onProgress &&
600
+ job.status !== 'succeeded' &&
601
+ typeof job.segmentsDone === 'number' &&
602
+ job.segmentsDone !== lastProgress
603
+ ) {
604
+ lastProgress = job.segmentsDone;
605
+ try {
606
+ onProgress({
607
+ segmentsDone: job.segmentsDone,
608
+ segmentsPlanned: job.segmentsPlanned,
609
+ durationSeconds: job.durationSeconds,
610
+ // Playable already — show it instead of a spinner.
611
+ videoUrl: job.videoUrl,
612
+ thumbnailUrl: job.thumbnailUrl,
613
+ });
614
+ } catch {
615
+ // A throwing progress handler is the caller's bug, not a
616
+ // reason to abandon a video they are paying for.
617
+ }
618
+ }
550
619
  if (job.status === 'succeeded') {
551
620
  return {
552
621
  videoUrl: job.videoUrl,
553
622
  thumbnailUrl: job.thumbnailUrl,
554
623
  prompt: job.prompt,
555
624
  usage: job.usage || { creditsUsed: 0 },
625
+ // Session turns only. Spread conditionally so a plain
626
+ // generation's result keeps exactly the shape earlier SDK
627
+ // versions returned — no undefined keys appearing in it.
628
+ ...(job.sessionId ? { sessionId: job.sessionId } : {}),
629
+ ...(job.segmentUrl ? { segmentUrl: job.segmentUrl } : {}),
630
+ ...(job.durationSeconds != null
631
+ ? { durationSeconds: job.durationSeconds }
632
+ : {}),
633
+ ...(job.segmentsDone != null
634
+ ? { segmentsDone: job.segmentsDone }
635
+ : {}),
636
+ // Short of the requested length, but real and paid for.
637
+ ...(job.warning ? { warning: job.warning } : {}),
556
638
  };
557
639
  }
558
640
  if (job.status === 'failed') {
@@ -574,12 +656,363 @@ export class AIFlowClient {
574
656
  }
575
657
 
576
658
  /**
577
- * Generate music / background audio from a text prompt (Lyria).
659
+ * Join clips you ALREADY HAVE into one longer video.
660
+ *
661
+ * Pure assembly — no model runs, nothing is generated, no AI credits are
662
+ * charged, and the clips need not have come from AIFlow. Use it to stitch
663
+ * separately generated clips, or the user's own uploads, into one file.
664
+ *
665
+ * ```js
666
+ * const joined = await aiflow.mergeVideos({
667
+ * videos: [clipA.videoUrl, clipB.videoUrl, uploadedDataUrl],
668
+ * });
669
+ * joined.videoUrl; // the single joined video
670
+ * joined.durationSeconds; // its measured length
671
+ * ```
672
+ *
673
+ * Clips are joined IN THE ORDER GIVEN. The FIRST one sets the output format:
674
+ * every other clip is scaled and letterboxed (never cropped) to its frame
675
+ * size and frame rate, so a mixed set produces one consistent video rather
676
+ * than one that changes size halfway through. Silent clips get a silent
677
+ * audio track so the join does not drop sound.
678
+ *
679
+ * ⚠️ Merged clips do NOT continue each other — each cut is a hard cut, which
680
+ * is right for a montage and wrong for one continuous scene. For a single
681
+ * flowing shot use {@link generateLongVideo} instead, which generates each
682
+ * segment FROM the previous one.
683
+ *
684
+ * @returns {Promise<{videoUrl:string, thumbnailUrl?:string, durationSeconds?:number, usage:{creditsUsed:number}}>}
685
+ */
686
+ async mergeVideos({
687
+ videos,
688
+ onProgress,
689
+ signal,
690
+ timeout,
691
+ pollIntervalMs,
692
+ } = {}) {
693
+ if (!Array.isArray(videos) || videos.length < 2) {
694
+ throw new AIFlowError('mergeVideos needs at least two videos');
695
+ }
696
+ const { jobId } = await this.submitVideoMerge({ videos, signal });
697
+ return this._pollVideoJob(jobId, {
698
+ signal,
699
+ // Every clip is fetched and usually re-encoded on the gateway, so the
700
+ // budget scales with how many were handed over.
701
+ timeout: timeout ?? Math.max(600_000, videos.length * 120_000),
702
+ pollIntervalMs: pollIntervalMs ?? 3_000,
703
+ onProgress,
704
+ });
705
+ }
706
+
707
+ /**
708
+ * Submit a merge without waiting. Returns a job id to poll with
709
+ * {@link getVideoJob}.
710
+ * @returns {Promise<{jobId:string, status:'queued'}>}
711
+ */
712
+ async submitVideoMerge({ videos, signal, timeout } = {}) {
713
+ if (!Array.isArray(videos) || videos.length < 2) {
714
+ throw new AIFlowError('mergeVideos needs at least two videos');
715
+ }
716
+ const res = await this._request(
717
+ '/video/merge',
718
+ { videos },
719
+ // Data-URL clips ride in the body, so allow more than the default.
720
+ { signal, timeout: timeout ?? 300_000 },
721
+ );
722
+ return await res.json();
723
+ }
724
+
725
+ // ── Stateful video sessions (Gemini Omni `extend`) ──────────────────────
726
+ // A session is ONE GROWING TIMELINE. Omni has no "generate 40 seconds" mode
727
+ // and no concatenation endpoint: a long clip is built turn by turn, each turn
728
+ // appending 3–10s while the model keeps the characters, motion and audio bed
729
+ // continuous. The gateway concatenates the segments and always hands back the
730
+ // whole timeline, so an app plays ONE url and never stitches anything itself.
731
+ //
732
+ // Runs on Gemini Omni — Veo and Seedance hold no context between calls. The
733
+ // gateway picks Omni itself when the module's video model is one of those;
734
+ // it refuses only a non-Omni `model` the caller passed explicitly.
735
+
736
+ /**
737
+ * Open a stateful video session.
738
+ *
739
+ * Two ways to start:
740
+ * - `prompt` (± `image`): the opening clip is GENERATED. The returned
741
+ * `jobId` is polled like any video job; `session.videoUrl` is empty until
742
+ * it lands.
743
+ * - `video`: the timeline is SEEDED from a clip you already have (an
744
+ * upload, a `generateVideo` result, a `mergeVideos` result) — ready on
745
+ * return, no `jobId`. The WHOLE clip stays on the timeline and counts
746
+ * toward the 40s cap, so it can be at most 37s; the model continues from
747
+ * its last ~10s (Omni's input limit).
748
+ *
749
+ * `aspectRatio` / `resolution` are fixed for the WHOLE session here: Omni
750
+ * inherits them across the chain, and segments of differing geometry could
751
+ * not be concatenated without re-encoding the timeline.
752
+ *
753
+ * @returns {Promise<{sessionId:string, jobId?:string, session:object}>}
754
+ */
755
+ async createVideoSession({
756
+ prompt,
757
+ model,
758
+ aspectRatio = '16:9',
759
+ resolution,
760
+ image,
761
+ video,
762
+ description,
763
+ targetDurationSeconds,
764
+ signal,
765
+ timeout,
766
+ } = {}) {
767
+ if (!prompt && !video) {
768
+ throw new AIFlowError(
769
+ 'createVideoSession needs either a prompt (to generate the opening clip) or a video (to seed the timeline)',
770
+ );
771
+ }
772
+ // `model` is sent only when the caller chose one. Filling it from the
773
+ // module default (as every other call does) would name `veo` on a module
774
+ // pinned to Veo, and the gateway refuses a session on an explicitly
775
+ // named non-Omni model; left out, it resolves to Omni itself.
776
+ const res = await this._request(
777
+ '/video/sessions',
778
+ {
779
+ model,
780
+ prompt,
781
+ aspectRatio,
782
+ resolution,
783
+ image,
784
+ video,
785
+ description,
786
+ targetDurationSeconds,
787
+ },
788
+ // Seeding from an upload transcodes inline on the gateway, so this
789
+ // call can run longer than a plain submit — but never for minutes.
790
+ { signal, timeout: timeout ?? 300_000 },
791
+ );
792
+ return await res.json();
793
+ }
794
+
795
+ /**
796
+ * Generate a LONG video from ONE prompt and a duration — the whole thing in
797
+ * a single call.
798
+ *
799
+ * The gateway splits your prompt into a storyboard of ~10s beats, generates
800
+ * the opening clip, then extends turn after turn, concatenating until the
801
+ * timeline reaches `durationSeconds`. You get back one finished video url.
802
+ *
803
+ * ```js
804
+ * const video = await aiflow.generateLongVideo({
805
+ * prompt: 'A lighthouse keeper climbing the spiral stairs at dawn',
806
+ * durationSeconds: 30, // 5-40
807
+ * onProgress: (p) => setStatus(`${p.segmentsDone}/${p.segmentsPlanned} — ${p.durationSeconds ?? 0}s`),
808
+ * });
809
+ * ```
810
+ *
811
+ * **Maximum 40 seconds.** A video is one Omni chain — an opening clip of up
812
+ * to 10s plus consecutive extends — and Google will not extend one past 40s.
813
+ * A larger `durationSeconds` is CLAMPED to 40 and the result carries a
814
+ * `warning`. For anything longer, generate several videos and
815
+ * {@link AIFlowClient#mergeVideos} them; the joins are hard cuts.
816
+ *
817
+ * Three things to design the UI around:
818
+ * - cap the duration control at 40s (chips of 10 / 20 / 30 / 40 read best);
819
+ * - it takes MINUTES (roughly two to three per 10s of video), and
820
+ * `onProgress` fires after every segment with a PLAYABLE partial
821
+ * `videoUrl` — show it rather than a spinner;
822
+ * - the result is "at least" `durationSeconds` up to the cap. Omni cannot be
823
+ * asked for a clip length, so the timeline overshoots by up to one
824
+ * segment; read `durationSeconds` off the result for the real length.
825
+ *
826
+ * A build that comes up short still RESOLVES — with a shorter, already-paid
827
+ * video and a `warning` saying why. Show the video and the warning; do not
828
+ * treat it as a failure.
829
+ *
830
+ * @returns {Promise<{videoUrl:string, thumbnailUrl?:string, durationSeconds?:number, sessionId?:string, segmentsDone?:number, warning?:string, usage:{creditsUsed:number}}>}
831
+ */
832
+ /**
833
+ * Generate a LONG video from ONE prompt and a duration.
834
+ * (see the class-level docs on {@link AIFlowClient#generateLongVideo})
835
+ */
836
+ async generateLongVideo({
837
+ prompt,
838
+ durationSeconds,
839
+ model,
840
+ aspectRatio = '16:9',
841
+ resolution,
842
+ image,
843
+ description,
844
+ onProgress,
845
+ signal,
846
+ timeout,
847
+ pollIntervalMs,
848
+ } = {}) {
849
+ if (!prompt || typeof prompt !== 'string') {
850
+ throw new AIFlowError('prompt is required');
851
+ }
852
+ if (!durationSeconds || typeof durationSeconds !== 'number') {
853
+ throw new AIFlowError(
854
+ 'durationSeconds is required — use generateVideo() for a single short clip',
855
+ );
856
+ }
857
+ const { jobId, sessionId } = await this.createVideoSession({
858
+ prompt,
859
+ model,
860
+ aspectRatio,
861
+ resolution,
862
+ image,
863
+ description,
864
+ targetDurationSeconds: durationSeconds,
865
+ signal,
866
+ });
867
+ const result = await this._pollVideoJob(jobId, {
868
+ signal,
869
+ timeout: timeout ?? longVideoTimeoutMs(durationSeconds),
870
+ // Minutes-long builds: a 5s poll on a 40-minute job is 480 pointless
871
+ // requests. Progress is published per segment, not per second.
872
+ pollIntervalMs:
873
+ pollIntervalMs ??
874
+ (durationSeconds > CONTINUOUS_MAX_SECONDS ? 15_000 : 5_000),
875
+ onProgress,
876
+ });
877
+ return { sessionId, ...result };
878
+ }
879
+
880
+ /**
881
+ * Resume a LONG-FORM build that stopped short — after a gateway restart, a
882
+ * provider hiccup, or credits that have since been topped up.
883
+ *
884
+ * Only the MISSING scenes are generated: every finished scene is already
885
+ * paid for and is never regenerated, which is what makes an hours-long build
886
+ * survivable at all. Resolves with the re-assembled video.
887
+ *
888
+ * Throws if the session is already complete, or if it is a continuous
889
+ * (chained) video — that one is lengthened with {@link extendVideo}.
890
+ *
891
+ * @returns {Promise<{videoUrl:string, durationSeconds?:number, warning?:string, usage:{creditsUsed:number}}>}
892
+ */
893
+ async resumeLongVideo(
894
+ sessionId,
895
+ { onProgress, signal, timeout, pollIntervalMs } = {},
896
+ ) {
897
+ if (!sessionId || typeof sessionId !== 'string') {
898
+ throw new AIFlowError('sessionId is required');
899
+ }
900
+ const res = await this._request(
901
+ `/video/sessions/${encodeURIComponent(sessionId)}/resume`,
902
+ {},
903
+ { signal, timeout: DEFAULT_TIMEOUT_MS },
904
+ );
905
+ const { jobId } = await res.json();
906
+ // Read the session to size the wait from what is actually left, rather
907
+ // than from the whole film that was originally asked for.
908
+ let remaining = 0;
909
+ try {
910
+ const session = await this.getVideoSession(sessionId, { signal });
911
+ remaining =
912
+ Math.max(
913
+ (session.scenesTotal || 0) - (session.scenesDone || 0),
914
+ 1,
915
+ ) * 10;
916
+ } catch {
917
+ remaining = 600;
918
+ }
919
+ return this._pollVideoJob(jobId, {
920
+ signal,
921
+ timeout: timeout ?? longVideoTimeoutMs(remaining),
922
+ pollIntervalMs: pollIntervalMs ?? 15_000,
923
+ onProgress,
924
+ });
925
+ }
926
+
927
+ /**
928
+ * Append one 3–10s continuation to a session's timeline and WAIT for it.
929
+ *
930
+ * Submits an extend turn and polls to completion, so a single `await`
931
+ * returns the finished timeline. For your own progress UI use
932
+ * {@link submitVideoExtend} + {@link getVideoJob} instead.
933
+ *
934
+ * Keep `prompt` SIMPLE — Google's guidance is that terse continuation
935
+ * prompts extend best ("the car drives out of frame"); a densely-worded
936
+ * prompt fights the continuity the model is preserving. Omit it entirely and
937
+ * the gateway uses "Continue the scene."
938
+ *
939
+ * @returns {Promise<{videoUrl:string, segmentUrl?:string, thumbnailUrl?:string, durationSeconds?:number, prompt?:string, usage:{creditsUsed:number}}>}
940
+ * `videoUrl` is the WHOLE timeline; `segmentUrl` is just the new tail.
941
+ */
942
+ async extendVideo(sessionId, opts = {}) {
943
+ const { jobId } = await this.submitVideoExtend(sessionId, opts);
944
+ return this._pollVideoJob(jobId, {
945
+ signal: opts.signal,
946
+ timeout: opts.timeout ?? 600_000,
947
+ pollIntervalMs: opts.pollIntervalMs,
948
+ });
949
+ }
950
+
951
+ /**
952
+ * Submit an extend turn without waiting. Returns immediately with a job id
953
+ * to poll via {@link getVideoJob}.
954
+ * @returns {Promise<{jobId:string, status:'queued', sessionId:string}>}
955
+ */
956
+ async submitVideoExtend(
957
+ sessionId,
958
+ { prompt, description, signal, timeout } = {},
959
+ ) {
960
+ if (!sessionId || typeof sessionId !== 'string') {
961
+ throw new AIFlowError('sessionId is required');
962
+ }
963
+ const res = await this._request(
964
+ `/video/sessions/${encodeURIComponent(sessionId)}/extend`,
965
+ { prompt, description },
966
+ { signal, timeout: timeout ?? DEFAULT_TIMEOUT_MS },
967
+ );
968
+ return await res.json();
969
+ }
970
+
971
+ /**
972
+ * Read a session's current timeline — the stitched `videoUrl`, its measured
973
+ * `durationSeconds`, every `segments[]` entry, and `canExtend` /
974
+ * `remainingSeconds` for driving the extend control.
975
+ *
976
+ * `canExtend` is the ONLY thing a UI should gate its extend button on: it is
977
+ * false both while the opening clip is still generating and once the 40s
978
+ * ceiling is reached, so a client never has to know the limit itself.
979
+ * @returns {Promise<object>}
980
+ */
981
+ async getVideoSession(sessionId, { signal, timeout } = {}) {
982
+ if (!sessionId || typeof sessionId !== 'string') {
983
+ throw new AIFlowError('sessionId is required');
984
+ }
985
+ const res = await this._get(
986
+ `/video/sessions/${encodeURIComponent(sessionId)}`,
987
+ { signal, timeout: timeout ?? DEFAULT_TIMEOUT_MS },
988
+ );
989
+ return await res.json();
990
+ }
991
+
992
+ /**
993
+ * List the caller's own video sessions, newest first — the backing call for
994
+ * a "my videos" screen. Scoped to the signed-in end user when there is one.
995
+ * @returns {Promise<{sessions:object[]}>}
996
+ */
997
+ async listVideoSessions({ limit, signal, timeout } = {}) {
998
+ const query = limit ? `?limit=${encodeURIComponent(limit)}` : '';
999
+ const res = await this._get(`/video/sessions${query}`, {
1000
+ signal,
1001
+ timeout: timeout ?? DEFAULT_TIMEOUT_MS,
1002
+ });
1003
+ return await res.json();
1004
+ }
1005
+
1006
+ /**
1007
+ * Generate music / background audio from a text prompt (Lyria 3.5),
1008
+ * optionally inspired by up to 10 reference `images` (https:// or data:
1009
+ * URLs) on the models in `config.audioImageInputModels`.
578
1010
  * @returns {Promise<{audioUrl:string, model:string, durationSeconds:number|null, prompt?:string, usage:{creditsUsed:number}}>}
579
1011
  */
580
1012
  async generateAudio({
581
1013
  prompt,
582
1014
  model,
1015
+ images,
583
1016
  negativePrompt,
584
1017
  seed,
585
1018
  signal,
@@ -588,6 +1021,9 @@ export class AIFlowClient {
588
1021
  if (!prompt || typeof prompt !== 'string') {
589
1022
  throw new AIFlowError('prompt is required');
590
1023
  }
1024
+ if (images !== undefined && !Array.isArray(images)) {
1025
+ throw new AIFlowError('images must be an array of URLs');
1026
+ }
591
1027
  const resolvedModel =
592
1028
  model || (await this._resolveDefaultModel('audio'));
593
1029
  const res = await this._request(
@@ -595,11 +1031,12 @@ export class AIFlowClient {
595
1031
  {
596
1032
  model: resolvedModel,
597
1033
  prompt,
1034
+ images: images?.length ? images : undefined,
598
1035
  negativePrompt,
599
1036
  seed,
600
1037
  },
601
- // Music generation (esp. full-song Lyria 3 Pro) runs well past the
602
- // 60s client default — allow 3 minutes before aborting.
1038
+ // Music generation (a full Lyria 3.5 song) runs well past the 60s
1039
+ // client default — allow 3 minutes before aborting.
603
1040
  { signal, timeout: timeout ?? 180_000 },
604
1041
  );
605
1042
  return await res.json();
@@ -995,6 +1432,7 @@ export class AIFlowClient {
995
1432
  systemPrompt,
996
1433
  defaults,
997
1434
  defaultModel,
1435
+ imageBackground,
998
1436
  signal,
999
1437
  } = {}) {
1000
1438
  // `defaultModel` is sugar for setting the chat default; fold it into
@@ -1007,6 +1445,9 @@ export class AIFlowClient {
1007
1445
  if (moduleId != null) body.moduleId = moduleId;
1008
1446
  if (systemPrompt !== undefined) body.systemPrompt = systemPrompt;
1009
1447
  if (resolvedDefaults !== undefined) body.defaults = resolvedDefaults;
1448
+ // A TOP-LEVEL sibling of `defaults`, never inside it: the gateway reads
1449
+ // every `defaults` key as a feature and rejects this one.
1450
+ if (imageBackground !== undefined) body.imageBackground = imageBackground;
1010
1451
  const res = await this._adminRequest('/admin/config', body, {
1011
1452
  method: 'PATCH',
1012
1453
  signal,