@devvibex/aiflow 1.15.2 → 1.16.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
@@ -129,7 +129,71 @@ 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. `chat`,
194
+ `generateImage`, `generateImageBatch`, `generateAudio` and `generateSfx` submit
195
+ such a job once more by themselves (≥ 1.16.1; `onJob` fires again with the new
196
+ id); `waitForJob` on a stored id and `chatStream` throw it, so offer a retry.
133
197
 
134
198
  ### `aiflow.generateImage({ prompt, model?, size?, aspectRatio?, n?, image?, images?, system?, language?, background?, signal? })`
135
199
 
@@ -592,6 +656,10 @@ setTimeout(() => ctrl.abort(), 3000);
592
656
  await aiflow.chat({ messages, signal: ctrl.signal });
593
657
  ```
594
658
 
659
+ With background jobs (≥ 1.16.0 on a gateway that has them) aborting stops the
660
+ waiting, not the generation: the job finishes and `waitForJob(jobId)` returns
661
+ its result.
662
+
595
663
  ## Publishing to npmjs
596
664
 
597
665
  > 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.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
@@ -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,86 @@ 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)`. Fires again with a new id
31
+ * when a job cut off by a gateway restart is run once more (chat, image,
32
+ * music and SFX calls do that automatically).
33
+ */
34
+ onJob?: (jobId: string, info?: { sessionId?: string }) => void;
35
+ /** Label for the job in `jobs.latest(tag)` / `listJobs()` (max 128 chars). */
36
+ tag?: string;
37
+ }
38
+
39
+ export type JobKind =
40
+ | 'chat'
41
+ | 'chat_stream'
42
+ | 'image'
43
+ | 'image_batch'
44
+ | 'audio'
45
+ | 'sfx'
46
+ | 'video';
47
+
48
+ export type JobStatus = 'queued' | 'processing' | 'succeeded' | 'failed';
49
+
50
+ /** A background job as the gateway reports it (`getJob` / `listJobs`). */
51
+ export interface JobView {
52
+ jobId: string;
53
+ kind: JobKind;
54
+ status: JobStatus;
55
+ tag?: string;
56
+ model?: string;
57
+ /** The request's prompt, shortened. */
58
+ prompt?: string;
59
+ createdAt?: string;
60
+ finishedAt?: string;
61
+ /** On success (`getJob` only): what the starting call resolves with. */
62
+ result?: any;
63
+ /** Characters of a streamed chat answer written so far. */
64
+ contentLength?: number;
65
+ /** Video builds and merges: progress while running. */
66
+ progress?: Partial<VideoBuildProgress>;
67
+ error?: string;
68
+ errorStatus?: number;
69
+ errorCode?: string;
70
+ }
71
+
72
+ /** A job this browser started, as `jobs.latest()` / `jobs.list()` keep it. */
73
+ export interface RememberedJob {
74
+ jobId: string;
75
+ kind: JobKind;
76
+ tag?: string;
77
+ status: JobStatus;
78
+ /** What the call resolved with, once it succeeded (absent when too large — use `waitForJob`). */
79
+ result?: any;
80
+ resultOmitted?: boolean;
81
+ error?: string;
82
+ createdAt: number;
83
+ updatedAt: number;
84
+ }
85
+
86
+ export interface JobsNamespace {
87
+ /** Newest remembered job with this tag (any tag when omitted), or null. */
88
+ latest(tag?: string): RememberedJob | null;
89
+ /** Remembered jobs, newest first, optionally only one tag. */
90
+ list(filter?: { tag?: string }): RememberedJob[];
91
+ /** Forget one job (by id) or every job with a tag. */
92
+ forget(jobIdOrTag: string): void;
93
+ }
94
+
17
95
  export type ChatRole = 'system' | 'user' | 'assistant';
18
96
 
19
97
  // ─── Multimodal content blocks ───────────────────────────────────────────────
@@ -61,7 +139,12 @@ export interface ChatRequest {
61
139
  webSearch?: boolean;
62
140
  /** @deprecated Not supported by the gateway — passing it throws. */
63
141
  tools?: ChatTool[];
142
+ /** Stops waiting (or reading the stream); the generation itself continues. */
64
143
  signal?: AbortSignal;
144
+ /** `chat()` only: overall wait (ms). Defaults to 30 min with background jobs, else 60s. */
145
+ timeout?: number;
146
+ onJob?: BackgroundJobOptions['onJob'];
147
+ tag?: string;
65
148
  }
66
149
 
