@devvibex/aiflow 1.16.0 → 1.17.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.
Files changed (4) hide show
  1. package/README.md +104 -32
  2. package/package.json +1 -1
  3. package/src/index.d.ts +103 -7
  4. package/src/index.js +1484 -63
package/README.md CHANGED
@@ -83,6 +83,7 @@ console.log(emb.data[0].embedding.length);
83
83
  | `timeout` | `number` | `60000` | Per-request timeout (ms). |
84
84
  | `maxRetries` | `number` | `2` | Retries on 429 / 5xx / network errors. |
85
85
  | `fetch` | `typeof fetch` | `globalThis.fetch` | Custom fetch (Node <18, testing). |
86
+ | `backgroundNotice` | `boolean` | `true` | `false` turns off the [background notice](#the-background-notice--1170) for the whole page. |
86
87
 
87
88
  When you don't pass a `defaultModel`, the SDK calls `GET /config` on the
88
89
  first `chat` / `chatStream` / `generateImage` / `embed` and caches the
@@ -145,61 +146,132 @@ away from, and keeps the result for a week. The calls resolve with exactly the
145
146
  same value as before; on an older gateway they fall back to one synchronous
146
147
  request.
147
148
 
148
- Every generation call takes two extra options:
149
+ Every generation call takes these extra options:
149
150
 
150
151
  | Option | |
151
152
  | --- | --- |
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()`. |
153
+ | `saveTo: { entity, id, field }` | **≥ 1.17.0.** The gateway writes the outcome into that row itself when the job ends — even if the tab was closed. See below. |
154
+ | `tag` | A label (≤ 128 chars) for `jobs.attach(tag)`, `jobs.latest(tag)` and `listJobs()`. |
155
+ | `onJob(jobId, info?)` | Fires once the gateway has accepted the job, before it finishes. |
154
156
 
155
- Aborting `signal` now **stops only the waiting** — the generation carries on
156
- and stays retrievable.
157
+ Aborting `signal` **stops only the waiting** — the generation carries on and
158
+ stays retrievable.
159
+
160
+ ### Features that save their results — `saveTo` (≥ 1.17.0)
161
+
162
+ Create the row first, then name it in `saveTo`. When the job ends, the gateway
163
+ writes into the row itself:
164
+
165
+ | When | Written (only the fields the entity has) |
166
+ | --- | --- |
167
+ | accepted | `job_id` |
168
+ | succeeded | `{ [field]: value, status: 'done' }` |
169
+ | failed | `{ status: 'failed', error }` |
170
+
171
+ `value` is the answer text (`chat` / `chatStream`), the image URL (every URL
172
+ when `field` is an array; image batches give URLs), the audio URL
173
+ (`generateAudio` / `generateSfx`) or the video URL (`generateVideo`,
174
+ `generateLongVideo`). The submit is refused (400 / 403 / 404) when the target
175
+ is invalid, the row does not exist or the signed-in user may not update it —
176
+ the same rules as the app's own data API.
157
177
 
158
178
  ```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 });
179
+ const row = await Creation.create({ prompt, status: 'generating' });
180
+ try {
181
+ const res = await aiflow.generateImage({
182
+ prompt,
183
+ saveTo: { entity: 'Creation', id: row.id, field: 'image_url' },
184
+ });
185
+ // Already saved by the gateway; this keeps the page instant.
186
+ await Creation.update(row.id, { status: 'done', image_url: res.images[0].url });
187
+ } catch (err) {
188
+ await Creation.update(row.id, { status: 'failed', error: err.message });
189
+ }
166
190
 
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
191
+ // Wherever the rows are listed: refresh while any is still generating.
192
+ useEffect(() => {
193
+ if (!rows.some((r) => r.status === 'generating')) return;
194
+ const timer = setInterval(reload, 5000);
195
+ return () => clearInterval(timer);
196
+ }, [rows]);
169
197
  ```
170
198
 
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. |
199
+ `saveTo` needs `config.capabilities.saveTo`; an older gateway ignores it (the
200
+ SDK warns once in the console), so keep saving from the resolved value as
201
+ above.
178
202
 
179
- Without a database row, the browser's own record is enough for a page that
180
- shows its latest result:
203
+ ### Features that keep the result only on screen — `jobs.attach` (≥ 1.17.0)
204
+
205
+ Pass a `tag`, and pick the job up again on mount. `jobs.attach(tag)` returns
206
+ `null` or `{ jobId, kind, tag, status, result?, error?, done }`; `done`
207
+ resolves with what the starting call resolved with — at once when it already
208
+ finished, or when it does (also after a page change or a reload):
181
209
 
182
210
  ```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));
