@devvibex/aiflow 1.15.1 → 1.16.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
@@ -129,7 +129,68 @@ throws.
129
129
  ### `aiflow.chatStream({ ... })`
130
130
 
131
131
  Async iterable of `{ delta: string, done: boolean }` chunks. The final chunk
132
- has `done: true` and carries the cumulative `usage` object.
132
+ has `done: true` and carries the cumulative `usage` object (and `jobId` on a
133
+ gateway with background jobs). A server error inside the stream — e.g. a 402
134
+ when the owner is out of credits — throws an `AIFlowError` (≥ 1.16.0; older
135
+ versions yielded it as a chunk with `error: true`). A dropped connection is
136
+ re-attached to the answer automatically.
137
+
138
+ ## Background jobs — generation that survives leaving the page (≥ 1.16.0)
139
+
140
+ On a gateway that supports it (`config.capabilities.jobs`), `chat`,
141
+ `chatStream`, `generateImage`, `generateImageBatch`, `generateAudio` and
142
+ `generateSfx` run as **background jobs**, as video always has: the gateway
143
+ keeps generating when the page that asked is closed, reloaded or navigated
144
+ away from, and keeps the result for a week. The calls resolve with exactly the
145
+ same value as before; on an older gateway they fall back to one synchronous
146
+ request.
147
+
148
+ Every generation call takes two extra options:
149
+
150
+ | Option | |
151
+ | --- | --- |
152
+ | `onJob(jobId, info?)` | Fires once the gateway has accepted the job, before it finishes. Store the id (e.g. on a "generating" row) to pick the result up later. |
153
+ | `tag` | A label (≤ 128 chars) for `jobs.latest(tag)` and `listJobs()`. |
154
+
155
+ Aborting `signal` now **stops only the waiting** — the generation carries on
156
+ and stays retrievable.
157
+
158
+ ```js
159
+ // Start: keep the job id with the row that is waiting for the result.
160
+ const row = await Artwork.create({ prompt, status: 'generating' });
161
+ const res = await aiflow.generateImage({
162
+ prompt,
163
+ onJob: (jobId) => Artwork.update(row.id, { job_id: jobId }),
164
+ });
165
+ await Artwork.update(row.id, { status: 'done', image_url: res.images[0].url });
166
+
167
+ // Later — after a reload, on another page or device: finish any row still waiting.
168
+ const finished = await aiflow.waitForJob(row.job_id); // same value generateImage resolves with
169
+ ```
170
+
171
+ | Method | |
172
+ | --- | --- |
173
+ | `waitForJob(jobId, { signal?, timeout?, onProgress? })` | Resolves with the job's result (what the starting call resolves with; a video job resolves like `generateVideo`). Throws an `AIFlowError` with the job's `status` / `code` when it failed. `timeout` defaults to 30 min. |
174
+ | `resumeChatStream(jobId, { from?, signal? })` | Re-attach to a streamed chat answer: chunks from character `from` (the length already shown; `0` replays all of it), then live until done. |
175
+ | `getJob(jobId, { waitMs? })` | One job now: `{ jobId, kind, status, tag?, prompt?, result?, error?, errorStatus?, errorCode? }`. |
176
+ | `listJobs({ active?, limit? })` | The signed-in end user's own jobs on this module, from any device (needs `setEndUser(id, token)`; anonymous → `[]`). No results — read one with `waitForJob`. |
177
+ | `jobs.latest(tag?)` / `jobs.list({ tag? })` / `jobs.forget(idOrTag)` | Jobs started from **this browser**, kept a day in localStorage: `{ jobId, kind, tag, status, result?, error? }`. Works without login. |
178
+
179
+ Without a database row, the browser's own record is enough for a page that
180
+ shows its latest result:
181
+
182
+ ```js
183
+ // On mount: show what finished while the user was away, or keep waiting.
184
+ const last = aiflow.jobs.latest('poster');
185
+ if (last?.status === 'succeeded') setImages(last.result.images);
186
+ else if (last?.status === 'processing') aiflow.waitForJob(last.jobId).then((r) => setImages(r.images));
187
+
188
+ // Generate
189
+ const res = await aiflow.generateImage({ prompt, tag: 'poster' });
190
+ ```
191
+
192
+ A job whose server restarted mid-way fails with `code: 'interrupted'` (status
193
+ 503) and is not charged — credits are deducted only on success.
133
194
 
