@devvibex/aiflow 1.16.1 → 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 +100 -31
  2. package/package.json +1 -1
  3. package/src/index.d.ts +100 -6
  4. package/src/index.js +1459 -62
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,50 +146,117 @@ 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
261
  503) and is not charged — credits are deducted only on success. `chat`,
194
262
  `generateImage`, `generateImageBatch`, `generateAudio` and `generateSfx` submit
@@ -199,10 +267,11 @@ id); `waitForJob` on a stored id and `chatStream` throw it, so offer a retry.
199
267
 
200
268
  Returns `{ images: [{ url?, b64?, mimeType }], usage: { creditsUsed } }`.
201
269
  `url` is a short-lived signed URL (~1h). Pass `image`/`images` to edit an
202
- 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`.
203
272
  `aspectRatio` (`'1:1'`, `'2:3'`, `'3:2'`, `'3:4'`, `'4:3'`, `'9:16'`, `'16:9'`,
204
- `'21:9'`) sets the frame on the Gemini image models; GPT image models use
205
- `size` instead. `background`
273
+ `'21:9'`) sets the frame on the Gemini and Seedream image models; GPT image
274
+ models use `size` instead. `background`
206
275
  (`'auto'` | `'transparent'` | `'opaque'`) is honoured only by the models in
207
276
  `config.imageBackgroundModels`; `generateImageBatch` takes it top-level or per
208
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.1",
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
@@ -32,8 +32,31 @@ export interface BackgroundJobOptions {
32
32
  * music and SFX calls do that automatically).
33
33
  */
34
34
  onJob?: (jobId: string, info?: { sessionId?: string }) => void;
35
- /** 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). */
36
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;
37
60
  }
38
61
 
39
62
  export type JobKind =
@@ -79,10 +102,42 @@ export interface RememberedJob {
79
102
  result?: any;
80
103
  resultOmitted?: boolean;
81
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;
82
119
  createdAt: number;
83
120
  updatedAt: number;
84
121
  }
85
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
+
86
141
  export interface JobsNamespace {
87
142
  /** Newest remembered job with this tag (any tag when omitted), or null. */
88
143
  latest(tag?: string): RememberedJob | null;
@@ -90,6 +145,22 @@ export interface JobsNamespace {
90
145
  list(filter?: { tag?: string }): RememberedJob[];
91
146
  /** Forget one job (by id) or every job with a tag. */
92
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;
93
164
  }
94
165
 
95
166
  export type ChatRole = 'system' | 'user' | 'assistant';
@@ -145,6 +216,7 @@ export interface ChatRequest {
145
216
  timeout?: number;
146
217
  onJob?: BackgroundJobOptions['onJob'];
147
218
  tag?: string;
219
+ saveTo?: SaveTarget;
148
220
  }
149
221
 
150
222
  export interface ChatUsage {
@@ -186,13 +258,14 @@ export interface ImageRequest {
186
258
  model?: string;
187
259
  size?: '512x512' | '1024x1024' | '1024x1792' | string;
188
260
  /**
189
- * Output aspect ratio for the Gemini image models — wins over the ratio
190
- * `size` implies and over an input image's ratio. GPT image models ignore
191
- * 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`).
192
264
  */
193
265
  aspectRatio?: '1:1' | '2:3' | '3:2' | '3:4' | '4:3' | '9:16' | '16:9' | '21:9';
194
266
  n?: number;
195
267
  image?: string;
268
+ /** More input images to combine; with `image`, at most 16 (10 on `seedream`). */
196
269
  images?: string[];
