@devvibex/aiflow 1.5.0 → 1.7.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devvibex/aiflow",
3
- "version": "1.5.0",
3
+ "version": "1.7.0",
4
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",
package/src/index.d.ts CHANGED
@@ -61,16 +61,26 @@ export interface ChatUsage {
61
61
  creditsUsed: number;
62
62
  }
63
63
 
64
+ /** Where the resolved `model` came from. */
65
+ export type ModelSource = 'request' | 'message' | 'default';
66
+
64
67
  export interface ChatResponse {
65
68
  id: string;
69
+ /** Resolved model id. */
66
70
  model: string;
67
71
  content: string;
68
72
  usage: ChatUsage;
73
+ /** Where the resolved `model` came from. */
74
+ modelSource?: ModelSource;
69
75
  }
70
76
 
71
77
  export interface ChatStreamChunk {
72
78
  delta: string;
73
79
  done: boolean;
80
+ /** Resolved model id (present on the final `done: true` chunk). */
81
+ model?: string;
82
+ /** Where the resolved `model` came from (present on the final `done: true` chunk). */
83
+ modelSource?: ModelSource;
74
84
  [key: string]: unknown;
75
85
  }
76
86
 
@@ -498,9 +508,16 @@ export interface AIFlowClientOptions {
498
508
  defaultSfxModel?: string | null;
499
509
  /**
500
510
  * Current end-user id (the app's logged-in user). Scopes the per-user
501
- * knowledge base; sent as `x-end-user-id`. Set/clear later with `setEndUser`.
511
+ * knowledge base. Set/clear later with `setEndUser`.
502
512
  */
503
513
  endUserId?: string | null;
514
+ /**
515
+ * The logged-in end user's access token (from your app's
516
+ * `POST /:projectKey/auth/login`). REQUIRED for the knowledge base: the
517
+ * gateway verifies it and derives a TRUSTED end-user id (sent as
518
+ * `x-app-user-token`). Set/clear later with `setEndUser(id, token)`.
519
+ */
520
+ appUserToken?: string | null;
504
521
  timeout?: number;
505
522
  maxRetries?: number;
506
523
  fetch?: typeof fetch;
@@ -515,6 +532,8 @@ export interface AiflowConfig {
515
532
  video: string[];
516
533
  audio: string[];
517
534
  sfx: string[];
535
+ /** Real-time translate models, when configured. */
536
+ translate?: string[];
518
537
  };
519
538
  defaults: {
520
539
  chat: string;
@@ -523,6 +542,8 @@ export interface AiflowConfig {
523
542
  video: string;
524
543
  audio: string;
525
544
  sfx: string;
545
+ /** Default real-time translate model, when configured. */
546
+ translate?: string;
526
547
  };
527
548
  limits: {
528
549
  maxTokens: number;
@@ -534,6 +555,53 @@ export interface AiflowConfig {
534
555
  creditValue: number;
535
556
  /** Module-configured default system prompt, or null if none. */
536
557
  systemPrompt?: string | null;
558
+ /** Whether server-side web search is enabled for chat by default. */
559
+ webSearch?: boolean;
560
+ /** Whether the real-time live-translate feature is enabled. */
561
+ liveTranslate?: boolean;
562
+ }
563
+
564
+ // ─── Admin (module config) ───────────────────────────────────────────────────
565
+
566
+ /** One AIFlow module in the app's project, as returned by `admin.listModules`. */
567
+ export interface AiflowAdminModule {
568
+ appId: string;
569
+ moduleId: number;
570
+ feature: string | null;
571
+ useCase: string;
572
+ useCaseName: string | null;
573
+ title: string | null;
574
+ systemPrompt: string | null;
575
+ defaults: Record<string, string>;
576
+ models: string[];
577
+ }
578
+
579
+ /** Input for `admin.updateConfig`. */
580
+ export interface AiflowAdminUpdateConfigInput {
581
+ /**
582
+ * Target module. Optional — defaults to the module for this client's app_id.
583
+ * When set it must be a sibling module in the same project.
584
+ */
585
+ moduleId?: number;
586
+ systemPrompt?: string;
587
+ defaults?: Record<string, string>;
588
+ /** Sugar: sets the chat default model (folded into `defaults.chat`). */
589
+ defaultModel?: string;
590
+ }
591
+
592
+ /**
593
+ * Admin namespace — manage the app's AIFlow module config. Requires an admin
594
+ * bearer token set via `setAdminToken()`; the gateway rejects non-admins (403).
595
+ */
596
+ export interface AiflowAdminNamespace {
597
+ /** List every AIFlow module in this app's project. */
598
+ listModules(opts?: {
599
+ signal?: AbortSignal;
600
+ }): Promise<{ modules: AiflowAdminModule[] }>;
601
+ /** Update the target module's system prompt and/or default models. */
602
+ updateConfig(
603
+ input: AiflowAdminUpdateConfigInput,
604
+ ): Promise<{ module: AiflowAdminModule }>;
537
605
  }
538
606
 
539
607
  export class AIFlowClient {
@@ -543,18 +611,42 @@ export class AIFlowClient {
543
611
  readonly maxRetries: number;
544
612
  /** Current end-user id (or null). Set via `setEndUser`. */
545
613
  endUserId: string | null;
614
+ /** Current end-user access token (or null), sent as `x-app-user-token`. Set via `setEndUser`. */
615
+ appUserToken: string | null;
546
616
  /** Per-user knowledge base — upload / list / delete the current user's docs. */
547
617
  readonly knowledge: KnowledgeNamespace;
618
+ /** Admin namespace — manage the app's AIFlow module config (needs `setAdminToken`). */
619
+ readonly admin: AiflowAdminNamespace;
548
620
 
549
621
  constructor(options: AIFlowClientOptions);
550
622
 
551
623
  /**
552
624
  * Set (or clear with `null`) the current end user. Call after your app
553
- * authenticates a user — every subsequent knowledge AND chat call then
554
- * carries `x-end-user-id`, so the user's own uploaded documents ground their
555
- * answers. Returns `this` for chaining.
625
+ * authenticates a user, passing the user's id AND their access token (from
626
+ * your app's `POST /:projectKey/auth/login`). Every subsequent knowledge AND
627
+ * chat call then carries the verified `x-app-user-token`, so the gateway
628
+ * derives a TRUSTED end-user id and grounds answers in that user's own
629
+ * documents. The token is REQUIRED for the knowledge base. Returns `this`.
630
+ */
631
+ setEndUser(endUserId: string | null, appUserToken?: string | null): this;
632
+
633
+ /**
634
+ * Set a session-level default model for one generation kind. Wins over the
635
+ * server config default, but a per-call `model` still wins over this. Pass
636
+ * `null` to clear the override. Returns `this` for chaining.
637
+ */
638
+ setModel(
639
+ kind: 'chat' | 'image' | 'embed' | 'video' | 'audio' | 'sfx',
640
+ model: string | null,
641
+ ): this;
642
+
643
+ /**
644
+ * Set (or clear with `null`) the admin bearer token — the generated app's
645
+ * own logged-in admin JWT (the same bearer the app's `vibex` SDK reads from
646
+ * localStorage['access_token']). Required for every `admin.*` call. Returns
647
+ * `this` for chaining.
556
648
  */
557
- setEndUser(endUserId: string | null): this;
649
+ setAdminToken(token: string | null): this;
558
650
 
559
651
  /**
560
652
  * Fetch (and cache) the server-side AIFlow config. Pass `{ refresh: true }`
package/src/index.js CHANGED
@@ -28,7 +28,8 @@ 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
+ * @param {string} [options.endUserId] Current end-user id (the app's logged-in user). Scopes the per-user knowledge base. Set/clear later with `setEndUser()`.
32
+ * @param {string} [options.appUserToken] The logged-in end user's access token (from your app's `POST /:projectKey/auth/login`). REQUIRED for the knowledge base: the gateway verifies it and derives a TRUSTED end-user id (sent as `x-app-user-token`). Set/clear later with `setEndUser(id, token)`.
32
33
  * @param {number} [options.timeout] Per-request timeout (ms). Default 60000.
33
34
  * @param {number} [options.maxRetries] Retries on 429/5xx / network errors. Default 2.
34
35
  * @param {typeof fetch} [options.fetch] Custom fetch implementation.
@@ -43,6 +44,7 @@ export class AIFlowClient {
43
44
  defaultAudioModel = null,
44
45
  defaultSfxModel = null,
45
46
  endUserId = null,
47
+ appUserToken = null,
46
48
  timeout = DEFAULT_TIMEOUT_MS,
47
49
  maxRetries = DEFAULT_MAX_RETRIES,
48
50
  fetch: customFetch,
@@ -55,6 +57,10 @@ export class AIFlowClient {
55
57
  // Current end user (the app's logged-in user). Scopes the knowledge base
56
58
  // so each user only ever sees/retrieves their own uploaded documents.
57
59
  this.endUserId = endUserId ? String(endUserId) : null;
60
+ // The end user's access token (issued by your app's own login). The
61
+ // gateway VERIFIES it and derives a trusted end-user id from it — this is
62
+ // what secures the per-user knowledge base against a spoofed id header.
63
+ this.appUserToken = appUserToken ? String(appUserToken) : null;
58
64
  // Caller-provided overrides — win over server-fetched config.
59
65
  this._userDefaults = {
60
66
  chat: defaultModel,
@@ -64,6 +70,9 @@ export class AIFlowClient {
64
70
  audio: defaultAudioModel,
65
71
  sfx: defaultSfxModel,
66
72
  };
73
+ // Admin bearer token (the generated app's own logged-in admin JWT).
74
+ // Set via setAdminToken(); required by the /admin/* routes.
75
+ this._adminToken = null;
67
76
  this.timeout = timeout;
68
77
  this.maxRetries = maxRetries;
69
78
  this._fetch =
@@ -95,17 +104,62 @@ export class AIFlowClient {
95
104
  /** Delete one of the current user's own knowledge sources by id. */
96
105
  deleteMine: (id, opts) => this._knowledgeDelete(id, opts),
97
106
  };
107
+
108
+ /**
109
+ * Admin namespace — manage the app's AIFlow module config (system
110
+ * prompt + per-kind default models). Requires an admin bearer token set
111
+ * via `setAdminToken()`; the gateway rejects non-admin callers (403).
112
+ */
113
+ this.admin = {
114
+ /** List every AIFlow module in this app's project. */
115
+ listModules: (opts) => this._adminListModules(opts),
116
+ /** Update this app's (or a sibling) module system prompt / defaults. */
117
+ updateConfig: (input) => this._adminUpdateConfig(input),
118
+ };
98
119
  }
99
120
 
100
121
  /**
101
122
  * 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.
123
+ * user, passing the user's id AND their access token (the one your app got
124
+ * from `POST /:projectKey/auth/login`). Every subsequent knowledge AND chat
125
+ * call then carries the verified `x-app-user-token`, so the gateway can
126
+ * derive a TRUSTED end-user id and ground answers in that user's own
127
+ * documents. Pass `null` (or no args) on logout to clear both. Returns
128
+ * `this` for chaining.
129
+ *
130
+ * The token is REQUIRED for the knowledge base to work securely: without it
131
+ * the gateway has no authenticated identity, so uploads are rejected and
132
+ * chat is not grounded in the user's documents (the legacy id-only mode is
133
+ * off by default because a raw id header is spoofable).
105
134
  * @param {string|null} endUserId
135
+ * @param {string|null} [appUserToken] The user's access token from your app's login.
106
136
  */
107
- setEndUser(endUserId) {
137
+ setEndUser(endUserId, appUserToken = null) {
108
138
  this.endUserId = endUserId ? String(endUserId) : null;
139
+ this.appUserToken = appUserToken ? String(appUserToken) : null;
140
+ return this;
141
+ }
142
+
143
+ /**
144
+ * Set a session-level default model for one generation kind. Wins over the
145
+ * server-fetched config default, but a per-call `model` still wins over
146
+ * this. Pass `null` to clear the override and fall back to config.
147
+ * @param {'chat'|'image'|'embed'|'video'|'audio'|'sfx'} kind
148
+ * @param {string|null} model
149
+ */
150
+ setModel(kind, model) {
151
+ this._userDefaults[kind] = model || null;
152
+ return this;
153
+ }
154
+
155
+ /**
156
+ * Set (or clear) the admin bearer token. This is the generated app's own
157
+ * logged-in admin JWT (the same bearer the app's `vibex` SDK reads from
158
+ * localStorage['access_token']). Required for every `admin.*` call.
159
+ * @param {string|null} token
160
+ */
161
+ setAdminToken(token) {
162
+ this._adminToken = token || null;
109
163
  return this;
110
164
  }
111
165
 
@@ -679,15 +733,32 @@ export class AIFlowClient {
679
733
  // ────────────────────────────────────────────────────────────────────────
680
734
 
681
735
  /**
682
- * Auth/identity headers attached to every gateway call: the public app id
683
- * and (when set) the current end-user id that scopes the knowledge base.
736
+ * Auth/identity headers attached to every gateway call: the public app id,
737
+ * the current end-user's VERIFIED access token (`x-app-user-token`, the
738
+ * secure identity the gateway trusts), and the end-user id (`x-end-user-id`,
739
+ * legacy/diagnostic only — the gateway ignores it unless an operator opts
740
+ * into the unverified mode).
684
741
  */
685
742
  _authHeaders() {
686
743
  const h = { 'x-app-id': this.appId };
744
+ if (this.appUserToken) h['x-app-user-token'] = this.appUserToken;
687
745
  if (this.endUserId) h['x-end-user-id'] = this.endUserId;
688
746
  return h;
689
747
  }
690
748
 
749
+ /**
750
+ * Auth headers for the admin (`/admin/*`) routes: the standard app/end-user
751
+ * headers PLUS the admin bearer token (when set via `setAdminToken()`).
752
+ */
753
+ _adminHeaders() {
754
+ return {
755
+ ...this._authHeaders(),
756
+ ...(this._adminToken
757
+ ? { Authorization: 'Bearer ' + this._adminToken }
758
+ : {}),
759
+ };
760
+ }
761
+
691
762
  /** POST a JSON body to the gateway. */
692
763
  async _request(path, body, { signal, stream = false, timeout } = {}) {
693
764
  const headers = {
@@ -702,6 +773,29 @@ export class AIFlowClient {
702
773
  );
703
774
  }
704
775
 
776
+ /**
777
+ * Request an admin (`/admin/*`) route. Mirrors {@link _request} but attaches
778
+ * the admin bearer via {@link _adminHeaders}. Supports GET (no body) and
779
+ * PATCH/POST (JSON body). Reuses the shared timeout/retry + error mapping.
780
+ */
781
+ async _adminRequest(path, body, { method = 'GET', signal, timeout } = {}) {
782
+ const isBodyMethod = method !== 'GET' && method !== 'HEAD';
783
+ const headers = {
784
+ ...this._adminHeaders(),
785
+ Accept: 'application/json',
786
+ };
787
+ if (isBodyMethod) headers['Content-Type'] = 'application/json';
788
+ return this._fetchWithRetry(
789
+ `${this.baseUrl}${path}`,
790
+ {
791
+ method,
792
+ headers,
793
+ ...(isBodyMethod ? { body: JSON.stringify(body ?? {}) } : {}),
794
+ },
795
+ { signal, timeout },
796
+ );
797
+ }
798
+
705
799
  /** GET from the gateway (used by short status polls). */
706
800
  async _get(path, { signal, timeout } = {}) {
707
801
  return this._fetchWithRetry(
@@ -789,9 +883,11 @@ export class AIFlowClient {
789
883
  if (!file) {
790
884
  throw new AIFlowError('a File/Blob is required to ingest knowledge');
791
885
  }
792
- if (!this.endUserId) {
886
+ if (!this.appUserToken) {
793
887
  throw new AIFlowError(
794
- 'setEndUser(id) must be called before uploading knowledge',
888
+ 'setEndUser(id, appUserToken) must be called with the logged-in ' +
889
+ "user's access token before uploading knowledge — the gateway " +
890
+ 'verifies it to scope uploads to that user.',
795
891
  );
796
892
  }
797
893
  if (typeof FormData === 'undefined') {
@@ -837,6 +933,42 @@ export class AIFlowClient {
837
933
  );
838
934
  return await res.json();
839
935
  }
936
+
937
+ // ────────────────────────────────────────────────────────────────────────
938
+ // Admin (module config) internals
939
+ // ────────────────────────────────────────────────────────────────────────
940
+
941
+ async _adminListModules({ signal } = {}) {
942
+ const res = await this._adminRequest('/admin/modules', undefined, {
943
+ method: 'GET',
944
+ signal,
945
+ });
946
+ return await res.json();
947
+ }
948
+
949
+ async _adminUpdateConfig({
950
+ moduleId,
951
+ systemPrompt,
952
+ defaults,
953
+ defaultModel,
954
+ signal,
955
+ } = {}) {
956
+ // `defaultModel` is sugar for setting the chat default; fold it into
957
+ // `defaults.chat` without clobbering any explicit `defaults` passed.
958
+ let resolvedDefaults = defaults;
959
+ if (defaultModel != null) {
960
+ resolvedDefaults = { ...(defaults || {}), chat: defaultModel };
961
+ }
962
+ const body = {};
963
+ if (moduleId != null) body.moduleId = moduleId;
964
+ if (systemPrompt !== undefined) body.systemPrompt = systemPrompt;
965
+ if (resolvedDefaults !== undefined) body.defaults = resolvedDefaults;
966
+ const res = await this._adminRequest('/admin/config', body, {
967
+ method: 'PATCH',
968
+ signal,
969
+ });
970
+ return await res.json();
971
+ }
840
972
  }
841
973
 
842
974
  // ────────────────────────────────────────────────────────────────────────────