@devvibex/aiflow 1.16.1 → 1.17.1

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
@@ -145,50 +145,96 @@ away from, and keeps the result for a week. The calls resolve with exactly the
145
145
  same value as before; on an older gateway they fall back to one synchronous
146
146
  request.
147
147
 
148
- Every generation call takes two extra options:
148
+ Every generation call takes these extra options:
149
149
 
150
150
  | Option | |
151
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()`. |
152
+ | `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. |
153
+ | `tag` | A label (≤ 128 chars) for `jobs.attach(tag)`, `jobs.latest(tag)` and `listJobs()`. |
154
+ | `onJob(jobId, info?)` | Fires once the gateway has accepted the job, before it finishes. |
154
155
 
155
- Aborting `signal` now **stops only the waiting** — the generation carries on
156
- and stays retrievable.
156
+ Aborting `signal` **stops only the waiting** — the generation carries on and
157
+ stays retrievable.
158
+
159
+ ### Features that save their results — `saveTo` (≥ 1.17.0)
160
+
161
+ Create the row first, then name it in `saveTo`. When the job ends, the gateway
162
+ writes into the row itself:
163
+
164
+ | When | Written (only the fields the entity has) |
165
+ | --- | --- |
166
+ | accepted | `job_id` |
167
+ | succeeded | `{ [field]: value, status: 'done' }` |
168
+ | failed | `{ status: 'failed', error }` |
169
+
170
+ `value` is the answer text (`chat` / `chatStream`), the image URL (every URL
171
+ when `field` is an array; image batches give URLs), the audio URL
172
+ (`generateAudio` / `generateSfx`) or the video URL (`generateVideo`,
173
+ `generateLongVideo`). The submit is refused (400 / 403 / 404) when the target
174
+ is invalid, the row does not exist or the signed-in user may not update it —
175
+ the same rules as the app's own data API.
157
176
 
158
177
  ```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 });
178
+ const row = await Creation.create({ prompt, status: 'generating' });
179
+ try {
180
+ const res = await aiflow.generateImage({
181
+ prompt,
182
+ saveTo: { entity: 'Creation', id: row.id, field: 'image_url' },
183
+ });
184
+ // Already saved by the gateway; this keeps the page instant.
185
+ await Creation.update(row.id, { status: 'done', image_url: res.images[0].url });
186
+ } catch (err) {
187
+ await Creation.update(row.id, { status: 'failed', error: err.message });
188
+ }
166
189
 
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
190
+ // Wherever the rows are listed: refresh while any is still generating.
191
+ useEffect(() => {
192
+ if (!rows.some((r) => r.status === 'generating')) return;
193
+ const timer = setInterval(reload, 5000);
194
+ return () => clearInterval(timer);
195
+ }, [rows]);
169
196
  ```
170
197
 
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. |
198
+ `saveTo` needs `config.capabilities.saveTo`; an older gateway ignores it (the
199
+ SDK warns once in the console), so keep saving from the resolved value as
200
+ above.
201
+
202
+ ### Features that keep the result only on screen — `jobs.attach` (≥ 1.17.0)
178
203
 
179
- Without a database row, the browser's own record is enough for a page that
180
- shows its latest result:
204
+ Pass a `tag`, and pick the job up again on mount. `jobs.attach(tag)` returns
205
+ `null` or `{ jobId, kind, tag, status, result?, error?, done }`; `done`
206
+ resolves with what the starting call resolved with — at once when it already
207
+ finished, or when it does (also after a page change or a reload):
181
208
 
182
209
  ```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));
210
+ useEffect(() => {
211
+ const job = aiflow.jobs.attach('poster');
212
+ if (!job || job.status === 'failed') return; // an earlier failure: start fresh
213
+ if (job.status === 'processing') setLoading(true);
214
+ job.done
215
+ .then((res) => setImages(res.images))
216
+ .catch((err) => toast.error(err.message))
217
+ .finally(() => setLoading(false));
218
+ }, []);
187
219
 
188
- // Generate
189
220
  const res = await aiflow.generateImage({ prompt, tag: 'poster' });
190
221
  ```
191
222
 
223
+ Without a tag, `jobs.attach()` picks the newest job started from the current
224
+ page. A job still running joins the wait already open on the page, so it is
225
+ not polled twice.
226
+
227
+ ### Job methods
228
+
229
+ | Method | |
230
+ | --- | --- |
231
+ | `jobs.attach(tag?)` | See above. |
232
+ | `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. |
233
+ | `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. |
234
+ | `getJob(jobId, { waitMs? })` | One job now: `{ jobId, kind, status, tag?, prompt?, result?, error?, errorStatus?, errorCode? }`. |
235
+ | `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`. |
236
+ | `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? }`. Works without login. |
237
+
192
238
  A job whose server restarted mid-way fails with `code: 'interrupted'` (status
193
239
  503) and is not charged — credits are deducted only on success. `chat`,
194
240
  `generateImage`, `generateImageBatch`, `generateAudio` and `generateSfx` submit
@@ -199,10 +245,11 @@ id); `waitForJob` on a stored id and `chatStream` throw it, so offer a retry.
199
245
 
200
246
  Returns `{ images: [{ url?, b64?, mimeType }], usage: { creditsUsed } }`.
