@devvibex/aiflow 1.15.2 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -129,7 +129,68 @@ throws.
129
129
  ### `aiflow.chatStream({ ... })`
130
130
 
131
131
  Async iterable of `{ delta: string, done: boolean }` chunks. The final chunk
132
- has `done: true` and carries the cumulative `usage` object.
132
+ has `done: true` and carries the cumulative `usage` object (and `jobId` on a
133
+ gateway with background jobs). A server error inside the stream — e.g. a 402
134
+ when the owner is out of credits — throws an `AIFlowError` (≥ 1.16.0; older
135
+ versions yielded it as a chunk with `error: true`). A dropped connection is
136
+ re-attached to the answer automatically.
137
+
138
+ ## Background jobs — generation that survives leaving the page (≥ 1.16.0)
139
+
140
+ On a gateway that supports it (`config.capabilities.jobs`), `chat`,
141
+ `chatStream`, `generateImage`, `generateImageBatch`, `generateAudio` and
142
+ `generateSfx` run as **background jobs**, as video always has: the gateway
143
+ keeps generating when the page that asked is closed, reloaded or navigated
144
+ away from, and keeps the result for a week. The calls resolve with exactly the
145
+ same value as before; on an older gateway they fall back to one synchronous
146
+ request.
147
+
148
+ Every generation call takes two extra options:
149
+
150
+ | Option | |
151
+ | --- | --- |
152
+ | `onJob(jobId, info?)` | Fires once the gateway has accepted the job, before it finishes. Store the id (e.g. on a "generating" row) to pick the result up later. |
153
+ | `tag` | A label (≤ 128 chars) for `jobs.latest(tag)` and `listJobs()`. |
154
+
155
+ Aborting `signal` now **stops only the waiting** — the generation carries on
156
+ and stays retrievable.
157
+
158
+ ```js
159
+ // Start: keep the job id with the row that is waiting for the result.
160
+ const row = await Artwork.create({ prompt, status: 'generating' });
161
+ const res = await aiflow.generateImage({
162
+ prompt,
163
+ onJob: (jobId) => Artwork.update(row.id, { job_id: jobId }),
164
+ });
165
+ await Artwork.update(row.id, { status: 'done', image_url: res.images[0].url });
166
+
167
+ // Later — after a reload, on another page or device: finish any row still waiting.
168
+ const finished = await aiflow.waitForJob(row.job_id); // same value generateImage resolves with
169
+ ```
170
+
171
+ | Method | |
172
+ | --- | --- |
173
+ | `waitForJob(jobId, { signal?, timeout?, onProgress? })` | Resolves with the job's result (what the starting call resolves with; a video job resolves like `generateVideo`). Throws an `AIFlowError` with the job's `status` / `code` when it failed. `timeout` defaults to 30 min. |
174
+ | `resumeChatStream(jobId, { from?, signal? })` | Re-attach to a streamed chat answer: chunks from character `from` (the length already shown; `0` replays all of it), then live until done. |
175
+ | `getJob(jobId, { waitMs? })` | One job now: `{ jobId, kind, status, tag?, prompt?, result?, error?, errorStatus?, errorCode? }`. |
176
+ | `listJobs({ active?, limit? })` | The signed-in end user's own jobs on this module, from any device (needs `setEndUser(id, token)`; anonymous → `[]`). No results — read one with `waitForJob`. |
177
+ | `jobs.latest(tag?)` / `jobs.list({ tag? })` / `jobs.forget(idOrTag)` | Jobs started from **this browser**, kept a day in localStorage: `{ jobId, kind, tag, status, result?, error? }`. Works without login. |
178
+
179
+ Without a database row, the browser's own record is enough for a page that
180
+ shows its latest result:
181
+
182
+ ```js
183
+ // On mount: show what finished while the user was away, or keep waiting.
184
+ const last = aiflow.jobs.latest('poster');
185
+ if (last?.status === 'succeeded') setImages(last.result.images);
186
+ else if (last?.status === 'processing') aiflow.waitForJob(last.jobId).then((r) => setImages(r.images));
187
+
188
+ // Generate
189
+ const res = await aiflow.generateImage({ prompt, tag: 'poster' });
190
+ ```
191
+
192
+ A job whose server restarted mid-way fails with `code: 'interrupted'` (status
193
+ 503) and is not charged — credits are deducted only on success.
133
194
 
134
195
  ### `aiflow.generateImage({ prompt, model?, size?, aspectRatio?, n?, image?, images?, system?, language?, background?, signal? })`
