@devvibex/aiflow 1.1.0 → 1.3.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
@@ -77,6 +77,7 @@ console.log(emb.data[0].embedding.length);
77
77
  | `defaultVideoModel` | `string` | from `GET /config` | Override. |
78
78
  | `defaultAudioModel` | `string` | from `GET /config` | Override (music / Lyria). |
79
79
  | `defaultSfxModel` | `string` | from `GET /config` | Override (sound effects / ElevenLabs). |
80
+ | `endUserId` | `string` | `null` | Current end-user id; scopes the knowledge base (`x-end-user-id`). Set/clear later with `setEndUser`. |
80
81
  | `timeout` | `number` | `60000` | Per-request timeout (ms). |
81
82
  | `maxRetries` | `number` | `2` | Retries on 429 / 5xx / network errors. |
82
83
  | `fetch` | `typeof fetch` | `globalThis.fetch` | Custom fetch (Node <18, testing). |
@@ -151,6 +152,98 @@ repeated UI sounds client-side rather than calling per interaction.
151
152
 
152
153
  Returns `{ data: [{ embedding: number[], index }], usage: { creditsUsed } }`.
153
154
 
155
+ ### `aiflow.setEndUser(endUserId)` + `aiflow.knowledge.*` — per-user knowledge base (RAG)
156
+
157
+ Let your app's **end users** upload their own documents; AIFlow vectorizes them
158
+ transparently and **automatically grounds that user's chat answers** in the
159
+ relevant passages. Knowledge is scoped **per end user** — a user only ever
160
+ retrieves their own uploads. You don't implement retrieval/embeddings yourself.
161
+
162
+ ```js
163
+ // 1. After your app authenticates a user, identify them (sent as x-end-user-id
164
+ // on every knowledge AND chat call). Pass null on logout.
165
+ aiflow.setEndUser(currentUser.id);
166
+
167
+ // 2. Upload a document the user picked (pdf, docx, txt, csv, md, xlsx, pptx).
168
+ const source = await aiflow.knowledge.ingest(file); // a File/Blob
169
+ // → { id, name, status: 'processing', ... } — vectorizes in the background.
170
+
171
+ // 3. Show the user their library (poll while any is 'processing').
172
+ const mine = await aiflow.knowledge.listMine();
173
+ // → [{ id, name, status: 'ready'|'processing'|'error', chunk_count, error_message? }]
174
+
175
+ // 4. Let them remove one.
176
+ await aiflow.knowledge.deleteMine(source.id); // → { success: true }
177
+
178
+ // 5. Just chat — passages from the user's READY docs are injected automatically.
179
+ const res = await aiflow.chat({ messages: [{ role: 'user', content: '...' }] });
180
+ ```
181
+
182
+ > `setEndUser` is **required** before `knowledge.ingest` (uploads are rejected
183
+ > without an end-user id), and chat only grounds in personal docs when it's set.
184
+ > Ingestion is billed to the app owner. Don't tell users their files are
185
+ > "vectorized" — from their view they uploaded a file the assistant can now use.
186
+
187
+ ### `aiflow.connectLiveTranslate({ targetLang, sourceLang?, mode?, voice?, echoTargetLanguage?, ...handlers })`
188
+
189
+ Real-time **speech translation** over WebSocket (**Gemini 3.5 Live Translate**,
190
+ routed through the gateway — no Google key in the browser). Stream microphone
191
+ audio in and receive spoken translation + source/target transcripts back, live.
192
+
193
+ > Requires the optional peer dependency `socket.io-client`:
194
+ > `npm i socket.io-client`
195
+
196
+ **Audio-only input** — the translate model does not accept text input. Audio
197
+ formats are fixed by the model: **input** = 16 kHz, 16-bit, mono PCM;
198
+ **output** (`onAudio`) = 24 kHz PCM. The source language is **auto-detected**
199
+ (`sourceLang` is just an optional hint). Mic capture and playback stay in your
200
+ app — the session is transport-only.
201
+
202
+ ```js
203
+ const session = await aiflow.connectLiveTranslate({
204
+ targetLang: 'ko', // required — translate INTO this language
205
+ // sourceLang is optional (auto-detected)
206
+ mode: 'speech', // 'speech' (default) → render audio + transcripts; 'text' → transcripts only
207
+ onTranscript: ({ role, text }) => {
208
+ // role: 'input' = what you said, 'output' = the translation
209
+ console.log(role, text);
210
+ },
211
+ onAudio: ({ chunk }) => {
212
+ // base64 24 kHz PCM — decode + queue into a Web Audio buffer to play
213
+ playPcm(chunk);
214
+ },
215
+ onTurnComplete: ({ interrupted }) => {
216
+ if (interrupted) stopPlayback(); // user barged in — drop stale audio
217
+ },
218
+ onError: ({ code, message }) => console.warn(code, message),
219
+ onClosed: ({ reason, usage }) => console.log('closed', reason, usage),
220
+ });
221
+
222
+ // Pump 16 kHz mono PCM frames from the mic (base64 string, ArrayBuffer, or typed array)
223
+ micProcessor.onaudioframe = (pcm) => session.sendAudio(pcm);
224
+
225
+ // When the mic turns off / you're done
226
+ session.audioEnd();
227
+ session.stop();
228
+ ```
229
+
230
+ **Modes.** `mode: 'speech'` (default) renders spoken translated audio **and** the
231
+ source/translated transcripts. `mode: 'text'` renders transcripts only
232
+ (captions/subtitles). The model always streams audio + transcripts; the mode is
233
+ a client-side hint for what to render. `echoTargetLanguage` (default `true`)
234
+ controls whether audio is still spoken when the input is already in the target
235
+ language.
236
+
237
+ **Session API:** `start(params?)`, `sendAudio(chunk)`, `audioEnd()`, `stop()`,
238
+ `close()`, and `on(event, cb)` where `event` is one of
239
+ `ready | transcript | audio | turn_complete | error | closed`. (`sendText` exists
240
+ but the translate model rejects text input.)
241
+
242
+ **Billing.** Metered against the project owner's credits per token (audio tokens
243
+ cost more than text), settled periodically and on close. If the balance runs
244
+ out mid-session you'll get `onError({ code: 'INSUFFICIENT_CREDITS' })` and the
245
+ session closes.
246
+
154
247
  ## Error handling