201
247
  `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.
248
+ existing image (image-to-image) instead of generating from text — up to 16 input
249
+ images per call, 10 on `seedream`.
203
250
  `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`
251
+ `'21:9'`) sets the frame on the Gemini and Seedream image models; GPT image
252
+ models use `size` instead. `background`
206
253
  (`'auto'` | `'transparent'` | `'opaque'`) is honoured only by the models in
207
254
  `config.imageBackgroundModels`; `generateImageBatch` takes it top-level or per
208
255
  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.1",
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,29 @@ 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;
82
107
  createdAt: number;
83
108
  updatedAt: number;
84
109
  }
85
110
 
111
+ /** A job picked up again with `jobs.attach()`. */
112
+ export interface AttachedJob<T = any> {
113
+ jobId: string;
114
+ kind: JobKind;
115
+ tag?: string;
116
+ status: 'processing' | 'succeeded' | 'failed';
117
+ /** Already known when it succeeded (absent when it was too large to keep). */
118
+ result?: T;
119
+ error?: string;
120
+ /**
121
+ * Resolves with what the starting call resolved with — at once when it
122
+ * already finished, else when it does (also after a page change or a
123
+ * reload). Rejects with an AIFlowError when it failed.
124
+ */
125
+ readonly done: Promise<T>;
126
+ }
127
+
86
128
  export interface JobsNamespace {
87
129
  /** Newest remembered job with this tag (any tag when omitted), or null. */
88
130
  latest(tag?: string): RememberedJob | null;
@@ -90,6 +132,11 @@ export interface JobsNamespace {
90
132
  list(filter?: { tag?: string }): RememberedJob[];
91
133
  /** Forget one job (by id) or every job with a tag. */
92
134
  forget(jobIdOrTag: string): void;
135
+ /**
136
+ * Pick a job up again on mount: the newest one with `tag` (with no tag,
137
+ * the newest one started from the current page), or null.
138
+ */
139
+ attach<T = any>(tag?: string): AttachedJob<T> | null;
93
140
  }
94
141
 
95
142
  export type ChatRole = 'system' | 'user' | 'assistant';
@@ -145,6 +192,7 @@ export interface ChatRequest {
145
192
  timeout?: number;
146
193
  onJob?: BackgroundJobOptions['onJob'];
147
194
  tag?: string;
195
+ saveTo?: SaveTarget;
148
196
  }
149
197
 
150
198
  export interface ChatUsage {
@@ -186,13 +234,14 @@ export interface ImageRequest {
186
234
  model?: string;
187
235
  size?: '512x512' | '1024x1024' | '1024x1792' | string;
188
236
  /**
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`).
237
+ * Output aspect ratio for the Gemini and Seedream image models — wins over
238
+ * the ratio `size` implies and over an input image's ratio. GPT image
239
+ * models ignore it (use `size`).
192
240
  */
193
241
  aspectRatio?: '1:1' | '2:3' | '3:2' | '3:4' | '4:3' | '9:16' | '16:9' | '21:9';
194
242
  n?: number;
195
243
  image?: string;
244
+ /** More input images to combine; with `image`, at most 16 (10 on `seedream`). */
196
245
  images?: string[];
197
246
  /**
198
247
  * System prompt for image generation/editing (e.g. a translation
@@ -219,6 +268,7 @@ export interface ImageRequest {
219
268
  timeout?: number;
220
269
  onJob?: BackgroundJobOptions['onJob'];
221
270
  tag?: string;
271
+ saveTo?: SaveTarget;
222
272
  }
223
273
 
224
274
  export interface GeneratedImage {
@@ -271,6 +321,7 @@ export interface ImageBatchRequest {
271
321
  timeout?: number;
272
322
  onJob?: BackgroundJobOptions['onJob'];
273
323
  tag?: string;
324
+ saveTo?: SaveTarget;
274
325
  }
275
326
 
276
327
  export interface ImageBatchPageResult {
@@ -375,6 +426,7 @@ export interface VideoRequest {
375
426
  /** `generateVideo` only — see {@link BackgroundJobOptions}. */
376
427
  onJob?: BackgroundJobOptions['onJob'];
377
428
  tag?: string;
429
+ saveTo?: SaveTarget;
378
430
  }
379
431
 
