@devvibex/aiflow 1.8.0 → 1.13.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
@@ -136,6 +136,169 @@ existing image (image-to-image) instead of generating from text.
136
136
  Returns `{ videoUrl, usage: { creditsUsed } }`. Pass `image` for image-to-video
137
137
  or `video` for video-to-video; omit both for pure text-to-video.
138
138
 
139
+ ### `aiflow.generateLongVideo({ prompt, durationSeconds, ... })` — long video from one prompt
140
+
141
+ One prompt plus a duration, one call, one finished video. The gateway splits your
142
+ prompt into a storyboard of ~10s beats, generates the opening clip, then extends
143
+ turn after turn — concatenating as it goes — until the timeline reaches the
144
+ length you asked for.
145
+
146
+ ```js
147
+ const video = await aiflow.generateLongVideo({
148
+ prompt: 'A lighthouse keeper climbing the spiral stairs at dawn, then the lamp sweeping out over the water',
149
+ durationSeconds: 30,
150
+ aspectRatio: '16:9',
151
+ onProgress: ({ segmentsDone, segmentsPlanned, durationSeconds, videoUrl }) => {
152
+ // videoUrl is ALREADY PLAYABLE — show the partial video, not a spinner
153
+ setStatus(`${segmentsDone}/${segmentsPlanned} — ${durationSeconds ?? 0}s`);
154
+ setPreview(videoUrl);
155
+ },
156
+ });
157
+
158
+ video.videoUrl; // the finished, concatenated video
159
+ video.durationSeconds; // the REAL length — read this, not what you requested
160
+ video.usage.creditsUsed;
161
+ video.warning; // set if it finished shorter than asked (still playable)
162
+ ```
163
+
164
+ **Two shapes, chosen automatically from the duration you ask for:**
165
+
166
+ | | up to 2 min | over 2 min |
167
+ |---|---|---|
168
+ | Shape | ONE continuous shot (chained) | independent SCENES, hard cuts |
169
+ | Generated | sequentially — each clip continues the last | **in parallel** |
170
+ | 10 min of video | impossible (~2.75h, and continuity is gone after ~1 min) | ~55 min |
171
+ | Resumable | no (extend it instead) | **yes** — `resumeLongVideo` |
172
+
173
+ Because scenes run in parallel, a 2m01s video finishes FASTER than a 2m00s one
174
+ (~14 min vs ~33 min). That is not a bug: past two minutes there is no continuous
175
+ shot left to preserve, so the build stops paying for sequencing.
176
+
177
+ Long-form scenes are planned to restate the subject and style verbatim in every
178
+ scene, which is what holds the film together visually across the cuts.
179
+
180
+ ```js
181
+ // 10 minutes. ~60 scenes, ~55 min of building, ~$61 of provider cost.
182
+ const film = await aiflow.generateLongVideo({ prompt, durationSeconds: 600, onProgress });
183
+
184
+ // If it stopped short (gateway restart, provider hiccup, credits ran out):
185
+ if (film.warning) {
186
+ const finished = await aiflow.resumeLongVideo(film.sessionId, { onProgress });
187
+ }
188
+ ```
189
+
190
+ `resumeLongVideo` regenerates **only the missing scenes** — every finished scene
191
+ is already paid for and is never regenerated. That is what makes an hours-long
192
+ build survivable, so treat `warning` as "call resume", not as a failure.
193
+
194
+ Design the UI around three facts:
195
+
196
+ - **It takes a long time** — roughly 2.5–3 minutes per 10 seconds for a
197
+ continuous video (~8 min for 30s, ~33 min for 2 min), and roughly that divided
198
+ by the gateway's scene concurrency for long-form (~55 min for 10 min of video).
199
+ `onProgress` fires after each clip, so show progress — and for continuous
200
+ builds the partial video, which is already playable.
201
+ - **The result is "at least" the requested length.** Omni cannot be asked for a
202
+ clip length, so the timeline overshoots by up to one segment.
203
+ - **A short build still resolves.** If a turn fails or credits run out mid-way,
204
+ you get the shorter video plus `warning` explaining why — show both; it is not
205
+ an error.
206
+
207
+ Cost scales with the finished length (Omni bills per delivered second), so show a
208
+ credit estimate before calling. The platform caps what can be requested
209
+ (`AIFLOW_VIDEO_MAX_TARGET_SECONDS`, default 120s); a larger request is clamped,
210
+ not refused.
211
+
212
+ Under the hood this is a video session (below) that the gateway drives for you —
213
+ `sessionId` comes back on the result, so you can keep extending it manually
214
+ afterwards.
215
+
216
+ ### `aiflow.mergeVideos({ videos })` — join clips you already have
217
+
218
+ Pure assembly: no model runs, nothing is generated, **no AI credits are charged**,
219
+ and the clips need not have come from AIFlow.
220
+
221
+ ```js
222
+ const joined = await aiflow.mergeVideos({
223
+ videos: [clipA.videoUrl, clipB.videoUrl, uploadedDataUrl],
224
+ });
225
+ joined.videoUrl; // one joined video
226
+ joined.durationSeconds; // its measured length
227
+ ```
228
+
229
+ Clips are joined **in the order given**. The first one sets the output format —
230
+ every other clip is scaled and letterboxed (never cropped) to its frame size and
231
+ frame rate, so a mixed-resolution set produces one consistent video instead of
232
+ one that changes size halfway through. Silent clips get a silent audio track so
233
+ the join does not drop sound. Limits: 2–20 clips, 600s of output.
234
+
235
+ **Which long-video call do I want?**
236
+
237
+ | | `mergeVideos` | `generateLongVideo` |
238
+ | --- | --- | --- |
239
+ | What it joins | clips you already have | clips it generates for you |
240
+ | Between clips | a hard cut | one continuous shot |
241
+ | Speed | seconds | minutes (~2–3 per 10s) |
242
+ | AI cost | none | per generated second |
243
+ | Good for | montages, compilations, ads, joining user uploads | one flowing scene from one prompt |
244
+
245
+ They compose: generate several clips with `generateVideo` (fast, in parallel),
246
+ then `mergeVideos` them into a montage. Use `generateLongVideo` only when the
247
+ camera and subject must carry across the joins.
248
+
249
+ ### Stateful video sessions — extend and concatenate (Gemini Omni)
250
+
251
+ Gemini Omni has no "generate 40 seconds" mode and no concatenation endpoint. A
252
+ longer clip is built **turn by turn**: each turn appends 3–10s while the model
253
+ keeps the characters, motion and audio bed continuous, chaining on the previous
254
+ interaction it still holds server-side. The gateway concatenates the segments
255
+ and always hands back the whole timeline, so your app plays **one url** and
256
+ never stitches anything itself.
257
+
258
+ Requires a Gemini Omni model — Veo and Seedance hold no context between calls,
259
+ so the gateway refuses to open a session on them rather than accept one clip and
260
+ then fail every extend. Total length is capped at **40 seconds**.
261
+
262
+ ```js
263
+ // 1. Open a session — generate the opening clip…
264
+ const { sessionId, jobId } = await aiflow.createVideoSession({
265
+ prompt: 'A lighthouse keeper climbing the spiral stairs at dawn',
266
+ aspectRatio: '16:9', // fixed for the whole session
267
+ });
268
+ const opening = await aiflow.getVideoJob(jobId); // poll until 'succeeded'
269
+
270
+ // …or seed it from the user's own clip instead (no jobId — ready on return;
271
+ // a clip longer than 10s is trimmed to its last 10s, Omni's input limit)
272
+ const { sessionId: seeded } = await aiflow.createVideoSession({
273
+ video: uploadedVideoUrlOrDataUrl,
274
+ });
275
+
276
+ // 2. Extend. Keep the prompt SIMPLE — terse continuation prompts extend best.
277
+ const turn = await aiflow.extendVideo(sessionId, {
278
+ prompt: 'he reaches the top and the lamp sweeps out over the water',
279
+ });
280
+ turn.videoUrl; // the WHOLE timeline, re-stitched
281
+ turn.segmentUrl; // just the new tail
282
+
283
+ // 3. Read the timeline at any time
284
+ const session = await aiflow.getVideoSession(sessionId);
285
+ session.videoUrl; // play this
286
+ session.durationSeconds; // measured length so far
287
+ session.remainingSeconds; // left before the 40s ceiling
288
+ session.canExtend; // gate your "Extend" button on THIS, nothing else
289
+ session.segments; // [{ url, durationSeconds, prompt, kind }, ...]
290
+
291
+ // 4. "My videos"
292
+ const { sessions } = await aiflow.listVideoSessions({ limit: 20 });
293
+ ```
294
+
295
+ `extendVideo` submits and polls to completion. For your own progress UI use
296
+ `submitVideoExtend(sessionId, { prompt })` → `getVideoJob(jobId)` instead; the
297
+ job's `videoUrl` is the timeline and `segmentUrl` the new tail.
298
+
299
+ Every turn is billed separately (Omni prices by output token), and
300
+ `session.usage.creditsUsed` is the running total for the whole session.
301
+
139
302
  ### `aiflow.generateAudio({ prompt, model?, negativePrompt?, seed?, signal?, timeout? })`