155
248
 
156
249
  All failures throw `AIFlowError` with `.status`, `.code`, and `.requestId`.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@devvibex/aiflow",
3
- "version": "1.1.0",
4
- "description": "First-party LLM gateway SDK for apps generated on the VibeX platform — chat, streaming, image, video, music (Lyria), sound effects (ElevenLabs) and embeddings without shipping any third-party API key.",
3
+ "version": "1.3.0",
4
+ "description": "First-party LLM gateway SDK for apps generated on the VibeX platform — chat, streaming, image, video, 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",
7
7
  "llm",
@@ -35,6 +35,14 @@
35
35
  "engines": {
36
36
  "node": ">=18"
37
37
  },
38
+ "peerDependencies": {
39
+ "socket.io-client": "^4.0.0"
40
+ },
41
+ "peerDependenciesMeta": {
42
+ "socket.io-client": {
43
+ "optional": true
44
+ }
45
+ },
38
46
  "sideEffects": false,
39
47
  "license": "MIT",
40
48
  "repository": {
package/src/index.d.ts CHANGED
@@ -162,11 +162,29 @@ export interface ImageBatchResponse {
162
162
 
163
163
  export interface VideoRequest {
164
164
  prompt: string;
165
+ /**
166
+ * Video model. Defaults to the app's configured default. Veo models
167
+ * (`veo-*`) run on Google Vertex; Seedance/Dreamina
168
+ * (`dreamina-seedance-*`) run on BytePlus Ark.
169
+ */
165
170
  model?: string;
166
- aspectRatio?: '16:9' | '9:16' | '1:1' | string;
171
+ /**
172
+ * Output aspect ratio. Veo supports 16:9 / 9:16 / 1:1; Seedance also
173
+ * accepts 4:3 / 3:4 / 21:9 (the server maps unsupported ratios to 16:9).
174
+ */
175
+ aspectRatio?: '16:9' | '9:16' | '1:1' | '4:3' | '3:4' | '21:9' | string;
176
+ /**
177
+ * Clip length in seconds. Seedance 2.0 supports an integer 4–15 (clamped to
178
+ * that range, default 5). Ignored by Veo, which uses a fixed length per mode.
179
+ */
180
+ duration?: number;
181
+ /** Burn the provider watermark into the output (Seedance only). */
182
+ watermark?: boolean;
167
183
  image?: string;
168
184
  video?: string;
169
185
  signal?: AbortSignal;
186
+ /** Per-request timeout (ms). Defaults to 600000 (10 min). */
187
+ timeout?: number;
170
188
  }
171
189
 
172
190
  export interface VideoResponse {
@@ -208,6 +226,13 @@ export interface SfxRequest {
208
226
  model?: string;
209
227
  /** Clip length in seconds (0.5–30). Omit to let the model auto-decide. */
210
228
  durationSeconds?: number;
229
+ /**
230
+ * How strictly the output follows the prompt (0–1). Higher = more literal
231
+ * and less variable; lower = more creative/ambient. Omit to use the strict
232
+ * SFX default (0.7) — keeps a concrete prompt (e.g. "clapping") from
233
+ * drifting into a musical/ambient soundscape.
234
+ */
235
+ promptInfluence?: number;
211
236
  signal?: AbortSignal;
212
237
  /** Per-call timeout (ms). Defaults to 120000 (2 min). */
213
238
  timeout?: number;
@@ -263,6 +288,158 @@ export interface EmbedResponse {
263
288
  usage: { creditsUsed: number };
264
289
  }
265
290
 
291
+ // ─── Knowledge base (per-user RAG) ───────────────────────────────────────────
292
+
293
+ export type KnowledgeStatus = 'processing' | 'ready' | 'error';
294
+
295
+ export interface KnowledgeSource {
296
+ id: string;
297
+ name: string;
298
+ status: KnowledgeStatus;
299
+ chunk_count?: number;
300
+ char_count?: number;
301
+ mime_type?: string;
302
+ size_bytes?: number;
303
+ /** Present when `status === 'error'`. */
304
+ error_message?: string;
305
+ source_type?: string;
306
+ created_at?: string;
307
+ }
308
+
309
+ export interface KnowledgeIngestOptions {
310
+ signal?: AbortSignal;
311
+ /** Per-call timeout (ms). Defaults to 180000 (3 min). */
312
+ timeout?: number;
313
+ }
314
+
315
+ export interface KnowledgeRequestOptions {
316
+ signal?: AbortSignal;
317
+ }
318
+
319
+ /**
320
+ * Per-user knowledge base (RAG). Documents are uploaded by the app's END USERS,
321
+ * vectorized transparently and scoped to the current end user (set via
322
+ * `setEndUser`). Relevant passages are injected into that user's chat answers
323
+ * automatically — you only upload / list / delete here.
324
+ */
325
+ export interface KnowledgeNamespace {
326
+ /** Upload a File/Blob (pdf, docx, txt, csv, md, xlsx, pptx) to vectorize. */
327
+ ingest(
328
+ file: Blob | File,
329
+ options?: KnowledgeIngestOptions,
330
+ ): Promise<KnowledgeSource>;
331
+ /** List the current end user's own knowledge sources. */
332
+ listMine(options?: KnowledgeRequestOptions): Promise<KnowledgeSource[]>;
333
+ /** Delete one of the current end user's own sources by id. */
334
+ deleteMine(
335
+ id: string,
336
+ options?: KnowledgeRequestOptions,
337
+ ): Promise<{ success: boolean }>;
338
+ }
339
+
340
+ // ─── Live translation ──────────────────────────────────────────────────────
341
+
342
+ export type LiveTranslateMode = 'speech' | 'text';
343
+
344
+ export interface LiveUsage {
345
+ inputTokens: number;
346
+ outputTokens: number;
347
+ audioInputTokens: number;
348
+ audioOutputTokens: number;
349
+ creditsUsed: number;
350
+ }
351
+
352
+ export interface LiveReadyPayload {
353
+ sessionId: string;
354
+ model: string;
355
+ mode: LiveTranslateMode;
356
+ sourceLang: string;
357
+ targetLang: string;
358
+ }
359
+
360
+ export interface LiveTranscript {
361
+ /** 'input' = recognized source speech; 'output' = translated text. */
362
+ role: 'input' | 'output';
363
+ text: string;
364
+ isFinal: boolean;
365
+ }
366
+
367
+ export interface LiveAudioOut {
368
+ /** Base64-encoded PCM audio (24 kHz) of the spoken translation. */
369
+ chunk: string;
370
+ mimeType: string;
371
+ }
372
+
373
+ export interface LiveTurnComplete {
374
+ interrupted: boolean;
375
+ }
376
+
377
+ export interface LiveError {
378
+ code: string;
379
+ message: string;
380
+ }
381
+
382
+ export interface LiveClosed {
383
+ reason: string;
384
+ usage: LiveUsage | null;
385
+ }
386
+
387
+ export interface LiveTranslateOptions {
388
+ /** Target language to translate into (e.g. "ko" / "Korean"). Required. */
389
+ targetLang: string;
390
+ /** Source language hint. Optional — Gemini Live Translate auto-detects it. */
391
+ sourceLang?: string;
392
+ /** 'speech' (render audio + transcripts, default) or 'text' (transcripts only). */
393
+ mode?: LiveTranslateMode;
394
+ /** Prebuilt voice name for the spoken translation. */
395
+ voice?: string;
396
+ /** Speak audio even when the input is already in the target language (default true). */
397
+ echoTargetLanguage?: boolean;
398
+ /** Override the WebSocket origin (defaults to the `baseUrl` origin). */
399
+ wsUrl?: string;
400
+ /** Emit `translate:start` automatically on connect. Default true. */
401
+ autoStart?: boolean;
402
+ onReady?: (payload: LiveReadyPayload) => void;
403
+ onTranscript?: (payload: LiveTranscript) => void;
404
+ onAudio?: (payload: LiveAudioOut) => void;
405
+ onTurnComplete?: (payload: LiveTurnComplete) => void;
406
+ onError?: (payload: LiveError) => void;
407
+ onClosed?: (payload: LiveClosed) => void;
408
+ }
409
+
410
+ export type LiveTranslateEvent =
411
+ | 'ready'
412
+ | 'transcript'
413
+ | 'audio'
414
+ | 'turn_complete'
415
+ | 'error'
416
+ | 'closed';
417
+
418
+ /**
419
+ * A real-time translation session. Transport-only — mic capture and audio
420
+ * playback stay in your app. Audio in: 16 kHz, 16-bit, mono PCM. Audio out
421
+ * (`onAudio`): 24 kHz PCM.
422
+ */
423
+ export class LiveTranslateSession {
424
+ readonly params: LiveTranslateOptions;
425
+ ready: boolean;
426
+ closed: boolean;
427
+ /** (Re)start a translation turn with the configured (or given) params. */
428
+ start(params?: Partial<LiveTranslateOptions>): void;
429
+ /** Push a realtime audio chunk (base64 string, ArrayBuffer, or typed array). */
430
+ sendAudio(chunk: string | ArrayBuffer | ArrayBufferView): void;
431
+ /** Push text to translate (alternative to audio). */
432
+ sendText(text: string): void;
433
+ /** Signal the audio input stream ended (mic off). */
434
+ audioEnd(): void;
435
+ /** Stop the session (settles billing and closes upstream). */
436
+ stop(): void;
437
+ /** Tear down the socket immediately. */
438
+ close(): void;
439
+ /** Subscribe to an event; returns an unsubscribe function. */
440
+ on(event: LiveTranslateEvent, cb: (payload: any) => void): () => void;
441
+ }
442
+
266
443
  export interface AIFlowClientOptions {
267
444
  appId: string;
268
445
  baseUrl: string;
@@ -273,6 +450,11 @@ export interface AIFlowClientOptions {
273
450
  defaultVideoModel?: string | null;
274
451
  defaultAudioModel?: string | null;
275
452
  defaultSfxModel?: string | null;
453
+ /**
454
+ * Current end-user id (the app's logged-in user). Scopes the per-user
455
+ * knowledge base; sent as `x-end-user-id`. Set/clear later with `setEndUser`.
456
+ */
457
+ endUserId?: string | null;
276
458
  timeout?: number;
277
459
  maxRetries?: number;
278
460
  fetch?: typeof fetch;
@@ -313,9 +495,21 @@ export class AIFlowClient {
313
495
  readonly baseUrl: string;
314
496
  readonly timeout: number;
315
497
  readonly maxRetries: number;
498
+ /** Current end-user id (or null). Set via `setEndUser`. */
499
+ endUserId: string | null;
500
+ /** Per-user knowledge base — upload / list / delete the current user's docs. */
501
+ readonly knowledge: KnowledgeNamespace;
316
502
 
317
503
  constructor(options: AIFlowClientOptions);
318
504
 
505
+ /**
506
+ * Set (or clear with `null`) the current end user. Call after your app
507
+ * authenticates a user — every subsequent knowledge AND chat call then
508
+ * carries `x-end-user-id`, so the user's own uploaded documents ground their
509
+ * answers. Returns `this` for chaining.
510
+ */
511
+ setEndUser(endUserId: string | null): this;
512
+
319
513
  /**
320
514
  * Fetch (and cache) the server-side AIFlow config. Pass `{ refresh: true }`
321
515
  * to force a reload.
@@ -330,6 +524,14 @@ export class AIFlowClient {
330
524
  generateSfx(request: SfxRequest): Promise<SfxResponse>;
331
525
  embed(request: EmbedRequest): Promise<EmbedResponse>;
332
526
  vision(request: VisionRequest): Promise<VisionResponse>;
527
+ /**
528
+ * Open a real-time speech-translation session over WebSocket (Gemini Live
529
+ * via the gateway). Requires the optional peer dependency
530
+ * `socket.io-client`. Resolves once connected.
531
+ */
532
+ connectLiveTranslate(
533
+ options: LiveTranslateOptions,
534
+ ): Promise<LiveTranslateSession>;
333
535
  }
334
536
 
335
537
  export default AIFlowClient;
package/src/index.js CHANGED
@@ -28,6 +28,7 @@ export class AIFlowClient {
28
28
  * @param {string} options.baseUrl VibeX gateway base URL (e.g. "https://api.vibe-x.io/aiflow").
29
29
  * @param {string} [options.defaultModel]
30
30
  * @param {string} [options.defaultImageModel]
31
+ * @param {string} [options.endUserId] Current end-user id (the app's logged-in user). Scopes the per-user knowledge base; sent as `x-end-user-id`. Set/clear later with `setEndUser()`.
31
32
  * @param {number} [options.timeout] Per-request timeout (ms). Default 60000.
32
33
  * @param {number} [options.maxRetries] Retries on 429/5xx / network errors. Default 2.
33
34
  * @param {typeof fetch} [options.fetch] Custom fetch implementation.
@@ -41,6 +42,7 @@ export class AIFlowClient {
41
42
  defaultVideoModel = null,
42
43
  defaultAudioModel = null,
43
44
  defaultSfxModel = null,
45
+ endUserId = null,
44
46
  timeout = DEFAULT_TIMEOUT_MS,
45
47
  maxRetries = DEFAULT_MAX_RETRIES,
46
48
  fetch: customFetch,
@@ -50,6 +52,9 @@ export class AIFlowClient {
50
52
 
51
53
  this.appId = appId;
52
54
  this.baseUrl = String(baseUrl).replace(/\/+$/, '');
55
+ // Current end user (the app's logged-in user). Scopes the knowledge base
56
+ // so each user only ever sees/retrieves their own uploaded documents.
57
+ this.endUserId = endUserId ? String(endUserId) : null;
53
58
  // Caller-provided overrides — win over server-fetched config.
54
59
  this._userDefaults = {
55
60
  chat: defaultModel,
@@ -75,6 +80,33 @@ export class AIFlowClient {
75
80
  // getConfig() / chat() / generateImage() / embed().
76
81
  this._config = null;
77
82
  this._configPromise = null;
83
+
84
+ /**
85
+ * Per-user knowledge base (RAG). The data is uploaded by the app's END
86
+ * USERS through the app itself, vectorized transparently and scoped to
87
+ * the current end user (set via `setEndUser()`). Retrieval into chat is
88
+ * automatic server-side — you only upload / list / delete here.
89
+ */
90
+ this.knowledge = {
91
+ /** Upload a File/Blob to vectorize into the current user's knowledge. */
92
+ ingest: (file, opts) => this._knowledgeIngest(file, opts),
93
+ /** List the current user's own knowledge sources. */
94
+ listMine: (opts) => this._knowledgeList(opts),
95
+ /** Delete one of the current user's own knowledge sources by id. */
96
+ deleteMine: (id, opts) => this._knowledgeDelete(id, opts),
97
+ };
98
+ }
99
+
100
+ /**
101
+ * Set (or clear) the current end user. Call after your app authenticates a
102
+ * user — every subsequent knowledge AND chat call carries `x-end-user-id`,
103
+ * so the user's own uploaded documents ground their answers. Pass `null` on
104
+ * logout. Returns `this` for chaining.
105
+ * @param {string|null} endUserId
106
+ */
107
+ setEndUser(endUserId) {
108
+ this.endUserId = endUserId ? String(endUserId) : null;
109
+ return this;
78
110
  }
79
111
 
80
112
  /**
@@ -341,9 +373,12 @@ export class AIFlowClient {
341
373
  prompt,
342
374
  model,
343
375
  aspectRatio = '16:9',
376
+ duration,
377
+ watermark,
344
378
  image,
345
379
  video,
346
380
  signal,
381
+ timeout,
347
382
  } = {}) {
348
383
  if (!prompt || typeof prompt !== 'string') {
349
384
  throw new AIFlowError('prompt is required');
@@ -356,10 +391,15 @@ export class AIFlowClient {
356
391
  model: resolvedModel,
357
392
  prompt,
358
393
  aspectRatio,
394
+ duration,
395
+ watermark,
359
396
  image,
360
397
  video,
361
398
  },
362
- { signal },
399
+ // Video generation is long-running (the server polls the provider
400
+ // for up to ~10 minutes). Match that ceiling so the socket isn't
401
+ // closed mid-generation.
402
+ { signal, timeout: timeout ?? 600_000 },
363
403
  );
364
404
  return await res.json();
365
405
  }
@@ -404,6 +444,7 @@ export class AIFlowClient {
404
444
  prompt,
405
445
  model,
406
446
  durationSeconds,
447
+ promptInfluence,
407
448
  signal,
408
449
  timeout,
409
450
  } = {}) {
@@ -417,6 +458,7 @@ export class AIFlowClient {
417
458
  model: resolvedModel,
418
459
  prompt,
419
460
  durationSeconds,
461
+ promptInfluence,
420
462
  },
421
463
  { signal, timeout: timeout ?? 120_000 },
422
464
  );
@@ -468,17 +510,115 @@ export class AIFlowClient {
468
510
  return await res.json();
469
511
  }
470
512
 
513
+ /**
514
+ * Open a real-time speech-translation session over WebSocket (Gemini Live
515
+ * via the platform gateway — no Google key in the browser). Stream 16 kHz
516
+ * 16-bit mono PCM audio in; receive translated audio (24 kHz PCM) and
517
+ * source/target transcripts back.
518
+ *
519
+ * Requires the optional peer dependency `socket.io-client`.
520
+ *
521
+ * Input is AUDIO ONLY — text input is not supported by the translate model.
522
+ *
523
+ * @param {object} opts
524
+ * @param {string} opts.targetLang Target language to translate into (e.g. "ko" / "Korean"). Required.
525
+ * @param {string} [opts.sourceLang] Source language hint. Optional — the model auto-detects.
526
+ * @param {'speech'|'text'} [opts.mode] 'speech' (render audio + transcripts, default) or 'text' (transcripts only).
527
+ * @param {string} [opts.voice] Prebuilt voice for the spoken translation.
528
+ * @param {boolean} [opts.echoTargetLanguage] Speak audio even when input is already in the target language (default true).
529
+ * @param {string} [opts.wsUrl] Override the ws origin (defaults to baseUrl's origin).
530
+ * @param {boolean} [opts.autoStart] Send `translate:start` automatically on connect (default true).
531
+ * @param {(p:object)=>void} [opts.onReady]
532
+ * @param {(p:{role:'input'|'output',text:string,isFinal:boolean})=>void} [opts.onTranscript]
533
+ * @param {(p:{chunk:string,mimeType:string})=>void} [opts.onAudio]
534
+ * @param {(p:{interrupted:boolean})=>void} [opts.onTurnComplete]
535
+ * @param {(p:{code:string,message:string})=>void} [opts.onError]
536
+ * @param {(p:{reason:string,usage:object})=>void} [opts.onClosed]
537
+ * @returns {Promise<LiveTranslateSession>} Resolves once connected.
538
+ */
539
+ async connectLiveTranslate({
540
+ targetLang,
541
+ sourceLang,
542
+ mode,
543
+ voice,
544
+ echoTargetLanguage,
545
+ wsUrl,
546
+ autoStart = true,
547
+ onReady,
548
+ onTranscript,
549
+ onAudio,
550
+ onTurnComplete,
551
+ onError,
552
+ onClosed,
553
+ } = {}) {
554
+ if (!targetLang) {
555
+ throw new AIFlowError(
556
+ 'connectLiveTranslate requires targetLang',
557
+ );
558
+ }
559
+ const io = await loadSocketIoClient();
560
+ let origin = wsUrl;
561
+ if (!origin) {
562
+ try {
563
+ origin = new URL(this.baseUrl).origin;
564
+ } catch {
565
+ throw new AIFlowError(
566
+ 'Could not derive the WebSocket origin from baseUrl — pass opts.wsUrl.',
567
+ );
568
+ }
569
+ }
570
+ const session = new LiveTranslateSession({
571
+ io,
572
+ origin,
573
+ appId: this.appId,
574
+ params: { targetLang, sourceLang, mode, voice, echoTargetLanguage },
575
+ autoStart,
576
+ handlers: {
577
+ onReady,
578
+ onTranscript,
579
+ onAudio,
580
+ onTurnComplete,
581
+ onError,
582
+ onClosed,
583
+ },
584
+ });
585
+ await session._connect();
586
+ return session;
587
+ }
588
+
471
589
  // ────────────────────────────────────────────────────────────────────────
472
590
  // Internals
473
591
  // ────────────────────────────────────────────────────────────────────────
474
592
 
593
+ /**
594
+ * Auth/identity headers attached to every gateway call: the public app id
595
+ * and (when set) the current end-user id that scopes the knowledge base.
596
+ */
597
+ _authHeaders() {
598
+ const h = { 'x-app-id': this.appId };
599
+ if (this.endUserId) h['x-end-user-id'] = this.endUserId;
600
+ return h;
601
+ }
602
+
603
+ /** POST a JSON body to the gateway. */
475
604
  async _request(path, body, { signal, stream = false, timeout } = {}) {
476
- const url = `${this.baseUrl}${path}`;
477
605
  const headers = {
478
606
  'Content-Type': 'application/json',
479
- 'x-app-id': this.appId,
607
+ ...this._authHeaders(),
480
608
  Accept: stream ? 'text/event-stream' : 'application/json',
481
609
  };
610
+ return this._fetchWithRetry(
611
+ `${this.baseUrl}${path}`,
612
+ { method: 'POST', headers, body: JSON.stringify(body) },
613
+ { signal, timeout },
614
+ );
615
+ }
616
+
617
+ /**
618
+ * Send a request with timeout + retry (429/5xx + network errors). `init`
619
+ * carries method/headers/body; the abort signal is composed per attempt.
620
+ */
621
+ async _fetchWithRetry(url, init, { signal, timeout } = {}) {
482
622
  // Per-call timeout override — image/video calls run far longer than the
483
623
  // 60s client default, so they pass a larger value here.
484
624
  const effectiveTimeout = timeout ?? this.timeout;
@@ -495,9 +635,7 @@ export class AIFlowClient {
495
635
  let res;
496
636
  try {
497
637
  res = await this._fetch(url, {
498
- method: 'POST',
499
- headers,
500
- body: JSON.stringify(body),
638
+ ...init,
501
639
  signal: composedSignal,
502
640
  });
503
641
  } catch (err) {
@@ -509,7 +647,7 @@ export class AIFlowClient {
509
647
  continue;
510
648
  }
511
649
  throw new AIFlowError(
512
- `Network error calling ${path}: ${err?.message || err}`,
650
+ `Network error calling ${url}: ${err?.message || err}`,
513
651
  { cause: err },
514
652
  );
515
653
  }
@@ -539,6 +677,240 @@ export class AIFlowClient {
539
677
  return res;
540
678
  }
541
679
  }
680
+
681
+ // ────────────────────────────────────────────────────────────────────────
682
+ // Knowledge base (per-user RAG) internals
683
+ // ────────────────────────────────────────────────────────────────────────
684
+
685
+ async _knowledgeIngest(file, { signal, timeout } = {}) {
686
+ if (!file) {
687
+ throw new AIFlowError('a File/Blob is required to ingest knowledge');
688
+ }
689
+ if (!this.endUserId) {
690
+ throw new AIFlowError(
691
+ 'setEndUser(id) must be called before uploading knowledge',
692
+ );
693
+ }
694
+ if (typeof FormData === 'undefined') {
695
+ throw new AIFlowError(
696
+ 'FormData is not available in this environment — knowledge upload needs a browser or Node 18+ with global FormData.',
697
+ );
698
+ }
699
+ const form = new FormData();
700
+ // Field name is irrelevant — the gateway accepts any (multer().any()).
701
+ form.append('file', file, file.name || 'document');
702
+ // NO Content-Type header — fetch sets the multipart boundary itself.
703
+ const res = await this._fetchWithRetry(
704
+ `${this.baseUrl}/knowledge/ingest`,
705
+ { method: 'POST', headers: this._authHeaders(), body: form },
706
+ // Extracting + embedding a large doc can run long; the server does it
707
+ // in the background but the upload itself may still take a while.
708
+ { signal, timeout: timeout ?? 180_000 },
709
+ );
710
+ return await res.json();
711
+ }
712
+
713
+ async _knowledgeList({ signal } = {}) {
714
+ const res = await this._fetchWithRetry(
715
+ `${this.baseUrl}/knowledge/sources`,
716
+ {
717
+ method: 'GET',
718
+ headers: { Accept: 'application/json', ...this._authHeaders() },
719
+ },
720
+ { signal },
721
+ );
722
+ return await res.json();
723
+ }
724
+
725
+ async _knowledgeDelete(id, { signal } = {}) {
726
+ if (!id) throw new AIFlowError('a source id is required');
727
+ const res = await this._fetchWithRetry(
728
+ `${this.baseUrl}/knowledge/sources/${encodeURIComponent(id)}`,
729
+ {
730
+ method: 'DELETE',
731
+ headers: { Accept: 'application/json', ...this._authHeaders() },
732
+ },
733
+ { signal },
734
+ );
735
+ return await res.json();
736
+ }
737
+ }
738
+
739
+ // ────────────────────────────────────────────────────────────────────────────
740
+ // Live translation
741
+ // ────────────────────────────────────────────────────────────────────────────
742
+
743
+ /**
744
+ * A real-time translation session. Created via
745
+ * `AIFlowClient.connectLiveTranslate(...)`. Transport-only: mic capture and
746
+ * audio playback stay in your app. Audio in must be 16 kHz, 16-bit, mono PCM;
747
+ * audio out (`onAudio`) is 24 kHz PCM.
748
+ */
749
+ export class LiveTranslateSession {
750
+ constructor({ io, origin, appId, params, autoStart, handlers }) {
751
+ this._io = io;
752
+ this._origin = String(origin).replace(/\/+$/, '');
753
+ this._appId = appId;
754
+ this.params = params;
755
+ this._autoStart = autoStart;
756
+ this._handlers = handlers || {};
757
+ this._listeners = new Map();
758
+ this.socket = null;
759
+ this.ready = false;
760
+ this.closed = false;
761
+ }
762
+
763
+ async _connect() {
764
+ this.socket = this._io(`${this._origin}/aiflow-live`, {
765
+ path: '/ws',
766
+ transports: ['websocket'],
767
+ auth: { appId: this._appId },
768
+ });
769
+
770
+ const fwd = (event, cb) =>
771
+ this.socket.on(event, (payload) => {
772
+ cb?.(payload);
773
+ this._emit(event, payload);
774
+ });
775
+
776
+ this.socket.on('translate:ready', (p) => {
777
+ this.ready = true;
778
+ this._handlers.onReady?.(p);
779
+ this._emit('ready', p);
780
+ });
781
+ fwd('translate:transcript', this._handlers.onTranscript);
782
+ fwd('translate:audio', this._handlers.onAudio);
783
+ fwd('translate:turn_complete', this._handlers.onTurnComplete);
784
+ fwd('translate:error', this._handlers.onError);
785
+ this.socket.on('translate:closed', (p) => {
786
+ this.closed = true;
787
+ this._handlers.onClosed?.(p);
788
+ this._emit('closed', p);
789
+ });
790
+
791
+ await new Promise((resolve, reject) => {
792
+ const timer = setTimeout(
793
+ () =>
794
+ reject(
795
+ new AIFlowError('AIFlow Live connection timed out'),
796
+ ),
797
+ 15_000,
798
+ );
799
+ this.socket.once('connect', () => {
800
+ clearTimeout(timer);
801
+ resolve();
802
+ });
803
+ this.socket.once('connect_error', (err) => {
804
+ clearTimeout(timer);
805
+ reject(
806
+ new AIFlowError(
807
+ `AIFlow Live connection failed: ${err?.message || err}`,
808
+ { cause: err },
809
+ ),
810
+ );
811
+ });
812
+ });
813
+
814
+ if (this._autoStart) this.start();
815
+ return this;
816
+ }
817
+
818
+ /** (Re)start the translation turn with the configured params. */
819
+ start(params) {
820
+ this.socket?.emit('translate:start', params || this.params);
821
+ }
822
+
823
+ /**
824
+ * Push a realtime audio chunk. Accepts a base64 string, an ArrayBuffer, or
825
+ * a typed array of 16 kHz 16-bit mono PCM.
826
+ */
827
+ sendAudio(chunk) {
828
+ this.socket?.emit('translate:audio', { chunk: toBase64(chunk) });
829
+ }
830
+
831
+ /** Push text to translate (alternative to audio). */
832
+ sendText(text) {
833
+ this.socket?.emit('translate:text', { text });
834
+ }
835
+
836
+ /** Signal that the audio input stream ended (mic off). */
837
+ audioEnd() {
838
+ this.socket?.emit('translate:audio_end');
839
+ }
840
+
841
+ /** Stop the session (settles billing and closes upstream). */
842
+ stop() {
843
+ this.socket?.emit('translate:stop');
844
+ }
845
+
846
+ /** Tear down the socket immediately. */
847
+ close() {
848
+ try {
849
+ this.socket?.close();
850
+ } catch {
851
+ /* noop */
852
+ }
853
+ }
854
+
855
+ /** Subscribe to an event ('ready'|'transcript'|'audio'|'turn_complete'|'error'|'closed' or the raw `translate:*`). */
856
+ on(event, cb) {
857
+ const key = event.startsWith('translate:')
858
+ ? event.slice('translate:'.length)
859
+ : event;
860
+ if (!this._listeners.has(key)) this._listeners.set(key, new Set());
861
+ this._listeners.get(key).add(cb);
862
+ return () => this._listeners.get(key)?.delete(cb);
863
+ }
864
+
865
+ _emit(event, payload) {
866
+ const key = event.startsWith('translate:')
867
+ ? event.slice('translate:'.length)
868
+ : event;
869
+ const set = this._listeners.get(key);
870
+ if (set) for (const cb of set) cb(payload);
871
+ }
872
+ }
873
+
874
+ async function loadSocketIoClient() {
875
+ try {
876
+ const mod = await import('socket.io-client');
877
+ return mod.io || mod.default?.io || mod.default;
878
+ } catch (err) {
879
+ throw new AIFlowError(
880
+ 'socket.io-client is required for live translation — install it: npm i socket.io-client',
881
+ { cause: err },
882
+ );
883
+ }
884
+ }
885
+
886
+ function toBase64(chunk) {
887
+ if (typeof chunk === 'string') return chunk; // assume already base64
888
+ let bytes;
889
+ if (chunk instanceof Uint8Array) bytes = chunk;
890
+ else if (chunk instanceof ArrayBuffer) bytes = new Uint8Array(chunk);
891
+ else if (ArrayBuffer.isView(chunk))
892
+ bytes = new Uint8Array(
893
+ chunk.buffer,
894
+ chunk.byteOffset,
895
+ chunk.byteLength,
896
+ );
897
+ else
898
+ throw new AIFlowError(
899
+ 'sendAudio expects a base64 string, ArrayBuffer, or typed array',
900
+ );
901
+
902
+ if (typeof btoa === 'function') {
903
+ let bin = '';
904
+ const CHUNK = 0x8000;
905
+ for (let i = 0; i < bytes.length; i += CHUNK) {
906
+ bin += String.fromCharCode.apply(
907
+ null,
908
+ bytes.subarray(i, i + CHUNK),
909
+ );
910
+ }
911
+ return btoa(bin);
912
+ }
913
+ return Buffer.from(bytes).toString('base64');
542
914
  }
543
915
 
544
916
  // ────────────────────────────────────────────────────────────────────────────