211
+ useEffect(() => {
212
+ const job = aiflow.jobs.attach('poster');
213
+ if (!job || job.status === 'failed') return; // an old failure: the notice shows it
214
+ if (job.status === 'processing') setLoading(true);
215
+ job.done
216
+ .then((res) => setImages(res.images))
217
+ .catch((err) => toast.error(err.message))
218
+ .finally(() => setLoading(false));
219
+ }, []);
187
220
 
188
- // Generate
189
221
  const res = await aiflow.generateImage({ prompt, tag: 'poster' });
190
222
  ```
191
223
 
224
+ Without a tag, `jobs.attach()` picks the newest job started from the current
225
+ page. Reading `done` is what tells the background notice that the page shows
226
+ the job; a page that skips a failed job leaves its card in the notice.
227
+
228
+ ### The background notice (≥ 1.17.0)
229
+
230
+ When the user leaves the page that started a generation (or reloads it), the
231
+ SDK shows a small panel in the corner: *"Generating your video… It keeps going
232
+ in the background."* When the job finishes, the panel shows the result — image
233
+ thumbnails, an audio or video player, or the start of the answer — with
234
+ **Open page**, **Download** / **Copy** and a close button. A page that picks the
235
+ job up itself (`jobs.attach(…).done`, `waitForJob`, `resumeChatStream`) takes
236
+ over and the panel hides it. It speaks English, Korean, Vietnamese, Japanese and
237
+ Chinese (from `<html lang>`, then the browser), follows the system light/dark
238
+ setting, and never appears in a client constructed with `appSecret` or outside
239
+ a browser.
240
+
241
+ ```js
242
+ // Move it, force a language, or turn it off for the whole page:
243
+ AIFlowClient.configureBackgroundNotice({ position: 'bottom-right', locale: 'ko' });
244
+ AIFlowClient.configureBackgroundNotice({ enabled: false });
245
+ // also: new AIFlowClient({ ..., backgroundNotice: false })
246
+ // or: window.__AIFLOW_BACKGROUND_NOTICE__ = false
247
+ ```
248
+
249
+ ### Job methods
250
+
251
+ | Method | |
252
+ | --- | --- |
253
+ | `jobs.attach(tag?)` | See above. |
254
+ | `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. |
255
+ | `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. |
256
+ | `getJob(jobId, { waitMs? })` | One job now: `{ jobId, kind, status, tag?, prompt?, result?, error?, errorStatus?, errorCode? }`. |
257
+ | `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`. |
258
+ | `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?, page?, label? }`. Works without login. |
259
+
192
260
  A job whose server restarted mid-way fails with `code: 'interrupted'` (status
193
- 503) and is not charged — credits are deducted only on success.
261
+ 503) and is not charged — credits are deducted only on success. `chat`,
262
+ `generateImage`, `generateImageBatch`, `generateAudio` and `generateSfx` submit
263
+ such a job once more by themselves (≥ 1.16.1; `onJob` fires again with the new
264
+ id); `waitForJob` on a stored id and `chatStream` throw it, so offer a retry.
194
265
 
195
266
  ### `aiflow.generateImage({ prompt, model?, size?, aspectRatio?, n?, image?, images?, system?, language?, background?, signal? })`
196
267
 
197
268
  Returns `{ images: [{ url?, b64?, mimeType }], usage: { creditsUsed } }`.
198
269
  `url` is a short-lived signed URL (~1h). Pass `image`/`images` to edit an
199
- existing image (image-to-image) instead of generating from text.
270
+ existing image (image-to-image) instead of generating from text — up to 16 input
271
+ images per call, 10 on `seedream`.
200
272
  `aspectRatio` (`'1:1'`, `'2:3'`, `'3:2'`, `'3:4'`, `'4:3'`, `'9:16'`, `'16:9'`,
201
- `'21:9'`) sets the frame on the Gemini image models; GPT image models use
202
- `size` instead. `background`
273
+ `'21:9'`) sets the frame on the Gemini and Seedream image models; GPT image
274
+ models use `size` instead. `background`
203
275
  (`'auto'` | `'transparent'` | `'opaque'`) is honoured only by the models in
204
276
  `config.imageBackgroundModels`; `generateImageBatch` takes it top-level or per
205
277
  page. The module default is set with `admin.updateConfig({ imageBackground })`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devvibex/aiflow",
3
- "version": "1.16.0",
3
+ "version": "1.17.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
@@ -27,11 +27,36 @@ export interface BackgroundJobOptions {
27
27
  /**
28
28
  * Called once the gateway has accepted the job, before it finishes. Store
29
29
  * the id (e.g. on a "generating" row) to pick the result up later with
30
- * `waitForJob(jobId)` / `resumeChatStream(jobId)`.
30
+ * `waitForJob(jobId)` / `resumeChatStream(jobId)`. Fires again with a new id
31
+ * when a job cut off by a gateway restart is run once more (chat, image,
32
+ * music and SFX calls do that automatically).
31
33
  */
32
34
  onJob?: (jobId: string, info?: { sessionId?: string }) => void;
33
- /** Label for the job in `jobs.latest(tag)` / `listJobs()` (max 128 chars). */
35
+ /** Label for the job in `jobs.latest(tag)` / `jobs.attach(tag)` / `listJobs()` (max 128 chars). */
34
36
  tag?: string;
37
+ /**
38
+ * Have the gateway write the outcome into this row when the job ends —
39
+ * even if the tab was closed (needs `config.capabilities.saveTo`).
40
+ */
41
+ saveTo?: SaveTarget;
42
+ }
43
+
44
+ /**
45
+ * A row the gateway finishes by itself. On accept it writes `job_id`; on
46
+ * success `{ [field]: value, status: 'done' }`; on failure
47
+ * `{ status: 'failed', error }` — each only where the entity has the field.
48
+ * `value` is the answer text (chat), the image URL (every URL when `field` is
49
+ * an array; image batches give URLs), the audio URL (music / SFX) or the video
50
+ * URL. The submit is refused with 400 / 403 / 404 when the target is invalid,
51
+ * the row is missing or the caller may not update it.
52
+ */
53
+ export interface SaveTarget {
54
+ /** Entity name, e.g. `'Creation'`. */
55
+ entity: string;
56
+ /** The row's id. */
57
+ id: string | number;
58
+ /** The field that receives the result, e.g. `'image_url'`. */
59
+ field: string;
35
60
  }
36
61
 
37
62
  export type JobKind =
@@ -77,10 +102,42 @@ export interface RememberedJob {
77
102
  result?: any;
78
103
  resultOmitted?: boolean;
79
104
  error?: string;
105
+ /** The page that started it: path, plus the `#/…` route of a hash router (≥ 1.17.0). */
106
+ page?: string;
107
+ /** Prompt (or last user message), shortened — what the background notice shows. */
108
+ label?: string;
109
+ /** Background-notice bookkeeping (≥ 1.17.0). */
110
+ bg?: 1;
111
+ /** The user left its page while it ran. */
112
+ orphaned?: boolean;
113
+ /** It finished where a page showed it. */
114
+ delivered?: boolean;
115
+ /** The user closed its card in the notice. */
116
+ dismissed?: boolean;
117
+ /** Replaced by a re-run, or no longer readable — never shown. */
118
+ hidden?: boolean;
80
119
  createdAt: number;