197
270
  /**
198
271
  * System prompt for image generation/editing (e.g. a translation
@@ -219,6 +292,7 @@ export interface ImageRequest {
219
292
  timeout?: number;
220
293
  onJob?: BackgroundJobOptions['onJob'];
221
294
  tag?: string;
295
+ saveTo?: SaveTarget;
222
296
  }
223
297
 
224
298
  export interface GeneratedImage {
@@ -271,6 +345,7 @@ export interface ImageBatchRequest {
271
345
  timeout?: number;
272
346
  onJob?: BackgroundJobOptions['onJob'];
273
347
  tag?: string;
348
+ saveTo?: SaveTarget;
274
349
  }
275
350
 
276
351
  export interface ImageBatchPageResult {
@@ -375,6 +450,7 @@ export interface VideoRequest {
375
450
  /** `generateVideo` only — see {@link BackgroundJobOptions}. */
376
451
  onJob?: BackgroundJobOptions['onJob'];
377
452
  tag?: string;
453
+ saveTo?: SaveTarget;
378
454
  }
379
455
 
380
456
  export interface VideoResponse {
@@ -530,6 +606,8 @@ export interface VideoSessionRequest {
530
606
  targetDurationSeconds?: number;
531
607
  signal?: AbortSignal;
532
608
  timeout?: number;
609
+ /** Write the opening clip's (or a build's) video URL into this row when it ends. */
610
+ saveTo?: SaveTarget;
533
611
  }
534
612
 
535
613
  /** Progress of an auto-build, reported after each completed segment. */
@@ -573,6 +651,7 @@ export interface LongVideoRequest {
573
651
  /** Receives the build's job id (and `sessionId`) as soon as it starts. */
574
652
  onJob?: BackgroundJobOptions['onJob'];
575
653
  tag?: string;
654
+ saveTo?: SaveTarget;
576
655
  }
577
656
 
578
657
  export interface LongVideoResponse extends VideoResponse {
@@ -686,6 +765,7 @@ export interface AudioRequest {
686
765
  timeout?: number;
687
766
  onJob?: BackgroundJobOptions['onJob'];
688
767
  tag?: string;
768
+ saveTo?: SaveTarget;
689
769
  }
690
770
 
691
771
  export interface AudioResponse {
@@ -725,6 +805,7 @@ export interface SfxRequest {
725
805
  timeout?: number;
726
806
  onJob?: BackgroundJobOptions['onJob'];
727
807
  tag?: string;
808
+ saveTo?: SaveTarget;
728
809
  }
729
810
 
730
811
  export interface SfxResponse {
@@ -969,6 +1050,8 @@ export interface AIFlowClientOptions {
969
1050
  timeout?: number;
970
1051
  maxRetries?: number;
971
1052
  fetch?: typeof fetch;
1053
+ /** `false` turns off the background notice for the whole page. */
1054
+ backgroundNotice?: boolean;
972
1055
  }
973
1056
 
974
1057
  export interface AiflowConfig {
@@ -1049,8 +1132,11 @@ export interface AiflowConfig {
1049
1132
  webSearch?: boolean;
1050
1133
  /** Whether the real-time live-translate feature is enabled. */
1051
1134
  liveTranslate?: boolean;
1052
- /** Gateway features. `jobs`: generations run as background jobs. */
1053
- 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 };
1054
1140
  }
1055
1141
 
1056
1142
  // ─── Admin (module config) ───────────────────────────────────────────────────
@@ -1128,6 +1214,13 @@ export class AIFlowClient {
1128
1214
 
1129
1215
  constructor(options: AIFlowClientOptions);
1130
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
+
1131
1224
  /**
1132
1225
  * Set (or clear with `null`) the current end user. Call after your app
1133
1226
  * authenticates a user, passing the user's id AND their access token (from
@@ -1283,6 +1376,7 @@ export class AIFlowClient {
1283
1376
  * that started it resolves with. Works after a reload or on another page.
1284
1377
  * Aborting `signal` / hitting `timeout` (default 30 min) stops only the
1285
1378
  * waiting. Throws an AIFlowError (`status`, `code`) when the job failed.
1379
+ * The page now shows the job, so the background notice hides it.
1286
1380
  */
1287
1381
  waitForJob<T = any>(
1288
1382
  jobId: string,