134
195
  ### `aiflow.generateImage({ prompt, model?, size?, aspectRatio?, n?, image?, images?, system?, language?, background?, signal? })`
135
196
 
@@ -167,7 +228,8 @@ const clip = await aiflow.generateVideo({
167
228
 
168
229
  **Seedance reference mode.** Instead of a first frame, Seedance can take
169
230
  reference assets and keep them consistent in a new shot — cite them in the
170
- prompt as `[Image 1]`, `[Video 1]`, `[Audio 1]` in the order you pass them.
231
+ prompt as `@Image 1`, `@Video 1`, `@Audio 1` (or `[Image 1]`) in the order you
232
+ pass them; the gateway converts to the form the running Seedance release uses.
171
233
  It is a separate mode: it cannot be combined with `image` / `lastFrame`.
172
234
 
173
235
  | | Seedance 2.0 | Seedance 2.5 |
@@ -183,12 +245,31 @@ default; `generateAudio: false` makes them silent.
183
245
  ```js
184
246
  const ad = await aiflow.generateVideo({
185
247
  model: 'seedance',
186
- prompt: 'The girl from [Image 1] unboxes the sneaker from [Image 2], dancing to [Audio 1]',
248
+ prompt: 'The girl from @Image 1 unboxes the sneaker from @Image 2, dancing to @Audio 1',
187
249
  referenceImages: [characterUrl, productUrl],
188
250
  referenceAudios: [musicUrl],
189
251
  });
190
252
  ```
191
253
 
254
+ **Sending audio (Seedance).** `referenceAudios` takes wav or mp3 clips — an
255
+ `https://` URL, a `data:` URL, an `asset://` id, or (≥ 1.15.2) the uploaded
256
+ `File` itself, which the SDK sends as a data URL. Each clip runs at least 2s and
257
+ is under 15 MB; together they stay within 15s on Seedance 2.0 and 30s on 2.5.
258
+ Browser microphone recordings (webm / ogg) are refused with an `AIFlowError`
259
+ before any request. Pair a voice or song with a picture of the performer for a
260
+ lip-synced clip:
261
+
262
+ ```js
263
+ const clip = await aiflow.generateVideo({
264
+ model: 'seedance',
265
+ prompt: 'The woman in @Image 1 sings @Audio 1 with precise lip sync',
266
+ referenceImages: [portraitFile], // File / Blob from <input type="file">
267
+ referenceAudios: [songFile], // wav or mp3 File
268
+ });
269
+ ```
270
+ Reference audio is its own mode: it cannot be combined with `image` /
271
+ `lastFrame` (start and end frames).
272
+
192
273
  The default model is **Gemini Omni**: one clip of ~10s, **with sound**, 16:9 or
193
274
  9:16 only, and no length parameter. For a longer or extendable video use
194
275
  `generateLongVideo` / `createVideoSession` below — same model, so a single clip
@@ -572,6 +653,10 @@ setTimeout(() => ctrl.abort(), 3000);
572
653
  await aiflow.chat({ messages, signal: ctrl.signal });
573
654
  ```
574
655
 
656
+ With background jobs (≥ 1.16.0 on a gateway that has them) aborting stops the
657
+ waiting, not the generation: the job finishes and `waitForJob(jobId)` returns
658
+ its result.
659
+
575
660
  ## Publishing to npmjs
576
661
 
577
662
  > Owned by the `@devvibex` org. You must be a member to publish.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devvibex/aiflow",
3
- "version": "1.15.1",
3
+ "version": "1.16.0",
4
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",
package/src/index.d.ts CHANGED
@@ -3,6 +3,7 @@ export interface AIFlowErrorOptions {
3
3
  code?: string;
4
4
  requestId?: string;
5
5
  cause?: unknown;
6
+ fromServer?: boolean;
6
7
  }
7
8
 
8
9
  export class AIFlowError extends Error {
@@ -11,9 +12,84 @@ export class AIFlowError extends Error {
11
12
  code?: string;
12
13
  requestId?: string;
13
14
  cause?: unknown;
15
+ /** Set on an error the gateway reported inside a chat stream. */
16
+ fromServer?: boolean;
14
17
  constructor(message: string, options?: AIFlowErrorOptions);
15
18
  }
16
19
 
20
+ /**
21
+ * Options every generation call takes on a gateway with background jobs
22
+ * (`config.capabilities.jobs`). The call still resolves with its usual result;
23
+ * the generation itself runs on the gateway and keeps going if the page goes
24
+ * away.
25
+ */
26
+ export interface BackgroundJobOptions {
27
+ /**
28
+ * Called once the gateway has accepted the job, before it finishes. Store
29
+ * the id (e.g. on a "generating" row) to pick the result up later with
30
+ * `waitForJob(jobId)` / `resumeChatStream(jobId)`.
31
+ */
32
+ onJob?: (jobId: string, info?: { sessionId?: string }) => void;
33
+ /** Label for the job in `jobs.latest(tag)` / `listJobs()` (max 128 chars). */
34
+ tag?: string;
35
+ }
36
+
37
+ export type JobKind =
38
+ | 'chat'
39
+ | 'chat_stream'
40
+ | 'image'
41
+ | 'image_batch'
42
+ | 'audio'
43
+ | 'sfx'
44
+ | 'video';
45
+
46
+ export type JobStatus = 'queued' | 'processing' | 'succeeded' | 'failed';
47
+
48
+ /** A background job as the gateway reports it (`getJob` / `listJobs`). */
49
+ export interface JobView {
50
+ jobId: string;
51
+ kind: JobKind;
52
+ status: JobStatus;
53
+ tag?: string;
54
+ model?: string;
55
+ /** The request's prompt, shortened. */
56
+ prompt?: string;
57
+ createdAt?: string;
58
+ finishedAt?: string;
59
+ /** On success (`getJob` only): what the starting call resolves with. */
60
+ result?: any;
61
+ /** Characters of a streamed chat answer written so far. */
62
+ contentLength?: number;
63
+ /** Video builds and merges: progress while running. */
64
+ progress?: Partial<VideoBuildProgress>;
65
+ error?: string;
66
+ errorStatus?: number;
67
+ errorCode?: string;
68
+ }
69
+
70
+ /** A job this browser started, as `jobs.latest()` / `jobs.list()` keep it. */
71
+ export interface RememberedJob {
72
+ jobId: string;
73
+ kind: JobKind;
74
+ tag?: string;
75
+ status: JobStatus;
76
+ /** What the call resolved with, once it succeeded (absent when too large — use `waitForJob`). */
77
+ result?: any;
78
+ resultOmitted?: boolean;
79
+ error?: string;
80
+ createdAt: number;
81
+ updatedAt: number;
82
+ }
83
+
84
+ export interface JobsNamespace {
85
+ /** Newest remembered job with this tag (any tag when omitted), or null. */
86
+ latest(tag?: string): RememberedJob | null;
87
+ /** Remembered jobs, newest first, optionally only one tag. */
88
+ list(filter?: { tag?: string }): RememberedJob[];
89
+ /** Forget one job (by id) or every job with a tag. */
90
+ forget(jobIdOrTag: string): void;
91
+ }
92
+
17
93
  export type ChatRole = 'system' | 'user' | 'assistant';
18
94
 
19
95
  // ─── Multimodal content blocks ───────────────────────────────────────────────
@@ -61,7 +137,12 @@ export interface ChatRequest {
61
137
  webSearch?: boolean;
62
138
  /** @deprecated Not supported by the gateway — passing it throws. */
63
139
  tools?: ChatTool[];
140
+ /** Stops waiting (or reading the stream); the generation itself continues. */
64
141
  signal?: AbortSignal;
142
+ /** `chat()` only: overall wait (ms). Defaults to 30 min with background jobs, else 60s. */
143
+ timeout?: number;
144
+ onJob?: BackgroundJobOptions['onJob'];
145
+ tag?: string;
65
146
  }
66
147
 
67
148
  export interface ChatUsage {
@@ -90,6 +171,8 @@ export interface ChatStreamChunk {
90
171
  model?: string;
91
172
  /** Where the resolved `model` came from (present on the final `done: true` chunk). */
92
173
  modelSource?: ModelSource;
174
+ /** Final chunk, on a gateway with background jobs: the answer's job id. */
175
+ jobId?: string;
93
176
  [key: string]: unknown;
94
177
  }
95
178
 
@@ -127,8 +210,13 @@ export interface ImageRequest {
127
210
  */
128
211
  background?: ImageBackground;
129
212
  signal?: AbortSignal;
130
- /** Per-call timeout (ms). Defaults to 180000 — image edits exceed the 60s client default. */
213
+ /**
214
+ * Overall wait (ms). Defaults to 30 min with background jobs; without
215
+ * them, the request timeout, 180000 — image edits exceed the 60s default.
216
+ */
131
217
  timeout?: number;
218
+ onJob?: BackgroundJobOptions['onJob'];
219
+ tag?: string;
132
220
  }
133
221
 
134
222
  export interface GeneratedImage {
@@ -177,8 +265,10 @@ export interface ImageBatchRequest {
177
265
  /** Shared `background` for every page — see {@link ImageRequest.background}. */
178
266
  background?: ImageBackground;
179
267
  signal?: AbortSignal;
180
- /** Per-call timeout (ms). Defaults to 600000 (10 min). */
268
+ /** Overall wait (ms). Defaults to 30 min with background jobs, else 600000 (10 min). */
181
269
  timeout?: number;
270
+ onJob?: BackgroundJobOptions['onJob'];
271
+ tag?: string;
182
272
  }
183
273
 
184
274
  export interface ImageBatchPageResult {
@@ -231,37 +321,40 @@ export interface VideoRequest {
231
321
  watermark?: boolean;
232
322
  /**
233
323
  * Still image to animate (image-to-video) — the clip's FIRST frame. An
234
- * `https://` URL or a `data:` URL.
324
+ * `https://` URL, a `data:` URL, or a `File` / `Blob` (≥ 1.15.2).
235
325
  */
236
- image?: string;
326
+ image?: string | Blob;
237
327
  /**
238
328
  * Image the clip must END on (first + last frame). Same formats as `image`
239
329
  * and requires it. Seedance and Kling — Gemini Omni and Veo ignore it, so
240
330
  * the module must be pinned to one of them. Kling takes JPG / PNG only.
241
331
  * Needs `@devvibex/aiflow` ≥ 1.15.0.
242
332
  */
243
- lastFrame?: string;
244
- video?: string;
333
+ lastFrame?: string | Blob;
334
+ video?: string | Blob;
245
335
  /**
246
336
  * Seedance only — reference images that keep a character, product or style
247
337
  * (omni reference mode). Up to 9 on Seedance 2.0, 30 on 2.5. Cited in the
248
- * prompt as [Image 1], [Image 2], … in this order. `https://`, `data:` or
338
+ * prompt as @Image 1, @Image 2, … (or [Image 1]) in this order. `https://`, `data:` or
249
339
  * `asset://`. Cannot be combined with `image` / `lastFrame`.
250
340
  */
251
- referenceImages?: string[];
341
+ referenceImages?: Array<string | Blob>;
252
342
  /**
253
343
  * Seedance only — reference videos for motion/camera, or the clip to edit
254
344
  * or extend. Up to 3 on Seedance 2.0 (2–15s each, ≤15s total), 10 on 2.5
255
- * (≤30s total). `https://` or `asset://` only. Cited as [Video 1], ….
345
+ * (≤30s total). `https://` or `asset://` only. Cited as @Video 1, ….
256
346
  */
257
347
  referenceVideos?: string[];
258
348
  /**
259
349
  * Seedance only — reference audio (voice, music, rhythm), wav or mp3. Up to
260
350
  * 3 on Seedance 2.0 (2–15s each, ≤15s total), and there it needs at least
261
351
  * one reference image or video; 10 on 2.5 (≤30s total), audio alone allowed.
262
- * Cited as [Audio 1], ….
352
+ * Cited as @Audio 1, …. A voice or song with a character picture gives a
353
+ * lip-synced performance ("the woman in @Image 1 sings @Audio 1"). Pass the
354
+ * uploaded `File`s directly (sent as data URLs, ≥ 1.15.2) or https:// URLs;
355
+ * each clip under 15 MB. Browser recordings (webm / ogg) are refused.
263
356
  */
264
- referenceAudios?: string[];
357
+ referenceAudios?: Array<string | Blob>;
265
358
  /**
266
359
  * Seedance and Kling — whether the clip gets synchronized sound (voice,
267
360
  * effects, music). Omitted: on for Seedance, off for Kling (where sound
@@ -277,6 +370,9 @@ export interface VideoRequest {
277
370
  timeout?: number;
278
371
  /** Interval between status polls (ms). Defaults to 3000. */
279
372
  pollIntervalMs?: number;
373
+ /** `generateVideo` only — see {@link BackgroundJobOptions}. */
374
+ onJob?: BackgroundJobOptions['onJob'];
375
+ tag?: string;
280
376
  }
281
377
 
282
378
  export interface VideoResponse {
@@ -472,6 +568,9 @@ export interface LongVideoRequest {
472
568
  /** Overall wait budget. Defaults to ~7 minutes per 10s requested. */
473
569
  timeout?: number;
474
570
  pollIntervalMs?: number;
571
+ /** Receives the build's job id (and `sessionId`) as soon as it starts. */
572
+ onJob?: BackgroundJobOptions['onJob'];
573
+ tag?: string;
475
574
  }
476
575
 
477
576
  export interface LongVideoResponse extends VideoResponse {
@@ -500,6 +599,8 @@ export interface VideoMergeRequest {
500
599
  /** Defaults to 2 minutes per clip (minimum 10 minutes). */
501
600
  timeout?: number;
502
601
  pollIntervalMs?: number;
602
+ onJob?: BackgroundJobOptions['onJob'];
603
+ tag?: string;
503
604
  }
504
605
 
505
606
  export interface VideoMergeResponse extends VideoResponse {
@@ -526,6 +627,9 @@ export interface VideoExtendRequest {
526
627
  signal?: AbortSignal;
527
628
  timeout?: number;
528
629
  pollIntervalMs?: number;
630
+ /** `extendVideo` only — receives the turn's job id. */
631
+ onJob?: BackgroundJobOptions['onJob'];
632
+ tag?: string;
529
633
  }
530
634
 
531
635
  /** Result of one completed extend turn. */
@@ -576,8 +680,10 @@ export interface AudioRequest {
576
680
  /** Passed to Lyria as a seed. Google does not promise the same song for the same seed. */
577
681
  seed?: number;
578
682
  signal?: AbortSignal;
579
- /** Per-call timeout (ms). Defaults to 180000 (3 min) — music gen is slow. */
683
+ /** Overall wait (ms). Defaults to 30 min with background jobs, else 180000 (3 min). */
580
684
  timeout?: number;
685
+ onJob?: BackgroundJobOptions['onJob'];
686
+ tag?: string;
581
687
  }
582
688
 
583
689
  export interface AudioResponse {
@@ -613,8 +719,10 @@ export interface SfxRequest {
613
719
  /** Make the clip loop seamlessly (ambience, engine hum, rain). */
614
720
  loop?: boolean;
615
721
  signal?: AbortSignal;
616
- /** Per-call timeout (ms). Defaults to 120000 (2 min). */
722
+ /** Overall wait (ms). Defaults to 30 min with background jobs, else 120000 (2 min). */
617
723
  timeout?: number;
724
+ onJob?: BackgroundJobOptions['onJob'];
725
+ tag?: string;
618
726
  }
619
727
 
620
728
  export interface SfxResponse {
@@ -939,6 +1047,8 @@ export interface AiflowConfig {
939
1047
  webSearch?: boolean;
940
1048
  /** Whether the real-time live-translate feature is enabled. */
941
1049
  liveTranslate?: boolean;
1050
+ /** Gateway features. `jobs`: generations run as background jobs. */
1051
+ capabilities?: { jobs?: boolean };
942
1052
  }
943
1053
 
944
1054
  // ─── Admin (module config) ───────────────────────────────────────────────────
@@ -1011,6 +1121,8 @@ export class AIFlowClient {
1011
1121
  readonly knowledge: KnowledgeNamespace;
1012
1122
  /** Admin namespace — manage the app's AIFlow module config (needs `setAdminToken`). */
1013
1123
  readonly admin: AiflowAdminNamespace;
1124
+ /** Background jobs started from this browser, remembered for a day. */
1125
+ readonly jobs: JobsNamespace;
1014
1126
 
1015
1127
  constructor(options: AIFlowClientOptions);
1016
1128
 
@@ -1126,6 +1238,8 @@ export class AIFlowClient {
1126
1238
  signal?: AbortSignal;
1127
1239
  timeout?: number;
1128
1240
  pollIntervalMs?: number;
1241
+ onJob?: BackgroundJobOptions['onJob'];
1242
+ tag?: string;
1129
1243
  },
1130
1244
  ): Promise<LongVideoResponse>;
1131
1245
  /** Submit a merge without waiting; poll it with {@link getVideoJob}. */
@@ -1162,6 +1276,42 @@ export class AIFlowClient {
1162
1276
  generateSfx(request: SfxRequest): Promise<SfxResponse>;
1163
1277
  embed(request: EmbedRequest): Promise<EmbedResponse>;
1164
1278
  vision(request: VisionRequest): Promise<VisionResponse>;
1279
+ /**
1280
+ * Wait for a background job and resolve with its result — what the call
1281
+ * that started it resolves with. Works after a reload or on another page.
1282
+ * Aborting `signal` / hitting `timeout` (default 30 min) stops only the
1283
+ * waiting. Throws an AIFlowError (`status`, `code`) when the job failed.
1284
+ */
1285
+ waitForJob<T = any>(
1286
+ jobId: string,
1287
+ options?: {
1288
+ signal?: AbortSignal;
1289
+ timeout?: number;
1290
+ onProgress?: (progress: VideoBuildProgress) => void;
1291
+ },
1292
+ ): Promise<T>;
1293
+ /** Read one job now; `waitMs` (≤ 25000) lets the gateway hold until it finishes. */
1294
+ getJob(
1295
+ jobId: string,
1296
+ options?: { waitMs?: number; signal?: AbortSignal },
1297
+ ): Promise<JobView>;
1298
+ /**
1299
+ * The signed-in end user's own jobs on this module (any device), newest
1300
+ * first, without results. Anonymous callers get an empty list.
1301
+ */
1302
+ listJobs(options?: {
1303
+ active?: boolean;
1304
+ limit?: number;
1305
+ signal?: AbortSignal;
1306
+ }): Promise<{ jobs: JobView[] }>;
1307
+ /**
1308
+ * Re-attach to a streamed chat answer from character `from` (0 replays
1309
+ * all of it), then follow it live until done.
1310
+ */
1311
+ resumeChatStream(
1312
+ jobId: string,
1313
+ options?: { from?: number; signal?: AbortSignal },
1314
+ ): AsyncGenerator<ChatStreamChunk, void, void>;
1165
1315
  /**
1166
1316
  * Open a real-time speech-translation session over WebSocket (Gemini Live
1167
1317
  * via the gateway). Requires the optional peer dependency