@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/src/index.js CHANGED
@@ -10,6 +10,13 @@ const DEFAULT_TIMEOUT_MS = 60_000;
10
10
  const DEFAULT_MAX_RETRIES = 2;
11
11
  const RETRY_STATUSES = new Set([429, 500, 502, 503, 504]);
12
12
 
13
+ /** How long one `GET /jobs/:id` asks the gateway to hold the request. */
14
+ const JOB_WAIT_MS = 20_000;
15
+ /** Default overall wait for a background job; the gateway fails one that overruns first. */
16
+ const DEFAULT_JOB_TIMEOUT_MS = 30 * 60_000;
17
+ /** Times a dropped chat stream is re-attached to its job before giving up. */
18
+ const STREAM_RESUME_ATTEMPTS = 3;
19
+
13
20
  /**
14
21
  * Above this many seconds the gateway builds a video as independent SCENES in
15
22
  * PARALLEL (hard cuts) instead of chaining one continuous shot — chaining is
@@ -44,13 +51,16 @@ function longVideoTimeoutMs(seconds) {
44
51
  }
45
52
 
46
53
  export class AIFlowError extends Error {
47
- constructor(message, { status, code, requestId, cause } = {}) {
54
+ constructor(message, { status, code, requestId, cause, fromServer } = {}) {
48
55
  super(message);
49
56
  this.name = 'AIFlowError';
50
57
  this.status = status;
51
58
  this.code = code;
52
59
  this.requestId = requestId;
53
60
  if (cause) this.cause = cause;
61
+ // An error the gateway reported inside a stream (not a dropped
62
+ // connection) — a stream does not reconnect after one.
63
+ if (fromServer) this.fromServer = true;
54
64
  }
55
65
  }
56
66
 
@@ -155,6 +165,23 @@ export class AIFlowClient {
155
165
  /** Update this app's (or a sibling) module system prompt / defaults. */
156
166
  updateConfig: (input) => this._adminUpdateConfig(input),
157
167
  };
168
+
169
+ this._jobStore = new JobStore(this.appId);
170
+ /**
171
+ * Background jobs started from this browser, remembered for a day
172
+ * (localStorage; in memory where there is none) so a page can show a
173
+ * generation that finished, or is still running, after the user left
174
+ * and came back. Entries: `{ jobId, kind, tag, status, result?, error?,
175
+ * createdAt, updatedAt }`; `result` is what the call resolved with.
176
+ */
177
+ this.jobs = {
178
+ /** Newest remembered job with this tag (any tag when omitted), or null. */
179
+ latest: (tag) => this._jobStore.latest(tag),
180
+ /** Remembered jobs, newest first, optionally only one tag. */
181
+ list: ({ tag } = {}) => this._jobStore.list(tag),
182
+ /** Forget one job (by id) or every job with a tag. */
183
+ forget: (jobIdOrTag) => this._jobStore.forget(jobIdOrTag),
184
+ };
158
185
  }
159
186
 
160
187
  /**
@@ -294,6 +321,9 @@ export class AIFlowClient {
294
321
  * Non-streaming chat completion. `webSearch: false` answers this one
295
322
  * request without the built-in web search; omitted, the module's setting
296
323
  * applies (on by default).
324
+ *
325
+ * Runs as a background job (see {@link waitForJob}): `onJob(jobId)` fires
326
+ * once the gateway has accepted it, `tag` labels it in `jobs.latest()`.
297
327
  * @returns {Promise<{id:string, model:string, content:string, usage:{inputTokens:number,outputTokens:number,creditsUsed:number}}>}
298
328
  */