81
120
  updatedAt: number;
82
121
  }
83
122
 
123
+ /** A job picked up again with `jobs.attach()`. */
124
+ export interface AttachedJob<T = any> {
125
+ jobId: string;
126
+ kind: JobKind;
127
+ tag?: string;
128
+ status: 'processing' | 'succeeded' | 'failed';
129
+ /** Already known when it succeeded (absent when it was too large to keep). */
130
+ result?: T;
131
+ error?: string;
132
+ /**
133
+ * Resolves with what the starting call resolved with — at once when it
134
+ * already finished, else when it does (also after a page change or a
135
+ * reload). Rejects with an AIFlowError when it failed. Reading it tells the
136
+ * background notice that this page shows the job.
137
+ */
138
+ readonly done: Promise<T>;
139
+ }
140
+
84
141
  export interface JobsNamespace {
85
142
  /** Newest remembered job with this tag (any tag when omitted), or null. */
86
143
  latest(tag?: string): RememberedJob | null;
@@ -88,6 +145,22 @@ export interface JobsNamespace {
88
145
  list(filter?: { tag?: string }): RememberedJob[];
89
146
  /** Forget one job (by id) or every job with a tag. */
90
147
  forget(jobIdOrTag: string): void;
148
+ /**
149
+ * Pick a job up again on mount: the newest one with `tag` (with no tag,
150
+ * the newest one started from the current page), or null. The page now
151
+ * shows it, so the background notice hides it.
152
+ */
153
+ attach<T = any>(tag?: string): AttachedJob<T> | null;
154
+ }
155
+
156
+ /** Page-wide settings for the background notice. */
157
+ export interface BackgroundNoticeOptions {
158
+ /** Default true in browsers. Also off when `window.__AIFLOW_BACKGROUND_NOTICE__ === false`. */
159
+ enabled?: boolean;
160
+ /** Default `'bottom-left'`. */
161
+ position?: 'bottom-left' | 'bottom-right';
162
+ /** `'en' | 'ko' | 'vi' | 'ja' | 'zh'`; default from `<html lang>`, then the browser. */
163
+ locale?: string | null;
91
164
  }
92
165
 
93
166
  export type ChatRole = 'system' | 'user' | 'assistant';
@@ -143,6 +216,7 @@ export interface ChatRequest {
143
216
  timeout?: number;
144
217
  onJob?: BackgroundJobOptions['onJob'];
145
218
  tag?: string;
219
+ saveTo?: SaveTarget;
146
220
  }
147
221
 
148
222
  export interface ChatUsage {
@@ -184,13 +258,14 @@ export interface ImageRequest {
184
258
  model?: string;
185
259
  size?: '512x512' | '1024x1024' | '1024x1792' | string;
186
260
  /**
187
- * Output aspect ratio for the Gemini image models — wins over the ratio
188
- * `size` implies and over an input image's ratio. GPT image models ignore
189
- * it (use `size`).
261
+ * Output aspect ratio for the Gemini and Seedream image models — wins over
262
+ * the ratio `size` implies and over an input image's ratio. GPT image
263
+ * models ignore it (use `size`).
190
264
  */
191
265
  aspectRatio?: '1:1' | '2:3' | '3:2' | '3:4' | '4:3' | '9:16' | '16:9' | '21:9';
192
266
  n?: number;
193
267
  image?: string;
268
+ /** More input images to combine; with `image`, at most 16 (10 on `seedream`). */
194
269
  images?: string[];
195
270
  /**
196
271
  * System prompt for image generation/editing (e.g. a translation
@@ -217,6 +292,7 @@ export interface ImageRequest {
217
292
  timeout?: number;
218
293
  onJob?: BackgroundJobOptions['onJob'];
219
294
  tag?: string;
295
+ saveTo?: SaveTarget;
220
296
  }
221
297
 
222
298
  export interface GeneratedImage {
@@ -269,6 +345,7 @@ export interface ImageBatchRequest {
269
345
  timeout?: number;
270
346
  onJob?: BackgroundJobOptions['onJob'];
271
347
  tag?: string;
348
+ saveTo?: SaveTarget;
272
349
  }
273
350
 
274
351
  export interface ImageBatchPageResult {
@@ -373,6 +450,7 @@ export interface VideoRequest {
373
450
  /** `generateVideo` only — see {@link BackgroundJobOptions}. */
374
451
  onJob?: BackgroundJobOptions['onJob'];
375
452
  tag?: string;
453
+ saveTo?: SaveTarget;
376
454
  }
377
455
 
378
456
  export interface VideoResponse {
@@ -528,6 +606,8 @@ export interface VideoSessionRequest {
528
606
  targetDurationSeconds?: number;
529
607
  signal?: AbortSignal;
530
608
  timeout?: number;
609
+ /** Write the opening clip's (or a build's) video URL into this row when it ends. */
610
+ saveTo?: SaveTarget;
531
611
  }
532
612
 
533
613
  /** Progress of an auto-build, reported after each completed segment. */
@@ -571,6 +651,7 @@ export interface LongVideoRequest {
571
651
  /** Receives the build's job id (and `sessionId`) as soon as it starts. */
572
652
  onJob?: BackgroundJobOptions['onJob'];
573
653
  tag?: string;
654
+ saveTo?: SaveTarget;
574
655
  }
575
656
 
576
657
  export interface LongVideoResponse extends VideoResponse {
@@ -684,6 +765,7 @@ export interface AudioRequest {
684
765
  timeout?: number;
685
766
  onJob?: BackgroundJobOptions['onJob'];
686
767
  tag?: string;
768
+ saveTo?: SaveTarget;
687
769
  }
688
770
 
689
771
  export interface AudioResponse {
@@ -723,6 +805,7 @@ export interface SfxRequest {
723
805
  timeout?: number;
724
806
  onJob?: BackgroundJobOptions['onJob'];
725
807
  tag?: string;
808
+ saveTo?: SaveTarget;
726
809
  }
727
810
 
728
811
  export interface SfxResponse {
@@ -967,6 +1050,8 @@ export interface AIFlowClientOptions {
967
1050
  timeout?: number;
968
1051
  maxRetries?: number;
969
1052
  fetch?: typeof fetch;
1053
+ /** `false` turns off the background notice for the whole page. */
1054
+ backgroundNotice?: boolean;
970
1055
  }
971
1056
 
972
1057
  export interface AiflowConfig {
@@ -1047,8 +1132,11 @@ export interface AiflowConfig {
1047
1132
  webSearch?: boolean;
1048
1133
  /** Whether the real-time live-translate feature is enabled. */
1049
1134
  liveTranslate?: boolean;
1050
- /** Gateway features. `jobs`: generations run as background jobs. */
1051
- capabilities?: { jobs?: boolean };
1135
+ /**
1136
+ * Gateway features. `jobs`: generations run as background jobs. `saveTo`:
1137
+ * the gateway writes results into rows (`saveTo` option).
1138
+ */
1139
+ capabilities?: { jobs?: boolean; saveTo?: boolean };
1052
1140
  }
1053
1141
 
1054
1142
  // ─── Admin (module config) ───────────────────────────────────────────────────
@@ -1126,6 +1214,13 @@ export class AIFlowClient {
1126
1214
 
1127
1215
  constructor(options: AIFlowClientOptions);
1128
1216
 
1217
+ /**
1218
+ * Configure the background notice for the whole page — the small panel
1219
+ * that tells a user who left a page mid-generation that it keeps going,
1220
+ * then shows the result with a way back to the page.
1221
+ */
1222
+ static configureBackgroundNotice(options: BackgroundNoticeOptions): void;
1223
+
1129
1224
  /**
1130
1225
  * Set (or clear with `null`) the current end user. Call after your app
1131
1226
  * authenticates a user, passing the user's id AND their access token (from
@@ -1281,6 +1376,7 @@ export class AIFlowClient {
1281
1376
  * that started it resolves with. Works after a reload or on another page.
1282
1377
  * Aborting `signal` / hitting `timeout` (default 30 min) stops only the
1283
1378
  * waiting. Throws an AIFlowError (`status`, `code`) when the job failed.
1379
+ * The page now shows the job, so the background notice hides it.
1284
1380
  */
1285
1381
  waitForJob<T = any>(
1286
1382
  jobId: string,