@devvibex/aiflow 1.3.0 → 1.5.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devvibex/aiflow",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
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.",
5
5
  "keywords": [
6
6
  "ai",
package/src/index.d.ts CHANGED
@@ -173,6 +173,12 @@ export interface VideoRequest {
173
173
  * accepts 4:3 / 3:4 / 21:9 (the server maps unsupported ratios to 16:9).
174
174
  */
175
175
  aspectRatio?: '16:9' | '9:16' | '1:1' | '4:3' | '3:4' | '21:9' | string;
176
+ /**
177
+ * Output resolution (Seedance/Dreamina only): '480p' | '720p' | '1080p'.
178
+ * Lower resolution generates faster. Defaults to the app's server-side
179
+ * default (720p) when omitted. Ignored by Veo.
180
+ */
181
+ resolution?: '480p' | '720p' | '1080p' | string;
176
182
  /**
177
183
  * Clip length in seconds. Seedance 2.0 supports an integer 4–15 (clamped to
178
184
  * that range, default 5). Ignored by Veo, which uses a fixed length per mode.
@@ -183,15 +189,48 @@ export interface VideoRequest {
183
189
  image?: string;
184
190
  video?: string;
185
191
  signal?: AbortSignal;
186
- /** Per-request timeout (ms). Defaults to 600000 (10 min). */
192
+ /**
193
+ * Overall wait budget across all status polls (ms). Defaults to 600000
194
+ * (10 min). `generateVideo` submits a job and polls under the hood — no
195
+ * single request is held open this long.
196
+ */
187
197
  timeout?: number;
198
+ /** Interval between status polls (ms). Defaults to 3000. */
199
+ pollIntervalMs?: number;
188
200
  }
189
201
 
190
202
  export interface VideoResponse {
191
203
  videoUrl: string;
204
+ thumbnailUrl?: string;
205
+ prompt?: string;
192
206
  usage: { creditsUsed: number };
193
207
  }
194
208
 
209
+ export type VideoJobStatus =
210
+ | 'queued'
211
+ | 'processing'
212
+ | 'succeeded'
213
+ | 'failed';
214
+
215
+ /** Acknowledgement returned by {@link AIFlowClient.submitVideoJob}. */
216
+ export interface VideoJobSubmitResponse {
217
+ jobId: string;
218
+ status: 'queued';
219
+ }
220
+
221
+ /** Status returned by {@link AIFlowClient.getVideoJob}. */
222
+ export interface VideoJobStatusResponse {
223
+ jobId: string;
224
+ status: VideoJobStatus;
225
+ /** Present once status === 'succeeded'. */
226
+ videoUrl?: string;
227
+ thumbnailUrl?: string;
228
+ prompt?: string;
229
+ usage?: { creditsUsed: number };
230
+ /** Present once status === 'failed'. */
231
+ error?: string;
232
+ }
233
+
195
234
  // ─── Audio (music — Lyria) ──────────────────────────────────────────────────
196
235
 
197
236
  export interface AudioRequest {
@@ -372,6 +411,7 @@ export interface LiveAudioOut {
372
411
 
373
412
  export interface LiveTurnComplete {
374
413
  interrupted: boolean;
414
+ turnComplete: boolean;
375
415
  }
376
416
 
377
417
  export interface LiveError {
@@ -402,6 +442,11 @@ export interface LiveTranslateOptions {
402
442
  onReady?: (payload: LiveReadyPayload) => void;
403
443
  onTranscript?: (payload: LiveTranscript) => void;
404
444
  onAudio?: (payload: LiveAudioOut) => void;
445
+ /**
446
+ * Barge-in: the model cancelled the in-flight turn. You MUST flush queued
447
+ * playback here so the abandoned translation doesn't talk over new speech.
448
+ */
449
+ onInterrupted?: () => void;
405
450
  onTurnComplete?: (payload: LiveTurnComplete) => void;
406
451
  onError?: (payload: LiveError) => void;
407
452
  onClosed?: (payload: LiveClosed) => void;
@@ -411,6 +456,7 @@ export type LiveTranslateEvent =
411
456
  | 'ready'
412
457
  | 'transcript'
413
458
  | 'audio'
459
+ | 'interrupted'
414
460
  | 'turn_complete'
415
461
  | 'error'
416
462
  | 'closed';
@@ -519,7 +565,19 @@ export class AIFlowClient {
519
565
  chatStream(request: ChatRequest): AsyncGenerator<ChatStreamChunk, void, void>;
520
566
  generateImage(request: ImageRequest): Promise<ImageResponse>;
521
567
  generateImageBatch(request: ImageBatchRequest): Promise<ImageBatchResponse>;
568
+ /**
569
+ * Generate a video. Submits an async job and polls to completion under the
570
+ * hood (no long-held socket), returning the final result. Use
571
+ * {@link submitVideoJob} + {@link getVideoJob} for manual polling.
572
+ */
522
573
  generateVideo(request: VideoRequest): Promise<VideoResponse>;
574
+ /** Submit an async video job; returns a job id immediately. */
575
+ submitVideoJob(request: VideoRequest): Promise<VideoJobSubmitResponse>;
576
+ /** Poll the status/result of an async video job. */
577
+ getVideoJob(
578
+ jobId: string,
579
+ options?: { signal?: AbortSignal; timeout?: number },
580
+ ): Promise<VideoJobStatusResponse>;
523
581
  generateAudio(request: AudioRequest): Promise<AudioResponse>;
524
582
  generateSfx(request: SfxRequest): Promise<SfxResponse>;
525
583
  embed(request: EmbedRequest): Promise<EmbedResponse>;
package/src/index.js CHANGED
@@ -367,12 +367,42 @@ export class AIFlowClient {
367
367
 
368
368
  /**
369
369
  * Generate a video from a text prompt.
370
- * @returns {Promise<{videoUrl:string, usage:{creditsUsed:number}}>}
370
+ *
371
+ * Implemented as SUBMIT + POLL: it submits an async job and polls the
372
+ * gateway for the result, so no single HTTP request is held open for the
373
+ * full (~minutes-long) generation. This avoids the upstream proxy timeout
374
+ * that long synchronous video calls used to hit. The return shape is
375
+ * unchanged from earlier SDK versions, so existing code keeps working.
376
+ *
377
+ * For finer control (e.g. your own polling UI) use {@link submitVideoJob}
378
+ * + {@link getVideoJob} directly.
379
+ *
380
+ * @returns {Promise<{videoUrl:string, thumbnailUrl?:string, prompt?:string, usage:{creditsUsed:number}}>}
371
381
  */
372
- async generateVideo({
382
+ async generateVideo(opts = {}) {
383
+ if (!opts.prompt || typeof opts.prompt !== 'string') {
384
+ throw new AIFlowError('prompt is required');
385
+ }
386
+ const { jobId } = await this.submitVideoJob(opts);
387
+ return this._pollVideoJob(jobId, {
388
+ signal: opts.signal,
389
+ // Overall wait budget across all polls (default 10 min). Each
390
+ // individual poll is a short request, so the socket is never held.
391
+ timeout: opts.timeout ?? 600_000,
392
+ pollIntervalMs: opts.pollIntervalMs,
393
+ });
394
+ }
395
+
396
+ /**
397
+ * Submit an async video-generation job. Returns immediately with a job id;
398
+ * the heavy generation runs in the background on the gateway.
399
+ * @returns {Promise<{jobId:string, status:'queued'}>}
400
+ */
401
+ async submitVideoJob({
373
402
  prompt,
374
403
  model,
375
404
  aspectRatio = '16:9',
405
+ resolution,
376
406
  duration,
377
407
  watermark,
378
408
  image,
@@ -386,24 +416,79 @@ export class AIFlowClient {
386
416
  const resolvedModel =
387
417
  model || (await this._resolveDefaultModel('video'));
388
418
  const res = await this._request(
389
- '/video',
419
+ '/video/jobs',
390
420
  {
391
421
  model: resolvedModel,
392
422
  prompt,
393
423
  aspectRatio,
424
+ resolution,
394
425
  duration,
395
426
  watermark,
396
427
  image,
397
428
  video,
398
429
  },
399
- // Video generation is long-running (the server polls the provider
400
- // for up to ~10 minutes). Match that ceiling so the socket isn't
401
- // closed mid-generation.
402
- { signal, timeout: timeout ?? 600_000 },
430
+ // Submit returns fast; the default client timeout is plenty even
431
+ // when an image-to-video request uploads a base64 first frame.
432
+ { signal, timeout: timeout ?? DEFAULT_TIMEOUT_MS },
403
433
  );
404
434
  return await res.json();
405
435
  }
406
436
 
437
+ /**
438
+ * Fetch the current status of an async video job.
439
+ * @returns {Promise<{jobId:string, status:'queued'|'processing'|'succeeded'|'failed', videoUrl?:string, thumbnailUrl?:string, prompt?:string, usage?:{creditsUsed:number}, error?:string}>}
440
+ */
441
+ async getVideoJob(jobId, { signal, timeout } = {}) {
442
+ if (!jobId || typeof jobId !== 'string') {
443
+ throw new AIFlowError('jobId is required');
444
+ }
445
+ const res = await this._get(
446
+ `/video/jobs/${encodeURIComponent(jobId)}`,
447
+ { signal, timeout: timeout ?? DEFAULT_TIMEOUT_MS },
448
+ );
449
+ return await res.json();
450
+ }
451
+
452
+ /** Poll a video job to completion and normalise the success payload. */
453
+ async _pollVideoJob(
454
+ jobId,
455
+ { signal, timeout = 600_000, pollIntervalMs = 3_000 } = {},
456
+ ) {
457
+ const deadline = Date.now() + timeout;
458
+ // eslint-disable-next-line no-constant-condition
459
+ while (true) {
460
+ if (signal?.aborted) {
461
+ throw new AIFlowError('Video generation aborted', {
462
+ code: 'aborted',
463
+ });
464
+ }
465
+ const job = await this.getVideoJob(jobId, { signal });
466
+ if (job.status === 'succeeded') {
467
+ return {
468
+ videoUrl: job.videoUrl,
469
+ thumbnailUrl: job.thumbnailUrl,
470
+ prompt: job.prompt,
471
+ usage: job.usage || { creditsUsed: 0 },
472
+ };
473
+ }
474
+ if (job.status === 'failed') {
475
+ throw new AIFlowError(
476
+ job.error || 'Video generation failed',
477
+ { code: 'video_failed' },
478
+ );
479
+ }
480
+ if (Date.now() >= deadline) {
481
+ throw new AIFlowError(
482
+ `Video generation timed out after ${Math.round(
483
+ timeout / 1000,
484
+ )}s`,
485
+ { code: 'timeout' },
486
+ );
487
+ }
488
+ await sleep(pollIntervalMs);
489
+ }
490
+ }
491
+
407
492
  /**
408
493
  * Generate music / background audio from a text prompt (Lyria).
409
494
  * @returns {Promise<{audioUrl:string, model:string, durationSeconds:number|null, prompt?:string, usage:{creditsUsed:number}}>}
@@ -531,7 +616,8 @@ export class AIFlowClient {
531
616
  * @param {(p:object)=>void} [opts.onReady]
532
617
  * @param {(p:{role:'input'|'output',text:string,isFinal:boolean})=>void} [opts.onTranscript]
533
618
  * @param {(p:{chunk:string,mimeType:string})=>void} [opts.onAudio]
534
- * @param {(p:{interrupted:boolean})=>void} [opts.onTurnComplete]
619
+ * @param {()=>void} [opts.onInterrupted] Barge-in: the model cancelled the in-flight turn. You MUST flush queued playback here so stale audio doesn't talk over new speech.
620
+ * @param {(p:{interrupted:boolean,turnComplete:boolean})=>void} [opts.onTurnComplete]
535
621
  * @param {(p:{code:string,message:string})=>void} [opts.onError]
536
622
  * @param {(p:{reason:string,usage:object})=>void} [opts.onClosed]
537
623
  * @returns {Promise<LiveTranslateSession>} Resolves once connected.
@@ -547,6 +633,7 @@ export class AIFlowClient {
547
633
  onReady,
548
634
  onTranscript,
549
635
  onAudio,
636
+ onInterrupted,
550
637
  onTurnComplete,
551
638
  onError,
552
639
  onClosed,
@@ -577,6 +664,7 @@ export class AIFlowClient {
577
664
  onReady,
578
665
  onTranscript,
579
666
  onAudio,
667
+ onInterrupted,
580
668
  onTurnComplete,
581
669
  onError,
582
670
  onClosed,
@@ -614,6 +702,21 @@ export class AIFlowClient {
614
702
  );
615
703
  }
616
704
 
705
+ /** GET from the gateway (used by short status polls). */
706
+ async _get(path, { signal, timeout } = {}) {
707
+ return this._fetchWithRetry(
708
+ `${this.baseUrl}${path}`,
709
+ {
710
+ method: 'GET',
711
+ headers: {
712
+ ...this._authHeaders(),
713
+ Accept: 'application/json',
714
+ },
715
+ },
716
+ { signal, timeout },
717
+ );
718
+ }
719
+
617
720
  /**
618
721
  * Send a request with timeout + retry (429/5xx + network errors). `init`
619
722
  * carries method/headers/body; the abort signal is composed per attempt.
@@ -780,6 +883,7 @@ export class LiveTranslateSession {
780
883
  });
781
884
  fwd('translate:transcript', this._handlers.onTranscript);
782
885
  fwd('translate:audio', this._handlers.onAudio);
886
+ fwd('translate:interrupted', this._handlers.onInterrupted);
783
887
  fwd('translate:turn_complete', this._handlers.onTurnComplete);
784
888
  fwd('translate:error', this._handlers.onError);
785
889
  this.socket.on('translate:closed', (p) => {