135
196
 
@@ -592,6 +653,10 @@ setTimeout(() => ctrl.abort(), 3000);
592
653
  await aiflow.chat({ messages, signal: ctrl.signal });
593
654
  ```
594
655
 
656
+ With background jobs (≥ 1.16.0 on a gateway that has them) aborting stops the
657
+ waiting, not the generation: the job finishes and `waitForJob(jobId)` returns
658
+ its result.
659
+
595
660
  ## Publishing to npmjs
596
661
 
597
662
  > Owned by the `@devvibex` org. You must be a member to publish.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devvibex/aiflow",
3
- "version": "1.15.2",
3
+ "version": "1.16.0",
4
4
  "description": "First-party LLM gateway SDK for apps generated on the VibeX platform — chat, streaming, image, video (including stateful multi-turn video extension with Gemini Omni), music (Lyria), sound effects (ElevenLabs), embeddings and real-time speech translation (Gemini Live) without shipping any third-party API key.",
5
5
  "keywords": [
6
6
  "ai",
package/src/index.d.ts CHANGED
@@ -3,6 +3,7 @@ export interface AIFlowErrorOptions {
3
3
  code?: string;
4
4
  requestId?: string;
5
5
  cause?: unknown;
6
+ fromServer?: boolean;
6
7
  }
7
8
 
8
9
  export class AIFlowError extends Error {
@@ -11,9 +12,84 @@ export class AIFlowError extends Error {
11
12
  code?: string;
12
13
  requestId?: string;
13
14
  cause?: unknown;
15
+ /** Set on an error the gateway reported inside a chat stream. */
16
+ fromServer?: boolean;
14
17
  constructor(message: string, options?: AIFlowErrorOptions);
15
18
  }
16
19
 
20
+ /**
21
+ * Options every generation call takes on a gateway with background jobs
22
+ * (`config.capabilities.jobs`). The call still resolves with its usual result;
23
+ * the generation itself runs on the gateway and keeps going if the page goes
24
+ * away.
25
+ */
26
+ export interface BackgroundJobOptions {
27
+ /**
28
+ * Called once the gateway has accepted the job, before it finishes. Store
29
+ * the id (e.g. on a "generating" row) to pick the result up later with
30
+ * `waitForJob(jobId)` / `resumeChatStream(jobId)`.
31
+ */
32
+ onJob?: (jobId: string, info?: { sessionId?: string }) => void;
33
+ /** Label for the job in `jobs.latest(tag)` / `listJobs()` (max 128 chars). */
34
+ tag?: string;
35
+ }
36
+
37
+ export type JobKind =
38
+ | 'chat'
39
+ | 'chat_stream'
40
+ | 'image'
41
+ | 'image_batch'
42
+ | 'audio'
43
+ | 'sfx'
44
+ | 'video';
45
+
46
+ export type JobStatus = 'queued' | 'processing' | 'succeeded' | 'failed';
47
+
48
+ /** A background job as the gateway reports it (`getJob` / `listJobs`). */
49
+ export interface JobView {
50
+ jobId: string;
51
+ kind: JobKind;
52
+ status: JobStatus;
53
+ tag?: string;
54
+ model?: string;
55
+ /** The request's prompt, shortened. */
56
+ prompt?: string;
57
+ createdAt?: string;
58
+ finishedAt?: string;
59
+ /** On success (`getJob` only): what the starting call resolves with. */
60
+ result?: any;
61
+ /** Characters of a streamed chat answer written so far. */
62
+ contentLength?: number;
63
+ /** Video builds and merges: progress while running. */
64
+ progress?: Partial<VideoBuildProgress>;
65
+ error?: string;
66
+ errorStatus?: number;
67
+ errorCode?: string;
68
+ }
69
+
70
+ /** A job this browser started, as `jobs.latest()` / `jobs.list()` keep it. */
71
+ export interface RememberedJob {
72
+ jobId: string;
73
+ kind: JobKind;
74
+ tag?: string;
75
+ status: JobStatus;
76
+ /** What the call resolved with, once it succeeded (absent when too large — use `waitForJob`). */
77
+ result?: any;
78
+ resultOmitted?: boolean;
79
+ error?: string;
80
+ createdAt: number;
81
+ updatedAt: number;
82
+ }
83
+
84
+ export interface JobsNamespace {
85
+ /** Newest remembered job with this tag (any tag when omitted), or null. */
86
+ latest(tag?: string): RememberedJob | null;
87
+ /** Remembered jobs, newest first, optionally only one tag. */
88
+ list(filter?: { tag?: string }): RememberedJob[];
89
+ /** Forget one job (by id) or every job with a tag. */
90
+ forget(jobIdOrTag: string): void;
91
+ }
92
+
17
93
  export type ChatRole = 'system' | 'user' | 'assistant';
18
94
 
19
95
  // ─── Multimodal content blocks ───────────────────────────────────────────────
@@ -61,7 +137,12 @@ export interface ChatRequest {
61
137
  webSearch?: boolean;
62
138
  /** @deprecated Not supported by the gateway — passing it throws. */
63
139
  tools?: ChatTool[];
140
+ /** Stops waiting (or reading the stream); the generation itself continues. */
64
141
  signal?: AbortSignal;
142
+ /** `chat()` only: overall wait (ms). Defaults to 30 min with background jobs, else 60s. */
143
+ timeout?: number;
144
+ onJob?: BackgroundJobOptions['onJob'];
145
+ tag?: string;
65
146
  }
66
147
 
67
148
  export interface ChatUsage {
@@ -90,6 +171,8 @@ export interface ChatStreamChunk {
90
171
  model?: string;
91
172
  /** Where the resolved `model` came from (present on the final `done: true` chunk). */
92
173
  modelSource?: ModelSource;
174
+ /** Final chunk, on a gateway with background jobs: the answer's job id. */
175
+ jobId?: string;
93
176
  [key: string]: unknown;
94
177
  }
95
178
 
@@ -127,8 +210,13 @@ export interface ImageRequest {
127
210
  */
128
211
  background?: ImageBackground;
129
212
  signal?: AbortSignal;
130
- /** Per-call timeout (ms). Defaults to 180000 — image edits exceed the 60s client default. */
213
+ /**
214
+ * Overall wait (ms). Defaults to 30 min with background jobs; without
215
+ * them, the request timeout, 180000 — image edits exceed the 60s default.
216
+ */
131
217
  timeout?: number;
218
+ onJob?: BackgroundJobOptions['onJob'];
219
+ tag?: string;
132
220
  }
133
221
 
134
222
  export interface GeneratedImage {
@@ -177,8 +265,10 @@ export interface ImageBatchRequest {
177
265
  /** Shared `background` for every page — see {@link ImageRequest.background}. */
178
266
  background?: ImageBackground;
179
267
  signal?: AbortSignal;
180
- /** Per-call timeout (ms). Defaults to 600000 (10 min). */
268
+ /** Overall wait (ms). Defaults to 30 min with background jobs, else 600000 (10 min). */
181
269
  timeout?: number;
270
+ onJob?: BackgroundJobOptions['onJob'];
271
+ tag?: string;
182
272
  }
183
273
 
184
274
  export interface ImageBatchPageResult {
@@ -280,6 +370,9 @@ export interface VideoRequest {
280
370
  timeout?: number;
281
371
  /** Interval between status polls (ms). Defaults to 3000. */
282
372
  pollIntervalMs?: number;
373
+ /** `generateVideo` only — see {@link BackgroundJobOptions}. */
374
+ onJob?: BackgroundJobOptions['onJob'];
375
+ tag?: string;
283
376
  }
284
377
 
285
378
  export interface VideoResponse {
@@ -475,6 +568,9 @@ export interface LongVideoRequest {
475
568
  /** Overall wait budget. Defaults to ~7 minutes per 10s requested. */
476
569
  timeout?: number;
477
570
  pollIntervalMs?: number;
571
+ /** Receives the build's job id (and `sessionId`) as soon as it starts. */
572
+ onJob?: BackgroundJobOptions['onJob'];
573
+ tag?: string;
478
574
  }
479
575
 
480
576
  export interface LongVideoResponse extends VideoResponse {
@@ -503,6 +599,8 @@ export interface VideoMergeRequest {
503
599
  /** Defaults to 2 minutes per clip (minimum 10 minutes). */
504
600
  timeout?: number;
505
601
  pollIntervalMs?: number;
602
+ onJob?: BackgroundJobOptions['onJob'];
603
+ tag?: string;
506
604
  }
507
605
 
508
606
  export interface VideoMergeResponse extends VideoResponse {
@@ -529,6 +627,9 @@ export interface VideoExtendRequest {
529
627
  signal?: AbortSignal;
530
628
  timeout?: number;
531
629
  pollIntervalMs?: number;
630
+ /** `extendVideo` only — receives the turn's job id. */
631
+ onJob?: BackgroundJobOptions['onJob'];
632
+ tag?: string;
532
633
  }
533
634
 
534
635
  /** Result of one completed extend turn. */
@@ -579,8 +680,10 @@ export interface AudioRequest {
579
680
  /** Passed to Lyria as a seed. Google does not promise the same song for the same seed. */
580
681
  seed?: number;
581
682
  signal?: AbortSignal;
582
- /** Per-call timeout (ms). Defaults to 180000 (3 min) — music gen is slow. */
683
+ /** Overall wait (ms). Defaults to 30 min with background jobs, else 180000 (3 min). */
583
684
  timeout?: number;
685
+ onJob?: BackgroundJobOptions['onJob'];
686
+ tag?: string;
584
687
  }
585
688
 
586
689
  export interface AudioResponse {
@@ -616,8 +719,10 @@ export interface SfxRequest {
616
719
  /** Make the clip loop seamlessly (ambience, engine hum, rain). */
617
720
  loop?: boolean;
618
721
  signal?: AbortSignal;
619
- /** Per-call timeout (ms). Defaults to 120000 (2 min). */
722
+ /** Overall wait (ms). Defaults to 30 min with background jobs, else 120000 (2 min). */
620
723
  timeout?: number;
724
+ onJob?: BackgroundJobOptions['onJob'];
725
+ tag?: string;
621
726
  }
622
727
 
623
728
  export interface SfxResponse {
@@ -942,6 +1047,8 @@ export interface AiflowConfig {
942
1047
  webSearch?: boolean;
943
1048
  /** Whether the real-time live-translate feature is enabled. */
944
1049
  liveTranslate?: boolean;
1050
+ /** Gateway features. `jobs`: generations run as background jobs. */
1051
+ capabilities?: { jobs?: boolean };
945
1052
  }
946
1053
 
947
1054
  // ─── Admin (module config) ───────────────────────────────────────────────────
@@ -1014,6 +1121,8 @@ export class AIFlowClient {
1014
1121
  readonly knowledge: KnowledgeNamespace;
1015
1122
  /** Admin namespace — manage the app's AIFlow module config (needs `setAdminToken`). */
1016
1123
  readonly admin: AiflowAdminNamespace;
1124
+ /** Background jobs started from this browser, remembered for a day. */
1125
+ readonly jobs: JobsNamespace;
1017
1126
 
1018
1127
  constructor(options: AIFlowClientOptions);
1019
1128
 
@@ -1129,6 +1238,8 @@ export class AIFlowClient {
1129
1238
  signal?: AbortSignal;
1130
1239
  timeout?: number;
1131
1240
  pollIntervalMs?: number;
1241
+ onJob?: BackgroundJobOptions['onJob'];
1242
+ tag?: string;
1132
1243
  },
1133
1244
  ): Promise<LongVideoResponse>;
1134
1245
  /** Submit a merge without waiting; poll it with {@link getVideoJob}. */
@@ -1165,6 +1276,42 @@ export class AIFlowClient {
1165
1276
  generateSfx(request: SfxRequest): Promise<SfxResponse>;
1166
1277
  embed(request: EmbedRequest): Promise<EmbedResponse>;
1167
1278
  vision(request: VisionRequest): Promise<VisionResponse>;
1279
+ /**
1280
+ * Wait for a background job and resolve with its result — what the call
1281
+ * that started it resolves with. Works after a reload or on another page.
1282
+ * Aborting `signal` / hitting `timeout` (default 30 min) stops only the
1283
+ * waiting. Throws an AIFlowError (`status`, `code`) when the job failed.
1284
+ */
1285
+ waitForJob<T = any>(
1286
+ jobId: string,
1287
+ options?: {
1288
+ signal?: AbortSignal;
1289
+ timeout?: number;
1290
+ onProgress?: (progress: VideoBuildProgress) => void;
1291
+ },
1292
+ ): Promise<T>;
1293
+ /** Read one job now; `waitMs` (≤ 25000) lets the gateway hold until it finishes. */
1294
+ getJob(
1295
+ jobId: string,
1296
+ options?: { waitMs?: number; signal?: AbortSignal },
1297
+ ): Promise<JobView>;
1298
+ /**
1299
+ * The signed-in end user's own jobs on this module (any device), newest
1300
+ * first, without results. Anonymous callers get an empty list.
1301
+ */
1302
+ listJobs(options?: {
1303
+ active?: boolean;
1304
+ limit?: number;
1305
+ signal?: AbortSignal;
1306
+ }): Promise<{ jobs: JobView[] }>;
1307
+ /**
1308
+ * Re-attach to a streamed chat answer from character `from` (0 replays
1309
+ * all of it), then follow it live until done.
1310
+ */
1311
+ resumeChatStream(
1312
+ jobId: string,
1313
+ options?: { from?: number; signal?: AbortSignal },
1314
+ ): AsyncGenerator<ChatStreamChunk, void, void>;
1168
1315
  /**
1169
1316
  * Open a real-time speech-translation session over WebSocket (Gemini Live
1170
1317
  * via the gateway). Requires the optional peer dependency
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
@@ -673,31 +821,14 @@ export class AIFlowClient {
673
821
  }
674
822
  }
675
823
  if (job.status === 'succeeded') {
676
- return {
677
- videoUrl: job.videoUrl,
678
- thumbnailUrl: job.thumbnailUrl,
679
- prompt: job.prompt,
680
- usage: job.usage || { creditsUsed: 0 },
681
- // Session turns only. Spread conditionally so a plain
682
- // generation's result keeps exactly the shape earlier SDK
683
- // versions returned — no undefined keys appearing in it.
684
- ...(job.sessionId ? { sessionId: job.sessionId } : {}),
685
- ...(job.segmentUrl ? { segmentUrl: job.segmentUrl } : {}),
686
- ...(job.durationSeconds != null
687
- ? { durationSeconds: job.durationSeconds }
688
- : {}),
689
- ...(job.segmentsDone != null
690
- ? { segmentsDone: job.segmentsDone }
691
- : {}),
692
- // Short of the requested length, but real and paid for.
693
- ...(job.warning ? { warning: job.warning } : {}),
694
- };
824
+ const result = toVideoResult(job);
825
+ this._jobStore.settle(jobId, { status: 'succeeded', result });
826
+ return result;
695
827
  }
696
828
  if (job.status === 'failed') {
697
- throw new AIFlowError(
698
- job.error || 'Video generation failed',
699
- { code: 'video_failed' },
700
- );
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' });
701
832
  }
702
833
  if (Date.now() >= deadline) {
703
834
  throw new AIFlowError(
@@ -745,11 +876,14 @@ export class AIFlowClient {
745
876
  signal,
746
877
  timeout,
747
878
  pollIntervalMs,
879
+ onJob,
880
+ tag,
748
881
  } = {}) {
749
882
  if (!Array.isArray(videos) || videos.length < 2) {
750
883
  throw new AIFlowError('mergeVideos needs at least two videos');
751
884
  }
752
885
  const { jobId } = await this.submitVideoMerge({ videos, signal });
886
+ this._trackJob(jobId, 'video', tag, onJob);
753
887
  return this._pollVideoJob(jobId, {
754
888
  signal,
755
889
  // Every clip is fetched and usually re-encoded on the gateway, so the
@@ -901,6 +1035,8 @@ export class AIFlowClient {
901
1035
  signal,
902
1036
  timeout,
903
1037
  pollIntervalMs,
1038
+ onJob,
1039
+ tag,
904
1040
  } = {}) {
905
1041
  if (!prompt || typeof prompt !== 'string') {
906
1042
  throw new AIFlowError('prompt is required');
@@ -920,6 +1056,7 @@ export class AIFlowClient {
920
1056
  targetDurationSeconds: durationSeconds,
921
1057
  signal,
922
1058
  });
1059
+ this._trackJob(jobId, 'video', tag, onJob, { sessionId });
923
1060
  const result = await this._pollVideoJob(jobId, {
924
1061
  signal,
925
1062
  timeout: timeout ?? longVideoTimeoutMs(durationSeconds),
@@ -948,7 +1085,7 @@ export class AIFlowClient {
948
1085
  */
949
1086
  async resumeLongVideo(
950
1087
  sessionId,
951
- { onProgress, signal, timeout, pollIntervalMs } = {},
1088
+ { onProgress, signal, timeout, pollIntervalMs, onJob, tag } = {},
952
1089
  ) {
953
1090
  if (!sessionId || typeof sessionId !== 'string') {
954
1091
  throw new AIFlowError('sessionId is required');
@@ -959,6 +1096,7 @@ export class AIFlowClient {
959
1096
  { signal, timeout: DEFAULT_TIMEOUT_MS },
960
1097
  );
961
1098
  const { jobId } = await res.json();
1099
+ this._trackJob(jobId, 'video', tag, onJob, { sessionId });
962
1100
  // Read the session to size the wait from what is actually left, rather
963
1101
  // than from the whole film that was originally asked for.
964
1102
  let remaining = 0;
@@ -997,6 +1135,7 @@ export class AIFlowClient {
997
1135
  */
998
1136
  async extendVideo(sessionId, opts = {}) {
999
1137
  const { jobId } = await this.submitVideoExtend(sessionId, opts);
1138
+ this._trackJob(jobId, 'video', opts.tag, opts.onJob, { sessionId });
1000
1139
  return this._pollVideoJob(jobId, {
1001
1140
  signal: opts.signal,
1002
1141
  timeout: opts.timeout ?? 600_000,
@@ -1079,6 +1218,8 @@ export class AIFlowClient {
1079
1218
  seed,
1080
1219
  signal,
1081
1220
  timeout,
1221
+ onJob,
1222
+ tag,
1082
1223
  } = {}) {
1083
1224
  if (!prompt || typeof prompt !== 'string') {
1084
1225
  throw new AIFlowError('prompt is required');
@@ -1088,9 +1229,10 @@ export class AIFlowClient {
1088
1229
  }
1089
1230
  const resolvedModel =
1090
1231
  model || (await this._resolveDefaultModel('audio'));
1091
- const res = await this._request(
1092
- '/audio',
1093
- {
1232
+ return this._generate({
1233
+ kind: 'audio',
1234
+ path: '/audio',
1235
+ body: {
1094
1236
  model: resolvedModel,
1095
1237
  prompt,
1096
1238
  images: images?.length ? images : undefined,
@@ -1100,11 +1242,14 @@ export class AIFlowClient {
1100
1242
  negativePrompt,
1101
1243
  seed,
1102
1244
  },
1245
+ signal,
1246
+ timeout,
1103
1247
  // Music generation (a full Lyria 3.5 song) runs well past the 60s
1104
- // client default — allow 3 minutes before aborting.
1105
- { signal, timeout: timeout ?? 180_000 },
1106
- );
1107
- return await res.json();
1248
+ // client default — the synchronous route gets 3 minutes.
1249
+ requestTimeout: 180_000,
1250
+ onJob,
1251
+ tag,
1252
+ });
1108
1253
  }
1109
1254
 
1110
1255
  /**
@@ -1119,23 +1264,29 @@ export class AIFlowClient {
1119
1264
  loop,
1120
1265
  signal,
1121
1266
  timeout,
1267
+ onJob,
1268
+ tag,
1122
1269
  } = {}) {
1123
1270
  if (!prompt || typeof prompt !== 'string') {
1124
1271
  throw new AIFlowError('prompt is required');
1125
1272
  }
1126
1273
  const resolvedModel = model || (await this._resolveDefaultModel('sfx'));
1127
- const res = await this._request(
1128
- '/sfx',
1129
- {
1274
+ return this._generate({
1275
+ kind: 'sfx',
1276
+ path: '/sfx',
1277
+ body: {
1130
1278
  model: resolvedModel,
1131
1279
  prompt,
1132
1280
  durationSeconds,
1133
1281
  promptInfluence,
1134
1282
  loop,
1135
1283
  },
1136
- { signal, timeout: timeout ?? 120_000 },
1137
- );
1138
- return await res.json();
1284
+ signal,
1285
+ timeout,
1286
+ requestTimeout: 120_000,
1287
+ onJob,
1288
+ tag,
1289
+ });
1139
1290
  }
1140
1291
 
1141
1292
  /**
@@ -1199,6 +1350,184 @@ export class AIFlowClient {
1199
1350
  return await res.json();
1200
1351
  }
1201
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
+
1202
1531
  /**
1203
1532
  * Open a real-time speech-translation session over WebSocket (Gemini Live
1204
1533
  * via the platform gateway — no Google key in the browser). Stream 16 kHz
@@ -1777,6 +2106,204 @@ function toBase64(chunk) {
1777
2106
  // Helpers
1778
2107
  // ────────────────────────────────────────────────────────────────────────────
1779
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
+
1780
2307
  function parseSseEvent(rawEvent) {
1781
2308
  const trimmed = rawEvent.trim();
1782
2309
  if (!trimmed) return null;