67
150
  export interface ChatUsage {
@@ -90,6 +173,8 @@ export interface ChatStreamChunk {
90
173
  model?: string;
91
174
  /** Where the resolved `model` came from (present on the final `done: true` chunk). */
92
175
  modelSource?: ModelSource;
176
+ /** Final chunk, on a gateway with background jobs: the answer's job id. */
177
+ jobId?: string;
93
178
  [key: string]: unknown;
94
179
  }
95
180
 
@@ -127,8 +212,13 @@ export interface ImageRequest {
127
212
  */
128
213
  background?: ImageBackground;
129
214
  signal?: AbortSignal;
130
- /** Per-call timeout (ms). Defaults to 180000 — image edits exceed the 60s client default. */
215
+ /**
216
+ * Overall wait (ms). Defaults to 30 min with background jobs; without
217
+ * them, the request timeout, 180000 — image edits exceed the 60s default.
218
+ */
131
219
  timeout?: number;
220
+ onJob?: BackgroundJobOptions['onJob'];
221
+ tag?: string;
132
222
  }
133
223
 
134
224
  export interface GeneratedImage {
@@ -177,8 +267,10 @@ export interface ImageBatchRequest {
177
267
  /** Shared `background` for every page — see {@link ImageRequest.background}. */
178
268
  background?: ImageBackground;
179
269
  signal?: AbortSignal;
180
- /** Per-call timeout (ms). Defaults to 600000 (10 min). */
270
+ /** Overall wait (ms). Defaults to 30 min with background jobs, else 600000 (10 min). */
181
271
  timeout?: number;
272
+ onJob?: BackgroundJobOptions['onJob'];
273
+ tag?: string;
182
274
  }
183
275
 
184
276
  export interface ImageBatchPageResult {
@@ -280,6 +372,9 @@ export interface VideoRequest {
280
372
  timeout?: number;
281
373
  /** Interval between status polls (ms). Defaults to 3000. */
282
374
  pollIntervalMs?: number;
375
+ /** `generateVideo` only — see {@link BackgroundJobOptions}. */
376
+ onJob?: BackgroundJobOptions['onJob'];
377
+ tag?: string;
283
378
  }
284
379
 
285
380
  export interface VideoResponse {
@@ -475,6 +570,9 @@ export interface LongVideoRequest {
475
570
  /** Overall wait budget. Defaults to ~7 minutes per 10s requested. */
476
571
  timeout?: number;
477
572
  pollIntervalMs?: number;
573
+ /** Receives the build's job id (and `sessionId`) as soon as it starts. */
574
+ onJob?: BackgroundJobOptions['onJob'];
575
+ tag?: string;
478
576
  }
479
577
 
480
578
  export interface LongVideoResponse extends VideoResponse {
@@ -503,6 +601,8 @@ export interface VideoMergeRequest {
503
601
  /** Defaults to 2 minutes per clip (minimum 10 minutes). */
504
602
  timeout?: number;
505
603
  pollIntervalMs?: number;
604
+ onJob?: BackgroundJobOptions['onJob'];
605
+ tag?: string;
506
606
  }
507
607
 
508
608
  export interface VideoMergeResponse extends VideoResponse {
@@ -529,6 +629,9 @@ export interface VideoExtendRequest {
529
629
  signal?: AbortSignal;
530
630
  timeout?: number;
531
631
  pollIntervalMs?: number;
632
+ /** `extendVideo` only — receives the turn's job id. */
633
+ onJob?: BackgroundJobOptions['onJob'];
634
+ tag?: string;
532
635
  }
533
636
 
534
637
  /** Result of one completed extend turn. */
@@ -579,8 +682,10 @@ export interface AudioRequest {
579
682
  /** Passed to Lyria as a seed. Google does not promise the same song for the same seed. */
580
683
  seed?: number;
581
684
  signal?: AbortSignal;
582
- /** Per-call timeout (ms). Defaults to 180000 (3 min) — music gen is slow. */
685
+ /** Overall wait (ms). Defaults to 30 min with background jobs, else 180000 (3 min). */
583
686
  timeout?: number;
687
+ onJob?: BackgroundJobOptions['onJob'];
688
+ tag?: string;
584
689
  }
585
690
 
586
691
  export interface AudioResponse {
@@ -616,8 +721,10 @@ export interface SfxRequest {
616
721
  /** Make the clip loop seamlessly (ambience, engine hum, rain). */
617
722
  loop?: boolean;
618
723
  signal?: AbortSignal;
619
- /** Per-call timeout (ms). Defaults to 120000 (2 min). */
724
+ /** Overall wait (ms). Defaults to 30 min with background jobs, else 120000 (2 min). */
620
725
  timeout?: number;
726
+ onJob?: BackgroundJobOptions['onJob'];
727
+ tag?: string;
621
728
  }
622
729
 
623
730
  export interface SfxResponse {
@@ -942,6 +1049,8 @@ export interface AiflowConfig {
942
1049
  webSearch?: boolean;
943
1050
  /** Whether the real-time live-translate feature is enabled. */
944
1051
  liveTranslate?: boolean;
1052
+ /** Gateway features. `jobs`: generations run as background jobs. */
1053
+ capabilities?: { jobs?: boolean };
945
1054
  }
946
1055
 
947
1056
  // ─── Admin (module config) ───────────────────────────────────────────────────
@@ -1014,6 +1123,8 @@ export class AIFlowClient {
1014
1123
  readonly knowledge: KnowledgeNamespace;
1015
1124
  /** Admin namespace — manage the app's AIFlow module config (needs `setAdminToken`). */
1016
1125
  readonly admin: AiflowAdminNamespace;
1126
+ /** Background jobs started from this browser, remembered for a day. */
1127
+ readonly jobs: JobsNamespace;
1017
1128
 
1018
1129
  constructor(options: AIFlowClientOptions);
1019
1130
 
@@ -1129,6 +1240,8 @@ export class AIFlowClient {
1129
1240
  signal?: AbortSignal;
1130
1241
  timeout?: number;
1131
1242
  pollIntervalMs?: number;
1243
+ onJob?: BackgroundJobOptions['onJob'];
1244
+ tag?: string;
1132
1245
  },
1133
1246
  ): Promise<LongVideoResponse>;
1134
1247
  /** Submit a merge without waiting; poll it with {@link getVideoJob}. */
@@ -1165,6 +1278,42 @@ export class AIFlowClient {
1165
1278
  generateSfx(request: SfxRequest): Promise<SfxResponse>;
1166
1279
  embed(request: EmbedRequest): Promise<EmbedResponse>;
1167
1280
  vision(request: VisionRequest): Promise<VisionResponse>;
1281
+ /**
1282
+ * Wait for a background job and resolve with its result — what the call
1283
+ * that started it resolves with. Works after a reload or on another page.
1284
+ * Aborting `signal` / hitting `timeout` (default 30 min) stops only the
1285
+ * waiting. Throws an AIFlowError (`status`, `code`) when the job failed.
1286
+ */
1287
+ waitForJob<T = any>(
1288
+ jobId: string,
1289
+ options?: {
1290
+ signal?: AbortSignal;
1291
+ timeout?: number;
1292
+ onProgress?: (progress: VideoBuildProgress) => void;
1293
+ },
1294
+ ): Promise<T>;
1295
+ /** Read one job now; `waitMs` (≤ 25000) lets the gateway hold until it finishes. */
1296
+ getJob(
1297
+ jobId: string,
1298
+ options?: { waitMs?: number; signal?: AbortSignal },
1299
+ ): Promise<JobView>;
1300
+ /**
1301
+ * The signed-in end user's own jobs on this module (any device), newest
1302
+ * first, without results. Anonymous callers get an empty list.
1303
+ */
1304
+ listJobs(options?: {
1305
+ active?: boolean;
1306
+ limit?: number;
1307
+ signal?: AbortSignal;
1308
+ }): Promise<{ jobs: JobView[] }>;
1309
+ /**
1310
+ * Re-attach to a streamed chat answer from character `from` (0 replays
1311
+ * all of it), then follow it live until done.
1312
+ */
1313
+ resumeChatStream(
1314
+ jobId: string,
1315
+ options?: { from?: number; signal?: AbortSignal },
1316
+ ): AsyncGenerator<ChatStreamChunk, void, void>;
1168
1317
  /**
1169
1318
  * Open a real-time speech-translation session over WebSocket (Gemini Live
1170
1319
  * via the gateway). Requires the optional peer dependency
package/src/index.js CHANGED
@@ -10,6 +10,18 @@ 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
+ /**
20
+ * Times a job cut off by a gateway restart (`code: 'interrupted'`) is
21
+ * submitted again. Such a job was never charged.
22
+ */
23
+ const INTERRUPTED_RESUBMITS = 1;
24
+
13
25
  /**
14
26
  * Above this many seconds the gateway builds a video as independent SCENES in
15
27
  * PARALLEL (hard cuts) instead of chaining one continuous shot — chaining is
@@ -44,13 +56,16 @@ function longVideoTimeoutMs(seconds) {
44
56
  }
45
57
 
46
58
  export class AIFlowError extends Error {
47
- constructor(message, { status, code, requestId, cause } = {}) {
59
+ constructor(message, { status, code, requestId, cause, fromServer } = {}) {
48
60
  super(message);
49
61
  this.name = 'AIFlowError';
50
62
  this.status = status;
51
63
  this.code = code;
52
64
  this.requestId = requestId;
53
65
  if (cause) this.cause = cause;
66
+ // An error the gateway reported inside a stream (not a dropped
67
+ // connection) — a stream does not reconnect after one.
68
+ if (fromServer) this.fromServer = true;
54
69
  }
55
70
  }
56
71
 
@@ -155,6 +170,23 @@ export class AIFlowClient {
155
170
  /** Update this app's (or a sibling) module system prompt / defaults. */
156
171
  updateConfig: (input) => this._adminUpdateConfig(input),
157
172
  };
173
+
174
+ this._jobStore = new JobStore(this.appId);
175
+ /**
176
+ * Background jobs started from this browser, remembered for a day
177
+ * (localStorage; in memory where there is none) so a page can show a
178
+ * generation that finished, or is still running, after the user left
179
+ * and came back. Entries: `{ jobId, kind, tag, status, result?, error?,
180
+ * createdAt, updatedAt }`; `result` is what the call resolved with.
181
+ */
182
+ this.jobs = {
183
+ /** Newest remembered job with this tag (any tag when omitted), or null. */
184
+ latest: (tag) => this._jobStore.latest(tag),
185
+ /** Remembered jobs, newest first, optionally only one tag. */
186
+ list: ({ tag } = {}) => this._jobStore.list(tag),
187
+ /** Forget one job (by id) or every job with a tag. */
188
+ forget: (jobIdOrTag) => this._jobStore.forget(jobIdOrTag),
189
+ };
158
190
  }
159
191
 
160
192
  /**
@@ -294,6 +326,9 @@ export class AIFlowClient {
294
326
  * Non-streaming chat completion. `webSearch: false` answers this one
295
327
  * request without the built-in web search; omitted, the module's setting
296
328
  * applies (on by default).
329
+ *
330
+ * Runs as a background job (see {@link waitForJob}): `onJob(jobId)` fires
331
+ * once the gateway has accepted it, `tag` labels it in `jobs.latest()`.
297
332
  * @returns {Promise<{id:string, model:string, content:string, usage:{inputTokens:number,outputTokens:number,creditsUsed:number}}>}
298
333
  */
299
334
  async chat({
@@ -305,6 +340,9 @@ export class AIFlowClient {
305
340
  webSearch,
306
341
  tools,
307
342
  signal,
343
+ timeout,
344
+ onJob,
345
+ tag,
308
346
  } = {}) {
309
347
  if (!Array.isArray(messages) || messages.length === 0) {
310
348
  throw new AIFlowError('messages must be a non-empty array');
@@ -312,9 +350,10 @@ export class AIFlowClient {
312
350
  assertNoTools(tools);
313
351
  const resolvedModel = model || (await this._resolveDefaultModel('chat'));
314
352
  const resolvedSystem = await this._resolveSystemPrompt(system);
315
- const res = await this._request(
316
- '/chat',
317
- {
353
+ return this._generate({
354
+ kind: 'chat',
355
+ path: '/chat',
356
+ body: {
318
357
  model: resolvedModel,
319
358
  system: resolvedSystem,
320
359
  messages,
@@ -322,14 +361,25 @@ export class AIFlowClient {
322
361
  temperature,
323
362
  webSearch,
324
363
  },
325
- { signal },
326
- );
327
- return await res.json();
364
+ signal,
365
+ timeout,
366
+ onJob,
367
+ tag,
368
+ });
328
369
  }
329
370
 
330
371
  /**
331
372
  * Streaming chat completion. Yields `{ delta: string, done: boolean }`
332
- * chunks as server-sent events arrive.
373
+ * chunks as server-sent events arrive; the last one (`done: true`) carries
374
+ * `model`, `modelSource`, `usage` and, on a gateway with background jobs,
375
+ * `jobId`.
376
+ *
377
+ * The answer is generated by a background job: leaving the page (or
378
+ * aborting `signal`) stops only this reader, and the answer keeps being
379
+ * written on the gateway — pick it up with {@link resumeChatStream} or
380
+ * {@link waitForJob}. `onJob(jobId)` fires as soon as the job id is known;
381
+ * a dropped connection is re-attached automatically. A server error frame
382
+ * (e.g. 402, out of credits) throws an AIFlowError.
333
383
  */
334
384
  async *chatStream({
335
385
  messages,
@@ -340,6 +390,8 @@ export class AIFlowClient {
340
390
  webSearch,
341
391
  tools,
342
392
  signal,
393
+ onJob,
394
+ tag,
343
395
  } = {}) {
344
396
  if (!Array.isArray(messages) || messages.length === 0) {
345
397
  throw new AIFlowError('messages must be a non-empty array');
@@ -348,7 +400,7 @@ export class AIFlowClient {
348
400
  const resolvedModel = model || (await this._resolveDefaultModel('chat'));
349
401
  const resolvedSystem = await this._resolveSystemPrompt(system);
350
402
  const res = await this._request(
351
- '/chat/stream',
403
+ `/chat/stream${tagQuery(tag)}`,
352
404
  {
353
405
  model: resolvedModel,
354
406
  system: resolvedSystem,
@@ -360,39 +412,126 @@ export class AIFlowClient {
360
412
  },
361
413
  { signal, stream: true },
362
414
  );
415
+ yield* this._streamChat(res, { signal, onJob, tag });
416
+ }
363
417
 
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
- );
418
+ /**
419
+ * Re-attach to a streamed chat answer — after a reload, on another page,
420
+ * or on another device for the same signed-in user. Yields the chunks from
421
+ * character `from` on (pass the length of the text already shown; 0 replays
422
+ * the whole answer), then live text until the answer is done. Same chunk
423
+ * shape as {@link chatStream}.
424
+ */
425
+ async *resumeChatStream(jobId, { from = 0, signal } = {}) {
426
+ if (!jobId || typeof jobId !== 'string') {
427
+ throw new AIFlowError('jobId is required');
368
428
  }
429
+ const res = await this._openJobStream(jobId, from, signal);
430
+ yield* this._streamChat(res, { signal, jobId, from });
431
+ }
369
432
 
370
- const reader = res.body.getReader();
371
- const decoder = new TextDecoder();
372
- let buffer = '';
433
+ async _openJobStream(jobId, from, signal) {
434
+ const offset = Math.max(0, Math.floor(Number(from) || 0));
435
+ return this._fetchWithRetry(
436
+ `${this.baseUrl}/jobs/${encodeURIComponent(jobId)}/stream?from=${offset}`,
437
+ {
438
+ method: 'GET',
439
+ headers: { ...this._authHeaders(), Accept: 'text/event-stream' },
440
+ },
441
+ { signal },
442
+ );
443
+ }
373
444
 
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
- }
445
+ /**
446
+ * Read a chat SSE response as chunks. A server error frame throws. If the
447
+ * connection ends before the answer does, the stream is re-attached to its
448
+ * job from the last character received — the gateway kept writing.
449
+ */
450
+ async *_streamChat(res, { signal, onJob, tag, jobId = null, from = 0 }) {
451
+ let current = res;
452
+ let received = Math.max(0, Number(from) || 0);
453
+ let content = '';
454
+ let resumes = 0;
455
+ while (true) {
456
+ if (!current.body || typeof current.body.getReader !== 'function') {
457
+ throw new AIFlowError(
458
+ 'Streaming response is not readable — your fetch implementation must expose a ReadableStream body.',
459
+ );
389
460
  }
390
- } finally {
391
461
  try {
392
- reader.releaseLock();
393
- } catch {
394
- /* ignore */
462
+ for await (const event of readSseEvents(current.body)) {
463
+ if (event.comment !== undefined) {
464
+ const match = /^aiflow-job\s+(\S+)/.exec(event.comment);
465
+ if (match && !jobId) {
466
+ jobId = match[1];
467
+ this._trackJob(jobId, 'chat_stream', tag, onJob);
468
+ }
469
+ continue;
470
+ }
471
+ const chunk = event.chunk;
472
+ if (chunk.error) {
473
+ const message = chunk.message || 'Chat stream failed';
474
+ if (jobId) {
475
+ this._jobStore.settle(jobId, {
476
+ status: 'failed',
477
+ error: message,
478
+ });
479
+ }
480
+ throw new AIFlowError(message, {
481
+ status: chunk.status,
482
+ code: chunk.code || 'stream_error',
483
+ fromServer: true,
484
+ });
485
+ }
486
+ if (typeof chunk.delta === 'string' && chunk.delta) {
487
+ received += chunk.delta.length;
488
+ content += chunk.delta;
489
+ }
490
+ if (chunk.done) {
491
+ if (!jobId) {
492
+ yield chunk;
493
+ return;
494
+ }
495
+ this._jobStore.settle(jobId, {
496
+ status: 'succeeded',
497
+ // Only a stream read from the start holds the whole answer.
498
+ ...(from === 0
499
+ ? {
500
+ result: {
501
+ content,
502
+ model: chunk.model,
503
+ modelSource: chunk.modelSource,
504
+ usage: chunk.usage,
505
+ },
506
+ }
507
+ : {}),
508
+ });
509
+ yield { ...chunk, jobId };
510
+ return;
511
+ }
512
+ yield chunk;
513
+ }
514
+ } catch (err) {
515
+ if (
516
+ err?.fromServer ||
517
+ signal?.aborted ||
518
+ !jobId ||
519
+ resumes >= STREAM_RESUME_ATTEMPTS
520
+ ) {
521
+ throw err;
522
+ }
523
+ }
524
+ // The connection ended before the answer did.
525
+ if (!jobId || signal?.aborted) return;
526
+ if (resumes >= STREAM_RESUME_ATTEMPTS) {
527
+ throw new AIFlowError(
528
+ 'Lost the connection to the chat stream — the answer may still finish; pick it up with resumeChatStream(jobId)',
529
+ { code: 'stream_lost' },
530
+ );
395
531
  }
532
+ resumes += 1;
533
+ await sleep(backoffMs(resumes));
534
+ current = await this._openJobStream(jobId, received, signal);
396
535
  }
397
536
  }
398
537
 
@@ -413,6 +552,8 @@ export class AIFlowClient {
413
552
  background,
414
553
  signal,
415
554
  timeout,
555
+ onJob,
556
+ tag,
416
557
  } = {}) {
417
558
  if (!prompt || typeof prompt !== 'string') {
418
559
  throw new AIFlowError('prompt is required');
@@ -423,9 +564,10 @@ export class AIFlowClient {
423
564
  // mirroring chat(). The server prepends it to the prompt and injects
424
565
  // the dynamic `language` into any {{language}} placeholder.
425
566
  const resolvedSystem = await this._resolveSystemPrompt(system);
426
- const res = await this._request(
427
- '/image',
428
- {
567
+ return this._generate({
568
+ kind: 'image',
569
+ path: '/image',
570
+ body: {
429
571
  model: resolvedModel,
430
572
  prompt,
431
573
  size,
@@ -440,13 +582,16 @@ export class AIFlowClient {
440
582
  // models in `config.imageBackgroundModels`.
441
583
  background,
442
584
  },
585
+ signal,
586
+ timeout,
443
587
  // 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();
588
+ // client default — a single 2K edit was observed at ~63s. The
589
+ // synchronous route gets 3 minutes; the job route the same for its
590
+ // upload of base64 inputs.
591
+ requestTimeout: 180_000,
592
+ onJob,
593
+ tag,
594
+ });
450
595
  }
451
596
 
452
597
  /**
@@ -471,6 +616,8 @@ export class AIFlowClient {
471
616
  background,
472
617
  signal,
473
618
  timeout,
619
+ onJob,
620
+ tag,
474
621
  } = {}) {
475
622
  if (!Array.isArray(pages) || pages.length === 0) {
476
623
  throw new AIFlowError('pages must be a non-empty array');
@@ -478,9 +625,10 @@ export class AIFlowClient {
478
625
  const resolvedModel =
479
626
  model || (await this._resolveDefaultModel('image'));
480
627
  const resolvedSystem = await this._resolveSystemPrompt(system);
481
- const res = await this._request(
482
- '/image/batch',
483
- {
628
+ return this._generate({
629
+ kind: 'image_batch',
630
+ path: '/image/batch',
631
+ body: {
484
632
  pages,
485
633
  prompt,
486
634
  model: resolvedModel,
@@ -490,11 +638,15 @@ export class AIFlowClient {
490
638
  concurrency,
491
639
  background,
492
640
  },
641
+ signal,
642
+ timeout,
493
643
  // 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();
644
+ // request — 10 minutes on the synchronous route, matching the
645
+ // server socket; the job route needs it for a large upload.
646
+ requestTimeout: 600_000,
647
+ onJob,
648
+ tag,
649
+ });
498
650
  }
499
651
 
500
652
  /**
@@ -516,6 +668,7 @@ export class AIFlowClient {
516
668
  throw new AIFlowError('prompt is required');
517
669
  }
518
670
  const { jobId } = await this.submitVideoJob(opts);
671
+ this._trackJob(jobId, 'video', opts.tag, opts.onJob);
519
672
  return this._pollVideoJob(jobId, {
520
673
  signal: opts.signal,
521
674
  // Overall wait budget across all polls (default 10 min). Each
@@ -673,31 +826,14 @@ export class AIFlowClient {
673
826
  }
674
827
  }
675
828
  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
- };
829
+ const result = toVideoResult(job);
830
+ this._jobStore.settle(jobId, { status: 'succeeded', result });
831
+ return result;
695
832
  }
696
833
  if (job.status === 'failed') {
697
- throw new AIFlowError(
698
- job.error || 'Video generation failed',
699
- { code: 'video_failed' },
700
- );
834
+ const message = job.error || 'Video generation failed';
835
+ this._jobStore.settle(jobId, { status: 'failed', error: message });
836
+ throw new AIFlowError(message, { code: 'video_failed' });
701
837
  }
702
838
  if (Date.now() >= deadline) {
703
839
  throw new AIFlowError(
@@ -745,11 +881,14 @@ export class AIFlowClient {
745
881
  signal,
746
882
  timeout,
747
883
  pollIntervalMs,
884
+ onJob,
885
+ tag,
748
886
  } = {}) {
749
887
  if (!Array.isArray(videos) || videos.length < 2) {
750
888
  throw new AIFlowError('mergeVideos needs at least two videos');
751
889
  }
752
890
  const { jobId } = await this.submitVideoMerge({ videos, signal });
891
+ this._trackJob(jobId, 'video', tag, onJob);
753
892
  return this._pollVideoJob(jobId, {
754
893
  signal,
755
894
  // Every clip is fetched and usually re-encoded on the gateway, so the
@@ -901,6 +1040,8 @@ export class AIFlowClient {
901
1040
  signal,
902
1041
  timeout,
903
1042
  pollIntervalMs,
1043
+ onJob,
1044
+ tag,
904
1045
  } = {}) {
905
1046
  if (!prompt || typeof prompt !== 'string') {
906
1047
  throw new AIFlowError('prompt is required');
@@ -920,6 +1061,7 @@ export class AIFlowClient {
920
1061
  targetDurationSeconds: durationSeconds,
921
1062
  signal,
922
1063
  });
1064
+ this._trackJob(jobId, 'video', tag, onJob, { sessionId });
923
1065
  const result = await this._pollVideoJob(jobId, {
924
1066
  signal,
925
1067
  timeout: timeout ?? longVideoTimeoutMs(durationSeconds),
@@ -948,7 +1090,7 @@ export class AIFlowClient {
948
1090
  */
949
1091
  async resumeLongVideo(
950
1092
  sessionId,
951
- { onProgress, signal, timeout, pollIntervalMs } = {},
1093
+ { onProgress, signal, timeout, pollIntervalMs, onJob, tag } = {},
952
1094
  ) {
953
1095
  if (!sessionId || typeof sessionId !== 'string') {
954
1096
  throw new AIFlowError('sessionId is required');
@@ -959,6 +1101,7 @@ export class AIFlowClient {
959
1101
  { signal, timeout: DEFAULT_TIMEOUT_MS },
960
1102
  );
961
1103
  const { jobId } = await res.json();
1104
+ this._trackJob(jobId, 'video', tag, onJob, { sessionId });
962
1105
  // Read the session to size the wait from what is actually left, rather
963
1106
  // than from the whole film that was originally asked for.
964
1107
  let remaining = 0;
@@ -997,6 +1140,7 @@ export class AIFlowClient {
997
1140
  */
998
1141
  async extendVideo(sessionId, opts = {}) {
999
1142
  const { jobId } = await this.submitVideoExtend(sessionId, opts);
1143
+ this._trackJob(jobId, 'video', opts.tag, opts.onJob, { sessionId });
1000
1144
  return this._pollVideoJob(jobId, {
1001
1145
  signal: opts.signal,
1002
1146
  timeout: opts.timeout ?? 600_000,
@@ -1079,6 +1223,8 @@ export class AIFlowClient {
1079
1223
  seed,
1080
1224
  signal,
1081
1225
  timeout,
1226
+ onJob,
1227
+ tag,
1082
1228
  } = {}) {
1083
1229
  if (!prompt || typeof prompt !== 'string') {
1084
1230
  throw new AIFlowError('prompt is required');
@@ -1088,9 +1234,10 @@ export class AIFlowClient {
1088
1234
  }
1089
1235
  const resolvedModel =
1090
1236
  model || (await this._resolveDefaultModel('audio'));
1091
- const res = await this._request(
1092
- '/audio',
1093
- {
1237
+ return this._generate({
1238
+ kind: 'audio',
1239
+ path: '/audio',
1240
+ body: {
1094
1241
  model: resolvedModel,
1095
1242
  prompt,
1096
1243
  images: images?.length ? images : undefined,
@@ -1100,11 +1247,14 @@ export class AIFlowClient {
1100
1247
  negativePrompt,
1101
1248
  seed,
1102
1249
  },
1250
+ signal,
1251
+ timeout,
1103
1252
  // 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();
1253
+ // client default — the synchronous route gets 3 minutes.
1254
+ requestTimeout: 180_000,
1255
+ onJob,
1256
+ tag,
1257
+ });
1108
1258
  }
1109
1259
 
1110
1260
  /**
@@ -1119,23 +1269,29 @@ export class AIFlowClient {
1119
1269
  loop,
1120
1270
  signal,
1121
1271
  timeout,
1272
+ onJob,
1273
+ tag,
1122
1274
  } = {}) {
1123
1275
  if (!prompt || typeof prompt !== 'string') {
1124
1276
  throw new AIFlowError('prompt is required');
1125
1277
  }
1126
1278
  const resolvedModel = model || (await this._resolveDefaultModel('sfx'));
1127
- const res = await this._request(
1128
- '/sfx',
1129
- {
1279
+ return this._generate({
1280
+ kind: 'sfx',
1281
+ path: '/sfx',
1282
+ body: {
1130
1283
  model: resolvedModel,
1131
1284
  prompt,
1132
1285
  durationSeconds,
1133
1286
  promptInfluence,
1134
1287
  loop,
1135
1288
  },
1136
- { signal, timeout: timeout ?? 120_000 },
1137
- );
1138
- return await res.json();
1289
+ signal,
1290
+ timeout,
1291
+ requestTimeout: 120_000,
1292
+ onJob,
1293
+ tag,
1294
+ });
1139
1295
  }
1140
1296
 
1141
1297
  /**
@@ -1199,6 +1355,203 @@ export class AIFlowClient {
1199
1355
  return await res.json();
1200
1356
  }
1201
1357
 
1358
+ // ── Background jobs ─────────────────────────────────────────────────────
1359
+ // On a gateway that supports them (`config.capabilities.jobs`), chat,
1360
+ // image, music and SFX calls run as background jobs, like video always
1361
+ // has: the gateway keeps generating — and keeps the result for a week —
1362
+ // when the page that asked goes away. The calls above still resolve with
1363
+ // the same value; these methods pick a job up again by its id.
1364
+
1365
+ /**
1366
+ * Wait for a background job and resolve with its result — the same value
1367
+ * the call that started it resolves with (a video job resolves like
1368
+ * `generateVideo`). Works with any job id the app has: from `onJob`,
1369
+ * `jobs.latest()` / `jobs.list()` or {@link listJobs}, after a reload or on
1370
+ * another page. Aborting `signal` or hitting `timeout` (default 30 min)
1371
+ * stops only the waiting; the job carries on. Throws an AIFlowError with
1372
+ * the job's `status` / `code` when it failed.
1373
+ */
1374
+ async waitForJob(jobId, { signal, timeout, onProgress } = {}) {
1375
+ if (!jobId || typeof jobId !== 'string') {
1376
+ throw new AIFlowError('jobId is required');
1377
+ }
1378
+ const deadline = Date.now() + (timeout ?? DEFAULT_JOB_TIMEOUT_MS);
1379
+ let lastProgress = -1;
1380
+ // eslint-disable-next-line no-constant-condition
1381
+ while (true) {
1382
+ if (signal?.aborted) {
1383
+ throw new AIFlowError(
1384
+ 'Stopped waiting — the job keeps running; call waitForJob(jobId) to pick it up again',
1385
+ { code: 'aborted' },
1386
+ );
1387
+ }
1388
+ const remaining = deadline - Date.now();
1389
+ if (remaining <= 0) {
1390
+ throw new AIFlowError(
1391
+ `Timed out waiting for job ${jobId} — it may still finish; call waitForJob(jobId) again`,
1392
+ { code: 'timeout' },
1393
+ );
1394
+ }
1395
+ const startedAt = Date.now();
1396
+ let job;
1397
+ try {
1398
+ job = await this.getJob(jobId, {
1399
+ waitMs: Math.min(JOB_WAIT_MS, remaining),
1400
+ signal,
1401
+ });
1402
+ } catch (err) {
1403
+ // A gateway without job routes still serves video jobs.
1404
+ if (err?.status === 404 && !(await this._jobsEnabled())) {
1405
+ return this._pollVideoJob(jobId, {
1406
+ signal,
1407
+ timeout: remaining,
1408
+ onProgress,
1409
+ });
1410
+ }
1411
+ throw err;
1412
+ }
1413
+ const progress = job.progress;
1414
+ if (
1415
+ onProgress &&
1416
+ progress &&
1417
+ typeof progress.segmentsDone === 'number' &&
1418
+ progress.segmentsDone !== lastProgress
1419
+ ) {
1420
+ lastProgress = progress.segmentsDone;
1421
+ try {
1422
+ onProgress({
1423
+ segmentsDone: progress.segmentsDone,
1424
+ segmentsPlanned: progress.segmentsPlanned,
1425
+ durationSeconds: progress.durationSeconds,
1426
+ videoUrl: progress.videoUrl,
1427
+ thumbnailUrl: progress.thumbnailUrl,
1428
+ });
1429
+ } catch {
1430
+ // A throwing progress handler is the caller's bug.
1431
+ }
1432
+ }
1433
+ if (job.status === 'succeeded') {
1434
+ const result =
1435
+ job.kind === 'video' ? toVideoResult(job.result || {}) : job.result;
1436
+ this._jobStore.settle(jobId, { status: 'succeeded', result });
1437
+ return result;
1438
+ }
1439
+ if (job.status === 'failed') {
1440
+ const message = job.error || 'Generation failed';
1441
+ this._jobStore.settle(jobId, { status: 'failed', error: message });
1442
+ throw new AIFlowError(message, {
1443
+ status: job.errorStatus,
1444
+ code: job.errorCode || 'job_failed',
1445
+ });
1446
+ }
1447
+ // The gateway holds each read until the job ends or `waitMs`
1448
+ // passes; pause only when it answered early without an outcome.
1449
+ if (Date.now() - startedAt < 1_000) await sleep(1_000);
1450
+ }
1451
+ }
1452
+
1453
+ /**
1454
+ * Read one background job now: `{ jobId, kind, status, tag?, prompt?,
1455
+ * result?, error?, errorStatus?, errorCode?, progress?, contentLength? }`.
1456
+ * `waitMs` (up to 25000) lets the gateway hold the request until the job
1457
+ * finishes. Needs a gateway with `config.capabilities.jobs`.
1458
+ */
1459
+ async getJob(jobId, { waitMs, signal } = {}) {
1460
+ if (!jobId || typeof jobId !== 'string') {
1461
+ throw new AIFlowError('jobId is required');
1462
+ }
1463
+ const wait = Math.max(0, Math.min(Number(waitMs) || 0, 25_000));
1464
+ const res = await this._get(
1465
+ `/jobs/${encodeURIComponent(jobId)}${wait ? `?waitMs=${wait}` : ''}`,
1466
+ { signal, timeout: wait + DEFAULT_TIMEOUT_MS },
1467
+ );
1468
+ return await res.json();
1469
+ }
1470
+
1471
+ /**
1472
+ * The signed-in end user's own jobs on this module, newest first, from any
1473
+ * device (`setEndUser` with the user's token is required; an anonymous
1474
+ * caller gets an empty list — use `jobs.latest()` for this browser's jobs).
1475
+ * `active: true` keeps only jobs still running. Entries carry no result:
1476
+ * read one with {@link waitForJob} or {@link getJob}.
1477
+ * @returns {Promise<{jobs: object[]}>}
1478
+ */
1479
+ async listJobs({ active, limit, signal } = {}) {
1480
+ const params = [];
1481
+ if (active) params.push('active=1');
1482
+ if (limit) params.push(`limit=${encodeURIComponent(limit)}`);
1483
+ const res = await this._get(
1484
+ `/jobs${params.length ? `?${params.join('&')}` : ''}`,
1485
+ { signal },
1486
+ );
1487
+ return await res.json();
1488
+ }
1489
+
1490
+ /**
1491
+ * Run one generation. On a gateway with background jobs it is submitted to
1492
+ * the job route and awaited, so it keeps running — and stays retrievable —
1493
+ * if this page goes away; otherwise it is one request to the synchronous
1494
+ * route. Both resolve with the same response body.
1495
+ */
1496
+ async _generate({ kind, path, body, signal, timeout, requestTimeout, onJob, tag }) {
1497
+ if (await this._jobsEnabled()) {
1498
+ const deadline = Date.now() + (timeout ?? DEFAULT_JOB_TIMEOUT_MS);
1499
+ for (let attempt = 0; ; attempt += 1) {
1500
+ const res = await this._request(`${path}/jobs${tagQuery(tag)}`, body, {
1501
+ signal,
1502
+ timeout: requestTimeout ?? DEFAULT_TIMEOUT_MS,
1503
+ });
1504
+ const { jobId } = await res.json();
1505
+ this._trackJob(jobId, kind, tag, onJob);
1506
+ try {
1507
+ return await this.waitForJob(jobId, {
1508
+ signal,
1509
+ timeout: Math.max(1, deadline - Date.now()),
1510
+ });
1511
+ } catch (err) {
1512
+ // The gateway pod running the job restarted (a deploy or a
1513
+ // scale-down) before it finished. Nothing was charged, so run
1514
+ // it once more — what the retry on a cut-off synchronous
1515
+ // request used to do. `onJob` fires again with the new id.
1516
+ const rerun =
1517
+ err?.code === 'interrupted' &&
1518
+ attempt < INTERRUPTED_RESUBMITS &&
1519
+ !signal?.aborted &&
1520
+ Date.now() < deadline;
1521
+ if (!rerun) throw err;
1522
+ }
1523
+ }
1524
+ }
1525
+ const res = await this._request(path, body, {
1526
+ signal,
1527
+ timeout: timeout ?? requestTimeout,
1528
+ });
1529
+ return await res.json();
1530
+ }
1531
+
1532
+ async _jobsEnabled() {
1533
+ try {
1534
+ const cfg = await this.getConfig();
1535
+ return cfg?.capabilities?.jobs === true;
1536
+ } catch {
1537
+ return false;
1538
+ }
1539
+ }
1540
+
1541
+ /** Remember a started job and hand its id to the caller's `onJob`. */
1542
+ _trackJob(jobId, kind, tag, onJob, extra) {
1543
+ if (!jobId) return;
1544
+ this._jobStore.put({ jobId, kind, tag, status: 'processing' });
1545
+ if (typeof onJob === 'function') {
1546
+ try {
1547
+ onJob(jobId, extra);
1548
+ } catch {
1549
+ // A throwing callback is the caller's bug, not a reason to
1550
+ // abandon a generation they are paying for.
1551
+ }
1552
+ }
1553
+ }
1554
+
1202
1555
  /**
1203
1556
  * Open a real-time speech-translation session over WebSocket (Gemini Live
1204
1557
  * via the platform gateway — no Google key in the browser). Stream 16 kHz
@@ -1777,6 +2130,204 @@ function toBase64(chunk) {
1777
2130
  // Helpers
1778
2131
  // ────────────────────────────────────────────────────────────────────────────
1779
2132
 
2133
+ const JOB_STORE_MAX_ENTRIES = 50;
2134
+ const JOB_STORE_TTL_MS = 24 * 60 * 60_000;
2135
+ const JOB_STORE_RESULT_MAX_CHARS = 200_000;
2136
+
2137
+ /**
2138
+ * The jobs this browser started, kept in localStorage (memory where there is
2139
+ * none) for a day, so a page that comes back can find a generation that
2140
+ * finished — or is still running — while it was gone. Results above
2141
+ * JOB_STORE_RESULT_MAX_CHARS are not kept (`resultOmitted`); `waitForJob`
2142
+ * fetches them from the gateway.
2143
+ */
2144
+ class JobStore {
2145
+ constructor(appId) {
2146
+ this._key = `aiflow:jobs:${appId}`;
2147
+ this._memory = [];
2148
+ }
2149
+
2150
+ _storage() {
2151
+ try {
2152
+ return typeof localStorage !== 'undefined' && localStorage
2153
+ ? localStorage
2154
+ : null;
2155
+ } catch {
2156
+ return null;
2157
+ }
2158
+ }
2159
+
2160
+ _read() {
2161
+ const storage = this._storage();
2162
+ let list = this._memory;
2163
+ if (storage) {
2164
+ try {
2165
+ list = JSON.parse(storage.getItem(this._key) || '[]');
2166
+ } catch {
2167
+ list = [];
2168
+ }
2169
+ }
2170
+ if (!Array.isArray(list)) return [];
2171
+ const cutoff = Date.now() - JOB_STORE_TTL_MS;
2172
+ return list.filter(
2173
+ (e) => e && e.jobId && (e.updatedAt || e.createdAt || 0) >= cutoff,
2174
+ );
2175
+ }
2176
+
2177
+ _write(list) {
2178
+ const kept = [...list]
2179
+ .sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0))
2180
+ .slice(0, JOB_STORE_MAX_ENTRIES);
2181
+ this._memory = kept;
2182
+ const storage = this._storage();
2183
+ if (!storage) return;
2184
+ try {
2185
+ storage.setItem(this._key, JSON.stringify(kept));
2186
+ } catch {
2187
+ // Over quota: keep the bookkeeping, drop the stored results.
2188
+ try {
2189
+ storage.setItem(
2190
+ this._key,
2191
+ JSON.stringify(
2192
+ kept.map(({ result, ...e }) =>
2193
+ result === undefined ? e : { ...e, resultOmitted: true },
2194
+ ),
2195
+ ),
2196
+ );
2197
+ } catch {
2198
+ /* storage unavailable */
2199
+ }
2200
+ }
2201
+ }
2202
+
2203
+ put(entry) {
2204
+ const list = this._read();
2205
+ const now = Date.now();
2206
+ const i = list.findIndex((e) => e.jobId === entry.jobId);
2207
+ const fields = Object.fromEntries(
2208
+ Object.entries(entry).filter(([, v]) => v !== undefined && v !== null),
2209
+ );
2210
+ const next = { ...(i >= 0 ? list[i] : { createdAt: now }), ...fields, updatedAt: now };
2211
+ if (i >= 0) list[i] = next;
2212
+ else list.push(next);
2213
+ this._write(list);
2214
+ }
2215
+
2216
+ /** Record an outcome — only for a job this browser is tracking. */
2217
+ settle(jobId, patch) {
2218
+ const list = this._read();
2219
+ const i = list.findIndex((e) => e.jobId === jobId);
2220
+ if (i < 0) return;
2221
+ const next = { ...list[i], ...patch, updatedAt: Date.now() };
2222
+ if (patch.status === 'succeeded') delete next.error;
2223
+ if (next.result !== undefined) {
2224
+ let size = Infinity;
2225
+ try {
2226
+ size = JSON.stringify(next.result).length;
2227
+ } catch {
2228
+ /* unserialisable */
2229
+ }
2230
+ if (size > JOB_STORE_RESULT_MAX_CHARS) {
2231
+ delete next.result;
2232
+ next.resultOmitted = true;
2233
+ } else {
2234
+ delete next.resultOmitted;
2235
+ }
2236
+ }
2237
+ list[i] = next;
2238
+ this._write(list);
2239
+ }
2240
+
2241
+ list(tag) {
2242
+ return this._read()
2243
+ .filter((e) => tag === undefined || tag === null || e.tag === tag)
2244
+ .sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0))
2245
+ .map((e) => ({ ...e }));
2246
+ }
2247
+
2248
+ latest(tag) {
2249
+ return this.list(tag)[0] ?? null;
2250
+ }
2251
+
2252
+ forget(jobIdOrTag) {
2253
+ if (!jobIdOrTag) return;
2254
+ this._write(
2255
+ this._read().filter(
2256
+ (e) => e.jobId !== jobIdOrTag && e.tag !== jobIdOrTag,
2257
+ ),
2258
+ );
2259
+ }
2260
+ }
2261
+
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))}`;
2266
+ }
2267
+
2268
+ /** A finished video job as `generateVideo` has always resolved it. */
2269
+ function toVideoResult(job) {
2270
+ return {
2271
+ videoUrl: job.videoUrl,
2272
+ thumbnailUrl: job.thumbnailUrl,
2273
+ prompt: job.prompt,
2274
+ usage: job.usage || { creditsUsed: 0 },
2275
+ // Session turns only. Spread conditionally so a plain generation's
2276
+ // result keeps exactly the shape earlier SDK versions returned — no
2277
+ // undefined keys appearing in it.
2278
+ ...(job.sessionId ? { sessionId: job.sessionId } : {}),
2279
+ ...(job.segmentUrl ? { segmentUrl: job.segmentUrl } : {}),
2280
+ ...(job.durationSeconds != null
2281
+ ? { durationSeconds: job.durationSeconds }
2282
+ : {}),
2283
+ ...(job.segmentsDone != null ? { segmentsDone: job.segmentsDone } : {}),
2284
+ // Short of the requested length, but real and paid for.
2285
+ ...(job.warning ? { warning: job.warning } : {}),
2286
+ };
2287
+ }
2288
+
2289
+ /**
2290
+ * Server-sent events from a fetch body: `{ comment }` for comment lines (the
2291
+ * gateway announces a stream's job id in one) and `{ chunk }` for data.
2292
+ * Stopping early cancels the body, which closes the connection.
2293
+ */
2294
+ async function* readSseEvents(body) {
2295
+ const reader = body.getReader();
2296
+ const decoder = new TextDecoder();
2297
+ let buffer = '';
2298
+ let finished = false;
2299
+ try {
2300
+ while (true) {
2301
+ const { value, done } = await reader.read();
2302
+ if (done) {
2303
+ finished = true;
2304
+ break;
2305
+ }
2306
+ buffer += decoder.decode(value, { stream: true });
2307
+ let idx;
2308
+ while ((idx = buffer.indexOf('\n\n')) !== -1) {
2309
+ const rawEvent = buffer.slice(0, idx);
2310
+ buffer = buffer.slice(idx + 2);
2311
+ for (const line of rawEvent.split(/\r?\n/)) {
2312
+ if (line.startsWith(':')) yield { comment: line.slice(1).trim() };
2313
+ }
2314
+ const chunk = parseSseEvent(rawEvent);
2315
+ if (chunk !== null) yield { chunk };
2316
+ }
2317
+ }
2318
+ } finally {
2319
+ if (finished) {
2320
+ try {
2321
+ reader.releaseLock();
2322
+ } catch {
2323
+ /* ignore */
2324
+ }
2325
+ } else {
2326
+ reader.cancel().catch(() => {});
2327
+ }
2328
+ }
2329
+ }
2330
+
1780
2331
  function parseSseEvent(rawEvent) {
1781
2332
  const trimmed = rawEvent.trim();
1782
2333
  if (!trimmed) return null;