@retrivora-ai/rag-engine 2.3.5 → 2.3.7

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.
Files changed (41) hide show
  1. package/dist/{BatchProcessor-tVzb9CdE.d.mts → BatchProcessor-BhLczWj5.d.mts} +179 -3
  2. package/dist/{BatchProcessor-CQDtlggz.d.ts → BatchProcessor-C42_RVWO.d.ts} +179 -3
  3. package/dist/{ILLMProvider-CcJ5N6XD.d.mts → ILLMProvider-B8TAVx3j.d.mts} +63 -1
  4. package/dist/{ILLMProvider-CcJ5N6XD.d.ts → ILLMProvider-B8TAVx3j.d.ts} +63 -1
  5. package/dist/handlers/index.d.mts +2 -2
  6. package/dist/handlers/index.d.ts +2 -2
  7. package/dist/handlers/index.js +493 -217
  8. package/dist/handlers/index.mjs +493 -217
  9. package/dist/{index-BwmyPJHp.d.ts → index-ejOWsaqb.d.ts} +1 -1
  10. package/dist/{index-CL-zF6bD.d.mts → index-xxQOFx-u.d.mts} +1 -1
  11. package/dist/index.css +9 -0
  12. package/dist/index.d.mts +19 -5
  13. package/dist/index.d.ts +19 -5
  14. package/dist/index.js +643 -207
  15. package/dist/index.mjs +683 -252
  16. package/dist/server.d.mts +253 -7
  17. package/dist/server.d.ts +253 -7
  18. package/dist/server.js +1145 -230
  19. package/dist/server.mjs +1131 -230
  20. package/package.json +1 -1
  21. package/src/LicensedRetrivora.ts +273 -0
  22. package/src/components/ChatWidget.tsx +44 -19
  23. package/src/components/ChatWindow.tsx +30 -14
  24. package/src/components/ConfigProvider.tsx +86 -6
  25. package/src/components/DocumentUpload.tsx +8 -2
  26. package/src/config/LicenseConfigResolver.ts +296 -0
  27. package/src/config/RagConfig.ts +4 -0
  28. package/src/config/serverConfig.ts +74 -14
  29. package/src/core/ConfigFetcher.ts +10 -1
  30. package/src/core/ConfigResolver.ts +1 -0
  31. package/src/core/LicenseValidator.ts +21 -12
  32. package/src/core/LicenseVerifier.ts +7 -11
  33. package/src/core/ProjectSettings.ts +247 -0
  34. package/src/handlers/index.ts +65 -5
  35. package/src/hooks/useProjectSettings.ts +105 -0
  36. package/src/index.css +9 -0
  37. package/src/index.ts +37 -0
  38. package/src/llm/providers/UniversalLLMAdapter.ts +67 -12
  39. package/src/server.ts +46 -2
  40. package/src/telemetry/TelemetryService.ts +330 -0
  41. package/src/types/props.ts +14 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@retrivora-ai/rag-engine",
3
- "version": "2.3.5",
3
+ "version": "2.3.7",
4
4
  "description": "Retrivora AI is a plug-and-play AI engine for RAG chat experiences — generic vector DB + LLM provider, embeddable or standalone.",
5
5
  "author": "Abhinav Alkuchi",
6
6
  "license": "UNLICENSED",
