@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/dist/server.js CHANGED
@@ -154,11 +154,339 @@ var init_BaseVectorProvider = __esm({
154
154
  }
155
155
  });
156
156
 
157
+ // src/core/ProjectSettings.ts
158
+ function createDefaultProjectSettings(projectId) {
159
+ return {
160
+ projectId,
161
+ branding: {
162
+ companyName: "Retrivora AI",
163
+ botName: "Retrivora Assistant",
164
+ welcomeMessage: "Hi, I can help you search your knowledge base.",
165
+ primaryColor: "#6366f1",
166
+ secondaryColor: "#8b5cf6",
167
+ fontFamily: "Inter",
168
+ borderRadius: 14,
169
+ logoUrl: "",
170
+ avatarUrl: "",
171
+ customCss: ""
172
+ },
173
+ ai: {
174
+ defaultModel: "llama-3.1-8b-instant",
175
+ embeddingModel: "text-embedding-3-small",
176
+ systemPrompt: "Answer using the connected knowledge base. Cite sources when available.",
177
+ memoryEnabled: true,
178
+ multiModelEnabled: true,
179
+ citationsEnabled: true,
180
+ fileUploadEnabled: true
181
+ },
182
+ auth: {
183
+ mode: "public",
184
+ allowedOrigins: [],
185
+ requireVerifiedEmail: false,
186
+ sessionTtlMinutes: 1440
187
+ },
188
+ widget: {
189
+ position: "bottom-right",
190
+ theme: "light",
191
+ lazyLoad: true,
192
+ autoReconnect: true,
193
+ persistConversations: true,
194
+ showRetrivoraBranding: false
195
+ },
196
+ telemetry: {
197
+ enabled: true,
198
+ collectBrowser: true,
199
+ collectCountry: false,
200
+ redactPii: true,
201
+ retentionDays: 30
202
+ },
203
+ lifecycleHooks: DEFAULT_LIFECYCLE_HOOKS,
204
+ conversationFeatures: DEFAULT_CONVERSATION_FEATURES
205
+ };
206
+ }
207
+ function cleanString(value, fallback, maxLength = 2e3) {
208
+ if (typeof value !== "string") return fallback;
209
+ return value.trim().slice(0, maxLength);
210
+ }
211
+ function cleanBoolean(value, fallback) {
212
+ return typeof value === "boolean" ? value : fallback;
213
+ }
214
+ function cleanNumber(value, fallback, min, max) {
215
+ const num = typeof value === "number" ? value : Number(value);
216
+ if (!Number.isFinite(num)) return fallback;
217
+ return Math.min(Math.max(Math.round(num), min), max);
218
+ }
219
+ function cleanEnum(value, fallback, allowed) {
220
+ return typeof value === "string" && allowed.includes(value) ? value : fallback;
221
+ }
222
+ function cleanStringList(value, fallback, maxItems = 20) {
223
+ if (!Array.isArray(value)) return fallback;
224
+ const cleaned = value.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean).slice(0, maxItems);
225
+ return cleaned.length > 0 ? Array.from(new Set(cleaned)) : fallback;
226
+ }
227
+ function normalizeProjectSettings(projectId, input) {
228
+ const defaults = createDefaultProjectSettings(projectId);
229
+ const branding = (input == null ? void 0 : input.branding) || {};
230
+ const ai = (input == null ? void 0 : input.ai) || {};
231
+ const auth = (input == null ? void 0 : input.auth) || {};
232
+ const widget = (input == null ? void 0 : input.widget) || {};
233
+ const telemetry = (input == null ? void 0 : input.telemetry) || {};
234
+ return {
235
+ projectId,
236
+ branding: {
237
+ companyName: cleanString(branding.companyName, defaults.branding.companyName, 120),
238
+ botName: cleanString(branding.botName, defaults.branding.botName, 120),
239
+ welcomeMessage: cleanString(branding.welcomeMessage, defaults.branding.welcomeMessage, 500),
240
+ primaryColor: cleanString(branding.primaryColor, defaults.branding.primaryColor, 32),
241
+ secondaryColor: cleanString(branding.secondaryColor, defaults.branding.secondaryColor, 32),
242
+ fontFamily: cleanString(branding.fontFamily, defaults.branding.fontFamily, 80),
243
+ borderRadius: cleanNumber(branding.borderRadius, defaults.branding.borderRadius, 0, 32),
244
+ logoUrl: cleanString(branding.logoUrl, defaults.branding.logoUrl, 500),
245
+ avatarUrl: cleanString(branding.avatarUrl, defaults.branding.avatarUrl, 500),
246
+ customCss: cleanString(branding.customCss, defaults.branding.customCss, 5e3)
247
+ },
248
+ ai: {
249
+ defaultModel: cleanString(ai.defaultModel, defaults.ai.defaultModel, 120),
250
+ embeddingModel: cleanString(ai.embeddingModel, defaults.ai.embeddingModel, 120),
251
+ systemPrompt: cleanString(ai.systemPrompt, defaults.ai.systemPrompt, 5e3),
252
+ memoryEnabled: cleanBoolean(ai.memoryEnabled, defaults.ai.memoryEnabled),
253
+ multiModelEnabled: cleanBoolean(ai.multiModelEnabled, defaults.ai.multiModelEnabled),
254
+ citationsEnabled: cleanBoolean(ai.citationsEnabled, defaults.ai.citationsEnabled),
255
+ fileUploadEnabled: cleanBoolean(ai.fileUploadEnabled, defaults.ai.fileUploadEnabled)
256
+ },
257
+ auth: {
258
+ mode: cleanEnum(auth.mode, defaults.auth.mode, ["public", "anonymous", "jwt", "oauth", "okta", "auth0", "supabase", "firebase", "sso", "custom_token"]),
259
+ allowedOrigins: cleanStringList(auth.allowedOrigins, defaults.auth.allowedOrigins, 25),
260
+ requireVerifiedEmail: cleanBoolean(auth.requireVerifiedEmail, defaults.auth.requireVerifiedEmail),
261
+ sessionTtlMinutes: cleanNumber(auth.sessionTtlMinutes, defaults.auth.sessionTtlMinutes, 15, 43200)
262
+ },
263
+ widget: {
264
+ position: cleanEnum(widget.position, defaults.widget.position, ["bottom-right", "bottom-left", "top-right", "top-left"]),
265
+ theme: cleanEnum(widget.theme, defaults.widget.theme, ["light", "dark", "system"]),
266
+ lazyLoad: cleanBoolean(widget.lazyLoad, defaults.widget.lazyLoad),
267
+ autoReconnect: cleanBoolean(widget.autoReconnect, defaults.widget.autoReconnect),
268
+ persistConversations: cleanBoolean(widget.persistConversations, defaults.widget.persistConversations),
269
+ showRetrivoraBranding: cleanBoolean(widget.showRetrivoraBranding, defaults.widget.showRetrivoraBranding)
270
+ },
271
+ telemetry: {
272
+ enabled: cleanBoolean(telemetry.enabled, defaults.telemetry.enabled),
273
+ collectBrowser: cleanBoolean(telemetry.collectBrowser, defaults.telemetry.collectBrowser),
274
+ collectCountry: cleanBoolean(telemetry.collectCountry, defaults.telemetry.collectCountry),
275
+ redactPii: cleanBoolean(telemetry.redactPii, defaults.telemetry.redactPii),
276
+ retentionDays: cleanNumber(telemetry.retentionDays, defaults.telemetry.retentionDays, 1, 365)
277
+ },
278
+ lifecycleHooks: cleanStringList(input == null ? void 0 : input.lifecycleHooks, defaults.lifecycleHooks, 30),
279
+ conversationFeatures: cleanStringList(input == null ? void 0 : input.conversationFeatures, defaults.conversationFeatures, 30),
280
+ updatedAt: input == null ? void 0 : input.updatedAt
281
+ };
282
+ }
283
+ function projectSettingsToUiConfig(settings) {
284
+ return {
285
+ title: settings.branding.botName,
286
+ subtitle: settings.branding.companyName,
287
+ primaryColor: settings.branding.primaryColor,
288
+ accentColor: settings.branding.secondaryColor,
289
+ logoUrl: settings.branding.logoUrl || settings.branding.avatarUrl,
290
+ welcomeMessage: settings.branding.welcomeMessage,
291
+ poweredBy: settings.widget.showRetrivoraBranding ? "Retrivora AI" : "",
292
+ allowUpload: settings.ai.fileUploadEnabled,
293
+ borderRadius: settings.branding.borderRadius <= 4 ? "sm" : settings.branding.borderRadius <= 8 ? "md" : settings.branding.borderRadius <= 16 ? "xl" : "full"
294
+ };
295
+ }
296
+ var DEFAULT_LIFECYCLE_HOOKS, DEFAULT_CONVERSATION_FEATURES;
297
+ var init_ProjectSettings = __esm({
298
+ "src/core/ProjectSettings.ts"() {
299
+ "use strict";
300
+ DEFAULT_LIFECYCLE_HOOKS = [
301
+ "beforeInitialize",
302
+ "afterInitialize",
303
+ "beforeSend",
304
+ "afterResponse",
305
+ "onMessage",
306
+ "onCitationClick",
307
+ "onFeedback",
308
+ "onError",
309
+ "onReconnect",
310
+ "onFileUpload"
311
+ ];
312
+ DEFAULT_CONVERSATION_FEATURES = [
313
+ "History",
314
+ "Resume",
315
+ "Search",
316
+ "Export",
317
+ "Rename",
318
+ "Delete",
319
+ "Tags",
320
+ "Pinned",
321
+ "Unread",
322
+ "Ratings"
323
+ ];
324
+ }
325
+ });
326
+
327
+ // package.json
328
+ var package_default;
329
+ var init_package = __esm({
330
+ "package.json"() {
331
+ package_default = {
332
+ name: "@retrivora-ai/rag-engine",
333
+ version: "2.3.7",
334
+ description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
335
+ author: "Abhinav Alkuchi",
336
+ license: "UNLICENSED",
337
+ keywords: [
338
+ "rag",
339
+ "retrieval-augmented-generation",
340
+ "chatbot",
341
+ "vector-database",
342
+ "pinecone",
343
+ "pgvector",
344
+ "postgresql",
345
+ "milvus",
346
+ "qdrant",
347
+ "chromadb",
348
+ "redis",
349
+ "weaviate",
350
+ "mongodb",
351
+ "openai",
352
+ "anthropic",
353
+ "ollama",
354
+ "nextjs",
355
+ "react",
356
+ "ai",
357
+ "llm",
358
+ "embeddings"
359
+ ],
360
+ main: "dist/index.js",
361
+ module: "dist/index.mjs",
362
+ types: "dist/index.d.ts",
363
+ exports: {
364
+ ".": {
365
+ types: "./dist/index.d.ts",
366
+ require: "./dist/index.js",
367
+ import: "./dist/index.mjs"
368
+ },
369
+ "./style.css": "./dist/index.css",
370
+ "./index.css": "./dist/index.css",
371
+ "./styles.css": "./dist/index.css",
372
+ "./handlers": {
373
+ types: "./dist/handlers/index.d.ts",
374
+ require: "./dist/handlers/index.js",
375
+ import: "./dist/handlers/index.mjs"
376
+ },
377
+ "./server": {
378
+ types: "./dist/server.d.ts",
379
+ require: "./dist/server.js",
380
+ import: "./dist/server.mjs"
381
+ }
382
+ },
383
+ browser: {
384
+ child_process: false,
385
+ fs: false,
386
+ net: false,
387
+ tls: false,
388
+ crypto: false,
389
+ os: false,
390
+ path: false,
391
+ stream: false,
392
+ http: false,
393
+ https: false,
394
+ zlib: false,
395
+ mongodb: false,
396
+ pg: false,
397
+ "pdf-parse": false,
398
+ mammoth: false
399
+ },
400
+ files: [
401
+ "dist",
402
+ "src",
403
+ ".env.example",
404
+ "README.md",
405
+ "FREE_TIER_ARCHITECTURE.md"
406
+ ],
407
+ scripts: {
408
+ dev: "npx @tailwindcss/cli -i src/tailwind.css -o src/index.css && tsup src/index.ts src/handlers/index.ts src/server.ts --format cjs,esm --watch --tsconfig tsconfig.build.json --external react,react-dom,next,mongodb,pg,openai,@anthropic-ai/sdk,@pinecone-database/pinecone,axios,lucide-react,mammoth,pdf-parse,xlsx,react-markdown,remark-gfm,next-themes,langchain,@langchain/core,@langchain/openai,llamaindex --inject-style",
409
+ build: "npm run build:pkg",
410
+ "build:pkg": "npx @tailwindcss/cli -i src/tailwind.css -o src/index.css && tsup src/index.ts src/handlers/index.ts src/server.ts --format cjs,esm --dts --clean --no-splitting --tsconfig tsconfig.build.json --external react,react-dom,next,mongodb,pg,openai,@anthropic-ai/sdk,@pinecone-database/pinecone,axios,lucide-react,mammoth,pdf-parse,xlsx,react-markdown,remark-gfm,next-themes,langchain,@langchain/core,@langchain/openai,llamaindex --inject-style && npx @tailwindcss/cli -i src/tailwind.css -o dist/index.css",
411
+ lint: "eslint",
412
+ typecheck: "tsc --noEmit -p tsconfig.build.json",
413
+ clean: "rm -rf dist"
414
+ },
415
+ peerDependencies: {
416
+ next: ">=15.0.0",
417
+ react: ">=18.0.0",
418
+ "react-dom": ">=18.0.0"
419
+ },
420
+ peerDependenciesMeta: {
421
+ next: {
422
+ optional: true
423
+ }
424
+ },
425
+ dependencies: {
426
+ "@anthropic-ai/sdk": "^0.95.1",
427
+ "@google/genai": "^0.8.0",
428
+ "@google/generative-ai": "^0.24.1",
429
+ "@pinecone-database/pinecone": "^7.2.0",
430
+ "@types/papaparse": "^5.5.2",
431
+ axios: "^1.15.0",
432
+ "lucide-react": "^1.8.0",
433
+ "next-themes": "^0.4.6",
434
+ openai: "^6.34.0",
435
+ papaparse: "^5.5.3",
436
+ "react-is": "^18.3.1",
437
+ "react-markdown": "^10.1.0",
438
+ recharts: "^3.8.1",
439
+ "remark-gfm": "^4.0.1",
440
+ xlsx: "^0.18.5"
441
+ },
442
+ optionalDependencies: {
443
+ "@langchain/core": "^1.1.42",
444
+ "@langchain/openai": "^1.4.5",
445
+ langchain: "^1.3.5",
446
+ llamaindex: "^0.11.9",
447
+ mammoth: "^1.8.0",
448
+ mongodb: "^7.1.1",
449
+ "pdf-parse": "^1.1.1",
450
+ pg: "^8.20.0"
451
+ },
452
+ devDependencies: {
453
+ "@tailwindcss/cli": "^4",
454
+ "@tailwindcss/postcss": "^4",
455
+ "@types/estree": "^1.0.9",
456
+ "@types/node": "^20",
457
+ "@types/pdf-parse": "^1.1.5",
458
+ "@types/pg": "^8.20.0",
459
+ "@types/react": "^19.2.14",
460
+ "@types/react-dom": "^19.2.3",
461
+ dotenv: "^17.4.2",
462
+ eslint: "^9",
463
+ "eslint-config-next": "16.2.4",
464
+ next: "16.2.10",
465
+ tailwindcss: "^4",
466
+ tsup: "^8.5.1",
467
+ typescript: "^5"
468
+ }
469
+ };
470
+ }
471
+ });
472
+
473
+ // src/version.ts
474
+ var SDK_VERSION;
475
+ var init_version = __esm({
476
+ "src/version.ts"() {
477
+ "use strict";
478
+ init_package();
479
+ SDK_VERSION = package_default.version || "2.1.3";
480
+ }
481
+ });
482
+
157
483
  // src/core/ConfigFetcher.ts