299
329
  async chat({
@@ -305,6 +335,9 @@ export class AIFlowClient {
305
335
  webSearch,
306
336
  tools,
307
337
  signal,
338
+ timeout,
339
+ onJob,
340
+ tag,
308
341
  } = {}) {
309
342
  if (!Array.isArray(messages) || messages.length === 0) {
310
343
  throw new AIFlowError('messages must be a non-empty array');
@@ -312,9 +345,10 @@ export class AIFlowClient {
312
345
  assertNoTools(tools);
313
346
  const resolvedModel = model || (await this._resolveDefaultModel('chat'));
314
347
  const resolvedSystem = await this._resolveSystemPrompt(system);
315
- const res = await this._request(
316
- '/chat',
317
- {
348
+ return this._generate({
349
+ kind: 'chat',
350
+ path: '/chat',
351
+ body: {
318
352
  model: resolvedModel,
319
353
  system: resolvedSystem,
320
354
  messages,
@@ -322,14 +356,25 @@ export class AIFlowClient {
322
356
  temperature,
323
357
  webSearch,
324
358
  },
325
- { signal },
326
- );
327
- return await res.json();
359
+ signal,
360
+ timeout,
361
+ onJob,
362
+ tag,
363
+ });
328
364
  }
329
365
 
330
366
  /**
331
367
  * Streaming chat completion. Yields `{ delta: string, done: boolean }`
332
- * chunks as server-sent events arrive.
368
+ * chunks as server-sent events arrive; the last one (`done: true`) carries
369
+ * `model`, `modelSource`, `usage` and, on a gateway with background jobs,
370
+ * `jobId`.
371
+ *
372
+ * The answer is generated by a background job: leaving the page (or
373
+ * aborting `signal`) stops only this reader, and the answer keeps being
374
+ * written on the gateway — pick it up with {@link resumeChatStream} or
375
+ * {@link waitForJob}. `onJob(jobId)` fires as soon as the job id is known;
376
+ * a dropped connection is re-attached automatically. A server error frame
377
+ * (e.g. 402, out of credits) throws an AIFlowError.
333
378
  */
334
379
  async *chatStream({
335
380
  messages,
@@ -340,6 +385,8 @@ export class AIFlowClient {
340
385
  webSearch,
341
386
  tools,
342
387
  signal,
388
+ onJob,
389
+ tag,
343
390
  } = {}) {
344
391
  if (!Array.isArray(messages) || messages.length === 0) {
345
392
  throw new AIFlowError('messages must be a non-empty array');
@@ -348,7 +395,7 @@ export class AIFlowClient {
348
395
  const resolvedModel = model || (await this._resolveDefaultModel('chat'));
349
396
  const resolvedSystem = await this._resolveSystemPrompt(system);
350
397
  const res = await this._request(
351
- '/chat/stream',
398
+ `/chat/stream${tagQuery(tag)}`,
352
399
  {
353
400
  model: resolvedModel,
354
401
  system: resolvedSystem,
@@ -360,39 +407,126 @@ export class AIFlowClient {
360
407
  },
361
408
  { signal, stream: true },
362
409
  );
410
+ yield* this._streamChat(res, { signal, onJob, tag });
411
+ }
363
412
 
364
- if (!res.body || typeof res.body.getReader !== 'function') {
365
- throw new AIFlowError(
366
- 'Streaming response is not readable — your fetch implementation must expose a ReadableStream body.',
367
- );
413
+ /**
414
+ * Re-attach to a streamed chat answer — after a reload, on another page,
415
+ * or on another device for the same signed-in user. Yields the chunks from
416
+ * character `from` on (pass the length of the text already shown; 0 replays
417
+ * the whole answer), then live text until the answer is done. Same chunk
418
+ * shape as {@link chatStream}.
419
+ */
420
+ async *resumeChatStream(jobId, { from = 0, signal } = {}) {
421
+ if (!jobId || typeof jobId !== 'string') {
422
+ throw new AIFlowError('jobId is required');
368
423
  }
424
+ const res = await this._openJobStream(jobId, from, signal);
425
+ yield* this._streamChat(res, { signal, jobId, from });
426
+ }
369
427
 
370
- const reader = res.body.getReader();
371
- const decoder = new TextDecoder();
372
- let buffer = '';
428
+ async _openJobStream(jobId, from, signal) {
429
+ const offset = Math.max(0, Math.floor(Number(from) || 0));
430
+ return this._fetchWithRetry(
431
+ `${this.baseUrl}/jobs/${encodeURIComponent(jobId)}/stream?from=${offset}`,
432
+ {
433
+ method: 'GET',
434
+ headers: { ...this._authHeaders(), Accept: 'text/event-stream' },
435
+ },
436
+ { signal },
437
+ );
438
+ }
373
439
 
374
- try {
375
- while (true) {
376
- const { value, done } = await reader.read();
377
- if (done) break;
378
- buffer += decoder.decode(value, { stream: true });
379
-
380
- let idx;
381
- while ((idx = buffer.indexOf('\n\n')) !== -1) {
382
- const rawEvent = buffer.slice(0, idx);
383
- buffer = buffer.slice(idx + 2);
384
- const parsed = parseSseEvent(rawEvent);
385
- if (parsed === null) continue;
386
- yield parsed;
387
- if (parsed.done) return;
388
- }
440
+ /**
441
+ * Read a chat SSE response as chunks. A server error frame throws. If the
442
+ * connection ends before the answer does, the stream is re-attached to its
443
+ * job from the last character received — the gateway kept writing.
444
+ */
445
+ async *_streamChat(res, { signal, onJob, tag, jobId = null, from = 0 }) {
446
+ let current = res;
447
+ let received = Math.max(0, Number(from) || 0);
448
+ let content = '';
449
+ let resumes = 0;
450
+ while (true) {
451
+ if (!current.body || typeof current.body.getReader !== 'function') {
452
+ throw new AIFlowError(
453
+ 'Streaming response is not readable — your fetch implementation must expose a ReadableStream body.',
454
+ );
389
455
  }
390
- } finally {
391
456
  try {
392
- reader.releaseLock();
393
- } catch {
394
- /* ignore */
457
+ for await (const event of readSseEvents(current.body)) {
458
+ if (event.comment !== undefined) {
459
+ const match = /^aiflow-job\s+(\S+)/.exec(event.comment);
460
+ if (match && !jobId) {
461
+ jobId = match[1];
462
+ this._trackJob(jobId, 'chat_stream', tag, onJob);
463
+ }
464
+ continue;
465
+ }
466
+ const chunk = event.chunk;
467
+ if (chunk.error) {
468
+ const message = chunk.message || 'Chat stream failed';
469
+ if (jobId) {
470
+ this._jobStore.settle(jobId, {
471
+ status: 'failed',
472
+ error: message,
473
+ });
474
+ }
475
+ throw new AIFlowError(message, {
476
+ status: chunk.status,
477
+ code: chunk.code || 'stream_error',
478
+ fromServer: true,
479
+ });
480
+ }
481
+ if (typeof chunk.delta === 'string' && chunk.delta) {
482
+ received += chunk.delta.length;
483
+ content += chunk.delta;
484
+ }
485
+ if (chunk.done) {
486
+ if (!jobId) {
487
+ yield chunk;
488
+ return;
489
+ }
490
+ this._jobStore.settle(jobId, {
491
+ status: 'succeeded',
492
+ // Only a stream read from the start holds the whole answer.
493
+ ...(from === 0
494
+ ? {
495
+ result: {
496
+ content,
497
+ model: chunk.model,
498
+ modelSource: chunk.modelSource,
499
+ usage: chunk.usage,
500
+ },
501
+ }
502
+ : {}),
503
+ });
504
+ yield { ...chunk, jobId };
505
+ return;
506
+ }
507
+ yield chunk;
508
+ }
509
+ } catch (err) {
510
+ if (
511
+ err?.fromServer ||
512
+ signal?.aborted ||
513
+ !jobId ||
514
+ resumes >= STREAM_RESUME_ATTEMPTS
515
+ ) {
516
+ throw err;
517
+ }
395
518
  }
519
+ // The connection ended before the answer did.
520
+ if (!jobId || signal?.aborted) return;
521
+ if (resumes >= STREAM_RESUME_ATTEMPTS) {
522
+ throw new AIFlowError(
523
+ 'Lost the connection to the chat stream — the answer may still finish; pick it up with resumeChatStream(jobId)',
524
+ { code: 'stream_lost' },
525
+ );
526
+ }
527
+ resumes += 1;
528
+ await sleep(backoffMs(resumes));
529
+ current = await this._openJobStream(jobId, received, signal);
396
530
  }
397
531
  }
398
532
 
@@ -413,6 +547,8 @@ export class AIFlowClient {
413
547
  background,
414
548
  signal,
415
549
  timeout,
550
+ onJob,
551
+ tag,
416
552
  } = {}) {
417
553
  if (!prompt || typeof prompt !== 'string') {
418
554
  throw new AIFlowError('prompt is required');
@@ -423,9 +559,10 @@ export class AIFlowClient {
423
559
  // mirroring chat(). The server prepends it to the prompt and injects
424
560
  // the dynamic `language` into any {{language}} placeholder.
425
561
  const resolvedSystem = await this._resolveSystemPrompt(system);
426
- const res = await this._request(
427
- '/image',
428
- {
562
+ return this._generate({
563
+ kind: 'image',
564
+ path: '/image',
565
+ body: {
429
566
  model: resolvedModel,
430
567
  prompt,
431
568
  size,
@@ -440,13 +577,16 @@ export class AIFlowClient {
440
577
  // models in `config.imageBackgroundModels`.
441
578
  background,
442
579
  },
580
+ signal,
581
+ timeout,
443
582
  // Image edits (esp. document translation) routinely exceed the 60s
444
- // client default — a single 2K edit was observed at ~63s. Default
445
- // to 3 minutes so the SDK doesn't abort a request the server is
446
- // still completing.
447
- { signal, timeout: timeout ?? 180_000 },
448
- );
449
- return await res.json();
583
+ // client default — a single 2K edit was observed at ~63s. The
584
+ // synchronous route gets 3 minutes; the job route the same for its
585
+ // upload of base64 inputs.
586
+ requestTimeout: 180_000,
587
+ onJob,
588
+ tag,
589
+ });
450
590
  }
451
591
 
452
592
  /**
@@ -471,6 +611,8 @@ export class AIFlowClient {
471
611
  background,
472
612
  signal,
473
613
  timeout,
614
+ onJob,
615
+ tag,
474
616
  } = {}) {
475
617
  if (!Array.isArray(pages) || pages.length === 0) {
476
618
  throw new AIFlowError('pages must be a non-empty array');
@@ -478,9 +620,10 @@ export class AIFlowClient {
478
620
  const resolvedModel =
479
621
  model || (await this._resolveDefaultModel('image'));
480
622
  const resolvedSystem = await this._resolveSystemPrompt(system);
481
- const res = await this._request(
482
- '/image/batch',
483
- {
623
+ return this._generate({
624
+ kind: 'image_batch',
625
+ path: '/image/batch',
626
+ body: {
484
627
  pages,
485
628
  prompt,
486
629
  model: resolvedModel,
@@ -490,11 +633,15 @@ export class AIFlowClient {
490
633
  concurrency,
491
634
  background,
492
635
  },
636
+ signal,
637
+ timeout,
493
638
  // A batch of multi-minute edits needs far longer than a single
494
- // request — default to 10 minutes, matching the server socket.
495
- { signal, timeout: timeout ?? 600_000 },
496
- );
497
- return await res.json();
639
+ // request — 10 minutes on the synchronous route, matching the
640
+ // server socket; the job route needs it for a large upload.
641
+ requestTimeout: 600_000,
642
+ onJob,
643
+ tag,
644
+ });
498
645
  }
499
646
 
500
647
  /**
@@ -516,6 +663,7 @@ export class AIFlowClient {
516
663
  throw new AIFlowError('prompt is required');
517
664
  }
518
665
  const { jobId } = await this.submitVideoJob(opts);
666
+ this._trackJob(jobId, 'video', opts.tag, opts.onJob);
519
667
  return this._pollVideoJob(jobId, {
520
668
  signal: opts.signal,
521
669
  // Overall wait budget across all polls (default 10 min). Each
@@ -562,6 +710,31 @@ export class AIFlowClient {
562
710
  'referenceImages / referenceVideos / referenceAudios cannot be combined with image / lastFrame',
563
711
  );
564
712
  }
713
+ if (referenceVideos?.some(isBlob)) {
714
+ throw new AIFlowError(
715
+ 'referenceVideos take https:// or asset:// URLs — upload the video file first',
716
+ );
717
+ }
718
+ // A File / Blob is sent as a data URL, so an upload can be passed as-is.
719
+ const [imageIn, lastFrameIn, videoIn, referenceImagesIn, referenceAudiosIn] =
720
+ await Promise.all([
721
+ toMediaInput(image),
722
+ toMediaInput(lastFrame),
723
+ toMediaInput(video),
724
+ referenceImages && Promise.all(referenceImages.map(toMediaInput)),
725
+ referenceAudios && Promise.all(referenceAudios.map(toMediaInput)),
726
+ ]);
727
+ const badAudio = referenceAudiosIn?.find(
728
+ (a) =>
729
+ typeof a === 'string' &&
730
+ a.startsWith('data:') &&
731
+ !REFERENCE_AUDIO_DATA_URL.test(a),
732
+ );
733
+ if (badAudio) {
734
+ throw new AIFlowError(
735
+ `referenceAudios must be wav or mp3 files (got ${badAudio.slice(5, badAudio.search(/[;,]/))}); browser recordings such as webm are not accepted`,
736
+ );
737
+ }
565
738
  const resolvedModel =
566
739
  model || (await this._resolveDefaultModel('video'));
567
740
  const res = await this._request(
@@ -573,12 +746,12 @@ export class AIFlowClient {
573
746
  resolution,
574
747
  duration,
575
748
  watermark,
576
- image,
577
- lastFrame,
578
- video,
579
- referenceImages,
749
+ image: imageIn,
750
+ lastFrame: lastFrameIn,
751
+ video: videoIn,
752
+ referenceImages: referenceImagesIn,
580
753
  referenceVideos,
581
- referenceAudios,
754
+ referenceAudios: referenceAudiosIn,
582
755
  generateAudio,
583
756
  },
584
757
  // Submit returns fast; the default client timeout is plenty even
@@ -648,31 +821,14 @@ export class AIFlowClient {
648
821
  }
649
822
  }
650
823
  if (job.status === 'succeeded') {
651
- return {
652
- videoUrl: job.videoUrl,
653
- thumbnailUrl: job.thumbnailUrl,
654
- prompt: job.prompt,
655
- usage: job.usage || { creditsUsed: 0 },
656
- // Session turns only. Spread conditionally so a plain
657
- // generation's result keeps exactly the shape earlier SDK
658
- // versions returned — no undefined keys appearing in it.
659
- ...(job.sessionId ? { sessionId: job.sessionId } : {}),
660
- ...(job.segmentUrl ? { segmentUrl: job.segmentUrl } : {}),
661
- ...(job.durationSeconds != null
662
- ? { durationSeconds: job.durationSeconds }
663
- : {}),
664
- ...(job.segmentsDone != null
665
- ? { segmentsDone: job.segmentsDone }
666
- : {}),
667
- // Short of the requested length, but real and paid for.
668
- ...(job.warning ? { warning: job.warning } : {}),
669
- };
824
+ const result = toVideoResult(job);
825
+ this._jobStore.settle(jobId, { status: 'succeeded', result });
826
+ return result;
670
827
  }
671
828
  if (job.status === 'failed') {
672
- throw new AIFlowError(
673
- job.error || 'Video generation failed',
674
- { code: 'video_failed' },
675
- );
829
+ const message = job.error || 'Video generation failed';
830
+ this._jobStore.settle(jobId, { status: 'failed', error: message });
831
+ throw new AIFlowError(message, { code: 'video_failed' });
676
832
  }
677
833
  if (Date.now() >= deadline) {
678
834
  throw new AIFlowError(
@@ -720,11 +876,14 @@ export class AIFlowClient {
720
876
  signal,
721
877
  timeout,
722
878
  pollIntervalMs,
879
+ onJob,
880
+ tag,
723
881
  } = {}) {
724
882
  if (!Array.isArray(videos) || videos.length < 2) {
725
883
  throw new AIFlowError('mergeVideos needs at least two videos');
726
884
  }
727
885
  const { jobId } = await this.submitVideoMerge({ videos, signal });
886
+ this._trackJob(jobId, 'video', tag, onJob);
728
887
  return this._pollVideoJob(jobId, {
729
888
  signal,
730
889
  // Every clip is fetched and usually re-encoded on the gateway, so the
@@ -876,6 +1035,8 @@ export class AIFlowClient {
876
1035
  signal,
877
1036
  timeout,
878
1037
  pollIntervalMs,
1038
+ onJob,
1039
+ tag,
879
1040
  } = {}) {
880
1041
  if (!prompt || typeof prompt !== 'string') {
881
1042
  throw new AIFlowError('prompt is required');
@@ -895,6 +1056,7 @@ export class AIFlowClient {
895
1056
  targetDurationSeconds: durationSeconds,
896
1057
  signal,
897
1058
  });
1059
+ this._trackJob(jobId, 'video', tag, onJob, { sessionId });
898
1060
  const result = await this._pollVideoJob(jobId, {
899
1061
  signal,
900
1062
  timeout: timeout ?? longVideoTimeoutMs(durationSeconds),
@@ -923,7 +1085,7 @@ export class AIFlowClient {
923
1085
  */
924
1086
  async resumeLongVideo(
925
1087
  sessionId,
926
- { onProgress, signal, timeout, pollIntervalMs } = {},
1088
+ { onProgress, signal, timeout, pollIntervalMs, onJob, tag } = {},
927
1089
  ) {
928
1090
  if (!sessionId || typeof sessionId !== 'string') {
929
1091
  throw new AIFlowError('sessionId is required');
@@ -934,6 +1096,7 @@ export class AIFlowClient {
934
1096
  { signal, timeout: DEFAULT_TIMEOUT_MS },
935
1097
  );
936
1098
  const { jobId } = await res.json();
1099
+ this._trackJob(jobId, 'video', tag, onJob, { sessionId });
937
1100
  // Read the session to size the wait from what is actually left, rather
938
1101
  // than from the whole film that was originally asked for.
939
1102
  let remaining = 0;
@@ -972,6 +1135,7 @@ export class AIFlowClient {
972
1135
  */
973
1136
  async extendVideo(sessionId, opts = {}) {
974
1137
  const { jobId } = await this.submitVideoExtend(sessionId, opts);
1138
+ this._trackJob(jobId, 'video', opts.tag, opts.onJob, { sessionId });
975
1139
  return this._pollVideoJob(jobId, {
976
1140
  signal: opts.signal,
977
1141
  timeout: opts.timeout ?? 600_000,
@@ -1054,6 +1218,8 @@ export class AIFlowClient {
1054
1218
  seed,
1055
1219
  signal,
1056
1220
  timeout,
1221
+ onJob,
1222
+ tag,
1057
1223
  } = {}) {
1058
1224
  if (!prompt || typeof prompt !== 'string') {
1059
1225
  throw new AIFlowError('prompt is required');
@@ -1063,9 +1229,10 @@ export class AIFlowClient {
1063
1229
  }
1064
1230
  const resolvedModel =
1065
1231
  model || (await this._resolveDefaultModel('audio'));
1066
- const res = await this._request(
1067
- '/audio',
1068
- {
1232
+ return this._generate({
1233
+ kind: 'audio',
1234
+ path: '/audio',
1235
+ body: {
1069
1236
  model: resolvedModel,
1070
1237
  prompt,
1071
1238
  images: images?.length ? images : undefined,
@@ -1075,11 +1242,14 @@ export class AIFlowClient {
1075
1242
  negativePrompt,
1076
1243
  seed,
1077
1244
  },
1245
+ signal,
1246
+ timeout,
1078
1247
  // Music generation (a full Lyria 3.5 song) runs well past the 60s
1079
- // client default — allow 3 minutes before aborting.
1080
- { signal, timeout: timeout ?? 180_000 },
1081
- );
1082
- return await res.json();
1248
+ // client default — the synchronous route gets 3 minutes.
1249
+ requestTimeout: 180_000,
1250
+ onJob,
1251
+ tag,
1252
+ });
1083
1253
  }
1084
1254
 
1085
1255
  /**
@@ -1094,23 +1264,29 @@ export class AIFlowClient {
1094
1264
  loop,
1095
1265
  signal,
1096
1266
  timeout,
1267
+ onJob,
1268
+ tag,
1097
1269
  } = {}) {
1098
1270
  if (!prompt || typeof prompt !== 'string') {
1099
1271
  throw new AIFlowError('prompt is required');
1100
1272
  }
1101
1273
  const resolvedModel = model || (await this._resolveDefaultModel('sfx'));
1102
- const res = await this._request(
1103
- '/sfx',
1104
- {
1274
+ return this._generate({
1275
+ kind: 'sfx',
1276
+ path: '/sfx',
1277
+ body: {
1105
1278
  model: resolvedModel,
1106
1279
  prompt,
1107
1280
  durationSeconds,
1108
1281
  promptInfluence,
1109
1282
  loop,
1110
1283
  },
1111
- { signal, timeout: timeout ?? 120_000 },
1112
- );
1113
- return await res.json();
1284
+ signal,
1285
+ timeout,
1286
+ requestTimeout: 120_000,
1287
+ onJob,
1288
+ tag,
1289
+ });
1114
1290
  }
1115
1291
 
1116
1292
  /**
@@ -1174,6 +1350,184 @@ export class AIFlowClient {
1174
1350
  return await res.json();
1175
1351
  }
1176
1352
 
1353
+ // ── Background jobs ─────────────────────────────────────────────────────
1354
+ // On a gateway that supports them (`config.capabilities.jobs`), chat,
1355
+ // image, music and SFX calls run as background jobs, like video always
1356
+ // has: the gateway keeps generating — and keeps the result for a week —
1357
+ // when the page that asked goes away. The calls above still resolve with
1358
+ // the same value; these methods pick a job up again by its id.
1359
+
1360
+ /**
1361
+ * Wait for a background job and resolve with its result — the same value
1362
+ * the call that started it resolves with (a video job resolves like
1363
+ * `generateVideo`). Works with any job id the app has: from `onJob`,
1364
+ * `jobs.latest()` / `jobs.list()` or {@link listJobs}, after a reload or on
1365
+ * another page. Aborting `signal` or hitting `timeout` (default 30 min)
1366
+ * stops only the waiting; the job carries on. Throws an AIFlowError with
1367
+ * the job's `status` / `code` when it failed.
1368
+ */
1369
+ async waitForJob(jobId, { signal, timeout, onProgress } = {}) {
1370
+ if (!jobId || typeof jobId !== 'string') {
1371
+ throw new AIFlowError('jobId is required');
1372
+ }
1373
+ const deadline = Date.now() + (timeout ?? DEFAULT_JOB_TIMEOUT_MS);
1374
+ let lastProgress = -1;
1375
+ // eslint-disable-next-line no-constant-condition
1376
+ while (true) {
1377
+ if (signal?.aborted) {
1378
+ throw new AIFlowError(
1379
+ 'Stopped waiting — the job keeps running; call waitForJob(jobId) to pick it up again',
1380
+ { code: 'aborted' },
1381
+ );
1382
+ }
1383
+ const remaining = deadline - Date.now();
1384
+ if (remaining <= 0) {
1385
+ throw new AIFlowError(
1386
+ `Timed out waiting for job ${jobId} — it may still finish; call waitForJob(jobId) again`,
1387
+ { code: 'timeout' },
1388
+ );
1389
+ }
1390
+ const startedAt = Date.now();
1391
+ let job;
1392
+ try {
1393
+ job = await this.getJob(jobId, {
1394
+ waitMs: Math.min(JOB_WAIT_MS, remaining),
1395
+ signal,
1396
+ });
1397
+ } catch (err) {
1398
+ // A gateway without job routes still serves video jobs.
1399
+ if (err?.status === 404 && !(await this._jobsEnabled())) {
1400
+ return this._pollVideoJob(jobId, {
1401
+ signal,
1402
+ timeout: remaining,
1403
+ onProgress,
1404
+ });
1405
+ }
1406
+ throw err;
1407
+ }
1408
+ const progress = job.progress;
1409
+ if (
1410
+ onProgress &&
1411
+ progress &&
1412
+ typeof progress.segmentsDone === 'number' &&
1413
+ progress.segmentsDone !== lastProgress
1414
+ ) {
1415
+ lastProgress = progress.segmentsDone;
1416
+ try {
1417
+ onProgress({
1418
+ segmentsDone: progress.segmentsDone,
1419
+ segmentsPlanned: progress.segmentsPlanned,
1420
+ durationSeconds: progress.durationSeconds,
1421
+ videoUrl: progress.videoUrl,
1422
+ thumbnailUrl: progress.thumbnailUrl,
1423
+ });
1424
+ } catch {
1425
+ // A throwing progress handler is the caller's bug.
1426
+ }
1427
+ }
1428
+ if (job.status === 'succeeded') {
1429
+ const result =
1430
+ job.kind === 'video' ? toVideoResult(job.result || {}) : job.result;
1431
+ this._jobStore.settle(jobId, { status: 'succeeded', result });
1432
+ return result;
1433
+ }
1434
+ if (job.status === 'failed') {
1435
+ const message = job.error || 'Generation failed';
1436
+ this._jobStore.settle(jobId, { status: 'failed', error: message });
1437
+ throw new AIFlowError(message, {
1438
+ status: job.errorStatus,
1439
+ code: job.errorCode || 'job_failed',
1440
+ });
1441
+ }
1442
+ // The gateway holds each read until the job ends or `waitMs`
1443
+ // passes; pause only when it answered early without an outcome.
1444
+ if (Date.now() - startedAt < 1_000) await sleep(1_000);
1445
+ }
1446
+ }
1447
+
1448
+ /**
1449
+ * Read one background job now: `{ jobId, kind, status, tag?, prompt?,
1450
+ * result?, error?, errorStatus?, errorCode?, progress?, contentLength? }`.
1451
+ * `waitMs` (up to 25000) lets the gateway hold the request until the job
1452
+ * finishes. Needs a gateway with `config.capabilities.jobs`.
1453
+ */
1454
+ async getJob(jobId, { waitMs, signal } = {}) {
1455
+ if (!jobId || typeof jobId !== 'string') {
1456
+ throw new AIFlowError('jobId is required');
1457
+ }
1458
+ const wait = Math.max(0, Math.min(Number(waitMs) || 0, 25_000));
1459
+ const res = await this._get(
1460
+ `/jobs/${encodeURIComponent(jobId)}${wait ? `?waitMs=${wait}` : ''}`,
1461
+ { signal, timeout: wait + DEFAULT_TIMEOUT_MS },
1462
+ );
1463
+ return await res.json();
1464
+ }
1465
+
1466
+ /**
1467
+ * The signed-in end user's own jobs on this module, newest first, from any
1468
+ * device (`setEndUser` with the user's token is required; an anonymous
1469
+ * caller gets an empty list — use `jobs.latest()` for this browser's jobs).
1470
+ * `active: true` keeps only jobs still running. Entries carry no result:
1471
+ * read one with {@link waitForJob} or {@link getJob}.
1472
+ * @returns {Promise<{jobs: object[]}>}
1473
+ */
1474
+ async listJobs({ active, limit, signal } = {}) {
1475
+ const params = [];
1476
+ if (active) params.push('active=1');
1477
+ if (limit) params.push(`limit=${encodeURIComponent(limit)}`);
1478
+ const res = await this._get(
1479
+ `/jobs${params.length ? `?${params.join('&')}` : ''}`,
1480
+ { signal },
1481
+ );
1482
+ return await res.json();
1483
+ }
1484
+
1485
+ /**
1486
+ * Run one generation. On a gateway with background jobs it is submitted to
1487
+ * the job route and awaited, so it keeps running — and stays retrievable —
1488
+ * if this page goes away; otherwise it is one request to the synchronous
1489
+ * route. Both resolve with the same response body.
1490
+ */
1491
+ async _generate({ kind, path, body, signal, timeout, requestTimeout, onJob, tag }) {
1492
+ if (await this._jobsEnabled()) {
1493
+ const res = await this._request(`${path}/jobs${tagQuery(tag)}`, body, {
1494
+ signal,
1495
+ timeout: requestTimeout ?? DEFAULT_TIMEOUT_MS,
1496
+ });
1497
+ const { jobId } = await res.json();
1498
+ this._trackJob(jobId, kind, tag, onJob);
1499
+ return this.waitForJob(jobId, { signal, timeout });
1500
+ }
1501
+ const res = await this._request(path, body, {
1502
+ signal,
1503
+ timeout: timeout ?? requestTimeout,
1504
+ });
1505
+ return await res.json();
1506
+ }
1507
+
1508
+ async _jobsEnabled() {
1509
+ try {
1510
+ const cfg = await this.getConfig();
1511
+ return cfg?.capabilities?.jobs === true;
1512
+ } catch {
1513
+ return false;
1514
+ }
1515
+ }
1516
+
1517
+ /** Remember a started job and hand its id to the caller's `onJob`. */
1518
+ _trackJob(jobId, kind, tag, onJob, extra) {
1519
+ if (!jobId) return;
1520
+ this._jobStore.put({ jobId, kind, tag, status: 'processing' });
1521
+ if (typeof onJob === 'function') {
1522
+ try {
1523
+ onJob(jobId, extra);
1524
+ } catch {
1525
+ // A throwing callback is the caller's bug, not a reason to
1526
+ // abandon a generation they are paying for.
1527
+ }
1528
+ }
1529
+ }
1530
+
1177
1531
  /**
1178
1532
  * Open a real-time speech-translation session over WebSocket (Gemini Live
1179
1533
  * via the platform gateway — no Google key in the browser). Stream 16 kHz
@@ -1683,6 +2037,41 @@ async function loadSocketIoClient() {
1683
2037
  }
1684
2038
  }
1685
2039
 
2040
+ // Media types for a File / Blob whose `type` the browser left empty.
2041
+ const MEDIA_TYPE_BY_EXTENSION = {
2042
+ mp3: 'audio/mpeg',
2043
+ wav: 'audio/wav',
2044
+ png: 'image/png',
2045
+ jpg: 'image/jpeg',
2046
+ jpeg: 'image/jpeg',
2047
+ webp: 'image/webp',
2048
+ gif: 'image/gif',
2049
+ mp4: 'video/mp4',
2050
+ mov: 'video/quicktime',
2051
+ };
2052
+
2053
+ // The audio types Seedance takes as reference audio (wav / mp3, any of the
2054
+ // names browsers give them); the gateway relabels them for Ark.
2055
+ const REFERENCE_AUDIO_DATA_URL =
2056
+ /^data:audio\/(mpeg|mp3|mpeg3|x-mp3|x-mpeg|mpg|wav|x-wav|wave|vnd\.wave)[;,]/i;
2057
+
2058
+ function isBlob(value) {
2059
+ return typeof Blob !== 'undefined' && value instanceof Blob;
2060
+ }
2061
+
2062
+ /** A File / Blob as a `data:` URL; strings and empty values pass through. */
2063
+ async function toMediaInput(value) {
2064
+ if (!isBlob(value)) return value;
2065
+ const ext = String(value.name || '')
2066
+ .split('.')
2067
+ .pop()
2068
+ .toLowerCase();
2069
+ const type =
2070
+ value.type || MEDIA_TYPE_BY_EXTENSION[ext] || 'application/octet-stream';
2071
+ const bytes = new Uint8Array(await value.arrayBuffer());
2072
+ return `data:${type};base64,${toBase64(bytes)}`;
2073
+ }
2074
+
1686
2075
  function toBase64(chunk) {
1687
2076
  if (typeof chunk === 'string') return chunk; // assume already base64
1688
2077
  let bytes;
@@ -1717,6 +2106,204 @@ function toBase64(chunk) {
1717
2106
  // Helpers
1718
2107
  // ────────────────────────────────────────────────────────────────────────────
1719
2108
 
2109
+ const JOB_STORE_MAX_ENTRIES = 50;
2110
+ const JOB_STORE_TTL_MS = 24 * 60 * 60_000;
2111
+ const JOB_STORE_RESULT_MAX_CHARS = 200_000;
2112
+
2113
+ /**
2114
+ * The jobs this browser started, kept in localStorage (memory where there is
2115
+ * none) for a day, so a page that comes back can find a generation that
2116
+ * finished — or is still running — while it was gone. Results above
2117
+ * JOB_STORE_RESULT_MAX_CHARS are not kept (`resultOmitted`); `waitForJob`
2118
+ * fetches them from the gateway.
2119
+ */
2120
+ class JobStore {
2121
+ constructor(appId) {
2122
+ this._key = `aiflow:jobs:${appId}`;
2123
+ this._memory = [];
2124
+ }
2125
+
2126
+ _storage() {
2127
+ try {
2128
+ return typeof localStorage !== 'undefined' && localStorage
2129
+ ? localStorage
2130
+ : null;
2131
+ } catch {
2132
+ return null;
2133
+ }
2134
+ }
2135
+
2136
+ _read() {
2137
+ const storage = this._storage();
2138
+ let list = this._memory;
2139
+ if (storage) {
2140
+ try {
2141
+ list = JSON.parse(storage.getItem(this._key) || '[]');
2142
+ } catch {
2143
+ list = [];
2144
+ }
2145
+ }
2146
+ if (!Array.isArray(list)) return [];
2147
+ const cutoff = Date.now() - JOB_STORE_TTL_MS;
2148
+ return list.filter(
2149
+ (e) => e && e.jobId && (e.updatedAt || e.createdAt || 0) >= cutoff,
2150
+ );
2151
+ }
2152
+
2153
+ _write(list) {
2154
+ const kept = [...list]
2155
+ .sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0))
2156
+ .slice(0, JOB_STORE_MAX_ENTRIES);
2157
+ this._memory = kept;
2158
+ const storage = this._storage();
2159
+ if (!storage) return;
2160
+ try {
2161
+ storage.setItem(this._key, JSON.stringify(kept));
2162
+ } catch {
2163
+ // Over quota: keep the bookkeeping, drop the stored results.
2164
+ try {
2165
+ storage.setItem(
2166
+ this._key,
2167
+ JSON.stringify(
2168
+ kept.map(({ result, ...e }) =>
2169
+ result === undefined ? e : { ...e, resultOmitted: true },
2170
+ ),
2171
+ ),
2172
+ );
2173
+ } catch {
2174
+ /* storage unavailable */
2175
+ }
2176
+ }
2177
+ }
2178
+
2179
+ put(entry) {
2180
+ const list = this._read();
2181
+ const now = Date.now();
2182
+ const i = list.findIndex((e) => e.jobId === entry.jobId);
2183
+ const fields = Object.fromEntries(
2184
+ Object.entries(entry).filter(([, v]) => v !== undefined && v !== null),
2185
+ );
2186
+ const next = { ...(i >= 0 ? list[i] : { createdAt: now }), ...fields, updatedAt: now };
2187
+ if (i >= 0) list[i] = next;
2188
+ else list.push(next);
2189
+ this._write(list);
2190
+ }
2191
+
2192
+ /** Record an outcome — only for a job this browser is tracking. */
2193
+ settle(jobId, patch) {
2194
+ const list = this._read();
2195
+ const i = list.findIndex((e) => e.jobId === jobId);
2196
+ if (i < 0) return;
2197
+ const next = { ...list[i], ...patch, updatedAt: Date.now() };
2198
+ if (patch.status === 'succeeded') delete next.error;
2199
+ if (next.result !== undefined) {
2200
+ let size = Infinity;
2201
+ try {
2202
+ size = JSON.stringify(next.result).length;
2203
+ } catch {
2204
+ /* unserialisable */
2205
+ }
2206
+ if (size > JOB_STORE_RESULT_MAX_CHARS) {
2207
+ delete next.result;
2208
+ next.resultOmitted = true;
2209
+ } else {
2210
+ delete next.resultOmitted;
2211
+ }
2212
+ }
2213
+ list[i] = next;
2214
+ this._write(list);
2215
+ }
2216
+
2217
+ list(tag) {
2218
+ return this._read()
2219
+ .filter((e) => tag === undefined || tag === null || e.tag === tag)
2220
+ .sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0))
2221
+ .map((e) => ({ ...e }));
2222
+ }
2223
+
2224
+ latest(tag) {
2225
+ return this.list(tag)[0] ?? null;
2226
+ }
2227
+
2228
+ forget(jobIdOrTag) {
2229
+ if (!jobIdOrTag) return;
2230
+ this._write(
2231
+ this._read().filter(
2232
+ (e) => e.jobId !== jobIdOrTag && e.tag !== jobIdOrTag,
2233
+ ),
2234
+ );
2235
+ }
2236
+ }
2237
+
2238
+ /** `?tag=…` for a job route (labels the job; capped like the gateway caps it). */
2239
+ function tagQuery(tag) {
2240
+ if (tag === undefined || tag === null || tag === '') return '';
2241
+ return `?tag=${encodeURIComponent(String(tag).slice(0, 128))}`;
2242
+ }
2243
+
2244
+ /** A finished video job as `generateVideo` has always resolved it. */
2245
+ function toVideoResult(job) {
2246
+ return {
2247
+ videoUrl: job.videoUrl,
2248
+ thumbnailUrl: job.thumbnailUrl,
2249
+ prompt: job.prompt,
2250
+ usage: job.usage || { creditsUsed: 0 },
2251
+ // Session turns only. Spread conditionally so a plain generation's
2252
+ // result keeps exactly the shape earlier SDK versions returned — no
2253
+ // undefined keys appearing in it.
2254
+ ...(job.sessionId ? { sessionId: job.sessionId } : {}),
2255
+ ...(job.segmentUrl ? { segmentUrl: job.segmentUrl } : {}),
2256
+ ...(job.durationSeconds != null
2257
+ ? { durationSeconds: job.durationSeconds }
2258
+ : {}),
2259
+ ...(job.segmentsDone != null ? { segmentsDone: job.segmentsDone } : {}),
2260
+ // Short of the requested length, but real and paid for.
2261
+ ...(job.warning ? { warning: job.warning } : {}),
2262
+ };
2263
+ }
2264
+
2265
+ /**
2266
+ * Server-sent events from a fetch body: `{ comment }` for comment lines (the
2267
+ * gateway announces a stream's job id in one) and `{ chunk }` for data.
2268
+ * Stopping early cancels the body, which closes the connection.
2269
+ */
2270
+ async function* readSseEvents(body) {
2271
+ const reader = body.getReader();
2272
+ const decoder = new TextDecoder();
2273
+ let buffer = '';
2274
+ let finished = false;
2275
+ try {
2276
+ while (true) {
2277
+ const { value, done } = await reader.read();
2278
+ if (done) {
2279
+ finished = true;
2280
+ break;
2281
+ }
2282
+ buffer += decoder.decode(value, { stream: true });
2283
+ let idx;
2284
+ while ((idx = buffer.indexOf('\n\n')) !== -1) {
2285
+ const rawEvent = buffer.slice(0, idx);
2286
+ buffer = buffer.slice(idx + 2);
2287
+ for (const line of rawEvent.split(/\r?\n/)) {
2288
+ if (line.startsWith(':')) yield { comment: line.slice(1).trim() };
2289
+ }
2290
+ const chunk = parseSseEvent(rawEvent);
2291
+ if (chunk !== null) yield { chunk };
2292
+ }
2293
+ }
2294
+ } finally {
2295
+ if (finished) {
2296
+ try {
2297
+ reader.releaseLock();
2298
+ } catch {
2299
+ /* ignore */
2300
+ }
2301
+ } else {
2302
+ reader.cancel().catch(() => {});
2303
+ }
2304
+ }
2305
+ }
2306
+
1720
2307
  function parseSseEvent(rawEvent) {
1721
2308
  const trimmed = rawEvent.trim();
1722
2309
  if (!trimmed) return null;