@@ -0,0 +1,273 @@
1
+ /**
2
+ * LicensedRetrivora — End-user facing SDK that only requires:
3
+ * - License Key (JWT from Retrivora)
4
+ * - Project ID (workspace identifier)
5
+ *
6
+ * Everything else (models, vector DB, embeddings) is resolved from
7
+ * the Retrivora admin dashboard based on tier.
8
+ *
9
+ * NOTE: This is a SERVER-ONLY module. Import from '@retrivora-ai/rag-engine/server'
10
+ * Do NOT import in client components.
11
+ */
12
+
13
+ import { LicenseConfigResolver } from './config/LicenseConfigResolver';
14
+ import { Pipeline } from './core/Pipeline';
15
+ import { RagConfig, VectorDBConfig, LLMConfig, EmbeddingConfig } from './config/RagConfig';
16
+ import {
17
+ initializeTelemetryService,
18
+ getTelemetryService,
19
+ shutdownTelemetryService,
20
+ EventType,
21
+ } from './telemetry/TelemetryService';
22
+ import { IngestDocument, ChatResponse } from './types';
23
+
24
+ export interface LicensedRetrivoraOptions {
25
+ licenseKey: string;
26
+ projectId: string;
27
+ userTelemetryUrl?: string; // Optional: user's telemetry endpoint
28
+ enableTelemetry?: boolean; // Default: true
29
+ }
30
+
31
+ /**
32
+ * End-user facing SDK for Retrivora RAG engine
33
+ */
34
+ export class LicensedRetrivora {
35
+ private licenseKey: string;
36
+ private projectId: string;
37
+ private pipeline?: Pipeline;
38
+ private ragConfig?: RagConfig;
39
+ private initialized: boolean = false;
40
+
41
+ constructor(options: LicensedRetrivoraOptions) {
42
+ this.licenseKey = options.licenseKey;
43
+ this.projectId = options.projectId;
44
+
45
+ // Initialize telemetry if enabled
46
+ if (options.enableTelemetry !== false) {
47
+ initializeTelemetryService(this.projectId, this.licenseKey, options.userTelemetryUrl);
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Initialize the SDK by validating license and fetching config
53
+ */
54
+ private generateId(): string {
55
+ return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
56
+ }
57
+
58
+ /**
59
+ * Initialize the SDK by validating license and fetching config
60
+ */
61
+ async initialize(): Promise<void> {
62
+ if (this.initialized) {
63
+ console.log('[LicensedRetrivora] Already initialized');
64
+ return;
65
+ }
66
+
67
+ console.log('[LicensedRetrivora] Initializing with license key...');
68
+ const operationId = this.generateId();
69
+
70
+ try {
71
+ // Resolve configuration from license tier
72
+ const { llmConfig, embeddingConfig, vectorDbConfig, tierConfig } =
73
+ await LicenseConfigResolver.resolveFromLicense(this.licenseKey, this.projectId);
74
+
75
+ // Log successful configuration load
76
+ const telemetry = getTelemetryService();
77
+ if (telemetry) {
78
+ telemetry.recordEvent({
79
+ eventType: EventType.CONFIGURATION_LOADED,
80
+ operationId,
81
+ metadata: {
82
+ tier: tierConfig.tier,
83
+ llmModel: tierConfig.llmModel,
84
+ embeddingModel: tierConfig.embeddingModel,
85
+ vectorDb: tierConfig.vectorDb.provider,
86
+ },
87
+ });
88
+ }
89
+
90
+ // Build RAG config
91
+ this.ragConfig = {
92
+ projectId: this.projectId,
93
+ licenseKey: this.licenseKey,
94
+ llm: llmConfig,
95
+ embedding: embeddingConfig,
96
+ vectorDb: vectorDbConfig,
97
+ rag: {
98
+ topK: tierConfig.topK,
99
+ chunkSize: tierConfig.chunkSize,
100
+ chunkOverlap: tierConfig.chunkOverlap,
101
+ scoreThreshold: 0,
102
+ },
103
+ telemetry: {
104
+ enabled: true,
105
+ url: 'https://www.retrivora.com/api/telemetry',
106
+ },
107
+ };
108
+
109
+ // Initialize pipeline
110
+ this.pipeline = new Pipeline(this.ragConfig);
111
+ await this.pipeline.initialize();
112
+
113
+ this.initialized = true;
114
+ console.log(`[LicensedRetrivora] Initialized successfully for tier: ${tierConfig.tier}`);
115
+ } catch (error) {
116
+ const telemetry = getTelemetryService();
117
+ if (telemetry && error instanceof Error) {
118
+ telemetry.recordError(error, { operationId });
119
+ await telemetry.flush();
120
+ }
121
+ throw error;
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Ingest documents (upload files to vector database)
127
+ * Returns success/failure status to end-user
128
+ */
129
+ async ingest(documents: IngestDocument[]): Promise<{ success: boolean; message: string; documentIds?: string[] }> {
130
+ if (!this.initialized || !this.pipeline) {
131
+ throw new Error('[LicensedRetrivora] SDK not initialized. Call initialize() first.');
132
+ }
133
+
134
+ const operationId = this.generateId();
135
+ const telemetry = getTelemetryService();
136
+ const startTime = Date.now();
137
+
138
+ try {
139
+ console.log(`[LicensedRetrivora] Starting ingestion of ${documents.length} document(s)`);
140
+
141
+ // Ingest documents
142
+ const results = await this.pipeline.ingest(documents);
143
+
144
+ const durationMs = Date.now() - startTime;
145
+
146
+ // Record successful ingestion
147
+ if (telemetry) {
148
+ for (const result of results) {
149
+ telemetry.recordDocumentIngested({
150
+ documentId: String(result.docId),
151
+ documentName: String(result.docId),
152
+ documentSize: 0, // TODO: track actual size
153
+ chunksGenerated: result.chunksIngested,
154
+ durationMs,
155
+ });
156
+ }
157
+ }
158
+
159
+ const successCount = results.length;
160
+ return {
161
+ success: successCount > 0,
162
+ message: `Successfully ingested ${successCount} document(s). Data is now available for search.`,
163
+ documentIds: results.map(r => String(r.docId)),
164
+ };
165
+ } catch (error) {
166
+ const durationMs = Date.now() - startTime;
167
+
168
+ if (telemetry && error instanceof Error) {
169
+ telemetry.recordError(error, { operationId, durationMs });
170
+ await telemetry.flush();
171
+ }
172
+
173
+ console.error('[LicensedRetrivora] Ingestion failed:', error);
174
+ throw error;
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Execute a user query and get response
180
+ * Returns only the response text and sources (abstracted from underlying models)
181
+ */
182
+ async query(queryText: string, options?: { topK?: number }): Promise<ChatResponse> {
183
+ if (!this.initialized || !this.pipeline) {
184
+ throw new Error('[LicensedRetrivora] SDK not initialized. Call initialize() first.');
185
+ }
186
+
187
+ const operationId = this.generateId();
188
+ const telemetry = getTelemetryService();
189
+ const startTime = Date.now();
190
+
191
+ try {
192
+ console.log(`[LicensedRetrivora] Executing query: "${queryText.substring(0, 100)}..."`);
193
+
194
+ // Execute query
195
+ const response = await this.pipeline.runNormalQuery(queryText);
196
+
197
+ const durationMs = Date.now() - startTime;
198
+
199
+ // Record query execution
200
+ if (telemetry) {
201
+ telemetry.recordQueryExecuted({
202
+ queryText,
203
+ resultCount: response.sources?.length || 0,
204
+ durationMs,
205
+ operationId,
206
+ });
207
+ }
208
+
209
+ // Return abstracted response (hide implementation details)
210
+ return {
211
+ reply: response.reply,
212
+ sources: response.sources,
213
+ };
214
+ } catch (error) {
215
+ const durationMs = Date.now() - startTime;
216
+
217
+ if (telemetry && error instanceof Error) {
218
+ telemetry.recordError(error, { operationId, durationMs });
219
+ await telemetry.flush();
220
+ }
221
+
222
+ console.error('[LicensedRetrivora] Query failed:', error);
223
+ throw error;
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Get license tier information (for UI display if needed)
229
+ */
230
+ async getTierInfo(): Promise<{ tier: string; model: string; embeddingModel: string }> {
231
+ if (!this.ragConfig) {
232
+ throw new Error('[LicensedRetrivora] SDK not initialized.');
233
+ }
234
+
235
+ return {
236
+ tier: 'Standard', // TODO: fetch from tier config
237
+ model: this.ragConfig.llm.model,
238
+ embeddingModel: this.ragConfig.embedding.model,
239
+ };
240
+ }
241
+
242
+ /**
243
+ * Cleanup and shutdown
244
+ */
245
+ async shutdown(): Promise<void> {
246
+ await shutdownTelemetryService();
247
+ this.initialized = false;
248
+ console.log('[LicensedRetrivora] Shutdown complete');
249
+ }
250
+
251
+ /**
252
+ * Check if SDK is initialized
253
+ */
254
+ isInitialized(): boolean {
255
+ return this.initialized;
256
+ }
257
+
258
+ /**
259
+ * Get current RAG configuration (for debugging)
260
+ */
261
+ getConfig(): RagConfig | undefined {
262
+ return this.ragConfig;
263
+ }
264
+ }
265
+
266
+ /**
267
+ * Convenience function to create and initialize SDK in one call
268
+ */
269
+ export async function createRetrivora(options: LicensedRetrivoraOptions): Promise<LicensedRetrivora> {
270
+ const retrivora = new LicensedRetrivora(options);
271
+ await retrivora.initialize();
272
+ return retrivora;
273
+ }
@@ -67,8 +67,19 @@ const GEMINI_STYLES = `
67
67
  *
68
68
  * @param props - Widget position, callbacks, API overrides, and license overrides
69
69
  */
70
- export function ChatWidget({ position = 'bottom-right', onAddToCart, apiUrl, retrivoraApiBase, licenseKey: licenseKeyProp, headers }: ChatWidgetProps) {
71
- const { ui, projectId } = useConfig();
70
+ export function ChatWidget({ position, onAddToCart, apiUrl, retrivoraApiBase, licenseKey: licenseKeyProp, headers }: ChatWidgetProps) {
71
+ const {
72
+ ui,
73
+ projectId,
74
+ projectSettings,
75
+ licenseKey: contextLicenseKey,
76
+ headers: contextHeaders,
77
+ retrivoraApiBase: contextApiBase,
78
+ } = useConfig();
79
+ const effectivePosition = position || projectSettings?.widget.position || 'bottom-right';
80
+ const effectiveHeaders = headers || contextHeaders;
81
+ const effectiveLicenseKey = licenseKeyProp || contextLicenseKey;
82
+ const effectiveApiBase = retrivoraApiBase || contextApiBase;
72
83
  const [isOpen, setIsOpen] = useState(false);
73
84
  const [hasUnread, setHasUnread] = useState(false);
74
85
  const [dimensions, setDimensions] = useState(DEFAULT_DIMENSIONS);
@@ -80,13 +91,21 @@ export function ChatWidget({ position = 'bottom-right', onAddToCart, apiUrl, ret
80
91
  const [hasMountValidationFailed, setHasMountValidationFailed] = useState(false);
81
92
 
82
93
  const positionClass =
83
- position === 'bottom-left'
94
+ effectivePosition === 'bottom-left'
84
95
  ? 'bottom-6 left-6'
96
+ : effectivePosition === 'top-left'
97
+ ? 'top-6 left-6'
98
+ : effectivePosition === 'top-right'
99
+ ? 'top-6 right-6'
85
100
  : 'bottom-6 right-6';
86
101
 
87
102
  const windowPositionClass =
88
- position === 'bottom-left'
103
+ effectivePosition === 'bottom-left'
89
104
  ? 'bottom-20 left-6'
105
+ : effectivePosition === 'top-left'
106
+ ? 'top-20 left-6'
107
+ : effectivePosition === 'top-right'
108
+ ? 'top-20 right-6'
90
109
  : 'bottom-20 right-6';
91
110
 
92
111
  /**
@@ -95,16 +114,16 @@ export function ChatWidget({ position = 'bottom-right', onAddToCart, apiUrl, ret
95
114
  */
96
115
  const resolveLicenseKey = useCallback((): string => {
97
116
  const getHeader = (name: string) => {
98
- if (!headers) return undefined;
117
+ if (!effectiveHeaders) return undefined;
99
118
  const target = name.toLowerCase();
100
- for (const [k, v] of Object.entries(headers)) {
119
+ for (const [k, v] of Object.entries(effectiveHeaders)) {
101
120
  if (k.toLowerCase() === target) return v;
102
121
  }
103
122
  return undefined;
104
123
  };
105
124
 
106
125
  return (
107
- licenseKeyProp ||
126
+ effectiveLicenseKey ||
108
127
  getHeader('x-license-key') ||
109
128
  getHeader('authorization')?.replace(/^Bearer\s+/i, '') ||
110
129
  (typeof process !== 'undefined'
@@ -112,7 +131,7 @@ export function ChatWidget({ position = 'bottom-right', onAddToCart, apiUrl, ret
112
131
  : '') ||
113
132
  ''
114
133
  );
115
- }, [licenseKeyProp, headers]);
134
+ }, [effectiveLicenseKey, effectiveHeaders]);
116
135
 
117
136
  /**
118
137
  * Proactively validate the license on mount.
@@ -127,8 +146,8 @@ export function ChatWidget({ position = 'bottom-right', onAddToCart, apiUrl, ret
127
146
  await LicenseValidator.getInstance().validate({
128
147
  licenseKey: resolvedLicenseKey,
129
148
  projectId,
130
- retrivoraApiBase,
131
- headers,
149
+ retrivoraApiBase: effectiveApiBase,
150
+ headers: effectiveHeaders,
132
151
  });
133
152
  if (isMounted) {
134
153
  setHasMountValidationFailed(false);
@@ -143,7 +162,7 @@ export function ChatWidget({ position = 'bottom-right', onAddToCart, apiUrl, ret
143
162
  }
144
163
  validateOnMount();
145
164
  return () => { isMounted = false; };
146
- }, [resolveLicenseKey, projectId, retrivoraApiBase, headers]);
165
+ }, [resolveLicenseKey, projectId, effectiveApiBase, effectiveHeaders]);
147
166
 
148
167
  /**
149
168
  * Validates the license key and opens the chat window.
@@ -162,8 +181,8 @@ export function ChatWidget({ position = 'bottom-right', onAddToCart, apiUrl, ret
162
181
  await LicenseValidator.getInstance().validate({
163
182
  licenseKey: resolvedLicenseKey,
164
183
  projectId,
165
- retrivoraApiBase,
166
- headers,
184
+ retrivoraApiBase: effectiveApiBase,
185
+ headers: effectiveHeaders,
167
186
  });
168
187
 
169
188
  setWidgetError(null);
@@ -177,7 +196,7 @@ export function ChatWidget({ position = 'bottom-right', onAddToCart, apiUrl, ret
177
196
  } finally {
178
197
  setIsValidating(false);
179
198
  }
180
- }, [hasMountValidationFailed, widgetError, resolveLicenseKey, projectId, retrivoraApiBase, headers]);
199
+ }, [hasMountValidationFailed, widgetError, resolveLicenseKey, projectId, effectiveApiBase, effectiveHeaders]);
181
200
 
182
201
  /** True when the license has been proven invalid and the widget must be locked. */
183
202
  const isWidgetLocked = hasMountValidationFailed || isValidating;
@@ -259,14 +278,14 @@ export function ChatWidget({ position = 'bottom-right', onAddToCart, apiUrl, ret
259
278
  isMaximized={isMaximized}
260
279
  onAddToCart={onAddToCart}
261
280
  apiUrl={apiUrl}
262
- retrivoraApiBase={retrivoraApiBase}
263
- licenseKey={licenseKeyProp}
264
- headers={headers}
281
+ retrivoraApiBase={effectiveApiBase}
282
+ licenseKey={effectiveLicenseKey}
283
+ headers={effectiveHeaders}
265
284
  />
266
285
  {/* Pointer (Tail) */}
267
286
  <div
268
287
  className={`absolute -bottom-1.5 w-4 h-4 rotate-45 border-r border-b border-slate-200 dark:border-white/10 z-0 ${ui.visualStyle === 'solid' ? 'bg-white dark:bg-[#0f0f1a]' : 'bg-white/90 dark:bg-[#0f0f1a]/90 backdrop-blur-xl'
269
- } ${position === 'bottom-left' ? 'left-5' : 'right-5'}`}
288
+ } ${effectivePosition === 'bottom-left' || effectivePosition === 'top-left' ? 'left-5' : 'right-5'}`}
270
289
  />
271
290
  </div>
272
291
 
@@ -274,7 +293,13 @@ export function ChatWidget({ position = 'bottom-right', onAddToCart, apiUrl, ret
274
293
  {widgetError && !isOpen && (
275
294
  <div
276
295
  className={`fixed z-[9999] max-w-sm p-4 rounded-2xl shadow-2xl border border-rose-200 dark:border-rose-900/60 bg-white/95 dark:bg-[#0f0f1a]/95 backdrop-blur-xl transition-all duration-300 animate-in fade-in slide-in-from-bottom-3 ${
277
- position === 'bottom-left' ? 'bottom-24 left-6' : 'bottom-24 right-6'
296
+ effectivePosition === 'bottom-left'
297
+ ? 'bottom-24 left-6'
298
+ : effectivePosition === 'top-left'
299
+ ? 'top-24 left-6'
300
+ : effectivePosition === 'top-right'
301
+ ? 'top-24 right-6'
302
+ : 'bottom-24 right-6'
278
303
  }`}
279
304
  >
280
305
  <div className="flex items-start gap-3">
@@ -106,7 +106,17 @@ export function ChatWindow({
106
106
  licenseKey: licenseKeyProp,
107
107
  headers
108
108
  }: ChatWindowProps) {
109
- const { ui, projectId } = useConfig();
109
+ const {
110
+ ui,
111
+ projectId,
112
+ licenseKey: contextLicenseKey,
113
+ headers: contextHeaders,
114
+ retrivoraApiBase: contextApiBase,
115
+ projectSettings,
116
+ } = useConfig();
117
+ const effectiveLicenseKey = licenseKeyProp || contextLicenseKey;
118
+ const effectiveHeaders = headers || contextHeaders;
119
+ const effectiveApiBase = retrivoraApiBase || contextApiBase;
110
120
  const [input, setInput] = useState('');
111
121
  const [mounted, setMounted] = useState(false);
112
122
  const [viewportSize, setViewportSize] = useState<'compact' | 'medium' | 'large'>('large');
@@ -116,9 +126,10 @@ export function ChatWindow({
116
126
  const { messages, send, clear, isLoading, error, stop, submitFeedback } = useRagChat(projectId, {
117
127
  namespace: projectId,
118
128
  apiUrl,
119
- retrivoraApiBase,
120
- licenseKey: licenseKeyProp,
121
- headers,
129
+ retrivoraApiBase: effectiveApiBase,
130
+ licenseKey: effectiveLicenseKey,
131
+ headers: effectiveHeaders,
132
+ persist: projectSettings?.widget.persistConversations,
122
133
  });
123
134
 
124
135
  const [suggestions, setSuggestions] = useState<string[]>([]);
@@ -142,16 +153,16 @@ export function ChatWindow({
142
153
  async function validateSessionLicense() {
143
154
  try {
144
155
  const getHeader = (name: string) => {
145
- if (!headers) return undefined;
156
+ if (!effectiveHeaders) return undefined;
146
157
  const target = name.toLowerCase();
147
- for (const [k, v] of Object.entries(headers)) {
158
+ for (const [k, v] of Object.entries(effectiveHeaders)) {
148
159
  if (k.toLowerCase() === target) return v;
149
160
  }
150
161
  return undefined;
151
162
  };
152
163
 
153
164
  const resolvedLicenseKey =
154
- licenseKeyProp ||
165
+ effectiveLicenseKey ||
155
166
  getHeader('x-license-key') ||
156
167
  getHeader('authorization')?.replace(/^Bearer\s+/i, '') ||
157
168
  (typeof process !== 'undefined'
@@ -162,8 +173,8 @@ export function ChatWindow({
162
173
  await LicenseValidator.getInstance().validate({
163
174
  licenseKey: resolvedLicenseKey,
164
175
  projectId,
165
- retrivoraApiBase,
166
- headers,
176
+ retrivoraApiBase: effectiveApiBase,
177
+ headers: effectiveHeaders,
167
178
  });
168
179
 
169
180
  if (isMounted) {
@@ -183,7 +194,7 @@ export function ChatWindow({
183
194
 
184
195
  validateSessionLicense();
185
196
  return () => { isMounted = false; };
186
- }, [retrivoraApiBase, headers, projectId]);
197
+ }, [effectiveApiBase, effectiveHeaders, effectiveLicenseKey, projectId]);
187
198
 
188
199
  // Initialize SpeechRecognition
189
200
  useEffect(() => {
@@ -313,18 +324,23 @@ export function ChatWindow({
313
324
  const timer = setTimeout(async () => {
314
325
  setIsSuggesting(true);
315
326
  try {
316
- const base = retrivoraApiBase || '/api/retrivora';
327
+ const base = effectiveApiBase || '/api/retrivora';
317
328
  const primaryUrl = `${base}/suggestions`;
329
+ const suggestionHeaders = {
330
+ 'Content-Type': 'application/json',
331
+ ...(effectiveLicenseKey ? { 'x-license-key': effectiveLicenseKey } : {}),
332
+ ...(effectiveHeaders || {}),
333
+ };
318
334
  let response = await fetch(primaryUrl, {
319
335
  method: 'POST',
320
- headers: { 'Content-Type': 'application/json', ...(headers || {}) },
336
+ headers: suggestionHeaders,
321
337
  body: JSON.stringify({ query: input, namespace: projectId }),
322
338
  });
323
339
 
324
340
  if (!response.ok && response.status === 404) {
325
341
  response = await fetch('/api/suggestions', {
326
342
  method: 'POST',
327
- headers: { 'Content-Type': 'application/json', ...(headers || {}) },
343
+ headers: suggestionHeaders,
328
344
  body: JSON.stringify({ query: input, namespace: projectId }),
329
345
  });
330
346
  }
@@ -341,7 +357,7 @@ export function ChatWindow({
341
357
  }, 800); // 800ms debounce to save costs/latency
342
358
 
343
359
  return () => clearTimeout(timer);
344
- }, [input, projectId, retrivoraApiBase, headers]);
360
+ }, [input, projectId, effectiveApiBase, effectiveHeaders, effectiveLicenseKey]);
345
361
 
346
362
  return (
347
363
  <div
@@ -7,23 +7,103 @@
7
7
  * Only the UI-safe portions of RagConfig are exposed to the client.
8
8
  */
9
9
 
10
- import React, { createContext, useContext } from 'react';
10
+ import React, { createContext, useContext, useEffect, useMemo, useState } from 'react';
11
11
  import { UIConfig } from '../config/RagConfig';
12
12
  import { mergeDefined } from '../utils/templateUtils';
13
13
  import { ClientConfig, ConfigProviderProps } from '../types';
14
14
  import { DEFAULT_CONFIG } from '../config/uiConstants';
15
+ import { ConfigFetcher } from '../core/ConfigFetcher';
16
+ import { normalizeProjectSettings, projectSettingsToUiConfig } from '../core/ProjectSettings';
15
17
 
16
18
  const ConfigContext = createContext<ClientConfig>(DEFAULT_CONFIG);
17
19
 
20
+ function resolveHeader(headers: Record<string, string> | undefined, name: string): string | undefined {
21
+ if (!headers) return undefined;
22
+ const target = name.toLowerCase();
23
+ for (const [key, value] of Object.entries(headers)) {
24
+ if (key.toLowerCase() === target) return value;
25
+ }
26
+ return undefined;
27
+ }
28
+
18
29
  export function ConfigProvider({
19
30
  config,
20
31
  children,
21
32
  }: ConfigProviderProps) {
22
- const merged: ClientConfig = {
23
- projectId: config?.projectId || DEFAULT_CONFIG.projectId,
24
- ui: mergeDefined(DEFAULT_CONFIG.ui, config?.ui) as Required<UIConfig>,
25
- embedding: config?.embedding,
26
- };
33
+ const projectId = config?.projectId || DEFAULT_CONFIG.projectId;
34
+ const projectSettingsInput = config?.projectSettings;
35
+ const autoLoadProjectSettings = config?.autoLoadProjectSettings;
36
+ const licenseKeyInput = config?.licenseKey;
37
+ const headersInput = config?.headers;
38
+ const retrivoraApiBaseInput = config?.retrivoraApiBase;
39
+ const embeddingInput = config?.embedding;
40
+ const uiInput = config?.ui;
41
+ const explicitSettings = useMemo(
42
+ () => projectSettingsInput
43
+ ? normalizeProjectSettings(projectId, projectSettingsInput)
44
+ : undefined,
45
+ [projectSettingsInput, projectId]
46
+ );
47
+ const [remoteSettings, setRemoteSettings] = useState(explicitSettings);
48
+ const [isLoading, setIsLoading] = useState(false);
49
+
50
+ useEffect(() => {
51
+ let cancelled = false;
52
+ const shouldLoad =
53
+ autoLoadProjectSettings !== false &&
54
+ !explicitSettings &&
55
+ Boolean(licenseKeyInput || resolveHeader(headersInput, 'x-license-key') || resolveHeader(headersInput, 'authorization'));
56
+
57
+ if (!shouldLoad) {
58
+ setRemoteSettings(explicitSettings);
59
+ setIsLoading(false);
60
+ return;
61
+ }
62
+
63
+ const licenseKey =
64
+ licenseKeyInput ||
65
+ resolveHeader(headersInput, 'x-license-key') ||
66
+ resolveHeader(headersInput, 'authorization')?.replace(/^Bearer\s+/i, '') ||
67
+ '';
68
+
69
+ async function loadProjectSettings() {
70
+ setIsLoading(true);
71
+ try {
72
+ const remoteConfig = await ConfigFetcher.fetchRemoteConfig(projectId, licenseKey);
73
+ if (!cancelled) {
74
+ setRemoteSettings(remoteConfig?.projectSettings || explicitSettings);
75
+ }
76
+ } catch {
77
+ if (!cancelled) setRemoteSettings(explicitSettings);
78
+ } finally {
79
+ if (!cancelled) setIsLoading(false);
80
+ }
81
+ }
82
+
83
+ loadProjectSettings();
84
+
85
+ return () => {
86
+ cancelled = true;
87
+ };
88
+ }, [autoLoadProjectSettings, headersInput, licenseKeyInput, explicitSettings, projectId]);
89
+
90
+ const merged: ClientConfig = useMemo(() => {
91
+ const settingsUi = remoteSettings ? projectSettingsToUiConfig(remoteSettings) : undefined;
92
+ return {
93
+ projectId,
94
+ ui: mergeDefined(
95
+ DEFAULT_CONFIG.ui,
96
+ mergeDefined(settingsUi || {}, uiInput)
97
+ ) as Required<UIConfig>,
98
+ embedding: embeddingInput,
99
+ licenseKey: licenseKeyInput,
100
+ headers: headersInput,
101
+ retrivoraApiBase: retrivoraApiBaseInput,
102
+ projectSettings: remoteSettings,
103
+ autoLoadProjectSettings,
104
+ isProjectSettingsLoading: isLoading,
105
+ };
106
+ }, [autoLoadProjectSettings, embeddingInput, headersInput, licenseKeyInput, retrivoraApiBaseInput, uiInput, isLoading, projectId, remoteSettings]);
27
107
 
28
108
  return <ConfigContext.Provider value={merged}>{children}</ConfigContext.Provider>;
29
109
  }
@@ -12,7 +12,7 @@ interface FileState {
12
12
  }
13
13
 
14
14
  export function DocumentUpload({ namespace, uploadUrl, retrivoraApiBase, onUploadComplete, className = '' }: DocumentUploadProps) {
15
- const { ui, embedding, projectId } = useConfig();
15
+ const { ui, embedding, projectId, licenseKey, headers: configHeaders, retrivoraApiBase: configuredApiBase } = useConfig();
16
16
  const [fileStates, setFileStates] = useState<FileState[]>([]);
17
17
  const [isDragging, setIsDragging] = useState(false);
18
18
  const fileInputRef = useRef<HTMLInputElement>(null);
@@ -93,14 +93,19 @@ export function DocumentUpload({ namespace, uploadUrl, retrivoraApiBase, onUploa
93
93
  if (targetNs) formData.append('namespace', targetNs);
94
94
  formData.append('dimension', dimension.toString());
95
95
 
96
- const apiBase = retrivoraApiBase || '/api/retrivora';
96
+ const apiBase = retrivoraApiBase || configuredApiBase || '/api/retrivora';
97
97
  const primaryUrl = uploadUrl || `${apiBase.replace(/\/$/, '')}/upload`;
98
+ const uploadHeaders = {
99
+ ...(configHeaders || {}),
100
+ ...(licenseKey ? { 'x-license-key': licenseKey } : {}),
101
+ };
98
102
 
99
103
  console.log(`[Retrivora SDK] 📤 Initiating upload request to "${primaryUrl}" (Files: ${idleFiles.length}, Namespace: "${targetNs}", Dimension: ${dimension})`);
100
104
 
101
105
  try {
102
106
  let response = await fetch(primaryUrl, {
103
107
  method: 'POST',
108
+ headers: uploadHeaders,
104
109
  body: formData,
105
110
  });
106
111
 
@@ -108,6 +113,7 @@ export function DocumentUpload({ namespace, uploadUrl, retrivoraApiBase, onUploa
108
113
  console.warn(`[Retrivora SDK] ⚠️ Upload endpoint "${primaryUrl}" returned 404. Retrying fallback to "/api/upload"...`);
109
114
  response = await fetch('/api/upload', {
110
115
  method: 'POST',
116
+ headers: uploadHeaders,
111
117
  body: formData,
112
118
  });
113
119
  }