158
484
  var CONTROL_PLANE_URL, LLM_PROXY_BASE_URL, ConfigFetcher;
159
485
  var init_ConfigFetcher = __esm({
160
486
  "src/core/ConfigFetcher.ts"() {
161
487
  "use strict";
488
+ init_ProjectSettings();
489
+ init_version();
162
490
  CONTROL_PLANE_URL = "https://www.retrivora.com";
163
491
  LLM_PROXY_BASE_URL = "https://www.retrivora.com/api/v1";
164
492
  ConfigFetcher = class {
@@ -191,11 +519,12 @@ var init_ConfigFetcher = __esm({
191
519
  ].filter((url) => Boolean(url) && !url.includes("localhost") && !url.includes("127.0.0.1")).map((url) => url.replace(/\/$/, ""));
192
520
  for (const baseUrl of controlPlaneUrls) {
193
521
  try {
194
- const url = `${baseUrl}/api/v1/config?projectId=${encodeURIComponent(projectId)}${licenseKey ? `&licenseKey=${encodeURIComponent(licenseKey)}` : ""}`;
522
+ const url = `${baseUrl}/api/v1/config?projectId=${encodeURIComponent(projectId)}`;
195
523
  const res = await fetch(url, {
196
524
  method: "GET",
197
525
  headers: __spreadValues({
198
- "Content-Type": "application/json"
526
+ "Content-Type": "application/json",
527
+ "x-sdk-version": SDK_VERSION
199
528
  }, licenseKey ? { "x-license-key": licenseKey } : {})
200
529
  });
201
530
  if (res.ok) {
@@ -235,7 +564,11 @@ var init_ConfigFetcher = __esm({
235
564
  workspace: data.workspace || {
236
565
  namespace: fetchedProjectId,
237
566
  indexName: data.vectorDb.indexName || "retrivora-free"
238
- }
567
+ },
568
+ projectSettings: normalizeProjectSettings(
569
+ fetchedProjectId,
570
+ data.projectSettings || data.settings
571
+ )
239
572
  };
240
573
  this.cache.set(cacheKey, { config, cachedAt: now });
241
574
  return config;
@@ -2237,6 +2570,7 @@ __export(server_exports, {
2237
2570
  ChartRendererStrategy: () => ChartRendererStrategy,
2238
2571
  ChromaDBProvider: () => ChromaDBProvider,
2239
2572
  ConfigBuilder: () => ConfigBuilder,
2573
+ ConfigFetcher: () => ConfigFetcher,
2240
2574
  ConfigResolver: () => ConfigResolver,
2241
2575
  ConfigValidator: () => ConfigValidator,
2242
2576
  ConfigurationException: () => ConfigurationException,
@@ -2245,13 +2579,16 @@ __export(server_exports, {
2245
2579
  EmbeddingFailedException: () => EmbeddingFailedException,
2246
2580
  EmbeddingStrategy: () => EmbeddingStrategy,
2247
2581
  EmbeddingStrategyResolver: () => EmbeddingStrategyResolver,
2582
+ EventType: () => EventType,
2248
2583
  GroqProvider: () => GroqProvider,
2249
2584
  IntentClassifier: () => IntentClassifier,
2250
2585
  LLMFactory: () => LLMFactory,
2251
2586
  LLM_PROFILES: () => LLM_PROFILES,
2587
+ LicenseConfigResolver: () => LicenseConfigResolver,
2252
2588
  LicenseValidationError: () => LicenseValidationError,
2253
2589
  LicenseValidator: () => LicenseValidator,
2254
2590
  LicenseVerifier: () => LicenseVerifier,
2591
+ LicensedRetrivora: () => LicensedRetrivora,
2255
2592
  MilvusProvider: () => MilvusProvider,
2256
2593
  MixedRendererStrategy: () => MixedRendererStrategy,
2257
2594
  MongoDBProvider: () => MongoDBProvider,
@@ -2284,6 +2621,7 @@ __export(server_exports, {
2284
2621
  SDKVersionUnsupportedError: () => SDKVersionUnsupportedError,
2285
2622
  SDK_VERSION: () => SDK_VERSION,
2286
2623
  TableRendererStrategy: () => TableRendererStrategy,
2624
+ TelemetryService: () => TelemetryService,
2287
2625
  TextRendererStrategy: () => TextRendererStrategy,
2288
2626
  UniversalLLMAdapter: () => UniversalLLMAdapter,
2289
2627
  UniversalVectorProvider: () => UniversalVectorProvider,
@@ -2292,17 +2630,26 @@ __export(server_exports, {
2292
2630
  VisualizationDecisionEngine: () => VisualizationDecisionEngine,
2293
2631
  WeaviateProvider: () => WeaviateProvider,
2294
2632
  createChatHandler: () => createChatHandler,
2633
+ createDefaultProjectSettings: () => createDefaultProjectSettings,
2295
2634
  createFeedbackHandler: () => createFeedbackHandler,
2296
2635
  createFromPreset: () => createFromPreset,
2297
2636
  createHealthHandler: () => createHealthHandler,
2298
2637
  createHistoryHandler: () => createHistoryHandler,
2299
2638
  createIngestHandler: () => createIngestHandler,
2300
2639
  createRagHandler: () => createRagHandler,
2640
+ createRetrivora: () => createRetrivora,
2301
2641
  createSessionsHandler: () => createSessionsHandler,
2302
2642
  createStreamHandler: () => createStreamHandler,
2303
2643
  createUploadHandler: () => createUploadHandler,
2304
2644
  decideVisualization: () => decideVisualization,
2305
2645
  getRagConfig: () => getRagConfig,
2646
+ getRuntimeConfig: () => getRuntimeConfig,
2647
+ getTelemetryService: () => getTelemetryService,
2648
+ initializeTelemetryService: () => initializeTelemetryService,
2649
+ injectRuntimeConfig: () => injectRuntimeConfig,
2650
+ normalizeProjectSettings: () => normalizeProjectSettings,
2651
+ projectSettingsToUiConfig: () => projectSettingsToUiConfig,
2652
+ shutdownTelemetryService: () => shutdownTelemetryService,
2306
2653
  sseErrorFrame: () => sseErrorFrame,
2307
2654
  sseFrame: () => sseFrame,
2308
2655
  sseMetaFrame: () => sseMetaFrame,
@@ -2413,10 +2760,6 @@ var LicenseVerifier = class {
2413
2760
  static verify(licenseKey, currentProjectId, provider, publicKeyOverride) {
2414
2761
  const isProduction = process.env.NODE_ENV === "production";
2415
2762
  const now = Date.now();
2416
- console.log(`[Retrivora SDK] LicenseVerifier.verify() - licenseKey`, licenseKey);
2417
- console.log(`[Retrivora SDK] LicenseVerifier.verify() - currentProjectId`, currentProjectId);
2418
- console.log(`[Retrivora SDK] LicenseVerifier.verify() - provider`, provider);
2419
- console.log(`[Retrivora SDK] LicenseVerifier.verify() - publicKeyOverride`, publicKeyOverride);
2420
2763
  if (licenseKey) {
2421
2764
  const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
2422
2765
  const cached = this.cache.get(cacheKey);
@@ -2604,13 +2947,13 @@ LicenseVerifier.CACHE_TTL_MS = 60 * 1e3;
2604
2947
  // In production, this matches the private key held by Retrivora SaaS.
2605
2948
  // Rotate this key only when the signing private key is replaced.
2606
2949
  LicenseVerifier.PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
2607
- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoOQlmDSKfCZaRy06rxwa
2608
- chuDimlF134xTCitKDTPTPizF23oSn34pGDJakm/0T09JVUX8L/cvhGPe/3lf/g9
2609
- 4Y1q+Gb2KVM17KNGeT1Aj9Ua3BKz/yao/oFhi/r3Zt3cWY13B/Rd6clqY9WshIAV
2610
- NqZNM8ilTl777cMbyym+6D+mzGXgmnJAO5brddIAI9FPLW0T3Znt8vEqDOIljEkC
2611
- HCGHeirKABLbjKSJ4hljCa3vVitWqndhiq8CBSJG6HatiSGYotgMWGRY+0EbdlEv
2612
- OJP4SqafQ3aD6YnL9q1n15QKwxu/uMK+JGM2VxxuyUi9GANtMIkCYy9xya73P4Qc
2613
- gQIDAQAB
2950
+ MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyKvvOSYdCimG3b236ebV
2951
+ jpG88xQiU8dSiaMahtBJDf4w0AewRj7hMNgmeZ1wyTOj8kVgeGBOolp1Z0QmTr6O
2952
+ Tj4EDQ/zjsg12If7hSf3NiwLHCYmMLslyK0aaP6PQoTrYkBv3GNdkMecrIjKCijb
2953
+ 6VvDLLF3X696melTVM0z/d2e50BW2AlRw/rf1EqYi10d0BcPo5zje0XETr/WGmqu
2954
+ sDiXtsP5MlwkL9X7RQY2uovRa+l/vOAqAfdmJ+OzXuk5P7mDUPb+gCtKnoDbb1tr
2955
+ 6UAu733dkUnetAcMqyT3fNPBLO66DCc6m9rGCYYAaG7piMEDwG0/ZySZBFbgllJc
2956
+ 6QIDAQAB
2614
2957
  -----END PUBLIC KEY-----`;
2615
2958
 
2616
2959
  // src/config/constants.ts
@@ -2659,6 +3002,20 @@ var PROVIDERS_WITH_EMBEDDINGS = [
2659
3002
  var UI_BORDER_RADIUS_OPTIONS = ["none", "sm", "md", "lg", "xl", "full"];
2660
3003
 
2661
3004
  // src/config/serverConfig.ts
3005
+ var _runtimeConfig = null;
3006
+ function injectRuntimeConfig(config) {
3007
+ _runtimeConfig = config;
3008
+ console.log("[serverConfig] \u2705 Runtime tier config injected:", {
3009
+ tier: config.tier,
3010
+ llmModel: config.llmModel,
3011
+ embeddingModel: config.embeddingModel,
3012
+ llmBaseUrl: config.llmBaseUrl,
3013
+ hasLitellmKey: !!config.litellmApiKey
3014
+ });
3015
+ }
3016
+ function getRuntimeConfig() {
3017
+ return _runtimeConfig;
3018
+ }
2662
3019
  function readString(env, name) {
2663
3020
  var _a3;
2664
3021
  const value = (_a3 = env[name]) == null ? void 0 : _a3.trim();
@@ -2685,7 +3042,7 @@ function getRagConfig(baseConfig, env = process.env) {
2685
3042
  return getEnvConfig(env, baseConfig);
2686
3043
  }
2687
3044
  function getEnvConfig(env = process.env, base) {
2688
- var _a3, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S, _T, _U, _V, _W, _X, _Y, _Z, __, _$, _aa, _ba, _ca, _da, _ea, _fa, _ga, _ha, _ia, _ja, _ka, _la, _ma, _na, _oa, _pa, _qa, _ra, _sa, _ta, _ua, _va, _wa, _xa, _ya, _za, _Aa, _Ba, _Ca, _Da, _Ea, _Fa, _Ga, _Ha, _Ia, _Ja, _Ka, _La, _Ma, _Na, _Oa, _Pa, _Qa, _Ra, _Sa, _Ta, _Ua, _Va, _Wa, _Xa, _Ya, _Za, __a, _$a, _ab, _bb, _cb, _db, _eb, _fb, _gb, _hb, _ib, _jb, _kb, _lb, _mb, _nb, _ob, _pb, _qb, _rb, _sb, _tb, _ub, _vb, _wb, _xb, _yb, _zb, _Ab, _Bb, _Cb, _Db, _Eb, _Fb, _Gb, _Hb, _Ib, _Jb, _Kb;
3045
+ var _a3, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S, _T, _U, _V, _W, _X, _Y, _Z, __, _$, _aa, _ba, _ca, _da, _ea, _fa, _ga, _ha, _ia, _ja, _ka, _la, _ma, _na, _oa, _pa, _qa, _ra, _sa, _ta, _ua, _va, _wa, _xa, _ya, _za, _Aa, _Ba, _Ca, _Da, _Ea, _Fa, _Ga, _Ha, _Ia, _Ja, _Ka, _La, _Ma, _Na, _Oa, _Pa, _Qa, _Ra, _Sa, _Ta, _Ua, _Va, _Wa, _Xa, _Ya, _Za, __a, _$a, _ab, _bb, _cb, _db, _eb, _fb, _gb, _hb, _ib, _jb, _kb, _lb, _mb, _nb, _ob, _pb, _qb, _rb, _sb, _tb, _ub, _vb, _wb, _xb, _yb, _zb, _Ab, _Bb, _Cb, _Db, _Eb, _Fb, _Gb, _Hb;
2689
3046
  const licenseKey = (_d = (_c = (_b = (_a3 = readString(env, "RAG_LICENSE_KEY")) != null ? _a3 : readString(env, "RETRIVORA_LICENSE_KEY")) != null ? _b : readString(env, "NEXT_PUBLIC_RETRIVORA_LICENSE_KEY")) != null ? _c : readString(env, "LICENSE_KEY")) != null ? _d : base == null ? void 0 : base.licenseKey;
2690
3047
  const jwtProjectId = (() => {
2691
3048
  if (!licenseKey) return void 0;
@@ -2777,25 +3134,35 @@ function getEnvConfig(env = process.env, base) {
2777
3134
  return true;
2778
3135
  }
2779
3136
  })();
2780
- const defaultGatewayUrl = (_ra = (_qa = readString(env, "LITELLM_BASE_URL")) != null ? _qa : readString(env, "LLM_BASE_URL")) != null ? _ra : "https://www.retrivora.com/api/v1";
2781
- const defaultLlmProvider = isFreeTier2 ? "universal_rest" : "universal_rest";
2782
- const llmProvider = (_ua = (_ta = readEnum(env, "LLM_PROVIDER", defaultLlmProvider, LLM_PROVIDERS)) != null ? _ta : (_sa = base == null ? void 0 : base.llm) == null ? void 0 : _sa.provider) != null ? _ua : defaultLlmProvider;
2783
- const llmBaseUrl = (_ya = (_xa = (_va = readString(env, "LITELLM_BASE_URL")) != null ? _va : readString(env, "LLM_BASE_URL")) != null ? _xa : (_wa = base == null ? void 0 : base.llm) == null ? void 0 : _wa.baseUrl) != null ? _ya : defaultGatewayUrl;
2784
- const llmModel = (_Ca = (_Aa = readString(env, "LLM_MODEL")) != null ? _Aa : (_za = base == null ? void 0 : base.llm) == null ? void 0 : _za.model) != null ? _Ca : isFreeTier2 ? "llama-3.1-8b-instant" : (_Ba = DEFAULT_MODEL_BY_PROVIDER[llmProvider]) != null ? _Ba : "gpt-4o";
2785
- const llmApiKey = (_Ia = (_Ha = (_Fa = (_Ea = (_Da = llmApiKeyByProvider[llmProvider]) != null ? _Da : readString(env, "LLM_API_KEY")) != null ? _Ea : readString(env, "LITELLM_MASTER_KEY")) != null ? _Fa : readString(env, "LITELLM_API_KEY")) != null ? _Ha : (_Ga = base == null ? void 0 : base.llm) == null ? void 0 : _Ga.apiKey) != null ? _Ia : licenseKey;
2786
- const llmProfile = (_Ma = (_La = readString(env, "LLM_UNIVERSAL_PROFILE")) != null ? _La : (_Ka = (_Ja = base == null ? void 0 : base.llm) == null ? void 0 : _Ja.options) == null ? void 0 : _Ka.profile) != null ? _Ma : "litellm";
2787
- const defaultEmbeddingProvider = isFreeTier2 ? "universal_rest" : "universal_rest";
2788
- const embeddingProvider = (_Pa = (_Oa = readEnum(env, "EMBEDDING_PROVIDER", defaultEmbeddingProvider, EMBEDDING_PROVIDERS)) != null ? _Oa : (_Na = base == null ? void 0 : base.embedding) == null ? void 0 : _Na.provider) != null ? _Pa : defaultEmbeddingProvider;
2789
- const embeddingBaseUrl = (_Ua = (_Ta = (_Ra = (_Qa = readString(env, "LITELLM_BASE_URL")) != null ? _Qa : readString(env, "EMBEDDING_BASE_URL")) != null ? _Ra : readString(env, "LLM_BASE_URL")) != null ? _Ta : (_Sa = base == null ? void 0 : base.embedding) == null ? void 0 : _Sa.baseUrl) != null ? _Ua : defaultGatewayUrl;
2790
- const embeddingModel = (_Xa = (_Wa = readString(env, "EMBEDDING_MODEL")) != null ? _Wa : (_Va = base == null ? void 0 : base.embedding) == null ? void 0 : _Va.model) != null ? _Xa : "text-embedding-004";
2791
- const embeddingApiKey = (_cb = (_bb = (_$a = (__a = (_Za = (_Ya = embeddingApiKeyByProvider[embeddingProvider]) != null ? _Ya : readString(env, "EMBEDDING_API_KEY")) != null ? _Za : readString(env, "LLM_API_KEY")) != null ? __a : readString(env, "LITELLM_MASTER_KEY")) != null ? _$a : readString(env, "LITELLM_API_KEY")) != null ? _bb : (_ab = base == null ? void 0 : base.embedding) == null ? void 0 : _ab.apiKey) != null ? _cb : licenseKey;
2792
- const embeddingProfile = (_gb = (_fb = readString(env, "EMBEDDING_UNIVERSAL_PROFILE")) != null ? _fb : (_eb = (_db = base == null ? void 0 : base.embedding) == null ? void 0 : _db.options) == null ? void 0 : _eb.profile) != null ? _gb : "litellm";
3137
+ const tierBasedLLMModel = isFreeTier2 ? "llama-3.1-8b-instant" : "llama-3.3-70b-versatile";
3138
+ const tierBasedEmbeddingModel = isFreeTier2 ? "text-embedding-004" : "text-embedding-004";
3139
+ const defaultGatewayUrl = "https://llm.retrivora.com/api/v1";
3140
+ const rt = _runtimeConfig;
3141
+ const defaultLlmProvider = "universal_rest";
3142
+ const llmProvider = (_sa = (_ra = readEnum(env, "LLM_PROVIDER", defaultLlmProvider, LLM_PROVIDERS)) != null ? _ra : (_qa = base == null ? void 0 : base.llm) == null ? void 0 : _qa.provider) != null ? _sa : defaultLlmProvider;
3143
+ const llmBaseUrl = (_xa = (_wa = (_va = (_ta = readString(env, "LITELLM_BASE_URL")) != null ? _ta : readString(env, "LLM_BASE_URL")) != null ? _va : (_ua = base == null ? void 0 : base.llm) == null ? void 0 : _ua.baseUrl) != null ? _wa : rt == null ? void 0 : rt.llmBaseUrl) != null ? _xa : defaultGatewayUrl;
3144
+ const llmModel = (_Ba = (_Aa = (_za = readString(env, "LLM_MODEL")) != null ? _za : (_ya = base == null ? void 0 : base.llm) == null ? void 0 : _ya.model) != null ? _Aa : rt == null ? void 0 : rt.llmModel) != null ? _Ba : tierBasedLLMModel;
3145
+ const llmApiKey = (_Fa = (_Ea = (_Ca = readString(env, "LITELLM_MASTER_KEY")) != null ? _Ca : rt == null ? void 0 : rt.litellmApiKey) != null ? _Ea : (_Da = base == null ? void 0 : base.llm) == null ? void 0 : _Da.apiKey) != null ? _Fa : licenseKey;
3146
+ const llmProfile = (_Ja = (_Ia = readString(env, "LLM_UNIVERSAL_PROFILE")) != null ? _Ia : (_Ha = (_Ga = base == null ? void 0 : base.llm) == null ? void 0 : _Ga.options) == null ? void 0 : _Ha.profile) != null ? _Ja : "litellm";
3147
+ console.log("[serverConfig] \u{1F527} LLM Configuration:", {
3148
+ baseUrl: llmBaseUrl,
3149
+ model: llmModel,
3150
+ provider: llmProvider,
3151
+ hasApiKey: !!llmApiKey,
3152
+ source: (rt == null ? void 0 : rt.llmModel) ? "runtime-injected" : "env/fallback"
3153
+ });
3154
+ const defaultEmbeddingProvider = "universal_rest";
3155
+ const embeddingProvider = (_Ma = (_La = readEnum(env, "EMBEDDING_PROVIDER", defaultEmbeddingProvider, EMBEDDING_PROVIDERS)) != null ? _La : (_Ka = base == null ? void 0 : base.embedding) == null ? void 0 : _Ka.provider) != null ? _Ma : defaultEmbeddingProvider;
3156
+ const embeddingBaseUrl = (_Ta = (_Sa = (_Ra = (_Qa = (_Oa = (_Na = readString(env, "LITELLM_BASE_URL")) != null ? _Na : readString(env, "EMBEDDING_BASE_URL")) != null ? _Oa : readString(env, "LLM_BASE_URL")) != null ? _Qa : (_Pa = base == null ? void 0 : base.embedding) == null ? void 0 : _Pa.baseUrl) != null ? _Ra : rt == null ? void 0 : rt.embeddingBaseUrl) != null ? _Sa : rt == null ? void 0 : rt.llmBaseUrl) != null ? _Ta : defaultGatewayUrl;
3157
+ const embeddingModel = (_Xa = (_Wa = (_Va = readString(env, "EMBEDDING_MODEL")) != null ? _Va : (_Ua = base == null ? void 0 : base.embedding) == null ? void 0 : _Ua.model) != null ? _Wa : rt == null ? void 0 : rt.embeddingModel) != null ? _Xa : tierBasedEmbeddingModel;
3158
+ const embeddingApiKey = (_$a = (__a = (_Ya = readString(env, "LITELLM_MASTER_KEY")) != null ? _Ya : rt == null ? void 0 : rt.litellmApiKey) != null ? __a : (_Za = base == null ? void 0 : base.embedding) == null ? void 0 : _Za.apiKey) != null ? _$a : licenseKey;
3159
+ const embeddingProfile = (_db = (_cb = readString(env, "EMBEDDING_UNIVERSAL_PROFILE")) != null ? _cb : (_bb = (_ab = base == null ? void 0 : base.embedding) == null ? void 0 : _ab.options) == null ? void 0 : _bb.profile) != null ? _db : "litellm";
2793
3160
  return __spreadProps(__spreadValues({
2794
3161
  projectId,
2795
3162
  licenseKey,
2796
3163
  vectorDb: {
2797
3164
  provider: vectorProvider,
2798
- indexName: (_ib = (_hb = readString(env, "VECTOR_DB_INDEX")) != null ? _hb : vectorDbOptions.indexName) != null ? _ib : "rag-index",
3165
+ indexName: (_fb = (_eb = readString(env, "VECTOR_DB_INDEX")) != null ? _eb : vectorDbOptions.indexName) != null ? _fb : "rag-index",
2799
3166
  options: vectorDbOptions
2800
3167
  },
2801
3168
  llm: {
@@ -2825,30 +3192,30 @@ function getEnvConfig(env = process.env, base) {
2825
3192
  }
2826
3193
  },
2827
3194
  ui: {
2828
- title: (_kb = (_jb = readString(env, "NEXT_PUBLIC_UI_TITLE")) != null ? _jb : readString(env, "UI_TITLE")) != null ? _kb : "AI Assistant",
2829
- subtitle: (_mb = (_lb = readString(env, "NEXT_PUBLIC_UI_SUBTITLE")) != null ? _lb : readString(env, "UI_SUBTITLE")) != null ? _mb : "Powered by RAG",
2830
- primaryColor: (_ob = (_nb = readString(env, "NEXT_PUBLIC_PRIMARY_COLOR")) != null ? _nb : readString(env, "UI_PRIMARY_COLOR")) != null ? _ob : "#10b981",
2831
- accentColor: (_qb = (_pb = readString(env, "NEXT_PUBLIC_ACCENT_COLOR")) != null ? _pb : readString(env, "UI_ACCENT_COLOR")) != null ? _qb : "#3b82f6",
2832
- logoUrl: (_rb = readString(env, "NEXT_PUBLIC_LOGO_URL")) != null ? _rb : readString(env, "UI_LOGO_URL"),
2833
- placeholder: (_tb = (_sb = readString(env, "NEXT_PUBLIC_PLACEHOLDER")) != null ? _sb : readString(env, "UI_PLACEHOLDER")) != null ? _tb : "Ask me anything\u2026",
2834
- showSources: ((_vb = (_ub = readString(env, "NEXT_PUBLIC_SHOW_SOURCES")) != null ? _ub : readString(env, "UI_SHOW_SOURCES")) != null ? _vb : "true") !== "false",
2835
- welcomeMessage: (_xb = (_wb = readString(env, "NEXT_PUBLIC_WELCOME_MESSAGE")) != null ? _wb : readString(env, "UI_WELCOME_MESSAGE")) != null ? _xb : "Hello! I'm your AI assistant. Ask me anything about your documents.",
2836
- visualStyle: (_zb = (_yb = readString(env, "NEXT_PUBLIC_UI_VISUAL_STYLE")) != null ? _yb : readString(env, "UI_VISUAL_STYLE")) != null ? _zb : "glass",
2837
- borderRadius: (_Bb = (_Ab = readString(env, "NEXT_PUBLIC_UI_BORDER_RADIUS")) != null ? _Ab : readString(env, "UI_BORDER_RADIUS")) != null ? _Bb : "xl",
2838
- allowUpload: ((_Db = (_Cb = readString(env, "NEXT_PUBLIC_ALLOW_UPLOAD")) != null ? _Cb : readString(env, "UI_ALLOW_UPLOAD")) != null ? _Db : "false") === "true"
3195
+ title: (_hb = (_gb = readString(env, "NEXT_PUBLIC_UI_TITLE")) != null ? _gb : readString(env, "UI_TITLE")) != null ? _hb : "AI Assistant",
3196
+ subtitle: (_jb = (_ib = readString(env, "NEXT_PUBLIC_UI_SUBTITLE")) != null ? _ib : readString(env, "UI_SUBTITLE")) != null ? _jb : "Powered by RAG",
3197
+ primaryColor: (_lb = (_kb = readString(env, "NEXT_PUBLIC_PRIMARY_COLOR")) != null ? _kb : readString(env, "UI_PRIMARY_COLOR")) != null ? _lb : "#10b981",
3198
+ accentColor: (_nb = (_mb = readString(env, "NEXT_PUBLIC_ACCENT_COLOR")) != null ? _mb : readString(env, "UI_ACCENT_COLOR")) != null ? _nb : "#3b82f6",
3199
+ logoUrl: (_ob = readString(env, "NEXT_PUBLIC_LOGO_URL")) != null ? _ob : readString(env, "UI_LOGO_URL"),
3200
+ placeholder: (_qb = (_pb = readString(env, "NEXT_PUBLIC_PLACEHOLDER")) != null ? _pb : readString(env, "UI_PLACEHOLDER")) != null ? _qb : "Ask me anything\u2026",
3201
+ showSources: ((_sb = (_rb = readString(env, "NEXT_PUBLIC_SHOW_SOURCES")) != null ? _rb : readString(env, "UI_SHOW_SOURCES")) != null ? _sb : "true") !== "false",
3202
+ welcomeMessage: (_ub = (_tb = readString(env, "NEXT_PUBLIC_WELCOME_MESSAGE")) != null ? _tb : readString(env, "UI_WELCOME_MESSAGE")) != null ? _ub : "Hello! I'm your AI assistant. Ask me anything about your documents.",
3203
+ visualStyle: (_wb = (_vb = readString(env, "NEXT_PUBLIC_UI_VISUAL_STYLE")) != null ? _vb : readString(env, "UI_VISUAL_STYLE")) != null ? _wb : "glass",
3204
+ borderRadius: (_yb = (_xb = readString(env, "NEXT_PUBLIC_UI_BORDER_RADIUS")) != null ? _xb : readString(env, "UI_BORDER_RADIUS")) != null ? _yb : "xl",
3205
+ allowUpload: ((_Ab = (_zb = readString(env, "NEXT_PUBLIC_ALLOW_UPLOAD")) != null ? _zb : readString(env, "UI_ALLOW_UPLOAD")) != null ? _Ab : "false") === "true"
2839
3206
  },
2840
3207
  rag: {
2841
3208
  topK: readNumber(env, "RAG_TOP_K", 5),
2842
3209
  scoreThreshold: readNumber(env, "RAG_SCORE_THRESHOLD", 0),
2843
3210
  chunkSize: readNumber(env, "RAG_CHUNK_SIZE", 1e3),
2844
3211
  chunkOverlap: readNumber(env, "RAG_CHUNK_OVERLAP", 200),
2845
- filterableFields: (_Eb = readString(env, "RAG_FILTERABLE_FIELDS")) == null ? void 0 : _Eb.split(",").map((f) => f.trim()),
3212
+ filterableFields: (_Bb = readString(env, "RAG_FILTERABLE_FIELDS")) == null ? void 0 : _Bb.split(",").map((f) => f.trim()),
2846
3213
  // Query pipeline toggles — read from .env.local
2847
3214
  useQueryTransformation: readString(env, "RAG_USE_QUERY_TRANSFORMATION") === "true",
2848
3215
  useReranking: readString(env, "RAG_USE_RERANKING") === "true",
2849
3216
  useGraphRetrieval: readString(env, "RAG_USE_GRAPH_RETRIEVAL") === "true",
2850
- architecture: (_Fb = readString(env, "RAG_ARCHITECTURE")) != null ? _Fb : "simple",
2851
- chunkingStrategy: (_Gb = readString(env, "RAG_CHUNKING_STRATEGY")) != null ? _Gb : "recursive",
3217
+ architecture: (_Cb = readString(env, "RAG_ARCHITECTURE")) != null ? _Cb : "simple",
3218
+ chunkingStrategy: (_Db = readString(env, "RAG_CHUNKING_STRATEGY")) != null ? _Db : "recursive",
2852
3219
  uiMapping: (() => {
2853
3220
  const raw = readString(env, "RAG_UI_MAPPING");
2854
3221
  if (!raw) return void 0;
@@ -2861,7 +3228,7 @@ function getEnvConfig(env = process.env, base) {
2861
3228
  },
2862
3229
  telemetry: {
2863
3230
  enabled: telemetryEnabled,
2864
- url: (_Kb = (_Jb = (_Hb = readString(env, "TELEMETRY_URL")) != null ? _Hb : readString(env, "NEXT_PUBLIC_TELEMETRY_URL")) != null ? _Jb : (_Ib = base == null ? void 0 : base.telemetry) == null ? void 0 : _Ib.url) != null ? _Kb : "https://www.retrivora.com/api/telemetry"
3231
+ url: (_Hb = (_Gb = (_Eb = readString(env, "TELEMETRY_URL")) != null ? _Eb : readString(env, "NEXT_PUBLIC_TELEMETRY_URL")) != null ? _Gb : (_Fb = base == null ? void 0 : base.telemetry) == null ? void 0 : _Fb.url) != null ? _Hb : "https://www.retrivora.com/api/telemetry"
2865
3232
  }
2866
3233
  }, readString(env, "GRAPH_DB_PROVIDER") ? {
2867
3234
  graphDb: {
@@ -2910,6 +3277,7 @@ var ConfigResolver = class {
2910
3277
  options: __spreadValues(__spreadValues({}, envConfig.embedding.options || {}), hostConfig.embedding.options || {})
2911
3278
  }) : envConfig.embedding,
2912
3279
  ui: hostConfig.ui ? mergeDefined(envConfig.ui, hostConfig.ui) : envConfig.ui,
3280
+ projectSettings: hostConfig.projectSettings || envConfig.projectSettings,
2913
3281
  rag: hostConfig.rag ? __spreadValues(__spreadValues({}, envConfig.rag), hostConfig.rag) : envConfig.rag,
2914
3282
  telemetry: hostConfig.telemetry ? __spreadValues(__spreadValues({}, envConfig.telemetry), hostConfig.telemetry) : envConfig.telemetry
2915
3283
  });
@@ -3384,8 +3752,8 @@ var OllamaProvider = class {
3384
3752
  const baseUrl = config.baseUrl || "http://localhost:11434";
3385
3753
  const modelName = config.model;
3386
3754
  try {
3387
- const axios9 = (await import("axios")).default;
3388
- const { data } = await axios9.get(`${baseUrl}/api/tags`);
3755
+ const axios11 = (await import("axios")).default;
3756
+ const { data } = await axios11.get(`${baseUrl}/api/tags`);
3389
3757
  const models = data.models || [];
3390
3758
  const hasModel = models.some((m) => m.name === modelName || m.name.startsWith(`${modelName}:`));
3391
3759
  return {
@@ -4217,7 +4585,7 @@ var UniversalLLMAdapter = class {
4217
4585
  });
4218
4586
  }
4219
4587
  async chat(messages, context) {
4220
- var _a3, _b, _c, _d, _e;
4588
+ var _a3, _b, _c, _d, _e, _f, _g2, _h, _i, _j;
4221
4589
  const path2 = (_a3 = this.opts.chatPath) != null ? _a3 : "/chat/completions";
4222
4590
  const safeMessages = (Array.isArray(messages) ? messages : []).filter((m) => Boolean(m && typeof m === "object")).map((m) => ({
4223
4591
  role: m.role || "user",
@@ -4247,16 +4615,27 @@ ${context != null ? context : "None"}` },
4247
4615
  };
4248
4616
  }
4249
4617
  try {
4618
+ console.debug(`[UniversalLLMAdapter] POST ${this.baseUrl}${path2}`);
4619
+ console.debug(`[UniversalLLMAdapter] Model: ${this.model}`);
4620
+ console.debug(`[UniversalLLMAdapter] Auth: Bearer ${((_b = this.apiKey) == null ? void 0 : _b.substring(0, 20)) || "none"}...`);
4250
4621
  const { data: data2 } = await this.http.post(path2, payload);
4251
- const extractPath2 = (_b = this.opts.responseExtractPath) != null ? _b : "choices[0].message.content";
4252
- const result2 = (_c = resolvePath(data2, extractPath2)) != null ? _c : extractContent(data2);
4622
+ const extractPath2 = (_c = this.opts.responseExtractPath) != null ? _c : "choices[0].message.content";
4623
+ const result2 = (_d = resolvePath(data2, extractPath2)) != null ? _d : extractContent(data2);
4253
4624
  if (result2 !== void 0) {
4254
4625
  return String(result2);
4255
4626
  }
4256
4627
  } catch (httpErr) {
4257
- const _g2 = globalThis;
4258
- const dispatch = _g2.__retrivoraDispatchChat;
4628
+ console.error("[UniversalLLMAdapter] \u274C HTTP chat request failed:", {
4629
+ status: (_e = httpErr == null ? void 0 : httpErr.response) == null ? void 0 : _e.status,
4630
+ statusText: (_f = httpErr == null ? void 0 : httpErr.response) == null ? void 0 : _f.statusText,
4631
+ url: (_g2 = httpErr == null ? void 0 : httpErr.config) == null ? void 0 : _g2.url,
4632
+ errorData: (_h = httpErr == null ? void 0 : httpErr.response) == null ? void 0 : _h.data,
4633
+ message: httpErr == null ? void 0 : httpErr.message
4634
+ });
4635
+ const _g3 = globalThis;
4636
+ const dispatch = _g3.__retrivoraDispatchChat;
4259
4637
  if (typeof dispatch === "function") {
4638
+ console.debug("[UniversalLLMAdapter] \u{1F504} Attempting in-process fallback dispatch");
4260
4639
  const res = await dispatch({
4261
4640
  model: this.model,
4262
4641
  messages: formattedMessages,
@@ -4271,8 +4650,8 @@ ${context != null ? context : "None"}` },
4271
4650
  throw httpErr;
4272
4651
  }
4273
4652
  const { data } = await this.http.post(path2, payload);
4274
- const extractPath = (_d = this.opts.responseExtractPath) != null ? _d : "choices[0].message.content";
4275
- const result = (_e = resolvePath(data, extractPath)) != null ? _e : extractContent(data);
4653
+ const extractPath = (_i = this.opts.responseExtractPath) != null ? _i : "choices[0].message.content";
4654
+ const result = (_j = resolvePath(data, extractPath)) != null ? _j : extractContent(data);
4276
4655
  if (result === void 0) {
4277
4656
  throw new Error(`[UniversalLLMAdapter] Could not extract text from path '${extractPath}' in response.`);
4278
4657
  }
@@ -4411,36 +4790,70 @@ ${context != null ? context : "None"}` },
4411
4790
  });
4412
4791
  }
4413
4792
  async embed(text) {
4414
- var _a3, _b, _c, _d, _e;
4793
+ var _a3, _b, _c, _d, _e, _f, _g2;
4415
4794
  const path2 = (_a3 = this.opts.embedPath) != null ? _a3 : "/embeddings";
4416
4795
  const payload = this.opts.embedPayloadTemplate ? buildPayload(this.opts.embedPayloadTemplate, { input: text, model: this.model }) : { input: text, model: this.model };
4417
4796
  try {
4418
- const { data: data2 } = await this.http.post(path2, payload);
4419
- const extractPath2 = (_b = this.opts.embedExtractPath) != null ? _b : "data[0].embedding";
4420
- const vector2 = resolvePath(data2, extractPath2);
4421
- if (Array.isArray(vector2)) return vector2;
4422
- } catch (e) {
4423
- const _g2 = globalThis;
4424
- const dispatchEmbed = _g2.__retrivoraDispatchEmbedding;
4797
+ const { data } = await this.http.post(path2, payload);
4798
+ const extractPath = (_b = this.opts.embedExtractPath) != null ? _b : "data[0].embedding";
4799
+ const vector = resolvePath(data, extractPath);
4800
+ if (Array.isArray(vector)) return vector;
4801
+ console.warn(
4802
+ `[UniversalLLMAdapter] Embedding API returned unexpected format for path '${extractPath}'. Response:`,
4803
+ data
4804
+ );
4805
+ } catch (err) {
4806
+ console.warn(
4807
+ `[UniversalLLMAdapter] HTTP embedding request failed: ${(err == null ? void 0 : err.message) || err}`,
4808
+ { path: path2, model: this.model }
4809
+ );
4810
+ const _g3 = globalThis;
4811
+ const dispatchEmbed = _g3.__retrivoraDispatchEmbedding;
4425
4812
  if (typeof dispatchEmbed === "function") {
4426
- const res = await dispatchEmbed({ input: text, model: this.model }, this.apiKey);
4427
- if ((_d = (_c = res == null ? void 0 : res.data) == null ? void 0 : _c[0]) == null ? void 0 : _d.embedding) {
4428
- return res.data[0].embedding;
4813
+ try {
4814
+ const res = await dispatchEmbed({ input: text, model: this.model }, this.apiKey);
4815
+ if ((_d = (_c = res == null ? void 0 : res.data) == null ? void 0 : _c[0]) == null ? void 0 : _d.embedding) {
4816
+ return res.data[0].embedding;
4817
+ }
4818
+ } catch (dispatchErr) {
4819
+ console.warn("[UniversalLLMAdapter] In-process dispatch embedding failed:", dispatchErr);
4429
4820
  }
4430
4821
  }
4431
4822
  }
4432
- const { data } = await this.http.post(path2, payload);
4433
- const extractPath = (_e = this.opts.embedExtractPath) != null ? _e : "data[0].embedding";
4434
- const vector = resolvePath(data, extractPath);
4435
- if (!Array.isArray(vector)) {
4436
- throw new Error(`[UniversalLLMAdapter] Could not extract embedding vector from path '${extractPath}' in response.`);
4823
+ try {
4824
+ const { data } = await this.http.post(path2, payload);
4825
+ const extractPath = (_e = this.opts.embedExtractPath) != null ? _e : "data[0].embedding";
4826
+ const vector = resolvePath(data, extractPath);
4827
+ if (Array.isArray(vector)) {
4828
+ return vector;
4829
+ }
4830
+ console.error(
4831
+ `[UniversalLLMAdapter] Retry embedding failed: unexpected response format for path '${extractPath}'. Response:`,
4832
+ data
4833
+ );
4834
+ throw new Error(
4835
+ `[UniversalLLMAdapter] Could not extract embedding vector. Expected array at '${extractPath}', got: ${typeof vector}. Response keys: ${Object.keys(data || {})}.`
4836
+ );
4837
+ } catch (err) {
4838
+ console.error(
4839
+ `[UniversalLLMAdapter] Both embedding attempts failed. Path: ${path2}, Model: ${this.model}`,
4840
+ { error: err == null ? void 0 : err.message, statusCode: (_f = err == null ? void 0 : err.response) == null ? void 0 : _f.status, response: (_g2 = err == null ? void 0 : err.response) == null ? void 0 : _g2.data }
4841
+ );
4842
+ throw new Error(
4843
+ `[UniversalLLMAdapter] Failed to generate embedding after 2 attempts: ${(err == null ? void 0 : err.message) || err}`
4844
+ );
4437
4845
  }
4438
- return vector;
4439
4846
  }
4440
4847
  async batchEmbed(texts) {
4441
4848
  const results = [];
4442
4849
  for (const text of texts) {
4443
- results.push(await this.embed(text));
4850
+ try {
4851
+ const vector = await this.embed(text);
4852
+ results.push(vector);
4853
+ } catch (err) {
4854
+ console.warn(`[UniversalLLMAdapter] batchEmbed failed for text (first 50 chars): ${text.slice(0, 50)}...`, err);
4855
+ throw err;
4856
+ }
4444
4857
  }
4445
4858
  return results;
4446
4859
  }
@@ -4851,149 +5264,8 @@ var ConfigValidator = class {
4851
5264
  }
4852
5265
  };
4853
5266
 
4854
- // package.json
4855
- var package_default = {
4856
- name: "@retrivora-ai/rag-engine",
4857
- version: "2.3.5",
4858
- description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
4859
- author: "Abhinav Alkuchi",
4860
- license: "UNLICENSED",
4861
- keywords: [
4862
- "rag",
4863
- "retrieval-augmented-generation",
4864
- "chatbot",
4865
- "vector-database",
4866
- "pinecone",
4867
- "pgvector",
4868
- "postgresql",
4869
- "milvus",
4870
- "qdrant",
4871
- "chromadb",
4872
- "redis",
4873
- "weaviate",
4874
- "mongodb",
4875
- "openai",
4876
- "anthropic",
4877
- "ollama",
4878
- "nextjs",
4879
- "react",
4880
- "ai",
4881
- "llm",
4882
- "embeddings"
4883
- ],
4884
- main: "dist/index.js",
4885
- module: "dist/index.mjs",
4886
- types: "dist/index.d.ts",
4887
- exports: {
4888
- ".": {
4889
- types: "./dist/index.d.ts",
4890
- require: "./dist/index.js",
4891
- import: "./dist/index.mjs"
4892
- },
4893
- "./style.css": "./dist/index.css",
4894
- "./index.css": "./dist/index.css",
4895
- "./styles.css": "./dist/index.css",
4896
- "./handlers": {
4897
- types: "./dist/handlers/index.d.ts",
4898
- require: "./dist/handlers/index.js",
4899
- import: "./dist/handlers/index.mjs"
4900
- },
4901
- "./server": {
4902
- types: "./dist/server.d.ts",
4903
- require: "./dist/server.js",
4904
- import: "./dist/server.mjs"
4905
- }
4906
- },
4907
- browser: {
4908
- child_process: false,
4909
- fs: false,
4910
- net: false,
4911
- tls: false,
4912
- crypto: false,
4913
- os: false,
4914
- path: false,
4915
- stream: false,
4916
- http: false,
4917
- https: false,
4918
- zlib: false,
4919
- mongodb: false,
4920
- pg: false,
4921
- "pdf-parse": false,
4922
- mammoth: false
4923
- },
4924
- files: [
4925
- "dist",
4926
- "src",
4927
- ".env.example",
4928
- "README.md",
4929
- "FREE_TIER_ARCHITECTURE.md"
4930
- ],
4931
- scripts: {
4932
- dev: "npx @tailwindcss/cli -i src/tailwind.css -o src/index.css && tsup src/index.ts src/handlers/index.ts src/server.ts --format cjs,esm --watch --tsconfig tsconfig.build.json --external react,react-dom,next,mongodb,pg,openai,@anthropic-ai/sdk,@pinecone-database/pinecone,axios,lucide-react,mammoth,pdf-parse,xlsx,react-markdown,remark-gfm,next-themes,langchain,@langchain/core,@langchain/openai,llamaindex --inject-style",
4933
- build: "npm run build:pkg",
4934
- "build:pkg": "npx @tailwindcss/cli -i src/tailwind.css -o src/index.css && tsup src/index.ts src/handlers/index.ts src/server.ts --format cjs,esm --dts --clean --no-splitting --tsconfig tsconfig.build.json --external react,react-dom,next,mongodb,pg,openai,@anthropic-ai/sdk,@pinecone-database/pinecone,axios,lucide-react,mammoth,pdf-parse,xlsx,react-markdown,remark-gfm,next-themes,langchain,@langchain/core,@langchain/openai,llamaindex --inject-style && npx @tailwindcss/cli -i src/tailwind.css -o dist/index.css",
4935
- lint: "eslint",
4936
- typecheck: "tsc --noEmit -p tsconfig.build.json",
4937
- clean: "rm -rf dist"
4938
- },
4939
- peerDependencies: {
4940
- next: ">=15.0.0",
4941
- react: ">=18.0.0",
4942
- "react-dom": ">=18.0.0"
4943
- },
4944
- peerDependenciesMeta: {
4945
- next: {
4946
- optional: true
4947
- }
4948
- },
4949
- dependencies: {
4950
- "@anthropic-ai/sdk": "^0.95.1",
4951
- "@google/genai": "^0.8.0",
4952
- "@google/generative-ai": "^0.24.1",
4953
- "@pinecone-database/pinecone": "^7.2.0",
4954
- "@types/papaparse": "^5.5.2",
4955
- axios: "^1.15.0",
4956
- "lucide-react": "^1.8.0",
4957
- "next-themes": "^0.4.6",
4958
- openai: "^6.34.0",
4959
- papaparse: "^5.5.3",
4960
- "react-is": "^18.3.1",
4961
- "react-markdown": "^10.1.0",
4962
- recharts: "^3.8.1",
4963
- "remark-gfm": "^4.0.1",
4964
- xlsx: "^0.18.5"
4965
- },
4966
- optionalDependencies: {
4967
- "@langchain/core": "^1.1.42",
4968
- "@langchain/openai": "^1.4.5",
4969
- langchain: "^1.3.5",
4970
- llamaindex: "^0.11.9",
4971
- mammoth: "^1.8.0",
4972
- mongodb: "^7.1.1",
4973
- "pdf-parse": "^1.1.1",
4974
- pg: "^8.20.0"
4975
- },
4976
- devDependencies: {
4977
- "@tailwindcss/cli": "^4",
4978
- "@tailwindcss/postcss": "^4",
4979
- "@types/estree": "^1.0.9",
4980
- "@types/node": "^20",
4981
- "@types/pdf-parse": "^1.1.5",
4982
- "@types/pg": "^8.20.0",
4983
- "@types/react": "^19.2.14",
4984
- "@types/react-dom": "^19.2.3",
4985
- dotenv: "^17.4.2",
4986
- eslint: "^9",
4987
- "eslint-config-next": "16.2.4",
4988
- next: "16.2.10",
4989
- tailwindcss: "^4",
4990
- tsup: "^8.5.1",
4991
- typescript: "^5"
4992
- }
4993
- };
4994
-
4995
- // src/version.ts
4996
- var SDK_VERSION = package_default.version || "2.1.3";
5267
+ // src/core/Pipeline.ts
5268
+ init_version();
4997
5269
 
4998
5270
  // src/rag/DocumentChunker.ts
4999
5271
  var DocumentChunker = class {
@@ -10229,6 +10501,11 @@ var VectorPlugin = class {
10229
10501
  }
10230
10502
  };
10231
10503
 
10504
+ // src/server.ts
10505
+ init_version();
10506
+ init_ConfigFetcher();
10507
+ init_ProjectSettings();
10508
+
10232
10509
  // src/config/ConfigBuilder.ts
10233
10510
  var ConfigBuilder = class {
10234
10511
  /**
@@ -10975,6 +11252,7 @@ var DatabaseStorage = class {
10975
11252
  };
10976
11253
 
10977
11254
  // src/handlers/index.ts
11255
+ init_version();
10978
11256
  async function checkAuth(req, onAuthorize) {
10979
11257
  if (!onAuthorize) return null;
10980
11258
  try {
@@ -11106,6 +11384,35 @@ function enforceLicense(req, config, bodyLicenseKey) {
11106
11384
  };
11107
11385
  }
11108
11386
  }
11387
+ function getAllowedNamespaces(projectId) {
11388
+ const trimmed = projectId.trim();
11389
+ const withoutPrefix = trimmed.startsWith("retrivora-") ? trimmed.replace(/^retrivora-/, "") : trimmed;
11390
+ return new Set([
11391
+ trimmed,
11392
+ withoutPrefix,
11393
+ `retrivora-${withoutPrefix}`
11394
+ ].filter(Boolean));
11395
+ }
11396
+ function resolveLicensedNamespace(payload, requestedNamespace) {
11397
+ const allowed = getAllowedNamespaces(payload.projectId);
11398
+ const requested = requestedNamespace == null ? void 0 : requestedNamespace.trim();
11399
+ if (requested && !allowed.has(requested)) {
11400
+ return {
11401
+ ok: false,
11402
+ response: new Response(JSON.stringify({
11403
+ error: {
11404
+ code: "NAMESPACE_FORBIDDEN",
11405
+ message: "Requested namespace is not authorized for this license."
11406
+ }
11407
+ }), {
11408
+ status: 403,
11409
+ headers: { "Content-Type": "application/json" }
11410
+ })
11411
+ };
11412
+ }
11413
+ const defaultNamespace = payload.projectId.startsWith("retrivora-") ? payload.projectId : `retrivora-${payload.projectId}`;
11414
+ return { ok: true, namespace: requested || defaultNamespace };
11415
+ }
11109
11416
  var MAX_MESSAGE_LENGTH = 8e3;
11110
11417
  function sanitizeInput(raw) {
11111
11418
  const stripped = raw.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g, "");
@@ -11266,6 +11573,8 @@ function createChatHandler(configOrPlugin, options) {
11266
11573
  }
11267
11574
  const history = bodyObj.history || (Array.isArray(bodyObj.messages) ? bodyObj.messages.slice(0, -1) : []);
11268
11575
  const { namespace, sessionId = "default", messageId, userMessageId } = bodyObj;
11576
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
11577
+ if (!namespaceCheck.ok) return namespaceCheck.response;
11269
11578
  const sanitized = sanitizeInput(rawMessage != null ? rawMessage : "");
11270
11579
  if (!sanitized.ok) {
11271
11580
  return import_server.NextResponse.json({ error: { code: "INVALID_INPUT", message: sanitized.error } }, { status: 400 });
@@ -11277,7 +11586,7 @@ function createChatHandler(configOrPlugin, options) {
11277
11586
  role: "user",
11278
11587
  content: message
11279
11588
  }).catch((err) => console.warn("[createChatHandler] Failed to save user message:", err));
11280
- const result = await plugin.chat(message, history, namespace);
11589
+ const result = await plugin.chat(message, history, namespaceCheck.namespace);
11281
11590
  const assistantMsgId = messageId || `assistant_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
11282
11591
  await storage.saveMessage(sessionId, {
11283
11592
  id: assistantMsgId,
@@ -11358,6 +11667,8 @@ function createStreamHandler(configOrPlugin, options) {
11358
11667
  }
11359
11668
  const history = bodyObj.history || (Array.isArray(bodyObj.messages) ? bodyObj.messages.slice(0, -1) : []);
11360
11669
  const { namespace, sessionId = "default", messageId, userMessageId } = bodyObj;
11670
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
11671
+ if (!namespaceCheck.ok) return namespaceCheck.response;
11361
11672
  const sanitized = sanitizeInput(rawMessage != null ? rawMessage : "");
11362
11673
  if (!sanitized.ok) {
11363
11674
  return new Response(
@@ -11387,7 +11698,7 @@ function createStreamHandler(configOrPlugin, options) {
11387
11698
  }
11388
11699
  };
11389
11700
  try {
11390
- const pipelineStream = plugin.chatStream(message, history, namespace);
11701
+ const pipelineStream = plugin.chatStream(message, history, namespaceCheck.namespace);
11391
11702
  let fullReply = "";
11392
11703
  try {
11393
11704
  for (var iter = __forAwait(pipelineStream), more, temp, error; more = !(temp = await iter.next()).done; more = false) {
@@ -11493,6 +11804,8 @@ function createIngestHandler(configOrPlugin, options) {
11493
11804
  if (!Array.isArray(documents) || documents.length === 0) {
11494
11805
  return import_server.NextResponse.json({ error: "documents array is required" }, { status: 400 });
11495
11806
  }
11807
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
11808
+ if (!namespaceCheck.ok) return namespaceCheck.response;
11496
11809
  if (isFreeTier(licenseCheck.payload.tier)) {
11497
11810
  const totalIncomingBytes = documents.reduce(
11498
11811
  (sum, d) => sum + Buffer.byteLength(d.content || "", "utf8"),
@@ -11514,7 +11827,7 @@ function createIngestHandler(configOrPlugin, options) {
11514
11827
  );
11515
11828
  }
11516
11829
  }
11517
- const results = await plugin.ingest(documents, namespace);
11830
+ const results = await plugin.ingest(documents, namespaceCheck.namespace);
11518
11831
  reportTelemetry(req, plugin, "DOCUMENT_INGESTION", "success", `Ingested ${documents.length} document(s)`);
11519
11832
  return import_server.NextResponse.json({ results });
11520
11833
  } catch (err) {
@@ -11591,6 +11904,7 @@ function createUploadHandler(configOrPlugin, options) {
11591
11904
  const plugin = getOrCreatePlugin(configOrPlugin);
11592
11905
  const onAuthorize = options == null ? void 0 : options.onAuthorize;
11593
11906
  return async function POST(req, context) {
11907
+ console.log("Upload handler invoked");
11594
11908
  const authResult = await checkAuth(req, onAuthorize);
11595
11909
  if (authResult) return authResult;
11596
11910
  const config = plugin.getConfig();
@@ -11599,9 +11913,12 @@ function createUploadHandler(configOrPlugin, options) {
11599
11913
  try {
11600
11914
  const formData = await req.formData();
11601
11915
  const files = formData.getAll("files");
11916
+ console.log("Files received for upload:", files.map((f) => f.name));
11602
11917
  const namespace = formData.get("namespace") || void 0;
11603
11918
  const dimensionRaw = formData.get("dimension");
11604
11919
  const dimension = dimensionRaw ? parseInt(dimensionRaw, 10) : void 0;
11920
+ const namespaceCheck = resolveLicensedNamespace(licenseCheck.payload, namespace);
11921
+ if (!namespaceCheck.ok) return namespaceCheck.response;
11605
11922
  if (!files || files.length === 0) {
11606
11923
  return import_server.NextResponse.json({ error: "No files provided" }, { status: 400 });
11607
11924
  }
@@ -11718,7 +12035,7 @@ function createUploadHandler(configOrPlugin, options) {
11718
12035
  });
11719
12036
  }
11720
12037
  }
11721
- const results = await plugin.ingest(documents, namespace);
12038
+ const results = await plugin.ingest(documents, namespaceCheck.namespace);
11722
12039
  reportTelemetry(req, plugin, "DOCUMENT_INGESTION", "success", `Uploaded & ingested ${files.length} file(s)`);
11723
12040
  return import_server.NextResponse.json({ message: "Upload successful", results });
11724
12041
  } catch (err) {
@@ -11737,6 +12054,7 @@ function createSuggestionsHandler(configOrPlugin, options) {
11737
12054
  const config = plugin.getConfig();
11738
12055
  const licenseCheck = enforceLicense(req, config);
11739
12056
  if (!licenseCheck.ok) return licenseCheck.response;
12057
+ let effectiveLicensePayload = licenseCheck.payload;
11740
12058
  try {
11741
12059
  let query = "";
11742
12060
  let namespace = void 0;
@@ -11749,6 +12067,7 @@ function createSuggestionsHandler(configOrPlugin, options) {
11749
12067
  if (bodyLicenseKey) {
11750
12068
  const recheck = enforceLicense(req, config, bodyLicenseKey);
11751
12069
  if (!recheck.ok) return recheck.response;
12070
+ effectiveLicensePayload = recheck.payload;
11752
12071
  }
11753
12072
  } else {
11754
12073
  const url = new URL(req.url);
@@ -11758,7 +12077,9 @@ function createSuggestionsHandler(configOrPlugin, options) {
11758
12077
  if (!query || typeof query !== "string" || !query.trim()) {
11759
12078
  return import_server.NextResponse.json({ suggestions: [] });
11760
12079
  }
11761
- const suggestions = await plugin.getSuggestions(query, namespace);
12080
+ const namespaceCheck = resolveLicensedNamespace(effectiveLicensePayload, namespace);
12081
+ if (!namespaceCheck.ok) return namespaceCheck.response;
12082
+ const suggestions = await plugin.getSuggestions(query, namespaceCheck.namespace);
11762
12083
  reportTelemetry(req, plugin, "AUTO_SUGGESTIONS", "success", `Fetched ${suggestions.length} suggestions for: ${query.slice(0, 30)}`);
11763
12084
  return import_server.NextResponse.json({ suggestions });
11764
12085
  } catch (err) {
@@ -11975,6 +12296,15 @@ function createRagHandler(configOrPlugin, options) {
11975
12296
  }
11976
12297
 
11977
12298
  // src/core/LicenseValidator.ts
12299
+ init_version();
12300
+ function canUseLocalValidationFallback(baseUrl, status) {
12301
+ const explicitFallback = typeof process !== "undefined" && process.env.RETRIVORA_ALLOW_LOCAL_LICENSE_FALLBACK === "true";
12302
+ const isLocalSdkRoute = baseUrl.startsWith("/api/retrivora") || baseUrl.includes("/api/retrivora");
12303
+ if (status !== void 0) {
12304
+ return status === 404 && (explicitFallback || isLocalSdkRoute);
12305
+ }
12306
+ return explicitFallback || isLocalSdkRoute;
12307
+ }
11978
12308
  var _LicenseValidator = class _LicenseValidator {
11979
12309
  // 5-minute TTL for successful validation only
11980
12310
  constructor() {
@@ -12034,17 +12364,8 @@ var _LicenseValidator = class _LicenseValidator {
12034
12364
  }
12035
12365
  return void 0;
12036
12366
  };
12037
- console.log("LicenseValidator.validate()", request);
12038
- console.log("LicenseValidator.validate() - licenseKey", licenseKey);
12039
- console.log("LicenseValidator.validate() - projectId", projectId);
12040
- console.log("LicenseValidator.validate() - sdkVersion", sdkVersion);
12041
- console.log("LicenseValidator.validate() - sdk", sdk);
12042
- console.log("LicenseValidator.validate() - platform", platform);
12043
- console.log("LicenseValidator.validate() - retrivoraApiBase", retrivoraApiBase);
12044
- console.log("LicenseValidator.validate() - customHeaders", customHeaders);
12045
12367
  const rawKey = licenseKey || getHeader("x-license-key") || ((_a3 = getHeader("authorization")) == null ? void 0 : _a3.replace(/^Bearer\s+/i, "")) || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY || process.env.RETRIVORA_LICENSE_KEY : "") || "";
12046
12368
  const effectiveLicenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
12047
- console.log("LicenseValidator.validate() - effectiveLicenseKey", effectiveLicenseKey);
12048
12369
  if (!effectiveLicenseKey) {
12049
12370
  this.purgeCache(effectiveLicenseKey);
12050
12371
  throw new LicenseValidationError("Missing RETRIVORA_LICENSE_KEY in request. Set NEXT_PUBLIC_RETRIVORA_LICENSE_KEY in your environment or pass licenseKey as a prop.");
@@ -12058,7 +12379,7 @@ var _LicenseValidator = class _LicenseValidator {
12058
12379
  this.cache.delete(effectiveLicenseKey);
12059
12380
  }
12060
12381
  }
12061
- const base = retrivoraApiBase || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_API_BASE || process.env.RETRIVORA_API_BASE : "") || "/api/retrivora";
12382
+ const base = retrivoraApiBase || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_API_BASE || process.env.RETRIVORA_API_BASE : "") || "https://www.retrivora.com/api";
12062
12383
  const validateUrl = `${base.replace(/\/$/, "")}/v1/license/validate`;
12063
12384
  let res = null;
12064
12385
  try {
@@ -12080,6 +12401,9 @@ var _LicenseValidator = class _LicenseValidator {
12080
12401
  });
12081
12402
  } catch (err) {
12082
12403
  try {
12404
+ if (!canUseLocalValidationFallback(base)) {
12405
+ throw err;
12406
+ }
12083
12407
  const payload = LicenseVerifier.verify(effectiveLicenseKey, projectId || "");
12084
12408
  const fallbackResp = {
12085
12409
  valid: true,
@@ -12097,7 +12421,7 @@ var _LicenseValidator = class _LicenseValidator {
12097
12421
  throw new LicenseValidationError(`License validation request failed: ${(err == null ? void 0 : err.message) || "Network error"}`);
12098
12422
  }
12099
12423
  }
12100
- if (res && !res.ok) {
12424
+ if (res && !res.ok && canUseLocalValidationFallback(base, res.status)) {
12101
12425
  try {
12102
12426
  const payload = LicenseVerifier.verify(effectiveLicenseKey, projectId || "");
12103
12427
  const fallbackResp = {
@@ -12143,6 +12467,583 @@ var _LicenseValidator = class _LicenseValidator {
12143
12467
  };
12144
12468
  _LicenseValidator.SUCCESS_CACHE_TTL_MS = 5 * 60 * 1e3;
12145
12469
  var LicenseValidator = _LicenseValidator;
12470
+
12471
+ // src/config/LicenseConfigResolver.ts
12472
+ var import_axios9 = __toESM(require("axios"));
12473
+ var LicenseConfigResolver = class {
12474
+ /**
12475
+ * Validate and resolve configuration from license key
12476
+ * @param licenseKey JWT token from Retrivora (format: rtv_eyJ...)
12477
+ * @param projectId Workspace identifier
12478
+ * @returns Resolved LLM and embedding configs with provider credentials
12479
+ */
12480
+ static async resolveFromLicense(licenseKey, projectId) {
12481
+ const cacheKey = `${licenseKey}:${projectId}`;
12482
+ const cached = this.configCache.get(cacheKey);
12483
+ if (cached && Date.now() - cached.timestamp < this.CACHE_TTL_MS) {
12484
+ console.log("[LicenseConfigResolver] Using cached config for", projectId);
12485
+ return this.buildConfigs(cached.config, cached.credentials, licenseKey, projectId);
12486
+ }
12487
+ console.log("[LicenseConfigResolver] Fetching tier config from Retrivora...");
12488
+ const tierConfig = await this.fetchTierConfig(licenseKey, projectId);
12489
+ console.log("[LicenseConfigResolver] Fetching provider credentials from Retrivora...");
12490
+ const credentials = await this.fetchProviderCredentials(licenseKey, projectId);
12491
+ this.configCache.set(cacheKey, { config: tierConfig, credentials, timestamp: Date.now() });
12492
+ console.log("[LicenseConfigResolver] \u2705 Successfully resolved config from Retrivora:", {
12493
+ tier: tierConfig.tier,
12494
+ llmModel: tierConfig.llmModel,
12495
+ embeddingModel: tierConfig.embeddingModel
12496
+ });
12497
+ return this.buildConfigs(tierConfig, credentials, licenseKey, projectId);
12498
+ }
12499
+ /**
12500
+ * Fetch tier configuration from Retrivora config API
12501
+ */
12502
+ static async fetchTierConfig(licenseKey, projectId) {
12503
+ try {
12504
+ const response = await import_axios9.default.post(
12505
+ this.RETRIVORA_CONFIG_URL,
12506
+ { licenseKey, projectId },
12507
+ {
12508
+ headers: {
12509
+ "Content-Type": "application/json",
12510
+ Authorization: `Bearer ${licenseKey}`,
12511
+ "X-License-Key": licenseKey,
12512
+ "X-Project-ID": projectId
12513
+ },
12514
+ timeout: 1e4
12515
+ }
12516
+ );
12517
+ if (!response.data.success || !response.data.config) {
12518
+ throw new Error(
12519
+ `[LicenseConfigResolver] Config API returned error: ${response.data.error || response.data.message}`
12520
+ );
12521
+ }
12522
+ console.log(`[LicenseConfigResolver] Resolved tier: ${response.data.config.tier}`);
12523
+ return response.data.config;
12524
+ } catch (err) {
12525
+ console.error("[LicenseConfigResolver] Failed to fetch config:", err.message);
12526
+ throw new Error(
12527
+ `[LicenseConfigResolver] Could not validate license key or fetch tier configuration: ${err.message}`
12528
+ );
12529
+ }
12530
+ }
12531
+ /**
12532
+ * Fetch provider credentials from Retrivora credentials API
12533
+ */
12534
+ static async fetchProviderCredentials(licenseKey, projectId) {
12535
+ try {
12536
+ const response = await import_axios9.default.post(
12537
+ this.RETRIVORA_CREDENTIALS_URL,
12538
+ { licenseKey, projectId },
12539
+ {
12540
+ headers: {
12541
+ "Content-Type": "application/json",
12542
+ Authorization: `Bearer ${licenseKey}`,
12543
+ "X-License-Key": licenseKey,
12544
+ "X-Project-ID": projectId
12545
+ },
12546
+ timeout: 1e4
12547
+ }
12548
+ );
12549
+ if (!response.data.success || !response.data.credentials) {
12550
+ throw new Error(
12551
+ `[LicenseConfigResolver] Credentials API returned error: ${response.data.error || response.data.message}`
12552
+ );
12553
+ }
12554
+ console.log(`[LicenseConfigResolver] Retrieved provider credentials for project: ${projectId}`);
12555
+ return response.data.credentials;
12556
+ } catch (err) {
12557
+ console.error("[LicenseConfigResolver] Failed to fetch credentials:", err.message);
12558
+ throw new Error(
12559
+ `[LicenseConfigResolver] Could not fetch provider credentials: ${err.message}`
12560
+ );
12561
+ }
12562
+ }
12563
+ /**
12564
+ * Build LLM, embedding, and vector DB configs from tier and credentials
12565
+ */
12566
+ static buildConfigs(tierConfig, credentials, licenseKey, projectId) {
12567
+ let llmProvider = "gemini";
12568
+ let llmApiKey = credentials.geminiApiKey || licenseKey;
12569
+ if (tierConfig.llmModel.includes("gpt")) {
12570
+ llmProvider = "openai";
12571
+ } else if (tierConfig.llmModel.includes("groq") || tierConfig.llmModel.includes("llama")) {
12572
+ llmProvider = "groq";
12573
+ llmApiKey = credentials.groqApiKey || licenseKey;
12574
+ }
12575
+ const llmConfig = {
12576
+ provider: llmProvider,
12577
+ model: tierConfig.llmModel,
12578
+ apiKey: llmApiKey,
12579
+ maxTokens: tierConfig.maxTokens,
12580
+ temperature: 0.7,
12581
+ options: {}
12582
+ };
12583
+ const embeddingConfig = {
12584
+ provider: "gemini",
12585
+ model: tierConfig.embeddingModel,
12586
+ apiKey: credentials.geminiApiKey || licenseKey,
12587
+ dimensions: tierConfig.embeddingDimensions,
12588
+ options: {}
12589
+ };
12590
+ const vectorDbConfig = {
12591
+ provider: tierConfig.vectorDb.provider,
12592
+ indexName: tierConfig.vectorDb.indexName,
12593
+ options: this.getVectorDbOptions(tierConfig.vectorDb.provider, projectId, credentials)
12594
+ };
12595
+ return { llmConfig, embeddingConfig, vectorDbConfig, tierConfig, credentials };
12596
+ }
12597
+ /**
12598
+ * Get provider-specific vector DB options
12599
+ */
12600
+ static getVectorDbOptions(provider, projectId, credentials) {
12601
+ switch (provider) {
12602
+ case "pinecone":
12603
+ return {
12604
+ apiKey: credentials.pineconeApiKey,
12605
+ indexName: `retrivora-${projectId}`
12606
+ };
12607
+ case "pgvector":
12608
+ case "postgresql":
12609
+ return {
12610
+ tables: [`documents_${projectId}`]
12611
+ };
12612
+ case "mongodb":
12613
+ return {
12614
+ database: `retrivora_${projectId}`,
12615
+ collection: `vectors_${projectId}`
12616
+ };
12617
+ case "qdrant":
12618
+ return {
12619
+ collection: `retrivora_${projectId}`
12620
+ };
12621
+ default:
12622
+ return {};
12623
+ }
12624
+ }
12625
+ /**
12626
+ * Clear configuration cache (useful for testing or manual refresh)
12627
+ */
12628
+ static clearCache() {
12629
+ this.configCache.clear();
12630
+ console.log("[LicenseConfigResolver] Configuration cache cleared");
12631
+ }
12632
+ /**
12633
+ * Get cache stats for debugging
12634
+ */
12635
+ static getCacheStats() {
12636
+ return {
12637
+ size: this.configCache.size,
12638
+ entries: Array.from(this.configCache.keys())
12639
+ };
12640
+ }
12641
+ };
12642
+ LicenseConfigResolver.RETRIVORA_CONFIG_URL = "https://www.retrivora.com/api/v1/config";
12643
+ LicenseConfigResolver.RETRIVORA_CREDENTIALS_URL = "https://www.retrivora.com/api/v1/credentials";
12644
+ LicenseConfigResolver.CACHE_TTL_MS = 36e5;
12645
+ // 1 hour
12646
+ LicenseConfigResolver.configCache = /* @__PURE__ */ new Map();
12647
+
12648
+ // src/telemetry/TelemetryService.ts
12649
+ var import_axios10 = __toESM(require("axios"));
12650
+ var EventType = /* @__PURE__ */ ((EventType2) => {
12651
+ EventType2["EMBEDDING_GENERATED"] = "embedding_generated";
12652
+ EventType2["LLM_CHAT_COMPLETION"] = "llm_chat_completion";
12653
+ EventType2["DOCUMENT_INGESTED"] = "document_ingested";
12654
+ EventType2["QUERY_EXECUTED"] = "query_executed";
12655
+ EventType2["ERROR_OCCURRED"] = "error_occurred";
12656
+ EventType2["CONFIGURATION_LOADED"] = "configuration_loaded";
12657
+ return EventType2;
12658
+ })(EventType || {});
12659
+ var _TelemetryService = class _TelemetryService {
12660
+ constructor(projectId, licenseKey, userTelemetryUrl) {
12661
+ this.batchSize = 10;
12662
+ this.flushIntervalMs = 3e4;
12663
+ // 30 seconds
12664
+ this.eventQueue = [];
12665
+ this.enabled = true;
12666
+ this.projectId = projectId;
12667
+ this.licenseKey = licenseKey;
12668
+ this.userTelemetryUrl = userTelemetryUrl || process.env[_TelemetryService.USER_TELEMETRY_URL_ENV_KEY];
12669
+ this.http = import_axios10.default.create({
12670
+ timeout: 5e3,
12671
+ headers: {
12672
+ "Content-Type": "application/json",
12673
+ "X-License-Key": licenseKey,
12674
+ "X-Project-ID": projectId
12675
+ }
12676
+ });
12677
+ this.startAutoFlush();
12678
+ }
12679
+ /**
12680
+ * Record a telemetry event
12681
+ */
12682
+ recordEvent(event) {
12683
+ if (!this.enabled) return;
12684
+ const _a3 = event, { licenseKey } = _a3, safeEvent = __objRest(_a3, ["licenseKey"]);
12685
+ const completeEvent = __spreadValues({
12686
+ eventType: event.eventType || "error_occurred" /* ERROR_OCCURRED */,
12687
+ projectId: this.projectId,
12688
+ timestamp: event.timestamp || Date.now()
12689
+ }, safeEvent);
12690
+ this.eventQueue.push(completeEvent);
12691
+ if (this.eventQueue.length >= this.batchSize) {
12692
+ this.flush().catch((err) => {
12693
+ console.warn("[TelemetryService] Flush error:", err.message);
12694
+ });
12695
+ }
12696
+ }
12697
+ /**
12698
+ * Record LLM completion event
12699
+ */
12700
+ recordLLMCompletion(data) {
12701
+ this.recordEvent({
12702
+ eventType: "llm_chat_completion" /* LLM_CHAT_COMPLETION */,
12703
+ model: data.model,
12704
+ inputTokens: data.inputTokens,
12705
+ outputTokens: data.outputTokens,
12706
+ totalTokens: data.inputTokens + data.outputTokens,
12707
+ durationMs: data.durationMs,
12708
+ operationId: data.operationId,
12709
+ metadata: data.metadata
12710
+ });
12711
+ }
12712
+ /**
12713
+ * Record embedding generation event
12714
+ */
12715
+ recordEmbeddingGenerated(data) {
12716
+ this.recordEvent({
12717
+ eventType: "embedding_generated" /* EMBEDDING_GENERATED */,
12718
+ embeddingModel: data.embeddingModel,
12719
+ vectorDimensions: data.vectorDimensions,
12720
+ textLength: data.textLength,
12721
+ durationMs: data.durationMs,
12722
+ operationId: data.operationId
12723
+ });
12724
+ }
12725
+ /**
12726
+ * Record document ingestion event
12727
+ */
12728
+ recordDocumentIngested(data) {
12729
+ this.recordEvent({
12730
+ eventType: "document_ingested" /* DOCUMENT_INGESTED */,
12731
+ documentId: data.documentId,
12732
+ documentName: data.documentName,
12733
+ documentSize: data.documentSize,
12734
+ chunksGenerated: data.chunksGenerated,
12735
+ durationMs: data.durationMs
12736
+ });
12737
+ }
12738
+ /**
12739
+ * Record query execution event
12740
+ */
12741
+ recordQueryExecuted(data) {
12742
+ this.recordEvent({
12743
+ eventType: "query_executed" /* QUERY_EXECUTED */,
12744
+ queryText: data.queryText,
12745
+ resultCount: data.resultCount,
12746
+ durationMs: data.durationMs,
12747
+ operationId: data.operationId
12748
+ });
12749
+ }
12750
+ /**
12751
+ * Record error event
12752
+ */
12753
+ recordError(error, context) {
12754
+ this.recordEvent({
12755
+ eventType: "error_occurred" /* ERROR_OCCURRED */,
12756
+ errorCode: error.code || "UNKNOWN",
12757
+ errorMessage: error.message,
12758
+ stackTrace: error.stack,
12759
+ metadata: context
12760
+ });
12761
+ }
12762
+ /**
12763
+ * Flush all queued events to telemetry endpoints
12764
+ */
12765
+ async flush() {
12766
+ if (this.eventQueue.length === 0) return;
12767
+ const events = this.eventQueue.splice(0, this.batchSize);
12768
+ const payload = {
12769
+ events: events.map((e) => {
12770
+ const eventWithoutKey = __objRest(e, []);
12771
+ return eventWithoutKey;
12772
+ }),
12773
+ batchId: `${this.projectId}_${Date.now()}`
12774
+ };
12775
+ try {
12776
+ await this.http.post(_TelemetryService.RETRIVORA_TELEMETRY_URL, payload);
12777
+ console.log(`[TelemetryService] Flushed ${events.length} events to Retrivora`);
12778
+ } catch (err) {
12779
+ console.warn("[TelemetryService] Failed to send telemetry to Retrivora:", err.message);
12780
+ this.eventQueue.unshift(...events);
12781
+ }
12782
+ if (this.userTelemetryUrl) {
12783
+ try {
12784
+ await import_axios10.default.post(this.userTelemetryUrl, payload, {
12785
+ timeout: 5e3,
12786
+ headers: {
12787
+ "Content-Type": "application/json",
12788
+ "X-Project-ID": this.projectId
12789
+ }
12790
+ });
12791
+ console.log(`[TelemetryService] Flushed ${events.length} events to user telemetry`);
12792
+ } catch (err) {
12793
+ console.warn("[TelemetryService] Failed to send telemetry to user endpoint:", err.message);
12794
+ }
12795
+ }
12796
+ }
12797
+ /**
12798
+ * Start automatic flush interval
12799
+ */
12800
+ startAutoFlush() {
12801
+ this.flushTimer = setInterval(() => {
12802
+ this.flush().catch((err) => {
12803
+ console.warn("[TelemetryService] Auto-flush error:", err.message);
12804
+ });
12805
+ }, this.flushIntervalMs);
12806
+ }
12807
+ /**
12808
+ * Stop telemetry service and flush remaining events
12809
+ */
12810
+ async shutdown() {
12811
+ if (this.flushTimer) {
12812
+ clearInterval(this.flushTimer);
12813
+ }
12814
+ await this.flush();
12815
+ this.enabled = false;
12816
+ }
12817
+ /**
12818
+ * Disable telemetry temporarily
12819
+ */
12820
+ disable() {
12821
+ this.enabled = false;
12822
+ }
12823
+ /**
12824
+ * Enable telemetry
12825
+ */
12826
+ enable() {
12827
+ this.enabled = true;
12828
+ }
12829
+ /**
12830
+ * Get current queue size (for debugging)
12831
+ */
12832
+ getQueueSize() {
12833
+ return this.eventQueue.length;
12834
+ }
12835
+ };
12836
+ _TelemetryService.RETRIVORA_TELEMETRY_URL = "https://www.retrivora.com/api/telemetry";
12837
+ _TelemetryService.USER_TELEMETRY_URL_ENV_KEY = "TELEMETRY_URL";
12838
+ var TelemetryService = _TelemetryService;
12839
+ var globalTelemetryService = null;
12840
+ function getTelemetryService() {
12841
+ return globalTelemetryService;
12842
+ }
12843
+ function initializeTelemetryService(projectId, licenseKey, userTelemetryUrl) {
12844
+ globalTelemetryService = new TelemetryService(projectId, licenseKey, userTelemetryUrl);
12845
+ console.log("[TelemetryService] Initialized for project:", projectId);
12846
+ return globalTelemetryService;
12847
+ }
12848
+ async function shutdownTelemetryService() {
12849
+ if (globalTelemetryService) {
12850
+ await globalTelemetryService.shutdown();
12851
+ globalTelemetryService = null;
12852
+ }
12853
+ }
12854
+
12855
+ // src/LicensedRetrivora.ts
12856
+ var LicensedRetrivora = class {
12857
+ constructor(options) {
12858
+ this.initialized = false;
12859
+ this.licenseKey = options.licenseKey;
12860
+ this.projectId = options.projectId;
12861
+ if (options.enableTelemetry !== false) {
12862
+ initializeTelemetryService(this.projectId, this.licenseKey, options.userTelemetryUrl);
12863
+ }
12864
+ }
12865
+ /**
12866
+ * Initialize the SDK by validating license and fetching config
12867
+ */
12868
+ generateId() {
12869
+ return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
12870
+ }
12871
+ /**
12872
+ * Initialize the SDK by validating license and fetching config
12873
+ */
12874
+ async initialize() {
12875
+ if (this.initialized) {
12876
+ console.log("[LicensedRetrivora] Already initialized");
12877
+ return;
12878
+ }
12879
+ console.log("[LicensedRetrivora] Initializing with license key...");
12880
+ const operationId = this.generateId();
12881
+ try {
12882
+ const { llmConfig, embeddingConfig, vectorDbConfig, tierConfig } = await LicenseConfigResolver.resolveFromLicense(this.licenseKey, this.projectId);
12883
+ const telemetry = getTelemetryService();
12884
+ if (telemetry) {
12885
+ telemetry.recordEvent({
12886
+ eventType: "configuration_loaded" /* CONFIGURATION_LOADED */,
12887
+ operationId,
12888
+ metadata: {
12889
+ tier: tierConfig.tier,
12890
+ llmModel: tierConfig.llmModel,
12891
+ embeddingModel: tierConfig.embeddingModel,
12892
+ vectorDb: tierConfig.vectorDb.provider
12893
+ }
12894
+ });
12895
+ }
12896
+ this.ragConfig = {
12897
+ projectId: this.projectId,
12898
+ licenseKey: this.licenseKey,
12899
+ llm: llmConfig,
12900
+ embedding: embeddingConfig,
12901
+ vectorDb: vectorDbConfig,
12902
+ rag: {
12903
+ topK: tierConfig.topK,
12904
+ chunkSize: tierConfig.chunkSize,
12905
+ chunkOverlap: tierConfig.chunkOverlap,
12906
+ scoreThreshold: 0
12907
+ },
12908
+ telemetry: {
12909
+ enabled: true,
12910
+ url: "https://www.retrivora.com/api/telemetry"
12911
+ }
12912
+ };
12913
+ this.pipeline = new Pipeline(this.ragConfig);
12914
+ await this.pipeline.initialize();
12915
+ this.initialized = true;
12916
+ console.log(`[LicensedRetrivora] Initialized successfully for tier: ${tierConfig.tier}`);
12917
+ } catch (error) {
12918
+ const telemetry = getTelemetryService();
12919
+ if (telemetry && error instanceof Error) {
12920
+ telemetry.recordError(error, { operationId });
12921
+ await telemetry.flush();
12922
+ }
12923
+ throw error;
12924
+ }
12925
+ }
12926
+ /**
12927
+ * Ingest documents (upload files to vector database)
12928
+ * Returns success/failure status to end-user
12929
+ */
12930
+ async ingest(documents) {
12931
+ if (!this.initialized || !this.pipeline) {
12932
+ throw new Error("[LicensedRetrivora] SDK not initialized. Call initialize() first.");
12933
+ }
12934
+ const operationId = this.generateId();
12935
+ const telemetry = getTelemetryService();
12936
+ const startTime = Date.now();
12937
+ try {
12938
+ console.log(`[LicensedRetrivora] Starting ingestion of ${documents.length} document(s)`);
12939
+ const results = await this.pipeline.ingest(documents);
12940
+ const durationMs = Date.now() - startTime;
12941
+ if (telemetry) {
12942
+ for (const result of results) {
12943
+ telemetry.recordDocumentIngested({
12944
+ documentId: String(result.docId),
12945
+ documentName: String(result.docId),
12946
+ documentSize: 0,
12947
+ // TODO: track actual size
12948
+ chunksGenerated: result.chunksIngested,
12949
+ durationMs
12950
+ });
12951
+ }
12952
+ }
12953
+ const successCount = results.length;
12954
+ return {
12955
+ success: successCount > 0,
12956
+ message: `Successfully ingested ${successCount} document(s). Data is now available for search.`,
12957
+ documentIds: results.map((r) => String(r.docId))
12958
+ };
12959
+ } catch (error) {
12960
+ const durationMs = Date.now() - startTime;
12961
+ if (telemetry && error instanceof Error) {
12962
+ telemetry.recordError(error, { operationId, durationMs });
12963
+ await telemetry.flush();
12964
+ }
12965
+ console.error("[LicensedRetrivora] Ingestion failed:", error);
12966
+ throw error;
12967
+ }
12968
+ }
12969
+ /**
12970
+ * Execute a user query and get response
12971
+ * Returns only the response text and sources (abstracted from underlying models)
12972
+ */
12973
+ async query(queryText, options) {
12974
+ var _a3;
12975
+ if (!this.initialized || !this.pipeline) {
12976
+ throw new Error("[LicensedRetrivora] SDK not initialized. Call initialize() first.");
12977
+ }
12978
+ const operationId = this.generateId();
12979
+ const telemetry = getTelemetryService();
12980
+ const startTime = Date.now();
12981
+ try {
12982
+ console.log(`[LicensedRetrivora] Executing query: "${queryText.substring(0, 100)}..."`);
12983
+ const response = await this.pipeline.runNormalQuery(queryText);
12984
+ const durationMs = Date.now() - startTime;
12985
+ if (telemetry) {
12986
+ telemetry.recordQueryExecuted({
12987
+ queryText,
12988
+ resultCount: ((_a3 = response.sources) == null ? void 0 : _a3.length) || 0,
12989
+ durationMs,
12990
+ operationId
12991
+ });
12992
+ }
12993
+ return {
12994
+ reply: response.reply,
12995
+ sources: response.sources
12996
+ };
12997
+ } catch (error) {
12998
+ const durationMs = Date.now() - startTime;
12999
+ if (telemetry && error instanceof Error) {
13000
+ telemetry.recordError(error, { operationId, durationMs });
13001
+ await telemetry.flush();
13002
+ }
13003
+ console.error("[LicensedRetrivora] Query failed:", error);
13004
+ throw error;
13005
+ }
13006
+ }
13007
+ /**
13008
+ * Get license tier information (for UI display if needed)
13009
+ */
13010
+ async getTierInfo() {
13011
+ if (!this.ragConfig) {
13012
+ throw new Error("[LicensedRetrivora] SDK not initialized.");
13013
+ }
13014
+ return {
13015
+ tier: "Standard",
13016
+ // TODO: fetch from tier config
13017
+ model: this.ragConfig.llm.model,
13018
+ embeddingModel: this.ragConfig.embedding.model
13019
+ };
13020
+ }
13021
+ /**
13022
+ * Cleanup and shutdown
13023
+ */
13024
+ async shutdown() {
13025
+ await shutdownTelemetryService();
13026
+ this.initialized = false;
13027
+ console.log("[LicensedRetrivora] Shutdown complete");
13028
+ }
13029
+ /**
13030
+ * Check if SDK is initialized
13031
+ */
13032
+ isInitialized() {
13033
+ return this.initialized;
13034
+ }
13035
+ /**
13036
+ * Get current RAG configuration (for debugging)
13037
+ */
13038
+ getConfig() {
13039
+ return this.ragConfig;
13040
+ }
13041
+ };
13042
+ async function createRetrivora(options) {
13043
+ const retrivora = new LicensedRetrivora(options);
13044
+ await retrivora.initialize();
13045
+ return retrivora;
13046
+ }
12146
13047
  // Annotate the CommonJS export names for ESM import in node:
12147
13048
  0 && (module.exports = {
12148
13049
  AnthropicProvider,
@@ -12153,6 +13054,7 @@ var LicenseValidator = _LicenseValidator;
12153
13054
  ChartRendererStrategy,
12154
13055
  ChromaDBProvider,
12155
13056
  ConfigBuilder,
13057
+ ConfigFetcher,
12156
13058
  ConfigResolver,
12157
13059
  ConfigValidator,
12158
13060
  ConfigurationException,
@@ -12161,13 +13063,16 @@ var LicenseValidator = _LicenseValidator;
12161
13063
  EmbeddingFailedException,
12162
13064
  EmbeddingStrategy,
12163
13065
  EmbeddingStrategyResolver,
13066
+ EventType,
12164
13067
  GroqProvider,
12165
13068
  IntentClassifier,
12166
13069
  LLMFactory,
12167
13070
  LLM_PROFILES,
13071
+ LicenseConfigResolver,
12168
13072
  LicenseValidationError,
12169
13073
  LicenseValidator,
12170
13074
  LicenseVerifier,
13075
+ LicensedRetrivora,
12171
13076
  MilvusProvider,
12172
13077
  MixedRendererStrategy,
12173
13078
  MongoDBProvider,
@@ -12200,6 +13105,7 @@ var LicenseValidator = _LicenseValidator;
12200
13105
  SDKVersionUnsupportedError,
12201
13106
  SDK_VERSION,
12202
13107
  TableRendererStrategy,
13108
+ TelemetryService,
12203
13109
  TextRendererStrategy,
12204
13110
  UniversalLLMAdapter,
12205
13111
  UniversalVectorProvider,
@@ -12208,17 +13114,26 @@ var LicenseValidator = _LicenseValidator;
12208
13114
  VisualizationDecisionEngine,
12209
13115
  WeaviateProvider,
12210
13116
  createChatHandler,
13117
+ createDefaultProjectSettings,
12211
13118
  createFeedbackHandler,
12212
13119
  createFromPreset,
12213
13120
  createHealthHandler,
12214
13121
  createHistoryHandler,
12215
13122
  createIngestHandler,
12216
13123
  createRagHandler,
13124
+ createRetrivora,
12217
13125
  createSessionsHandler,
12218
13126
  createStreamHandler,
12219
13127
  createUploadHandler,
12220
13128
  decideVisualization,
12221
13129
  getRagConfig,
13130
+ getRuntimeConfig,
13131
+ getTelemetryService,
13132
+ initializeTelemetryService,
13133
+ injectRuntimeConfig,
13134
+ normalizeProjectSettings,
13135
+ projectSettingsToUiConfig,
13136
+ shutdownTelemetryService,
12222
13137
  sseErrorFrame,
12223
13138
  sseFrame,
12224
13139
  sseMetaFrame,