140
303
 
141
304
  Generate music / background audio from a text prompt (Google Vertex AI **Lyria**).
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@devvibex/aiflow",
3
- "version": "1.8.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.13.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
@@ -239,6 +239,229 @@ export interface VideoJobStatusResponse {
239
239
  usage?: { creditsUsed: number };
240
240
  /** Present once status === 'failed'. */
241
241
  error?: string;
242
+ /**
243
+ * Session turns only (see {@link AIFlowClient.createVideoSession}). On
244
+ * success `videoUrl` is the WHOLE stitched timeline and `segmentUrl` the
245
+ * newly generated tail alone.
246
+ */
247
+ sessionId?: string;
248
+ segmentUrl?: string;
249
+ /** Measured length of the stitched `videoUrl` after this turn. */
250
+ durationSeconds?: number;
251
+ /** Auto-build progress; present while a build runs and once it finishes. */
252
+ segmentsDone?: number;
253
+ segmentsPlanned?: number;
254
+ /**
255
+ * A build SUCCEEDED but came up short of the requested length. There is a
256
+ * real playable video; this says why it is shorter. Distinct from `error`.
257
+ */
258
+ warning?: string;
259
+ }
260
+
261
+ // ─── Stateful video sessions (Gemini Omni `extend`) ─────────────────────────
262
+
263
+ /** One clip on a session's timeline, in play order. */
264
+ export interface VideoSegment {
265
+ /** CDN URL of THIS clip alone — not the stitched timeline. */
266
+ url: string;
267
+ thumbnailUrl?: string;
268
+ durationSeconds: number;
269
+ prompt?: string;
270
+ /**
271
+ * 'base' = generated opener, 'upload' = your seed clip, 'extension' = a
272
+ * chained turn, 'scene' = one clip of a LONG-FORM video (hard cut either
273
+ * side).
274
+ */
275
+ kind: 'base' | 'upload' | 'extension' | 'scene';
276
+ createdAt?: string;
277
+ }
278
+
279
+ /**
280
+ * A stateful video session: one growing timeline. Returned by session create,
281
+ * extend and read, so a client only ever renders one shape.
282
+ */
283
+ export interface VideoSession {
284
+ sessionId: string;
285
+ /** 'exhausted' once the 40s ceiling is reached — a state, not an error. */
286
+ status: 'active' | 'exhausted';
287
+ model: string;
288
+ aspectRatio?: string;
289
+ resolution?: string;
290
+ /**
291
+ * THE CONCATENATION — every segment stitched in play order. Play this.
292
+ * Empty while a session's opening clip is still generating, and a NEW url
293
+ * after every extend.
294
+ */
295
+ videoUrl: string;
296
+ thumbnailUrl?: string;
297
+ /** Measured length of `videoUrl`. */
298
+ durationSeconds: number;
299
+ /** Seconds left before Omni's 40s ceiling. */
300
+ remainingSeconds: number;
301
+ /**
302
+ * Whether another extend turn is possible. The ONLY flag a UI should gate
303
+ * its extend control on: false both while the opening clip is generating and
304
+ * once the ceiling is reached.
305
+ */
306
+ canExtend: boolean;
307
+ segments: VideoSegment[];
308
+ extendCount: number;
309
+ /** Credits charged across EVERY turn of this session so far. */
310
+ usage: { creditsUsed: number };
311
+ /** Length this session was auto-built to, when opened with a target. */
312
+ targetDurationSeconds?: number;
313
+ /** Ceiling `remainingSeconds` is measured against. */
314
+ maxDurationSeconds: number;
315
+ /** The per-segment beats an auto-build planned from the single prompt. */
316
+ storyboard?: string[];
317
+ /**
318
+ * `continuous` = one flowing shot built by chaining (up to ~2 min).
319
+ * `scenes` = LONG-FORM: independent scenes generated in parallel and merged
320
+ * with hard cuts — the only shape that reaches many minutes.
321
+ */
322
+ mode: 'continuous' | 'scenes';
323
+ /** Long-form progress. Absent for a continuous session. */
324
+ scenesTotal?: number;
325
+ scenesDone?: number;
326
+ /** A long-form build with scenes still missing can be resumed. */
327
+ canResume?: boolean;
328
+ }
329
+
330
+ export interface VideoSessionRequest {
331
+ /**
332
+ * What the opening clip shows. Required unless `video` seeds the session.
333
+ */
334
+ prompt?: string;
335
+ /**
336
+ * Must be a Gemini Omni model — it is the only one with a stateful extend
337
+ * protocol. Defaults to the module's configured video model, which the
338
+ * gateway rejects if it is not Omni.
339
+ */
340
+ model?: string;
341
+ /** Omni supports 16:9 and 9:16 only. Fixed for the whole session. */
342
+ aspectRatio?: '16:9' | '9:16';
343
+ /** Fixed for the whole session. Defaults to 720p. */
344
+ resolution?: '360p' | '720p' | '1080p' | '4k';
345
+ /** Still image to animate into the opening clip (image-to-video). */
346
+ image?: string;
347
+ /**
348
+ * Your OWN clip to seed the timeline with instead of generating an opener.
349
+ * An `https://` or `data:` URL. Longer than 10s is trimmed to its last 10s
350
+ * (Omni's input limit).
351
+ */
352
+ video?: string;
353
+ description?: string;
354
+ /**
355
+ * AUTO-BUILD: how long the finished video should be. With this set the
356
+ * gateway storyboards the prompt and takes every turn itself until the
357
+ * timeline is this long — see {@link AIFlowClient.generateLongVideo}, which
358
+ * wraps create + poll into one call.
359
+ */
360
+ targetDurationSeconds?: number;
361
+ signal?: AbortSignal;
362
+ timeout?: number;
363
+ }
364
+
365
+ /** Progress of an auto-build, reported after each completed segment. */
366
+ export interface VideoBuildProgress {
367
+ segmentsDone: number;
368
+ segmentsPlanned?: number;
369
+ /** Length of the timeline so far. */
370
+ durationSeconds?: number;
371
+ /** ALREADY PLAYABLE — show it instead of a spinner. */
372
+ videoUrl?: string;
373
+ thumbnailUrl?: string;
374
+ }
375
+
376
+ export interface LongVideoRequest {
377
+ /** What the whole video shows. The gateway splits it into per-segment beats. */
378
+ prompt: string;
379
+ /**
380
+ * How long the finished video should be, in seconds. The result is "at
381
+ * least" this: Omni cannot be asked for a clip length, so the timeline
382
+ * overshoots by up to one ~10s segment.
383
+ */
384
+ durationSeconds: number;
385
+ /** Must be a Gemini Omni model; defaults to the module's video model. */
386
+ model?: string;
387
+ aspectRatio?: '16:9' | '9:16';
388
+ resolution?: '360p' | '720p' | '1080p' | '4k';
389
+ /** Still image to animate into the OPENING segment. */
390
+ image?: string;
391
+ description?: string;
392
+ /** Fires after each completed segment, with a playable partial video. */
393
+ onProgress?: (progress: VideoBuildProgress) => void;
394
+ signal?: AbortSignal;
395
+ /** Overall wait budget. Defaults to ~7 minutes per 10s requested. */
396
+ timeout?: number;
397
+ pollIntervalMs?: number;
398
+ }
399
+
400
+ export interface LongVideoResponse extends VideoResponse {
401
+ sessionId?: string;
402
+ /** Real measured length — read this, not what you requested. */
403
+ durationSeconds?: number;
404
+ segmentsDone?: number;
405
+ /**
406
+ * Set when the build came up short of `durationSeconds`. The video is real
407
+ * and already paid for — show it, and the reason; do not treat it as an
408
+ * error.
409
+ */
410
+ warning?: string;
411
+ }
412
+
413
+ export interface VideoMergeRequest {
414
+ /**
415
+ * The clips to join, IN PLAY ORDER — `https://` URLs or `data:` URLs.
416
+ * The FIRST one sets the output frame size and frame rate; the rest are
417
+ * scaled and letterboxed to match. At least 2, at most 20.
418
+ */
419
+ videos: string[];
420
+ /** Fires as clips are fetched and prepared. */
421
+ onProgress?: (progress: VideoBuildProgress) => void;
422
+ signal?: AbortSignal;
423
+ /** Defaults to 2 minutes per clip (minimum 10 minutes). */
424
+ timeout?: number;
425
+ pollIntervalMs?: number;
426
+ }
427
+
428
+ export interface VideoMergeResponse extends VideoResponse {
429
+ /** Measured length of the joined video. */
430
+ durationSeconds?: number;
431
+ }
432
+
433
+ /** Returned by {@link AIFlowClient.createVideoSession}. */
434
+ export interface VideoSessionCreateResponse {
435
+ sessionId: string;
436
+ /** Present only when an opening clip is generating — poll it. */
437
+ jobId?: string;
438
+ /** Always present, so a client renders one shape either way. */
439
+ session: VideoSession;
440
+ }
441
+
442
+ export interface VideoExtendRequest {
443
+ /**
444
+ * What happens next. Keep it SIMPLE — terse continuation prompts extend
445
+ * best. Omitted, the gateway uses "Continue the scene."
446
+ */
447
+ prompt?: string;
448
+ description?: string;
449
+ signal?: AbortSignal;
450
+ timeout?: number;
451
+ pollIntervalMs?: number;
452
+ }
453
+
454
+ /** Result of one completed extend turn. */
455
+ export interface VideoExtendResponse extends VideoResponse {
456
+ /** The whole timeline is in `videoUrl`; this is the new tail alone. */
457
+ segmentUrl?: string;
458
+ durationSeconds?: number;
459
+ sessionId?: string;
460
+ }
461
+
462
+ /** Acknowledgement returned by {@link AIFlowClient.submitVideoExtend}. */
463
+ export interface VideoExtendSubmitResponse extends VideoJobSubmitResponse {
464
+ sessionId: string;
242
465
  }