380
432
  export interface VideoResponse {
@@ -530,6 +582,8 @@ export interface VideoSessionRequest {
530
582
  targetDurationSeconds?: number;
531
583
  signal?: AbortSignal;
532
584
  timeout?: number;
585
+ /** Write the opening clip's (or a build's) video URL into this row when it ends. */
586
+ saveTo?: SaveTarget;
533
587
  }
534
588
 
535
589
  /** Progress of an auto-build, reported after each completed segment. */
@@ -573,6 +627,7 @@ export interface LongVideoRequest {
573
627
  /** Receives the build's job id (and `sessionId`) as soon as it starts. */
574
628
  onJob?: BackgroundJobOptions['onJob'];
575
629
  tag?: string;
630
+ saveTo?: SaveTarget;
576
631
  }
577
632
 
578
633
  export interface LongVideoResponse extends VideoResponse {
@@ -686,6 +741,7 @@ export interface AudioRequest {
686
741
  timeout?: number;
687
742
  onJob?: BackgroundJobOptions['onJob'];
688
743
  tag?: string;
744
+ saveTo?: SaveTarget;
689
745
  }
690
746
 
691
747
  export interface AudioResponse {
@@ -725,6 +781,7 @@ export interface SfxRequest {
725
781
  timeout?: number;
726
782
  onJob?: BackgroundJobOptions['onJob'];
727
783
  tag?: string;
784
+ saveTo?: SaveTarget;
728
785
  }
729
786
 
730
787
  export interface SfxResponse {
@@ -1049,8 +1106,11 @@ export interface AiflowConfig {
1049
1106
  webSearch?: boolean;
1050
1107
  /** Whether the real-time live-translate feature is enabled. */
1051
1108
  liveTranslate?: boolean;
1052
- /** Gateway features. `jobs`: generations run as background jobs. */
1053
- capabilities?: { jobs?: boolean };
1109
+ /**
1110
+ * Gateway features. `jobs`: generations run as background jobs. `saveTo`:
1111
+ * the gateway writes results into rows (`saveTo` option).
1112
+ */
1113
+ capabilities?: { jobs?: boolean; saveTo?: boolean };
1054
1114
  }
1055
1115
 
1056
1116
  // ─── Admin (module config) ───────────────────────────────────────────────────
package/src/index.js CHANGED
@@ -177,7 +177,8 @@ export class AIFlowClient {
177
177
  * (localStorage; in memory where there is none) so a page can show a
178
178
  * generation that finished, or is still running, after the user left
179
179
  * and came back. Entries: `{ jobId, kind, tag, status, result?, error?,
180
- * createdAt, updatedAt }`; `result` is what the call resolved with.
180
+ * page?, createdAt, updatedAt }`; `result` is what the call resolved
181
+ * with.
181
182
  */
182
183
  this.jobs = {
183
184
  /** Newest remembered job with this tag (any tag when omitted), or null. */
@@ -186,6 +187,14 @@ export class AIFlowClient {
186
187
  list: ({ tag } = {}) => this._jobStore.list(tag),
187
188
  /** Forget one job (by id) or every job with a tag. */
188
189
  forget: (jobIdOrTag) => this._jobStore.forget(jobIdOrTag),
190
+ /**
191
+ * Pick a job up again on mount: the newest job with this tag (with no
192
+ * tag, the newest one started from the current page), or null.
193
+ * Returns `{ jobId, kind, tag, status, result?, error?, done }` —
194
+ * `done` resolves with what the starting call resolved with, also
195
+ * for a job still running after a page change or a reload.
196
+ */
197
+ attach: (tag) => this._attachJob(tag),
189
198
  };
190
199
  }
191
200
 
@@ -328,7 +337,9 @@ export class AIFlowClient {
328
337
  * applies (on by default).
329
338
  *
330
339
  * Runs as a background job (see {@link waitForJob}): `onJob(jobId)` fires
331
- * once the gateway has accepted it, `tag` labels it in `jobs.latest()`.
340
+ * once the gateway has accepted it, `tag` labels it in `jobs.latest()`,
341
+ * and `saveTo: { entity, id, field }` has the gateway write the answer
342
+ * into that row when the job ends (see {@link _generate}).
332
343
  * @returns {Promise<{id:string, model:string, content:string, usage:{inputTokens:number,outputTokens:number,creditsUsed:number}}>}
333
344
  */
334
345
  async chat({
@@ -343,11 +354,13 @@ export class AIFlowClient {
343
354
  timeout,
344
355
  onJob,
345
356
  tag,
357
+ saveTo,
346
358
  } = {}) {
347
359
  if (!Array.isArray(messages) || messages.length === 0) {
348
360
  throw new AIFlowError('messages must be a non-empty array');
349
361
  }
350
362
  assertNoTools(tools);
363
+ assertSaveTo(saveTo);
351
364
  const resolvedModel = model || (await this._resolveDefaultModel('chat'));
352
365
  const resolvedSystem = await this._resolveSystemPrompt(system);
353
366
  return this._generate({
@@ -365,6 +378,7 @@ export class AIFlowClient {
365
378
  timeout,
366
379
  onJob,
367
380
  tag,
381
+ saveTo,
368
382
  });
369
383
  }
370
384
 
@@ -379,7 +393,8 @@ export class AIFlowClient {
379
393
  * written on the gateway — pick it up with {@link resumeChatStream} or
380
394
  * {@link waitForJob}. `onJob(jobId)` fires as soon as the job id is known;
381
395
  * a dropped connection is re-attached automatically. A server error frame
382
- * (e.g. 402, out of credits) throws an AIFlowError.
396
+ * (e.g. 402, out of credits) throws an AIFlowError. With `saveTo`, the
397
+ * gateway writes the finished answer into that row itself.
383
398
  */
384
399
  async *chatStream({
385
400
  messages,
@@ -392,15 +407,17 @@ export class AIFlowClient {
392
407
  signal,
393
408
  onJob,
394
409
  tag,
410
+ saveTo,
395
411
  } = {}) {
396
412
  if (!Array.isArray(messages) || messages.length === 0) {
397
413
  throw new AIFlowError('messages must be a non-empty array');
398
414
  }
399
415
  assertNoTools(tools);
416
+ assertSaveTo(saveTo);
400
417
  const resolvedModel = model || (await this._resolveDefaultModel('chat'));
401
418
  const resolvedSystem = await this._resolveSystemPrompt(system);
402
419
  const res = await this._request(
403
- `/chat/stream${tagQuery(tag)}`,
420
+ `/chat/stream${await this._jobQuery({ tag, saveTo })}`,
404
421
  {
405
422
  model: resolvedModel,
406
423
  system: resolvedSystem,
@@ -554,10 +571,12 @@ export class AIFlowClient {
554
571
  timeout,
555
572
  onJob,
556
573
  tag,
574
+ saveTo,
557
575
  } = {}) {
558
576
  if (!prompt || typeof prompt !== 'string') {
559
577
  throw new AIFlowError('prompt is required');
560
578
  }
579
+ assertSaveTo(saveTo);
561
580
  const resolvedModel =
562
581
  model || (await this._resolveDefaultModel('image'));
563
582
  // Resolve the system prompt: user-provided > server config > null,
@@ -591,6 +610,7 @@ export class AIFlowClient {
591
610
  requestTimeout: 180_000,
592
611
  onJob,
593
612
  tag,
613
+ saveTo,
594
614
  });
595
615
  }
596
616
 
@@ -618,10 +638,12 @@ export class AIFlowClient {
618
638
  timeout,
619
639
  onJob,
620
640
  tag,
641
+ saveTo,
621
642
  } = {}) {
622
643
  if (!Array.isArray(pages) || pages.length === 0) {
623
644
  throw new AIFlowError('pages must be a non-empty array');
624
645
  }
646
+ assertSaveTo(saveTo);
625
647
  const resolvedModel =
626
648
  model || (await this._resolveDefaultModel('image'));
627
649
  const resolvedSystem = await this._resolveSystemPrompt(system);
@@ -646,6 +668,7 @@ export class AIFlowClient {
646
668
  requestTimeout: 600_000,
647
669
  onJob,
648
670
  tag,
671
+ saveTo,
649
672
  });
650
673
  }
651
674
 
@@ -659,7 +682,8 @@ export class AIFlowClient {
659
682
  * unchanged from earlier SDK versions, so existing code keeps working.
660
683
  *
661
684
  * For finer control (e.g. your own polling UI) use {@link submitVideoJob}
662
- * + {@link getVideoJob} directly.
685
+ * + {@link getVideoJob} directly. `saveTo: { entity, id, field }` has the
686
+ * gateway write the video URL into that row when the job ends.
663
687
  *
664
688
  * @returns {Promise<{videoUrl:string, thumbnailUrl?:string, prompt?:string, usage:{creditsUsed:number}}>}
665
689
  */
@@ -669,13 +693,16 @@ export class AIFlowClient {
669
693
  }
670
694
  const { jobId } = await this.submitVideoJob(opts);
671
695
  this._trackJob(jobId, 'video', opts.tag, opts.onJob);
672
- return this._pollVideoJob(jobId, {
673
- signal: opts.signal,
674
- // Overall wait budget across all polls (default 10 min). Each
675
- // individual poll is a short request, so the socket is never held.
676
- timeout: opts.timeout ?? 600_000,
677
- pollIntervalMs: opts.pollIntervalMs,
678
- });
696
+ return this._followJob(
697
+ jobId,
698
+ this._pollVideoJob(jobId, {
699
+ signal: opts.signal,
700
+ // Overall wait budget across all polls (default 10 min). Each
701
+ // individual poll is a short request, so the socket is never held.
702
+ timeout: opts.timeout ?? 600_000,
703
+ pollIntervalMs: opts.pollIntervalMs,
704
+ }),
705
+ );
679
706
  }
680
707
 
681
708
  /**
@@ -699,10 +726,12 @@ export class AIFlowClient {
699
726
  generateAudio,
700
727
  signal,
701
728
  timeout,
729
+ saveTo,
702
730
  } = {}) {
703
731
  if (!prompt || typeof prompt !== 'string') {
704
732
  throw new AIFlowError('prompt is required');
705
733
  }
734
+ assertSaveTo(saveTo);
706
735
  if (lastFrame && !image) {
707
736
  throw new AIFlowError('lastFrame requires image (the first frame)');
708
737
  }
@@ -743,7 +772,7 @@ export class AIFlowClient {
743
772
  const resolvedModel =
744
773
  model || (await this._resolveDefaultModel('video'));
745
774
  const res = await this._request(
746
- '/video/jobs',
775
+ `/video/jobs${await this._jobQuery({ saveTo })}`,
747
776
  {
748
777
  model: resolvedModel,
749
778
  prompt,
@@ -889,14 +918,17 @@ export class AIFlowClient {
889
918
  }
890
919
  const { jobId } = await this.submitVideoMerge({ videos, signal });
891
920
  this._trackJob(jobId, 'video', tag, onJob);
892
- return this._pollVideoJob(jobId, {
893
- signal,
894
- // Every clip is fetched and usually re-encoded on the gateway, so the
895
- // budget scales with how many were handed over.
896
- timeout: timeout ?? Math.max(600_000, videos.length * 120_000),
897
- pollIntervalMs: pollIntervalMs ?? 3_000,
898
- onProgress,
899
- });
921
+ return this._followJob(
922
+ jobId,
923
+ this._pollVideoJob(jobId, {
924
+ signal,
925
+ // Every clip is fetched and usually re-encoded on the gateway, so the
926
+ // budget scales with how many were handed over.
927
+ timeout: timeout ?? Math.max(600_000, videos.length * 120_000),
928
+ pollIntervalMs: pollIntervalMs ?? 3_000,
929
+ onProgress,
930
+ }),
931
+ );
900
932
  }
901
933
 
902
934
  /**
@@ -958,18 +990,20 @@ export class AIFlowClient {
958
990
  targetDurationSeconds,
959
991
  signal,
960
992
  timeout,
993
+ saveTo,
961
994
  } = {}) {
962
995
  if (!prompt && !video) {
963
996
  throw new AIFlowError(
964
997
  'createVideoSession needs either a prompt (to generate the opening clip) or a video (to seed the timeline)',
965
998
  );
966
999
  }
1000
+ assertSaveTo(saveTo);
967
1001
  // `model` is sent only when the caller chose one. Filling it from the
968
1002
  // module default (as every other call does) would name `veo` on a module
969
1003
  // pinned to Veo, and the gateway refuses a session on an explicitly
970
1004
  // named non-Omni model; left out, it resolves to Omni itself.
971
1005
  const res = await this._request(
972
- '/video/sessions',
1006
+ `/video/sessions${await this._jobQuery({ saveTo })}`,
973
1007
  {
974
1008
  model,
975
1009
  prompt,
@@ -1042,6 +1076,7 @@ export class AIFlowClient {
1042
1076
  pollIntervalMs,
1043
1077
  onJob,
1044
1078
  tag,
1079
+ saveTo,
1045
1080
  } = {}) {
1046
1081
  if (!prompt || typeof prompt !== 'string') {
1047
1082
  throw new AIFlowError('prompt is required');
@@ -1060,18 +1095,22 @@ export class AIFlowClient {
1060
1095
  description,
1061
1096
  targetDurationSeconds: durationSeconds,
1062
1097
  signal,
1098
+ saveTo,
1063
1099
  });
1064
1100
  this._trackJob(jobId, 'video', tag, onJob, { sessionId });
1065
- const result = await this._pollVideoJob(jobId, {
1066
- signal,
1067
- timeout: timeout ?? longVideoTimeoutMs(durationSeconds),
1068
- // Minutes-long builds: a 5s poll on a 40-minute job is 480 pointless
1069
- // requests. Progress is published per segment, not per second.
1070
- pollIntervalMs:
1071
- pollIntervalMs ??
1072
- (durationSeconds > CONTINUOUS_MAX_SECONDS ? 15_000 : 5_000),
1073
- onProgress,
1074
- });
1101
+ const result = await this._followJob(
1102
+ jobId,
1103
+ this._pollVideoJob(jobId, {
1104
+ signal,
1105
+ timeout: timeout ?? longVideoTimeoutMs(durationSeconds),
1106
+ // Minutes-long builds: a 5s poll on a 40-minute job is 480 pointless
1107
+ // requests. Progress is published per segment, not per second.
1108
+ pollIntervalMs:
1109
+ pollIntervalMs ??
1110
+ (durationSeconds > CONTINUOUS_MAX_SECONDS ? 15_000 : 5_000),
1111
+ onProgress,
1112
+ }),
1113
+ );
1075
1114
  return { sessionId, ...result };
1076
1115
  }
1077
1116
 
@@ -1115,12 +1154,15 @@ export class AIFlowClient {
1115
1154
  } catch {
1116
1155
  remaining = 600;
1117
1156
  }
1118
- return this._pollVideoJob(jobId, {
1119
- signal,
1120
- timeout: timeout ?? longVideoTimeoutMs(remaining),
1121
- pollIntervalMs: pollIntervalMs ?? 15_000,
1122
- onProgress,
1123
- });
1157
+ return this._followJob(
1158
+ jobId,
1159
+ this._pollVideoJob(jobId, {
1160
+ signal,
1161
+ timeout: timeout ?? longVideoTimeoutMs(remaining),
1162
+ pollIntervalMs: pollIntervalMs ?? 15_000,
1163
+ onProgress,
1164
+ }),
1165
+ );
1124
1166
  }
1125
1167
 
1126
1168
  /**
@@ -1141,11 +1183,14 @@ export class AIFlowClient {
1141
1183
  async extendVideo(sessionId, opts = {}) {
1142
1184
  const { jobId } = await this.submitVideoExtend(sessionId, opts);
1143
1185
  this._trackJob(jobId, 'video', opts.tag, opts.onJob, { sessionId });
1144
- return this._pollVideoJob(jobId, {
1145
- signal: opts.signal,
1146
- timeout: opts.timeout ?? 600_000,
1147
- pollIntervalMs: opts.pollIntervalMs,
1148
- });
1186
+ return this._followJob(
1187
+ jobId,
1188
+ this._pollVideoJob(jobId, {
1189
+ signal: opts.signal,
1190
+ timeout: opts.timeout ?? 600_000,
1191
+ pollIntervalMs: opts.pollIntervalMs,
1192
+ }),
1193
+ );
1149
1194
  }
1150
1195
 
1151
1196
  /**
@@ -1225,6 +1270,7 @@ export class AIFlowClient {
1225
1270
  timeout,
1226
1271
  onJob,
1227
1272
  tag,
1273
+ saveTo,
1228
1274
  } = {}) {
1229
1275
  if (!prompt || typeof prompt !== 'string') {
1230
1276
  throw new AIFlowError('prompt is required');
@@ -1232,6 +1278,7 @@ export class AIFlowClient {
1232
1278
  if (images !== undefined && !Array.isArray(images)) {
1233
1279
  throw new AIFlowError('images must be an array of URLs');
1234
1280
  }
1281
+ assertSaveTo(saveTo);
1235
1282
  const resolvedModel =
1236
1283
  model || (await this._resolveDefaultModel('audio'));
1237
1284
  return this._generate({
@@ -1254,6 +1301,7 @@ export class AIFlowClient {
1254
1301
  requestTimeout: 180_000,
1255
1302
  onJob,
1256
1303
  tag,
1304
+ saveTo,
1257
1305
  });
1258
1306
  }
1259
1307
 
@@ -1271,10 +1319,12 @@ export class AIFlowClient {
1271
1319
  timeout,
1272
1320
  onJob,
1273
1321
  tag,
1322
+ saveTo,
1274
1323
  } = {}) {
1275
1324
  if (!prompt || typeof prompt !== 'string') {
1276
1325
  throw new AIFlowError('prompt is required');
1277
1326
  }
1327
+ assertSaveTo(saveTo);
1278
1328
  const resolvedModel = model || (await this._resolveDefaultModel('sfx'));
1279
1329
  return this._generate({
1280
1330
  kind: 'sfx',
@@ -1291,6 +1341,7 @@ export class AIFlowClient {
1291
1341
  requestTimeout: 120_000,
1292
1342
  onJob,
1293
1343
  tag,
1344
+ saveTo,
1294
1345
  });
1295
1346
  }
1296
1347
 
@@ -1375,6 +1426,14 @@ export class AIFlowClient {
1375
1426
  if (!jobId || typeof jobId !== 'string') {
1376
1427
  throw new AIFlowError('jobId is required');
1377
1428
  }
1429
+ return this._followJob(
1430
+ jobId,
1431
+ this._waitForJob(jobId, { signal, timeout, onProgress }),
1432
+ );
1433
+ }
1434
+
1435
+ /** The wait loop behind {@link waitForJob}; the generation calls use it directly. */
1436
+ async _waitForJob(jobId, { signal, timeout, onProgress } = {}) {
1378
1437
  const deadline = Date.now() + (timeout ?? DEFAULT_JOB_TIMEOUT_MS);
1379
1438
  let lastProgress = -1;
1380
1439
  // eslint-disable-next-line no-constant-condition
@@ -1492,22 +1551,47 @@ export class AIFlowClient {
1492
1551
  * the job route and awaited, so it keeps running — and stays retrievable —
1493
1552
  * if this page goes away; otherwise it is one request to the synchronous
1494
1553
  * route. Both resolve with the same response body.
1554
+ *
1555
+ * `saveTo: { entity, id, field }` (gateways with `capabilities.saveTo`):
1556
+ * the gateway writes the outcome into that row itself, so it lands even
1557
+ * when the tab was closed — `job_id` on accept, then `{ [field]: value,
1558
+ * status: 'done' }` or `{ status: 'failed', error }`, each only where the
1559
+ * entity has the field. `value` is the answer text (chat), the image URL
1560
+ * (all URLs for an array field), the audio URL (music / SFX) or the video
1561
+ * URL. The submit is refused (400 / 403 / 404) when the row is missing or
1562
+ * the caller may not update it.
1495
1563
  */
1496
- async _generate({ kind, path, body, signal, timeout, requestTimeout, onJob, tag }) {
1564
+ async _generate({
1565
+ kind,
1566
+ path,
1567
+ body,
1568
+ signal,
1569
+ timeout,
1570
+ requestTimeout,
1571
+ onJob,
1572
+ tag,
1573
+ saveTo,
1574
+ }) {
1497
1575
  if (await this._jobsEnabled()) {
1498
1576
  const deadline = Date.now() + (timeout ?? DEFAULT_JOB_TIMEOUT_MS);
1577
+ const query = await this._jobQuery({ tag, saveTo });
1578
+ // A re-run belongs to the page the first submit came from.
1579
+ const page = pageKey();
1499
1580
  for (let attempt = 0; ; attempt += 1) {
1500
- const res = await this._request(`${path}/jobs${tagQuery(tag)}`, body, {
1581
+ const res = await this._request(`${path}/jobs${query}`, body, {
1501
1582
  signal,
1502
1583
  timeout: requestTimeout ?? DEFAULT_TIMEOUT_MS,
1503
1584
  });
1504
1585
  const { jobId } = await res.json();
1505
- this._trackJob(jobId, kind, tag, onJob);
1586
+ this._trackJob(jobId, kind, tag, onJob, undefined, { page });
1506
1587
  try {
1507
- return await this.waitForJob(jobId, {
1508
- signal,
1509
- timeout: Math.max(1, deadline - Date.now()),
1510
- });
1588
+ return await this._followJob(
1589
+ jobId,
1590
+ this._waitForJob(jobId, {
1591
+ signal,
1592
+ timeout: Math.max(1, deadline - Date.now()),
1593
+ }),
1594
+ );
1511
1595
  } catch (err) {
1512
1596
  // The gateway pod running the job restarted (a deploy or a
1513
1597
  // scale-down) before it finished. Nothing was charged, so run
@@ -1522,6 +1606,7 @@ export class AIFlowClient {
1522
1606
  }
1523
1607
  }
1524
1608
  }
1609
+ if (saveTo) this._warnSaveToUnsupported();
1525
1610
  const res = await this._request(path, body, {
1526
1611
  signal,
1527
1612
  timeout: timeout ?? requestTimeout,
@@ -1538,10 +1623,61 @@ export class AIFlowClient {
1538
1623
  }
1539
1624
  }
1540
1625
 
1541
- /** Remember a started job and hand its id to the caller's `onJob`. */
1542
- _trackJob(jobId, kind, tag, onJob, extra) {
1626
+ /**
1627
+ * Query string for a job route: `tag`, and `saveTo` as
1628
+ * `saveEntity` / `saveId` / `saveField` when the gateway can write
1629
+ * results into rows (`config.capabilities.saveTo`).
1630
+ */
1631
+ async _jobQuery({ tag, saveTo } = {}) {
1632
+ let save = null;
1633
+ if (saveTo) {
1634
+ let supported = false;
1635
+ try {
1636
+ const cfg = await this.getConfig();
1637
+ supported = cfg?.capabilities?.saveTo === true;
1638
+ } catch {
1639
+ supported = false;
1640
+ }
1641
+ if (supported) save = saveTo;
1642
+ else this._warnSaveToUnsupported();
1643
+ }
1644
+ return jobQuery({ tag, saveTo: save });
1645
+ }
1646
+
1647
+ _warnSaveToUnsupported() {
1648
+ if (this._warnedSaveTo) return;
1649
+ this._warnedSaveTo = true;
1650
+ try {
1651
+ console.warn(
1652
+ '[AIFlow] saveTo is ignored: this gateway cannot write results into rows yet — save the result from the resolved value instead.',
1653
+ );
1654
+ } catch {
1655
+ /* no console */
1656
+ }
1657
+ }
1658
+
1659
+ /**
1660
+ * Register `promise` as the page's wait for `jobId` (the starting call's
1661
+ * own wait), so `jobs.attach()` joins it instead of starting a second
1662
+ * one. Returns `promise`.
1663
+ */
1664
+ _followJob(jobId, promise) {
1665
+ return jobWaits().track(jobId, promise);
1666
+ }
1667
+
1668
+ /**
1669
+ * Remember a started job and hand its id to the caller's `onJob`.
1670
+ * `meta.page`: the page it belongs to (default: the current one).
1671
+ */
1672
+ _trackJob(jobId, kind, tag, onJob, extra, meta = {}) {
1543
1673
  if (!jobId) return;
1544
- this._jobStore.put({ jobId, kind, tag, status: 'processing' });
1674
+ this._jobStore.put({
1675
+ jobId,
1676
+ kind,
1677
+ tag,
1678
+ status: 'processing',
1679
+ page: meta.page ?? pageKey(),
1680
+ });
1545
1681
  if (typeof onJob === 'function') {
1546
1682
  try {
1547
1683
  onJob(jobId, extra);
@@ -1552,6 +1688,46 @@ export class AIFlowClient {
1552
1688
  }
1553
1689
  }
1554
1690
 
1691
+ /** `jobs.attach(tag?)` — see the constructor. */
1692
+ _attachJob(tag) {
1693
+ const page = pageKey();
1694
+ const entries = this._jobStore.list(tag);
1695
+ const entry =
1696
+ tag === undefined || tag === null
1697
+ ? entries.find((e) => (e.page ?? '') === page)
1698
+ : entries[0];
1699
+ if (!entry) return null;
1700
+ const client = this;
1701
+ const status = entry.status === 'queued' ? 'processing' : entry.status;
1702
+ let done = null;
1703
+ return {
1704
+ jobId: entry.jobId,
1705
+ kind: entry.kind,
1706
+ tag: entry.tag,
1707
+ status,
1708
+ ...(entry.result !== undefined ? { result: entry.result } : {}),
1709
+ ...(entry.error ? { error: entry.error } : {}),
1710
+ // Created on first read, so an attached failure nobody asked about
1711
+ // never surfaces as an unhandled rejection.
1712
+ get done() {
1713
+ if (!done) {
1714
+ if (status === 'succeeded' && entry.result !== undefined) {
1715
+ done = Promise.resolve(entry.result);
1716
+ } else if (status === 'failed') {
1717
+ done = Promise.reject(
1718
+ new AIFlowError(entry.error || 'Generation failed', {
1719
+ code: 'job_failed',
1720
+ }),
1721
+ );
1722
+ } else {
1723
+ done = jobWaits().wait(client, entry.jobId);
1724
+ }
1725
+ }
1726
+ return done;
1727
+ },
1728
+ };
1729
+ }
1730
+
1555
1731
  /**
1556
1732
  * Open a real-time speech-translation session over WebSocket (Gemini Live
1557
1733
  * via the platform gateway — no Google key in the browser). Stream 16 kHz
@@ -2213,6 +2389,11 @@ class JobStore {
2213
2389
  this._write(list);
2214
2390
  }
2215
2391
 
2392
+ get(jobId) {
2393
+ const entry = this._read().find((e) => e.jobId === jobId);
2394
+ return entry ? { ...entry } : null;
2395
+ }
2396
+
2216
2397
  /** Record an outcome — only for a job this browser is tracking. */
2217
2398
  settle(jobId, patch) {
2218
2399
  const list = this._read();
@@ -2259,10 +2440,37 @@ class JobStore {
2259
2440
  }
2260
2441
  }
2261
2442
 
2262
- /** `?tag=…` for a job route (labels the job; capped like the gateway caps it). */
2263
- function tagQuery(tag) {
2264
- if (tag === undefined || tag === null || tag === '') return '';
2265
- return `?tag=${encodeURIComponent(String(tag).slice(0, 128))}`;
2443
+ /**
2444
+ * Query string for a job route: `tag` (labels the job; capped like the
2445
+ * gateway caps it) and the `saveTo` target as `saveEntity` / `saveId` /
2446
+ * `saveField`.
2447
+ */
2448
+ function jobQuery({ tag, saveTo } = {}) {
2449
+ const params = [];
2450
+ if (tag !== undefined && tag !== null && tag !== '') {
2451
+ params.push(`tag=${encodeURIComponent(String(tag).slice(0, 128))}`);
2452
+ }
2453
+ if (saveTo) {
2454
+ params.push(
2455
+ `saveEntity=${encodeURIComponent(String(saveTo.entity))}`,
2456
+ `saveId=${encodeURIComponent(String(saveTo.id))}`,
2457
+ `saveField=${encodeURIComponent(String(saveTo.field))}`,
2458
+ );
2459
+ }
2460
+ return params.length ? `?${params.join('&')}` : '';
2461
+ }
2462
+
2463
+ /** `saveTo` must name a row and one of its fields: `{ entity, id, field }`. */
2464
+ function assertSaveTo(saveTo) {
2465
+ if (saveTo === undefined || saveTo === null) return;
2466
+ const filled = (v) => typeof v === 'string' && v.trim() !== '';
2467
+ const ok =
2468
+ typeof saveTo === 'object' &&
2469
+ filled(saveTo.entity) &&
2470
+ filled(saveTo.field) &&
2471
+ (filled(saveTo.id) ||
2472
+ (typeof saveTo.id === 'number' && Number.isFinite(saveTo.id)));
2473
+ if (!ok) throw new AIFlowError('saveTo needs entity, id and field');
2266
2474
  }
2267
2475
 
2268
2476
  /** A finished video job as `generateVideo` has always resolved it. */
@@ -2395,4 +2603,94 @@ async function safeJson(res) {
2395
2603
  }
2396
2604
  }
2397
2605
 
2606
+ // ────────────────────────────────────────────────────────────────────────────
2607
+ // Shared waits
2608
+ //
2609
+ // Every client on the page registers the wait it starts for a job, so a page
2610
+ // that comes back and calls `jobs.attach()` joins that wait instead of
2611
+ // polling the same job a second time.
2612
+ // ────────────────────────────────────────────────────────────────────────────
2613
+
2614
+ /** Longest `jobs.attach().done` waits for a video (builds run for many minutes). */
2615
+ const ATTACH_VIDEO_WAIT_MS = 2 * 60 * 60_000;
2616
+
2617
+ function isBrowser() {
2618
+ try {
2619
+ return (
2620
+ typeof window !== 'undefined' &&
2621
+ typeof document !== 'undefined' &&
2622
+ !!window.location
2623
+ );
2624
+ } catch {
2625
+ return false;
2626
+ }
2627
+ }
2628
+
2629
+ /**
2630
+ * The page a job belongs to: the path, plus the route of a hash router
2631
+ * (`#/…`). Empty outside a browser.
2632
+ */
2633
+ function pageKey() {
2634
+ if (!isBrowser()) return '';
2635
+ try {
2636
+ const { pathname, hash } = window.location;
2637
+ return hash && hash.startsWith('#/')
2638
+ ? `${pathname}${hash}`
2639
+ : pathname || '';
2640
+ } catch {
2641
+ return '';
2642
+ }
2643
+ }
2644
+
2645
+ let jobWaitsSingleton = null;
2646
+
2647
+ /** The page-wide registry, created on first use (never at import). */
2648
+ function jobWaits() {
2649
+ if (!jobWaitsSingleton) jobWaitsSingleton = new JobWaits();
2650
+ return jobWaitsSingleton;
2651
+ }
2652
+
2653
+ class JobWaits {
2654
+ constructor() {
2655
+ this._waits = new Map();
2656
+ }
2657
+
2658
+ /** Count `promise` as the page's wait for `jobId`. Returns it unchanged. */
2659
+ track(jobId, promise) {
2660
+ if (!jobId || !promise || typeof promise.then !== 'function') {
2661
+ return promise;
2662
+ }
2663
+ if (!this._waits.has(jobId)) {
2664
+ this._waits.set(jobId, promise);
2665
+ const release = () => {
2666
+ if (this._waits.get(jobId) === promise) this._waits.delete(jobId);
2667
+ };
2668
+ promise.then(release, release);
2669
+ }
2670
+ return promise;
2671
+ }
2672
+
2673
+ /** A wait for `jobId` that resolves like the call that started it. */
2674
+ wait(client, jobId) {
2675
+ const shared = this._waits.get(jobId);
2676
+ if (shared) {
2677
+ return shared.catch((err) => {
2678
+ // That wait stopped (its page aborted it, or it timed out)
2679
+ // without an outcome: wait afresh rather than inherit it.
2680
+ if (err?.code === 'aborted' || err?.code === 'timeout') {
2681
+ return this.wait(client, jobId);
2682
+ }
2683
+ throw err;
2684
+ });
2685
+ }
2686
+ const entry = client._jobStore.get(jobId);
2687
+ return this.track(
2688
+ jobId,
2689
+ client._waitForJob(jobId, {
2690
+ timeout: entry?.kind === 'video' ? ATTACH_VIDEO_WAIT_MS : undefined,
2691
+ }),
2692
+ );
2693
+ }
2694
+ }
2695
+
2398
2696
  export default AIFlowClient;