243
466
 
244
467
  // ─── Audio (music — Lyria) ──────────────────────────────────────────────────
@@ -543,6 +766,12 @@ export interface AiflowConfig {
543
766
  /** Real-time translate models, when configured. */
544
767
  translate?: string[];
545
768
  };
769
+ /**
770
+ * The STORED default per feature, verbatim. On a module whose owner chose
771
+ * "User Selection" this is the `__user_selection__` sentinel, NOT a model
772
+ * id — never send it as a request `model` and never preselect it in a
773
+ * dropdown. Use `resolvedDefaults` for that.
774
+ */
546
775
  defaults: {
547
776
  chat: string;
548
777
  image: string;
@@ -553,6 +782,34 @@ export interface AiflowConfig {
553
782
  /** Default real-time translate model, when configured. */
554
783
  translate?: string;
555
784
  };
785
+ /**
786
+ * The EFFECTIVE model per feature — always a real, callable id, with the
787
+ * "User Selection" sentinel already resolved. This is what runs when a
788
+ * request omits `model`, and what an end-user model picker should
789
+ * preselect. Absent on gateways older than the field.
790
+ */
791
+ resolvedDefaults?: {
792
+ chat: string;
793
+ image: string;
794
+ embed: string;
795
+ video: string;
796
+ audio: string;
797
+ sfx: string;
798
+ translate: string;
799
+ };
800
+ /**
801
+ * This module's own feature — use it to index `models`, `defaults`,
802
+ * `resolvedDefaults` and `userSelectable` without hardcoding a key.
803
+ */
804
+ feature?: string | null;
805
+ /**
806
+ * True when this module's default model is "User Selection": nothing is
807
+ * pinned and the app should render a model picker sourced from
808
+ * `models[feature]`, seeded from `resolvedDefaults[feature]`.
809
+ */
810
+ modelUserSelectable?: boolean;
811
+ /** Per-feature form of `modelUserSelectable`. */
812
+ userSelectable?: Record<string, boolean>;
556
813
  limits: {
557
814
  maxTokens: number;
558
815
  maxImageN: number;
@@ -693,6 +950,82 @@ export class AIFlowClient {
693
950
  jobId: string,
694
951
  options?: { signal?: AbortSignal; timeout?: number },
695
952
  ): Promise<VideoJobStatusResponse>;
953
+ /**
954
+ * Open a stateful video session — one growing timeline built turn by turn
955
+ * with Gemini Omni's `extend`.
956
+ *
957
+ * With `prompt`, the opening clip is generated and `jobId` is returned to
958
+ * poll. With `video`, the timeline is seeded from your own clip and is ready
959
+ * on return. The gateway keeps the concatenation, so the app always plays
960
+ * `session.videoUrl` and never stitches anything itself.
961
+ */
962
+ createVideoSession(
963
+ request: VideoSessionRequest,
964
+ ): Promise<VideoSessionCreateResponse>;
965
+ /**
966
+ * Generate a LONG video from one prompt and a duration, in a single call:
967
+ * the gateway storyboards the prompt into ~10s beats, generates them turn by
968
+ * turn and concatenates them into one finished clip.
969
+ *
970
+ * Takes MINUTES (roughly two to three per 10s). `onProgress` fires after
971
+ * every segment with a playable partial `videoUrl` — build the UI around
972
+ * that, not a spinner.
973
+ */
974
+ generateLongVideo(request: LongVideoRequest): Promise<LongVideoResponse>;
975
+ /**
976
+ * Join clips you already have into one longer video — no model call, no AI
977
+ * credits. Clips are joined in the order given, normalised to the first
978
+ * one's format.
979
+ *
980
+ * Each join is a HARD CUT: right for a montage, wrong for one continuous
981
+ * scene. Use {@link generateLongVideo} when the shot must flow.
982
+ */
983
+ mergeVideos(request: VideoMergeRequest): Promise<VideoMergeResponse>;
984
+ /**
985
+ * Resume a LONG-FORM build that stopped short — after a gateway restart, a
986
+ * provider hiccup, or credits that have since been topped up. Only missing
987
+ * scenes are generated; finished ones are already paid for and are never
988
+ * regenerated. Resolves with the re-assembled video.
989
+ */
990
+ resumeLongVideo(
991
+ sessionId: string,
992
+ request?: {
993
+ onProgress?: (progress: VideoBuildProgress) => void;
994
+ signal?: AbortSignal;
995
+ timeout?: number;
996
+ pollIntervalMs?: number;
997
+ },
998
+ ): Promise<LongVideoResponse>;
999
+ /** Submit a merge without waiting; poll it with {@link getVideoJob}. */
1000
+ submitVideoMerge(request: {
1001
+ videos: string[];
1002
+ signal?: AbortSignal;
1003
+ timeout?: number;
1004
+ }): Promise<VideoJobSubmitResponse>;
1005
+ /**
1006
+ * Append one 3–10s continuation to a session's timeline and wait for it.
1007
+ * Returns the re-stitched timeline in `videoUrl`.
1008
+ */
1009
+ extendVideo(
1010
+ sessionId: string,
1011
+ request?: VideoExtendRequest,
1012
+ ): Promise<VideoExtendResponse>;
1013
+ /** Submit an extend turn without waiting; poll it with {@link getVideoJob}. */
1014
+ submitVideoExtend(
1015
+ sessionId: string,
1016
+ request?: VideoExtendRequest,
1017
+ ): Promise<VideoExtendSubmitResponse>;
1018
+ /** Read a session's current timeline, segments and `canExtend` flag. */
1019
+ getVideoSession(
1020
+ sessionId: string,
1021
+ options?: { signal?: AbortSignal; timeout?: number },
1022
+ ): Promise<VideoSession>;
1023
+ /** The caller's own sessions, newest first — backs a "my videos" screen. */
1024
+ listVideoSessions(options?: {
1025
+ limit?: number;
1026
+ signal?: AbortSignal;
1027
+ timeout?: number;
1028
+ }): Promise<{ sessions: VideoSession[] }>;
696
1029
  generateAudio(request: AudioRequest): Promise<AudioResponse>;
697
1030
  generateSfx(request: SfxRequest): Promise<SfxResponse>;
698
1031
  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);
@@ -236,7 +269,14 @@ export class AIFlowClient {
236
269
  const userOverride = this._userDefaults[kind];
237
270
  if (userOverride) return userOverride;
238
271
  const cfg = await this.getConfig();
239
- return cfg.defaults[kind];
272
+ // `resolvedDefaults` is the EFFECTIVE model: `defaults` reports the
273
+ // stored value verbatim, so on a module whose owner chose "User
274
+ // Selection" it is the `__user_selection__` sentinel — not a model.
275
+ // Sending that does not fail loudly; the gateway reads it as "no model
276
+ // specified" and substitutes its own default, so the request silently
277
+ // runs on something the caller never saw. Fall back to `defaults` only
278
+ // for a gateway too old to send the resolved map.
279
+ return cfg.resolvedDefaults?.[kind] ?? cfg.defaults[kind];
240
280
  }
241
281
 
242
282
  /**
@@ -529,9 +569,15 @@ export class AIFlowClient {
529
569
  /** Poll a video job to completion and normalise the success payload. */
530
570
  async _pollVideoJob(
531
571
  jobId,
532
- { signal, timeout = 600_000, pollIntervalMs = 3_000 } = {},
572
+ {
573
+ signal,
574
+ timeout = 600_000,
575
+ pollIntervalMs = 3_000,
576
+ onProgress,
577
+ } = {},
533
578
  ) {
534
579
  const deadline = Date.now() + timeout;
580
+ let lastProgress = -1;
535
581
  // eslint-disable-next-line no-constant-condition
536
582
  while (true) {
537
583
  if (signal?.aborted) {
@@ -540,12 +586,49 @@ export class AIFlowClient {
540
586
  });
541
587
  }
542
588
  const job = await this.getVideoJob(jobId, { signal });
589
+ // Fired only when a SEGMENT actually landed, not on every poll — a
590
+ // progress callback that runs every 5s with identical numbers just
591
+ // re-renders the UI for nothing.
592
+ if (
593
+ onProgress &&
594
+ job.status !== 'succeeded' &&
595
+ typeof job.segmentsDone === 'number' &&
596
+ job.segmentsDone !== lastProgress
597
+ ) {
598
+ lastProgress = job.segmentsDone;
599
+ try {
600
+ onProgress({
601
+ segmentsDone: job.segmentsDone,
602
+ segmentsPlanned: job.segmentsPlanned,
603
+ durationSeconds: job.durationSeconds,
604
+ // Playable already — show it instead of a spinner.
605
+ videoUrl: job.videoUrl,
606
+ thumbnailUrl: job.thumbnailUrl,
607
+ });
608
+ } catch {
609
+ // A throwing progress handler is the caller's bug, not a
610
+ // reason to abandon a video they are paying for.
611
+ }
612
+ }
543
613
  if (job.status === 'succeeded') {
544
614
  return {
545
615
  videoUrl: job.videoUrl,
546
616
  thumbnailUrl: job.thumbnailUrl,
547
617
  prompt: job.prompt,
548
618
  usage: job.usage || { creditsUsed: 0 },
619
+ // Session turns only. Spread conditionally so a plain
620
+ // generation's result keeps exactly the shape earlier SDK
621
+ // versions returned — no undefined keys appearing in it.
622
+ ...(job.sessionId ? { sessionId: job.sessionId } : {}),
623
+ ...(job.segmentUrl ? { segmentUrl: job.segmentUrl } : {}),
624
+ ...(job.durationSeconds != null
625
+ ? { durationSeconds: job.durationSeconds }
626
+ : {}),
627
+ ...(job.segmentsDone != null
628
+ ? { segmentsDone: job.segmentsDone }
629
+ : {}),
630
+ // Short of the requested length, but real and paid for.
631
+ ...(job.warning ? { warning: job.warning } : {}),
549
632
  };
550
633
  }
551
634
  if (job.status === 'failed') {
@@ -566,6 +649,343 @@ export class AIFlowClient {
566
649
  }
567
650
  }
568
651
 
652
+ /**
653
+ * Join clips you ALREADY HAVE into one longer video.
654
+ *
655
+ * Pure assembly — no model runs, nothing is generated, no AI credits are
656
+ * charged, and the clips need not have come from AIFlow. Use it to stitch
657
+ * separately generated clips, or the user's own uploads, into one file.
658
+ *
659
+ * ```js
660
+ * const joined = await aiflow.mergeVideos({
661
+ * videos: [clipA.videoUrl, clipB.videoUrl, uploadedDataUrl],
662
+ * });
663
+ * joined.videoUrl; // the single joined video
664
+ * joined.durationSeconds; // its measured length
665
+ * ```
666
+ *
667
+ * Clips are joined IN THE ORDER GIVEN. The FIRST one sets the output format:
668
+ * every other clip is scaled and letterboxed (never cropped) to its frame
669
+ * size and frame rate, so a mixed set produces one consistent video rather
670
+ * than one that changes size halfway through. Silent clips get a silent
671
+ * audio track so the join does not drop sound.
672
+ *
673
+ * ⚠️ Merged clips do NOT continue each other — each cut is a hard cut, which
674
+ * is right for a montage and wrong for one continuous scene. For a single
675
+ * flowing shot use {@link generateLongVideo} instead, which generates each
676
+ * segment FROM the previous one.
677
+ *
678
+ * @returns {Promise<{videoUrl:string, thumbnailUrl?:string, durationSeconds?:number, usage:{creditsUsed:number}}>}
679
+ */
680
+ async mergeVideos({
681
+ videos,
682
+ onProgress,
683
+ signal,
684
+ timeout,
685
+ pollIntervalMs,
686
+ } = {}) {
687
+ if (!Array.isArray(videos) || videos.length < 2) {
688
+ throw new AIFlowError('mergeVideos needs at least two videos');
689
+ }
690
+ const { jobId } = await this.submitVideoMerge({ videos, signal });
691
+ return this._pollVideoJob(jobId, {
692
+ signal,
693
+ // Every clip is fetched and usually re-encoded on the gateway, so the
694
+ // budget scales with how many were handed over.
695
+ timeout: timeout ?? Math.max(600_000, videos.length * 120_000),
696
+ pollIntervalMs: pollIntervalMs ?? 3_000,
697
+ onProgress,
698
+ });
699
+ }
700
+
701
+ /**
702
+ * Submit a merge without waiting. Returns a job id to poll with
703
+ * {@link getVideoJob}.
704
+ * @returns {Promise<{jobId:string, status:'queued'}>}
705
+ */
706
+ async submitVideoMerge({ videos, signal, timeout } = {}) {
707
+ if (!Array.isArray(videos) || videos.length < 2) {
708
+ throw new AIFlowError('mergeVideos needs at least two videos');
709
+ }
710
+ const res = await this._request(
711
+ '/video/merge',
712
+ { videos },
713
+ // Data-URL clips ride in the body, so allow more than the default.
714
+ { signal, timeout: timeout ?? 300_000 },
715
+ );
716
+ return await res.json();
717
+ }
718
+
719
+ // ── Stateful video sessions (Gemini Omni `extend`) ──────────────────────
720
+ // A session is ONE GROWING TIMELINE. Omni has no "generate 40 seconds" mode
721
+ // and no concatenation endpoint: a long clip is built turn by turn, each turn
722
+ // appending 3–10s while the model keeps the characters, motion and audio bed
723
+ // continuous. The gateway concatenates the segments and always hands back the
724
+ // whole timeline, so an app plays ONE url and never stitches anything itself.
725
+ //
726
+ // Requires a Gemini Omni model — Veo and Seedance hold no context between
727
+ // calls, and the gateway refuses to open a session on them rather than accept
728
+ // one clip and then fail every extend.
729
+
730
+ /**
731
+ * Open a stateful video session.
732
+ *
733
+ * Two ways to start:
734
+ * - `prompt` (± `image`): the opening clip is GENERATED. The returned
735
+ * `jobId` is polled like any video job; `session.videoUrl` is empty until
736
+ * it lands.
737
+ * - `video`: the timeline is SEEDED from your own clip — ready on return,
738
+ * no `jobId`. A clip longer than Omni's 10s input limit is trimmed to its
739
+ * last 10 seconds.
740
+ *
741
+ * `aspectRatio` / `resolution` are fixed for the WHOLE session here: Omni
742
+ * inherits them across the chain, and segments of differing geometry could
743
+ * not be concatenated without re-encoding the timeline.
744
+ *
745
+ * @returns {Promise<{sessionId:string, jobId?:string, session:object}>}
746
+ */
747
+ async createVideoSession({
748
+ prompt,
749
+ model,
750
+ aspectRatio = '16:9',
751
+ resolution,
752
+ image,
753
+ video,
754
+ description,
755
+ targetDurationSeconds,
756
+ signal,
757
+ timeout,
758
+ } = {}) {
759
+ if (!prompt && !video) {
760
+ throw new AIFlowError(
761
+ 'createVideoSession needs either a prompt (to generate the opening clip) or a video (to seed the timeline)',
762
+ );
763
+ }
764
+ const resolvedModel =
765
+ model || (await this._resolveDefaultModel('video'));
766
+ const res = await this._request(
767
+ '/video/sessions',
768
+ {
769
+ model: resolvedModel,
770
+ prompt,
771
+ aspectRatio,
772
+ resolution,
773
+ image,
774
+ video,
775
+ description,
776
+ targetDurationSeconds,
777
+ },
778
+ // Seeding from an upload transcodes inline on the gateway, so this
779
+ // call can run longer than a plain submit — but never for minutes.
780
+ { signal, timeout: timeout ?? 300_000 },
781
+ );
782
+ return await res.json();
783
+ }
784
+
785
+ /**
786
+ * Generate a LONG video from ONE prompt and a duration — the whole thing in
787
+ * a single call.
788
+ *
789
+ * The gateway splits your prompt into a storyboard of ~10s beats, generates
790
+ * the opening clip, then extends turn after turn, concatenating until the
791
+ * timeline reaches `durationSeconds`. You get back one finished video url.
792
+ *
793
+ * ```js
794
+ * const video = await aiflow.generateLongVideo({
795
+ * prompt: 'A lighthouse keeper climbing the spiral stairs at dawn',
796
+ * durationSeconds: 30,
797
+ * onProgress: (p) => setStatus(`${p.segmentsDone}/${p.segmentsPlanned} — ${p.durationSeconds ?? 0}s`),
798
+ * });
799
+ * ```
800
+ *
801
+ * Two things to design the UI around:
802
+ * - it takes MINUTES (roughly two to three per 10s of video), and
803
+ * `onProgress` fires after every segment with a PLAYABLE partial
804
+ * `videoUrl` — show it rather than a spinner;
805
+ * - the result is "at least" `durationSeconds`. Omni cannot be asked for a
806
+ * clip length, so the timeline overshoots by up to one segment; read
807
+ * `durationSeconds` off the result for the real length.
808
+ *
809
+ * A build that comes up short still RESOLVES — with a shorter, already-paid
810
+ * video and a `warning` saying why. Show the video and the warning; do not
811
+ * treat it as a failure.
812
+ *
813
+ * @returns {Promise<{videoUrl:string, thumbnailUrl?:string, durationSeconds?:number, sessionId?:string, segmentsDone?:number, warning?:string, usage:{creditsUsed:number}}>}
814
+ */
815
+ /**
816
+ * Generate a LONG video from ONE prompt and a duration.
817
+ * (see the class-level docs on {@link AIFlowClient#generateLongVideo})
818
+ */
819
+ async generateLongVideo({
820
+ prompt,
821
+ durationSeconds,
822
+ model,
823
+ aspectRatio = '16:9',
824
+ resolution,
825
+ image,
826
+ description,
827
+ onProgress,
828
+ signal,
829
+ timeout,
830
+ pollIntervalMs,
831
+ } = {}) {
832
+ if (!prompt || typeof prompt !== 'string') {
833
+ throw new AIFlowError('prompt is required');
834
+ }
835
+ if (!durationSeconds || typeof durationSeconds !== 'number') {
836
+ throw new AIFlowError(
837
+ 'durationSeconds is required — use generateVideo() for a single short clip',
838
+ );
839
+ }
840
+ const { jobId, sessionId } = await this.createVideoSession({
841
+ prompt,
842
+ model,
843
+ aspectRatio,
844
+ resolution,
845
+ image,
846
+ description,
847
+ targetDurationSeconds: durationSeconds,
848
+ signal,
849
+ });
850
+ const result = await this._pollVideoJob(jobId, {
851
+ signal,
852
+ timeout: timeout ?? longVideoTimeoutMs(durationSeconds),
853
+ // Minutes-long builds: a 5s poll on a 40-minute job is 480 pointless
854
+ // requests. Progress is published per segment, not per second.
855
+ pollIntervalMs:
856
+ pollIntervalMs ??
857
+ (durationSeconds > CONTINUOUS_MAX_SECONDS ? 15_000 : 5_000),
858
+ onProgress,
859
+ });
860
+ return { sessionId, ...result };
861
+ }
862
+
863
+ /**
864
+ * Resume a LONG-FORM build that stopped short — after a gateway restart, a
865
+ * provider hiccup, or credits that have since been topped up.
866
+ *
867
+ * Only the MISSING scenes are generated: every finished scene is already
868
+ * paid for and is never regenerated, which is what makes an hours-long build
869
+ * survivable at all. Resolves with the re-assembled video.
870
+ *
871
+ * Throws if the session is already complete, or if it is a continuous
872
+ * (chained) video — that one is lengthened with {@link extendVideo}.
873
+ *
874
+ * @returns {Promise<{videoUrl:string, durationSeconds?:number, warning?:string, usage:{creditsUsed:number}}>}
875
+ */
876
+ async resumeLongVideo(
877
+ sessionId,
878
+ { onProgress, signal, timeout, pollIntervalMs } = {},
879
+ ) {
880
+ if (!sessionId || typeof sessionId !== 'string') {
881
+ throw new AIFlowError('sessionId is required');
882
+ }
883
+ const res = await this._request(
884
+ `/video/sessions/${encodeURIComponent(sessionId)}/resume`,
885
+ {},
886
+ { signal, timeout: DEFAULT_TIMEOUT_MS },
887
+ );
888
+ const { jobId } = await res.json();
889
+ // Read the session to size the wait from what is actually left, rather
890
+ // than from the whole film that was originally asked for.
891
+ let remaining = 0;
892
+ try {
893
+ const session = await this.getVideoSession(sessionId, { signal });
894
+ remaining =
895
+ Math.max(
896
+ (session.scenesTotal || 0) - (session.scenesDone || 0),
897
+ 1,
898
+ ) * 10;
899
+ } catch {
900
+ remaining = 600;
901
+ }
902
+ return this._pollVideoJob(jobId, {
903
+ signal,
904
+ timeout: timeout ?? longVideoTimeoutMs(remaining),
905
+ pollIntervalMs: pollIntervalMs ?? 15_000,
906
+ onProgress,
907
+ });
908
+ }
909
+
910
+ /**
911
+ * Append one 3–10s continuation to a session's timeline and WAIT for it.
912
+ *
913
+ * Submits an extend turn and polls to completion, so a single `await`
914
+ * returns the finished timeline. For your own progress UI use
915
+ * {@link submitVideoExtend} + {@link getVideoJob} instead.
916
+ *
917
+ * Keep `prompt` SIMPLE — Google's guidance is that terse continuation
918
+ * prompts extend best ("the car drives out of frame"); a densely-worded
919
+ * prompt fights the continuity the model is preserving. Omit it entirely and
920
+ * the gateway uses "Continue the scene."
921
+ *
922
+ * @returns {Promise<{videoUrl:string, segmentUrl?:string, thumbnailUrl?:string, durationSeconds?:number, prompt?:string, usage:{creditsUsed:number}}>}
923
+ * `videoUrl` is the WHOLE timeline; `segmentUrl` is just the new tail.
924
+ */
925
+ async extendVideo(sessionId, opts = {}) {
926
+ const { jobId } = await this.submitVideoExtend(sessionId, opts);
927
+ return this._pollVideoJob(jobId, {
928
+ signal: opts.signal,
929
+ timeout: opts.timeout ?? 600_000,
930
+ pollIntervalMs: opts.pollIntervalMs,
931
+ });
932
+ }
933
+
934
+ /**
935
+ * Submit an extend turn without waiting. Returns immediately with a job id
936
+ * to poll via {@link getVideoJob}.
937
+ * @returns {Promise<{jobId:string, status:'queued', sessionId:string}>}
938
+ */
939
+ async submitVideoExtend(
940
+ sessionId,
941
+ { prompt, description, signal, timeout } = {},
942
+ ) {
943
+ if (!sessionId || typeof sessionId !== 'string') {
944
+ throw new AIFlowError('sessionId is required');
945
+ }
946
+ const res = await this._request(
947
+ `/video/sessions/${encodeURIComponent(sessionId)}/extend`,
948
+ { prompt, description },
949
+ { signal, timeout: timeout ?? DEFAULT_TIMEOUT_MS },
950
+ );
951
+ return await res.json();
952
+ }
953
+
954
+ /**
955
+ * Read a session's current timeline — the stitched `videoUrl`, its measured
956
+ * `durationSeconds`, every `segments[]` entry, and `canExtend` /
957
+ * `remainingSeconds` for driving the extend control.
958
+ *
959
+ * `canExtend` is the ONLY thing a UI should gate its extend button on: it is
960
+ * false both while the opening clip is still generating and once the 40s
961
+ * ceiling is reached, so a client never has to know the limit itself.
962
+ * @returns {Promise<object>}
963
+ */
964
+ async getVideoSession(sessionId, { signal, timeout } = {}) {
965
+ if (!sessionId || typeof sessionId !== 'string') {
966
+ throw new AIFlowError('sessionId is required');
967
+ }
968
+ const res = await this._get(
969
+ `/video/sessions/${encodeURIComponent(sessionId)}`,
970
+ { signal, timeout: timeout ?? DEFAULT_TIMEOUT_MS },
971
+ );
972
+ return await res.json();
973
+ }
974
+
975
+ /**
976
+ * List the caller's own video sessions, newest first — the backing call for
977
+ * a "my videos" screen. Scoped to the signed-in end user when there is one.
978
+ * @returns {Promise<{sessions:object[]}>}
979
+ */
980
+ async listVideoSessions({ limit, signal, timeout } = {}) {
981
+ const query = limit ? `?limit=${encodeURIComponent(limit)}` : '';
982
+ const res = await this._get(`/video/sessions${query}`, {
983
+ signal,
984
+ timeout: timeout ?? DEFAULT_TIMEOUT_MS,
985
+ });
986
+ return await res.json();
987
+ }
988
+
569
989
  /**
570
990
  * Generate music / background audio from a text prompt (Lyria).
571
991
  * @returns {Promise<{audioUrl:string, model:string, durationSeconds:number|null, prompt?:string, usage:{creditsUsed:number}}>}