@retrivora-ai/rag-engine 2.4.3 → 2.4.6

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 (142) hide show
  1. package/README.md +22 -0
  2. package/dist/{BatchProcessor-zbQMaZHm.d.mts → BatchProcessor-BGslIR5l.d.mts} +65 -4
  3. package/dist/{BatchProcessor-D42E706a.d.ts → BatchProcessor-C3gY6kZ0.d.ts} +65 -4
  4. package/dist/handlers/index.js +668 -837
  5. package/dist/handlers/index.mjs +678 -837
  6. package/dist/index.css +5 -0
  7. package/dist/index.d.mts +4 -28
  8. package/dist/index.d.ts +4 -28
  9. package/dist/index.js +91 -43
  10. package/dist/index.min.css +1 -1
  11. package/dist/index.mjs +91 -43
  12. package/dist/server.d.mts +21 -7
  13. package/dist/server.d.ts +21 -7
  14. package/dist/server.js +731 -875
  15. package/dist/server.mjs +741 -875
  16. package/package.json +11 -4
  17. package/src/LicensedRetrivora.ts +0 -278
  18. package/src/app/api/chat/route.ts +0 -4
  19. package/src/app/api/health/route.ts +0 -5
  20. package/src/app/api/ingest/route.ts +0 -27
  21. package/src/app/api/suggestions/route.ts +0 -5
  22. package/src/app/api/upload/route.ts +0 -5
  23. package/src/app/constants.tsx +0 -270
  24. package/src/app/favicon.ico +0 -0
  25. package/src/app/globals.css +0 -449
  26. package/src/app/layout.tsx +0 -22
  27. package/src/app/page.tsx +0 -64
  28. package/src/app/types.ts +0 -30
  29. package/src/browser.tsx +0 -127
  30. package/src/components/ChatWidget.tsx +0 -393
  31. package/src/components/ChatWindow.tsx +0 -952
  32. package/src/components/CodeViewer.tsx +0 -56
  33. package/src/components/ConfigProvider.tsx +0 -141
  34. package/src/components/DocumentUpload.tsx +0 -354
  35. package/src/components/DynamicChart.tsx +0 -297
  36. package/src/components/HourglassLoader.tsx +0 -87
  37. package/src/components/MarkdownComponents.tsx +0 -186
  38. package/src/components/MessageBubble.tsx +0 -498
  39. package/src/components/ObservabilityPanel.tsx +0 -374
  40. package/src/components/ProductCard.tsx +0 -107
  41. package/src/components/ProductCarousel.tsx +0 -97
  42. package/src/components/SourceCard.tsx +0 -61
  43. package/src/components/ThemeProvider.tsx +0 -8
  44. package/src/components/ThemeToggle.tsx +0 -29
  45. package/src/components/ThinkingBlock.tsx +0 -75
  46. package/src/components/UIDispatcher.tsx +0 -342
  47. package/src/components/VisualizationRenderer.tsx +0 -621
  48. package/src/components/constants.tsx +0 -503
  49. package/src/config/ConfigBuilder.ts +0 -285
  50. package/src/config/EmbeddingStrategy.ts +0 -148
  51. package/src/config/LicenseConfigResolver.ts +0 -298
  52. package/src/config/RagConfig.ts +0 -328
  53. package/src/config/UniversalProfiles.ts +0 -82
  54. package/src/config/constants.ts +0 -64
  55. package/src/config/serverConfig.ts +0 -378
  56. package/src/config/uiConstants.ts +0 -47
  57. package/src/core/BatchProcessor.ts +0 -385
  58. package/src/core/CircuitBreaker.ts +0 -118
  59. package/src/core/ConfigFetcher.ts +0 -220
  60. package/src/core/ConfigResolver.ts +0 -165
  61. package/src/core/ConfigValidator.ts +0 -197
  62. package/src/core/DatabaseStorage.ts +0 -526
  63. package/src/core/FreeTierLimitsGuard.ts +0 -281
  64. package/src/core/LLMRouter.ts +0 -79
  65. package/src/core/LangChainAgent.ts +0 -132
  66. package/src/core/LicenseValidator.ts +0 -284
  67. package/src/core/LicenseVerifier.ts +0 -261
  68. package/src/core/MultiAgentCoordinator.ts +0 -239
  69. package/src/core/Pipeline.ts +0 -1279
  70. package/src/core/PluginManager.ts +0 -277
  71. package/src/core/ProjectSettings.ts +0 -247
  72. package/src/core/ProviderHealthCheck.ts +0 -133
  73. package/src/core/ProviderInterfaces.ts +0 -37
  74. package/src/core/ProviderRegistry.ts +0 -156
  75. package/src/core/QueryProcessor.ts +0 -399
  76. package/src/core/Retrivora.ts +0 -98
  77. package/src/core/VectorPlugin.ts +0 -193
  78. package/src/core/mcp.ts +0 -261
  79. package/src/exceptions/index.ts +0 -131
  80. package/src/handlers/index.ts +0 -1625
  81. package/src/hooks/useHydrated.ts +0 -13
  82. package/src/hooks/useProjectSettings.ts +0 -105
  83. package/src/hooks/useRagChat.ts +0 -436
  84. package/src/hooks/useStoredMessages.ts +0 -64
  85. package/src/index.css +0 -4269
  86. package/src/index.ts +0 -137
  87. package/src/lib/plugin.ts +0 -24
  88. package/src/llm/ILLMProvider.ts +0 -60
  89. package/src/llm/LLMFactory.ts +0 -141
  90. package/src/llm/providers/AnthropicProvider.ts +0 -215
  91. package/src/llm/providers/GeminiProvider.ts +0 -311
  92. package/src/llm/providers/GroqProvider.ts +0 -184
  93. package/src/llm/providers/OllamaProvider.ts +0 -232
  94. package/src/llm/providers/OpenAIProvider.ts +0 -188
  95. package/src/llm/providers/QwenProvider.ts +0 -199
  96. package/src/llm/providers/UniversalLLMAdapter.ts +0 -422
  97. package/src/llm/utils.ts +0 -46
  98. package/src/providers/graphdb/BaseGraphProvider.ts +0 -43
  99. package/src/providers/graphdb/SimpleGraphProvider.ts +0 -66
  100. package/src/providers/vectordb/BaseVectorProvider.ts +0 -98
  101. package/src/providers/vectordb/ChromaDBProvider.ts +0 -130
  102. package/src/providers/vectordb/MilvusProvider.ts +0 -134
  103. package/src/providers/vectordb/MongoDBProvider.ts +0 -250
  104. package/src/providers/vectordb/MultiTablePostgresProvider.ts +0 -461
  105. package/src/providers/vectordb/PineconeProvider.ts +0 -295
  106. package/src/providers/vectordb/PostgreSQLProvider.ts +0 -227
  107. package/src/providers/vectordb/QdrantProvider.ts +0 -294
  108. package/src/providers/vectordb/RedisProvider.ts +0 -105
  109. package/src/providers/vectordb/UniversalVectorProvider.ts +0 -221
  110. package/src/providers/vectordb/WeaviateProvider.ts +0 -172
  111. package/src/rag/DocumentChunker.ts +0 -144
  112. package/src/rag/EntityExtractor.ts +0 -90
  113. package/src/rag/LlamaIndexIngestor.ts +0 -60
  114. package/src/rag/Reranker.ts +0 -106
  115. package/src/rendering/IntentClassifier.ts +0 -167
  116. package/src/rendering/RendererRegistry.ts +0 -164
  117. package/src/rendering/RuleEngine.ts +0 -67
  118. package/src/rendering/VisualizationDecisionEngine.ts +0 -164
  119. package/src/rendering/__tests__/VisualizationDecisionEngine.test.ts +0 -237
  120. package/src/rendering/index.ts +0 -12
  121. package/src/rendering/rules/Rule1SpecificInfoRule.ts +0 -28
  122. package/src/rendering/rules/Rule2ComparisonRule.ts +0 -24
  123. package/src/rendering/rules/Rule3ProductDiscoveryRule.ts +0 -28
  124. package/src/rendering/rules/Rule4AnalyticalRule.ts +0 -38
  125. package/src/rendering/rules/Rule5MixedResponseRule.ts +0 -29
  126. package/src/rendering/rules/Rule6SmallResultSetRule.ts +0 -24
  127. package/src/rendering/rules/Rule7LargeTableRule.ts +0 -35
  128. package/src/rendering/types.ts +0 -96
  129. package/src/server.ts +0 -156
  130. package/src/tailwind.css +0 -194
  131. package/src/telemetry/TelemetryService.ts +0 -330
  132. package/src/types/chat.ts +0 -89
  133. package/src/types/index.ts +0 -278
  134. package/src/types/pdf-parse.d.ts +0 -13
  135. package/src/types/props.ts +0 -169
  136. package/src/utils/DocumentParser.ts +0 -111
  137. package/src/utils/ProductExtractor.ts +0 -350
  138. package/src/utils/SchemaMapper.ts +0 -176
  139. package/src/utils/UITransformer.ts +0 -1812
  140. package/src/utils/synonyms.ts +0 -80
  141. package/src/utils/templateUtils.ts +0 -78
  142. package/src/version.ts +0 -6
package/dist/server.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __defProps = Object.defineProperties;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
4
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
6
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
@@ -44,6 +45,15 @@ var __export = (target, all) => {
44
45
  for (var name in all)
45
46
  __defProp(target, name, { get: all[name], enumerable: true });
46
47
  };
48
+ var __copyProps = (to, from, except, desc) => {
49
+ if (from && typeof from === "object" || typeof from === "function") {
50
+ for (let key of __getOwnPropNames(from))
51
+ if (!__hasOwnProp.call(to, key) && key !== except)
52
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
53
+ }
54
+ return to;
55
+ };
56
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
47
57
  var __await = function(promise, isYieldStar) {
48
58
  this[0] = promise;
49
59
  this[1] = isYieldStar;
@@ -275,6 +285,7 @@ function projectSettingsToUiConfig(settings) {
275
285
  welcomeMessage: settings.branding.welcomeMessage,
276
286
  poweredBy: settings.widget.showRetrivoraBranding ? "Retrivora AI" : "",
277
287
  allowUpload: settings.ai.fileUploadEnabled,
288
+ showSources: settings.ai.citationsEnabled,
278
289
  borderRadius: settings.branding.borderRadius <= 4 ? "sm" : settings.branding.borderRadius <= 8 ? "md" : settings.branding.borderRadius <= 16 ? "xl" : "full"
279
290
  };
280
291
  }
@@ -315,7 +326,7 @@ var init_package = __esm({
315
326
  "package.json"() {
316
327
  package_default = {
317
328
  name: "@retrivora-ai/rag-engine",
318
- version: "2.4.3",
329
+ version: "2.4.6",
319
330
  description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
320
331
  author: "Abhinav Alkuchi",
321
332
  license: "UNLICENSED",
@@ -387,8 +398,6 @@ var init_package = __esm({
387
398
  },
388
399
  files: [
389
400
  "dist",
390
- "src",
391
- ".env.example",
392
401
  "README.md",
393
402
  "FREE_TIER_ARCHITECTURE.md"
394
403
  ],
@@ -398,14 +407,19 @@ var init_package = __esm({
398
407
  "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 && npx @tailwindcss/cli -i src/tailwind.css -o dist/index.min.css --minify",
399
408
  lint: "eslint",
400
409
  typecheck: "tsc --noEmit -p tsconfig.build.json",
410
+ test: "jest",
401
411
  clean: "rm -rf dist"
402
412
  },
403
413
  peerDependencies: {
414
+ axios: ">=1.0.0",
404
415
  next: ">=15.0.0",
405
416
  react: ">=18.0.0",
406
417
  "react-dom": ">=18.0.0"
407
418
  },
408
419
  peerDependenciesMeta: {
420
+ axios: {
421
+ optional: true
422
+ },
409
423
  next: {
410
424
  optional: true
411
425
  }
@@ -414,9 +428,9 @@ var init_package = __esm({
414
428
  "@anthropic-ai/sdk": "^0.95.1",
415
429
  "@google/genai": "^0.8.0",
416
430
  "@google/generative-ai": "^0.24.1",
431
+ "@retrivora-ai/billing-guards": "*",
417
432
  "@pinecone-database/pinecone": "^7.2.0",
418
433
  "@types/papaparse": "^5.5.2",
419
- axios: "^1.15.0",
420
434
  "lucide-react": "^1.8.0",
421
435
  "next-themes": "^0.4.6",
422
436
  openai: "^6.34.0",
@@ -441,16 +455,20 @@ var init_package = __esm({
441
455
  "@tailwindcss/cli": "^4",
442
456
  "@tailwindcss/postcss": "^4",
443
457
  "@types/estree": "^1.0.9",
458
+ "@types/jest": "^30.0.0",
444
459
  "@types/node": "^20",
445
460
  "@types/pdf-parse": "^1.1.5",
446
461
  "@types/pg": "^8.20.0",
447
462
  "@types/react": "^19.2.14",
448
463
  "@types/react-dom": "^19.2.3",
464
+ axios: "^1.15.0",
449
465
  dotenv: "^17.4.2",
450
466
  eslint: "^9",
451
467
  "eslint-config-next": "16.2.4",
468
+ jest: "^30.4.2",
452
469
  next: "16.2.10",
453
470
  tailwindcss: "^4",
471
+ "ts-jest": "^29.4.12",
454
472
  tsup: "^8.5.1",
455
473
  typescript: "^5"
456
474
  }
@@ -493,7 +511,7 @@ var init_ConfigFetcher = __esm({
493
511
  * PINECONE_API_KEY if available, or vector operations are handled server-side.
494
512
  */
495
513
  static async fetchRemoteConfig(projectId, licenseKey) {
496
- var _a3, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k;
514
+ var _a2, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k;
497
515
  const cacheKey = `${projectId}:${licenseKey || ""}`;
498
516
  const now = Date.now();
499
517
  const cached = this.cache.get(cacheKey);
@@ -538,7 +556,7 @@ var init_ConfigFetcher = __esm({
538
556
  indexName: data.vectorDb.indexName || "retrivora-free",
539
557
  provider: data.vectorDb.provider || "pinecone",
540
558
  projectId: fetchedProjectId,
541
- namespace: ((_a3 = data.workspace) == null ? void 0 : _a3.namespace) || data.vectorDb.namespace || fetchedProjectId
559
+ namespace: ((_a2 = data.workspace) == null ? void 0 : _a2.namespace) || data.vectorDb.namespace || fetchedProjectId
542
560
  },
543
561
  embedding: {
544
562
  provider: ((_b = data.embedding) == null ? void 0 : _b.provider) || "universal_rest",
@@ -595,16 +613,20 @@ var init_ConfigFetcher = __esm({
595
613
  return config;
596
614
  }
597
615
  }
598
- } catch (e) {
616
+ } catch (err) {
617
+ console.warn(
618
+ `[ConfigFetcher] Failed to fetch config from ${baseUrl}:`,
619
+ err instanceof Error ? err.message : String(err)
620
+ );
599
621
  }
600
622
  }
601
623
  return null;
602
624
  }
603
625
  /** Convenience: fetch only vector DB config (backwards compat). */
604
626
  static async fetchRemoteVectorConfig(projectId, licenseKey) {
605
- var _a3;
627
+ var _a2;
606
628
  const config = await this.fetchRemoteConfig(projectId, licenseKey);
607
- return (_a3 = config == null ? void 0 : config.vectorDb) != null ? _a3 : null;
629
+ return (_a2 = config == null ? void 0 : config.vectorDb) != null ? _a2 : null;
608
630
  }
609
631
  };
610
632
  ConfigFetcher.cache = /* @__PURE__ */ new Map();
@@ -644,7 +666,7 @@ var init_PineconeProvider = __esm({
644
666
  const errors = [];
645
667
  const opts = config.options || {};
646
668
  const hasLicenseKey = Boolean(
647
- config.licenseKey || process.env.RETRIVORA_LICENSE_KEY || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY
669
+ config.licenseKey || process.env.RETRIVORA_LICENSE_KEY
648
670
  );
649
671
  if (!opts.apiKey && !hasLicenseKey) {
650
672
  errors.push({
@@ -661,7 +683,7 @@ var init_PineconeProvider = __esm({
661
683
  static getHealthChecker() {
662
684
  return {
663
685
  async check(config) {
664
- var _a3, _b;
686
+ var _a2, _b;
665
687
  const opts = config.options || {};
666
688
  const indexName = config.indexName;
667
689
  const timestamp = Date.now();
@@ -669,7 +691,7 @@ var init_PineconeProvider = __esm({
669
691
  const { Pinecone: Pinecone2 } = await import("@pinecone-database/pinecone");
670
692
  const client = new Pinecone2({ apiKey: opts.apiKey });
671
693
  const indexes = await client.listIndexes();
672
- const indexNames = (_b = (_a3 = indexes.indexes) == null ? void 0 : _a3.map((i) => i.name)) != null ? _b : [];
694
+ const indexNames = (_b = (_a2 = indexes.indexes) == null ? void 0 : _a2.map((i) => i.name)) != null ? _b : [];
673
695
  if (!indexNames.includes(indexName)) {
674
696
  return {
675
697
  healthy: false,
@@ -696,25 +718,13 @@ var init_PineconeProvider = __esm({
696
718
  };
697
719
  }
698
720
  async initialize() {
699
- var _a3, _b;
721
+ var _a2, _b;
700
722
  if (this.client) return;
701
723
  let key = this.apiKey || process.env.PINECONE_API_KEY || "";
702
724
  if (!key) {
703
- const licenseKey = process.env.RETRIVORA_LICENSE_KEY || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY;
725
+ const licenseKey = process.env.RETRIVORA_LICENSE_KEY;
704
726
  this.licenseKey = licenseKey;
705
- const jwtProjectId = (() => {
706
- if (!licenseKey) return void 0;
707
- try {
708
- const parts = licenseKey.split(".");
709
- if (parts.length >= 2) {
710
- const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
711
- return payload == null ? void 0 : payload.projectId;
712
- }
713
- } catch (e) {
714
- }
715
- return void 0;
716
- })();
717
- const projectId = process.env.RAG_PROJECT_ID || process.env.NEXT_PUBLIC_RAG_PROJECT_ID || jwtProjectId || this.projectId || "default";
727
+ const projectId = process.env.RAG_PROJECT_ID || process.env.NEXT_PUBLIC_RAG_PROJECT_ID || this.projectId || "default";
718
728
  this.projectId = projectId;
719
729
  const remoteConfig = await ConfigFetcher.fetchRemoteVectorConfig(projectId, licenseKey);
720
730
  if (remoteConfig) {
@@ -742,7 +752,7 @@ var init_PineconeProvider = __esm({
742
752
  this.client = new Pinecone({ apiKey: key });
743
753
  try {
744
754
  const indexes = await this.client.listIndexes();
745
- const names = (_b = (_a3 = indexes.indexes) == null ? void 0 : _a3.map((i) => i.name)) != null ? _b : [];
755
+ const names = (_b = (_a2 = indexes.indexes) == null ? void 0 : _a2.map((i) => i.name)) != null ? _b : [];
746
756
  if (!names.includes(this.indexName)) {
747
757
  console.warn(`[PineconeProvider] Target index "${this.indexName}" not listed. Proceeding with configured index name.`);
748
758
  }
@@ -761,7 +771,7 @@ var init_PineconeProvider = __esm({
761
771
  return namespace ? idx.namespace(namespace) : idx.namespace("");
762
772
  }
763
773
  async upsert(doc, namespace) {
764
- var _a3, _b;
774
+ var _a2, _b;
765
775
  if (!this.client) {
766
776
  if (!this.licenseKey) throw new Error("[PineconeProvider] Cannot execute vector operation: Missing API key and License key.");
767
777
  const res = await fetch(`${this.getControlPlaneUrl()}/api/v1/vectors/upsert`, {
@@ -771,7 +781,7 @@ var init_PineconeProvider = __esm({
771
781
  projectId: this.projectId,
772
782
  indexName: this.indexName,
773
783
  namespace: namespace || this.projectId,
774
- records: [{ id: String(doc.id), values: doc.vector, metadata: __spreadValues({ content: doc.content }, (_a3 = doc.metadata) != null ? _a3 : {}) }]
784
+ records: [{ id: String(doc.id), values: doc.vector, metadata: __spreadValues({ content: doc.content }, (_a2 = doc.metadata) != null ? _a2 : {}) }]
775
785
  })
776
786
  });
777
787
  if (!res.ok) throw new Error(`[PineconeProvider] Proxy upsert failed: ${await res.text()}`);
@@ -792,11 +802,11 @@ var init_PineconeProvider = __esm({
792
802
  if (!this.licenseKey) throw new Error("[PineconeProvider] Cannot execute vector operation: Missing API key and License key.");
793
803
  for (let i = 0; i < docs.length; i += BATCH) {
794
804
  const records = docs.slice(i, i + BATCH).map((d) => {
795
- var _a3;
805
+ var _a2;
796
806
  return {
797
807
  id: String(d.id),
798
808
  values: d.vector,
799
- metadata: __spreadValues({ content: d.content }, (_a3 = d.metadata) != null ? _a3 : {})
809
+ metadata: __spreadValues({ content: d.content }, (_a2 = d.metadata) != null ? _a2 : {})
800
810
  };
801
811
  });
802
812
  const res = await fetch(`${this.getControlPlaneUrl()}/api/v1/vectors/upsert`, {
@@ -816,18 +826,18 @@ var init_PineconeProvider = __esm({
816
826
  const targetIdx = await this.getActiveIndex(namespace);
817
827
  for (let i = 0; i < docs.length; i += BATCH) {
818
828
  const records = docs.slice(i, i + BATCH).map((d) => {
819
- var _a3;
829
+ var _a2;
820
830
  return {
821
831
  id: String(d.id),
822
832
  values: d.vector,
823
- metadata: __spreadValues({ content: d.content }, (_a3 = d.metadata) != null ? _a3 : {})
833
+ metadata: __spreadValues({ content: d.content }, (_a2 = d.metadata) != null ? _a2 : {})
824
834
  };
825
835
  });
826
836
  await targetIdx.upsert({ records });
827
837
  }
828
838
  }
829
839
  async query(vector, topK, namespace, filter) {
830
- var _a3, _b;
840
+ var _a2, _b;
831
841
  const pineconeFilter = this.sanitizeFilter(filter);
832
842
  if (!this.client) {
833
843
  if (!this.licenseKey) throw new Error("[PineconeProvider] Cannot execute vector operation: Missing API key and License key.");
@@ -845,11 +855,11 @@ var init_PineconeProvider = __esm({
845
855
  });
846
856
  if (!res.ok) throw new Error(`[PineconeProvider] Proxy query failed: ${await res.text()}`);
847
857
  const data = await res.json();
848
- return ((_a3 = data.matches) != null ? _a3 : []).map((m) => {
849
- var _a4, _b2;
858
+ return ((_a2 = data.matches) != null ? _a2 : []).map((m) => {
859
+ var _a3, _b2;
850
860
  return {
851
861
  id: m.id,
852
- score: (_a4 = m.score) != null ? _a4 : 0,
862
+ score: (_a3 = m.score) != null ? _a3 : 0,
853
863
  content: ((_b2 = m.metadata) == null ? void 0 : _b2.content) || "",
854
864
  metadata: m.metadata
855
865
  };
@@ -862,10 +872,10 @@ var init_PineconeProvider = __esm({
862
872
  includeMetadata: true
863
873
  }, Object.keys(pineconeFilter).length > 0 ? { filter: pineconeFilter } : {}));
864
874
  return ((_b = result.matches) != null ? _b : []).map((m) => {
865
- var _a4, _b2;
875
+ var _a3, _b2;
866
876
  return {
867
877
  id: m.id,
868
- score: (_a4 = m.score) != null ? _a4 : 0,
878
+ score: (_a3 = m.score) != null ? _a3 : 0,
869
879
  content: ((_b2 = m.metadata) == null ? void 0 : _b2.content) || "",
870
880
  metadata: m.metadata
871
881
  };
@@ -908,13 +918,13 @@ var init_PostgreSQLProvider = __esm({
908
918
  init_BaseVectorProvider();
909
919
  PostgreSQLProvider = class extends BaseVectorProvider {
910
920
  constructor(config) {
911
- var _a3;
921
+ var _a2;
912
922
  super(config);
913
923
  this.tableName = this.indexName.replace(/[^a-z0-9_]/gi, "_");
914
924
  const opts = config.options;
915
925
  if (!opts.connectionString) throw new Error("[PostgreSQLProvider] options.connectionString is required");
916
926
  this.connectionString = opts.connectionString;
917
- this.dimensions = (_a3 = opts.dimensions) != null ? _a3 : 1536;
927
+ this.dimensions = (_a2 = opts.dimensions) != null ? _a2 : 1536;
918
928
  }
919
929
  static getValidator() {
920
930
  return {
@@ -995,7 +1005,7 @@ var init_PostgreSQLProvider = __esm({
995
1005
  }
996
1006
  }
997
1007
  async upsert(doc, namespace = "") {
998
- var _a3;
1008
+ var _a2;
999
1009
  const vectorLiteral = `[${doc.vector.join(",")}]`;
1000
1010
  await this.pool.query(
1001
1011
  `INSERT INTO ${this.tableName} (id, namespace, content, metadata, embedding)
@@ -1005,7 +1015,7 @@ var init_PostgreSQLProvider = __esm({
1005
1015
  content = EXCLUDED.content,
1006
1016
  metadata = EXCLUDED.metadata,
1007
1017
  embedding = EXCLUDED.embedding`,
1008
- [doc.id, namespace, doc.content, JSON.stringify((_a3 = doc.metadata) != null ? _a3 : {}), vectorLiteral]
1018
+ [doc.id, namespace, doc.content, JSON.stringify((_a2 = doc.metadata) != null ? _a2 : {}), vectorLiteral]
1009
1019
  );
1010
1020
  }
1011
1021
  async batchUpsert(docs, namespace = "") {
@@ -1018,9 +1028,9 @@ var init_PostgreSQLProvider = __esm({
1018
1028
  const batch = docs.slice(i, i + BATCH_SIZE);
1019
1029
  const values = [];
1020
1030
  const valuePlaceholders = batch.map((doc, idx) => {
1021
- var _a3;
1031
+ var _a2;
1022
1032
  const offset = idx * 5;
1023
- values.push(doc.id, namespace, doc.content, JSON.stringify((_a3 = doc.metadata) != null ? _a3 : {}), `[${doc.vector.join(",")}]`);
1033
+ values.push(doc.id, namespace, doc.content, JSON.stringify((_a2 = doc.metadata) != null ? _a2 : {}), `[${doc.vector.join(",")}]`);
1024
1034
  return `($${offset + 1}, $${offset + 2}, $${offset + 3}, $${offset + 4}, $${offset + 5}::vector)`;
1025
1035
  }).join(", ");
1026
1036
  const query = `
@@ -1103,8 +1113,8 @@ var init_PostgreSQLProvider = __esm({
1103
1113
 
1104
1114
  // src/utils/synonyms.ts
1105
1115
  function resolveMetadataValue(meta, uiKey) {
1106
- var _a3;
1107
- const synonyms = (_a3 = FIELD_SYNONYMS[uiKey]) != null ? _a3 : [];
1116
+ var _a2;
1117
+ const synonyms = (_a2 = FIELD_SYNONYMS[uiKey]) != null ? _a2 : [];
1108
1118
  const keys = Object.keys(meta);
1109
1119
  const systemKeys = ["namespace", "filename", "filesize", "filetype", "docid", "uploadedat", "dimension", "chunkindex"];
1110
1120
  let match = keys.find((k) => k.toLowerCase() === uiKey.toLowerCase());
@@ -1191,14 +1201,14 @@ var init_MultiTablePostgresProvider = __esm({
1191
1201
  init_synonyms();
1192
1202
  MultiTablePostgresProvider = class extends BaseVectorProvider {
1193
1203
  constructor(config) {
1194
- var _a3, _b, _c;
1204
+ var _a2, _b, _c;
1195
1205
  super(config);
1196
1206
  const opts = config.options || {};
1197
1207
  if (!opts.connectionString) {
1198
1208
  throw new Error("[MultiTablePostgresProvider] options.connectionString is required");
1199
1209
  }
1200
1210
  this.connectionString = opts.connectionString;
1201
- this.dimensions = (_a3 = opts.dimensions) != null ? _a3 : 768;
1211
+ this.dimensions = (_a2 = opts.dimensions) != null ? _a2 : 768;
1202
1212
  this.tables = [];
1203
1213
  const rawSearchFields = (_c = (_b = opts.searchFields) != null ? _b : process.env.VECTOR_DB_SEARCH_FIELDS) != null ? _c : ["name", "product_name", "productname", "title"];
1204
1214
  this.searchFields = typeof rawSearchFields === "string" ? rawSearchFields.split(",").map((f) => f.trim()).filter(Boolean) : rawSearchFields;
@@ -1237,7 +1247,6 @@ var init_MultiTablePostgresProvider = __esm({
1237
1247
  this.tables = res.rows.map((r) => r.table_name);
1238
1248
  if (this.tables.length === 0) {
1239
1249
  console.warn('[MultiTablePostgresProvider] No tables with "embedding" columns found in the database.');
1240
- } else {
1241
1250
  }
1242
1251
  } finally {
1243
1252
  client.release();
@@ -1253,11 +1262,11 @@ var init_MultiTablePostgresProvider = __esm({
1253
1262
  * Batch upsert documents by dynamically provisioning tables and columns based on CSV headers.
1254
1263
  */
1255
1264
  async batchUpsert(docs, namespace = "") {
1256
- var _a3;
1265
+ var _a2;
1257
1266
  if (docs.length === 0) return;
1258
1267
  const docsByFile = {};
1259
1268
  for (const doc of docs) {
1260
- const fileName = ((_a3 = doc.metadata) == null ? void 0 : _a3.fileName) || this.uploadTable;
1269
+ const fileName = ((_a2 = doc.metadata) == null ? void 0 : _a2.fileName) || this.uploadTable;
1261
1270
  if (!docsByFile[fileName]) docsByFile[fileName] = [];
1262
1271
  docsByFile[fileName].push(doc);
1263
1272
  }
@@ -1310,11 +1319,11 @@ var init_MultiTablePostgresProvider = __esm({
1310
1319
  const headerColumns = csvHeaders.map((h) => `"${h}"`).join(", ");
1311
1320
  const allColumns = `id, ${headerColumns ? headerColumns + ", " : ""}namespace, content, metadata, embedding`;
1312
1321
  const valuePlaceholders = batch.map((doc, idx) => {
1313
- var _a4, _b;
1322
+ var _a3, _b;
1314
1323
  const offset = idx * (5 + csvHeaders.length);
1315
1324
  values.push(doc.id);
1316
1325
  for (const h of csvHeaders) {
1317
- values.push(String(((_a4 = doc.metadata) == null ? void 0 : _a4[h]) || ""));
1326
+ values.push(String(((_a3 = doc.metadata) == null ? void 0 : _a3[h]) || ""));
1318
1327
  }
1319
1328
  values.push(namespace, doc.content, JSON.stringify((_b = doc.metadata) != null ? _b : {}), `[${doc.vector.join(",")}]`);
1320
1329
  const docPlaceholders = [];
@@ -1353,7 +1362,7 @@ var init_MultiTablePostgresProvider = __esm({
1353
1362
  * Query all configured tables and merge results, sorted by cosine similarity score.
1354
1363
  */
1355
1364
  async query(vector, topK, _namespace, _filter) {
1356
- var _a3;
1365
+ var _a2;
1357
1366
  if (!this.pool) {
1358
1367
  throw new Error("[MultiTablePostgresProvider] Provider not initialized. Call initialize() first.");
1359
1368
  }
@@ -1381,11 +1390,11 @@ var init_MultiTablePostgresProvider = __esm({
1381
1390
  const filterParams = [];
1382
1391
  if (metadataFilters && Object.keys(metadataFilters).length > 0) {
1383
1392
  const conditions = Object.entries(metadataFilters).map(([key, val]) => {
1384
- var _a5;
1393
+ var _a4;
1385
1394
  filterParams.push(String(val));
1386
1395
  const baseOffset = queryText && dynamicKeywordQuery ? 2 : 1;
1387
1396
  const paramIdx = baseOffset + filterParams.length;
1388
- const synonyms = (_a5 = FIELD_SYNONYMS[key]) != null ? _a5 : [];
1397
+ const synonyms = (_a4 = FIELD_SYNONYMS[key]) != null ? _a4 : [];
1389
1398
  const keysToCheck = [key, ...synonyms];
1390
1399
  const coalesceExprs = keysToCheck.flatMap((k) => [
1391
1400
  `metadata->>'${k}'`,
@@ -1452,7 +1461,7 @@ var init_MultiTablePostgresProvider = __esm({
1452
1461
  }
1453
1462
  const tableResults = [];
1454
1463
  for (const row of result.rows) {
1455
- const _a4 = row, { hybrid_score, id } = _a4, rest = __objRest(_a4, ["hybrid_score", "id"]);
1464
+ const _a3 = row, { hybrid_score, id } = _a3, rest = __objRest(_a3, ["hybrid_score", "id"]);
1456
1465
  delete rest.embedding;
1457
1466
  delete rest.vector_score;
1458
1467
  delete rest.keyword_score;
@@ -1481,10 +1490,10 @@ var init_MultiTablePostgresProvider = __esm({
1481
1490
  }
1482
1491
  allResults.sort((a, b) => b.score - a.score);
1483
1492
  if (allResults.length === 0) return [];
1484
- const bestMatchTable = (_a3 = allResults[0].metadata) == null ? void 0 : _a3.source_table;
1493
+ const bestMatchTable = (_a2 = allResults[0].metadata) == null ? void 0 : _a2.source_table;
1485
1494
  const finalSorted = allResults.filter((res) => {
1486
- var _a4;
1487
- return ((_a4 = res.metadata) == null ? void 0 : _a4.source_table) === bestMatchTable;
1495
+ var _a3;
1496
+ return ((_a3 = res.metadata) == null ? void 0 : _a3.source_table) === bestMatchTable;
1488
1497
  });
1489
1498
  return finalSorted.slice(0, Math.max(topK, 15));
1490
1499
  }
@@ -1882,14 +1891,14 @@ var init_QdrantProvider = __esm({
1882
1891
  * Samples points from the collection to discover available payload fields.
1883
1892
  */
1884
1893
  async discoverSchema() {
1885
- var _a3;
1894
+ var _a2;
1886
1895
  try {
1887
1896
  const { data } = await this.http.post(`/collections/${this.indexName}/points/scroll`, {
1888
1897
  limit: 20,
1889
1898
  with_payload: true,
1890
1899
  with_vector: false
1891
1900
  });
1892
- const points = ((_a3 = data.result) == null ? void 0 : _a3.points) || [];
1901
+ const points = ((_a2 = data.result) == null ? void 0 : _a2.points) || [];
1893
1902
  const keys = /* @__PURE__ */ new Set();
1894
1903
  for (const point of points) {
1895
1904
  const payload = point.payload || {};
@@ -1915,11 +1924,11 @@ var init_QdrantProvider = __esm({
1915
1924
  * Ensures the collection exists. Creates it if missing.
1916
1925
  */
1917
1926
  async ensureCollection() {
1918
- var _a3;
1927
+ var _a2;
1919
1928
  try {
1920
1929
  await this.http.get(`/collections/${this.indexName}`);
1921
1930
  } catch (err) {
1922
- if (axios4.isAxiosError(err) && ((_a3 = err.response) == null ? void 0 : _a3.status) === 404) {
1931
+ if (axios4.isAxiosError(err) && ((_a2 = err.response) == null ? void 0 : _a2.status) === 404) {
1923
1932
  const opts = this.config.options;
1924
1933
  const dimensionsForCreate = opts.dimensions || 1536;
1925
1934
  await this.http.put(`/collections/${this.indexName}`, {
@@ -1937,7 +1946,7 @@ var init_QdrantProvider = __esm({
1937
1946
  * Ensures that a payload field has an index.
1938
1947
  */
1939
1948
  async ensureIndex(fieldName, schema = "keyword") {
1940
- var _a3;
1949
+ var _a2;
1941
1950
  let fullPath = fieldName;
1942
1951
  if (!this.isFlatPayload && !fieldName.includes(".") && fieldName !== "namespace" && fieldName !== this.contentField) {
1943
1952
  fullPath = `${this.metadataField}.${fieldName}`;
@@ -1949,7 +1958,7 @@ var init_QdrantProvider = __esm({
1949
1958
  });
1950
1959
  } catch (err) {
1951
1960
  let status;
1952
- if (axios4.isAxiosError(err)) status = (_a3 = err.response) == null ? void 0 : _a3.status;
1961
+ if (axios4.isAxiosError(err)) status = (_a2 = err.response) == null ? void 0 : _a2.status;
1953
1962
  if (status === 409) return;
1954
1963
  console.warn(`[QdrantProvider] \u26A0\uFE0F Could not ensure index for "${fullPath}":`, err instanceof Error ? err.message : String(err));
1955
1964
  }
@@ -1978,7 +1987,7 @@ var init_QdrantProvider = __esm({
1978
1987
  await this.http.put(`/collections/${this.indexName}/points`, payload);
1979
1988
  }
1980
1989
  async query(vector, topK, namespace, _filter) {
1981
- var _a3;
1990
+ var _a2;
1982
1991
  const must = [];
1983
1992
  if (namespace) {
1984
1993
  must.push({ key: "namespace", match: { value: namespace } });
@@ -2000,7 +2009,7 @@ var init_QdrantProvider = __esm({
2000
2009
  limit: topK,
2001
2010
  with_payload: true,
2002
2011
  params: {
2003
- hnsw_ef: ((_a3 = this.config.options) == null ? void 0 : _a3.efSearch) || Math.max(topK * 20, 128),
2012
+ hnsw_ef: ((_a2 = this.config.options) == null ? void 0 : _a2.efSearch) || Math.max(topK * 20, 128),
2004
2013
  exact: false
2005
2014
  },
2006
2015
  filter: must.length > 0 ? { must } : void 0
@@ -2095,12 +2104,12 @@ var init_ChromaDBProvider = __esm({
2095
2104
  * Get or create the ChromaDB collection.
2096
2105
  */
2097
2106
  async initialize() {
2098
- var _a3;
2107
+ var _a2;
2099
2108
  try {
2100
2109
  const { data } = await this.http.get(`/api/v1/collections/${this.indexName}`);
2101
2110
  this.collectionId = data.id;
2102
2111
  } catch (err) {
2103
- if (axios5.isAxiosError(err) && ((_a3 = err.response) == null ? void 0 : _a3.status) === 404) {
2112
+ if (axios5.isAxiosError(err) && ((_a2 = err.response) == null ? void 0 : _a2.status) === 404) {
2104
2113
  const { data } = await this.http.post("/api/v1/collections", {
2105
2114
  name: this.indexName
2106
2115
  });
@@ -2318,7 +2327,7 @@ var init_WeaviateProvider = __esm({
2318
2327
  await this.http.post("/v1/batch/objects", payload);
2319
2328
  }
2320
2329
  async query(vector, topK, namespace, _filter) {
2321
- var _a3, _b;
2330
+ var _a2, _b;
2322
2331
  const queryText = _filter == null ? void 0 : _filter.queryText;
2323
2332
  const sanitizedFilter = this.sanitizeFilter(_filter);
2324
2333
  const searchParams = queryText ? `hybrid: { query: ${JSON.stringify(queryText)}, alpha: 0.5 }` : `nearVector: { vector: ${JSON.stringify(vector)} }`;
@@ -2344,7 +2353,7 @@ var init_WeaviateProvider = __esm({
2344
2353
  `
2345
2354
  };
2346
2355
  const { data } = await this.http.post("/v1/graphql", graphqlQuery);
2347
- const results = ((_b = (_a3 = data.data) == null ? void 0 : _a3.Get) == null ? void 0 : _b[this.indexName]) || [];
2356
+ const results = ((_b = (_a2 = data.data) == null ? void 0 : _a2.Get) == null ? void 0 : _b[this.indexName]) || [];
2348
2357
  return results.map((res) => ({
2349
2358
  id: res["_additional"].id,
2350
2359
  score: 1 - res["_additional"].distance,
@@ -2426,21 +2435,21 @@ var init_UniversalVectorProvider = __esm({
2426
2435
  }
2427
2436
  }
2428
2437
  async initialize() {
2429
- var _a3;
2438
+ var _a2;
2430
2439
  this.http = axios8.create({
2431
2440
  baseURL: this.opts.baseUrl,
2432
2441
  headers: __spreadValues({
2433
2442
  "Content-Type": "application/json"
2434
2443
  }, this.opts.headers),
2435
- timeout: (_a3 = this.opts.timeout) != null ? _a3 : 3e4
2444
+ timeout: (_a2 = this.opts.timeout) != null ? _a2 : 3e4
2436
2445
  });
2437
2446
  if (!await this.ping()) {
2438
2447
  throw new Error(`[UniversalVectorProvider] Failed to connect to ${this.opts.baseUrl}`);
2439
2448
  }
2440
2449
  }
2441
2450
  async upsert(doc, namespace) {
2442
- var _a3, _b, _c;
2443
- const endpoint = (_a3 = this.opts.upsertEndpoint) != null ? _a3 : "/upsert";
2451
+ var _a2, _b, _c;
2452
+ const endpoint = (_a2 = this.opts.upsertEndpoint) != null ? _a2 : "/upsert";
2444
2453
  const template = (_b = this.opts.upsertTemplate) != null ? _b : JSON.stringify({
2445
2454
  id: "{{id}}",
2446
2455
  vector: "{{vector}}",
@@ -2473,8 +2482,8 @@ var init_UniversalVectorProvider = __esm({
2473
2482
  }
2474
2483
  }
2475
2484
  async query(vector, topK, namespace, filter) {
2476
- var _a3, _b;
2477
- const endpoint = (_a3 = this.opts.queryEndpoint) != null ? _a3 : "/query";
2485
+ var _a2, _b;
2486
+ const endpoint = (_a2 = this.opts.queryEndpoint) != null ? _a2 : "/query";
2478
2487
  const template = (_b = this.opts.queryTemplate) != null ? _b : JSON.stringify({
2479
2488
  vector: "{{vector}}",
2480
2489
  limit: "{{topK}}",
@@ -2500,9 +2509,9 @@ var init_UniversalVectorProvider = __esm({
2500
2509
  );
2501
2510
  }
2502
2511
  return results.map((item) => {
2503
- var _a4, _b2, _c, _d, _e, _f, _g2;
2512
+ var _a3, _b2, _c, _d, _e, _f, _g2;
2504
2513
  return {
2505
- id: item[(_a4 = this.opts.queryIdField) != null ? _a4 : "id"],
2514
+ id: item[(_a3 = this.opts.queryIdField) != null ? _a3 : "id"],
2506
2515
  score: (_c = item[(_b2 = this.opts.queryScoreField) != null ? _b2 : "score"]) != null ? _c : 0,
2507
2516
  content: (_e = item[(_d = this.opts.queryContentField) != null ? _d : "content"]) != null ? _e : "",
2508
2517
  metadata: (_g2 = item[(_f = this.opts.queryMetadataField) != null ? _f : "metadata"]) != null ? _g2 : {}
@@ -2515,8 +2524,8 @@ var init_UniversalVectorProvider = __esm({
2515
2524
  }
2516
2525
  }
2517
2526
  async delete(id, namespace) {
2518
- var _a3, _b;
2519
- const endpoint = (_a3 = this.opts.deleteEndpoint) != null ? _a3 : "/delete";
2527
+ var _a2, _b;
2528
+ const endpoint = (_a2 = this.opts.deleteEndpoint) != null ? _a2 : "/delete";
2520
2529
  const template = (_b = this.opts.deleteTemplate) != null ? _b : JSON.stringify({
2521
2530
  id: "{{id}}",
2522
2531
  namespace: "{{namespace}}"
@@ -2534,8 +2543,8 @@ var init_UniversalVectorProvider = __esm({
2534
2543
  }
2535
2544
  }
2536
2545
  async deleteNamespace(namespace) {
2537
- var _a3;
2538
- const endpoint = (_a3 = this.opts.deleteNamespaceEndpoint) != null ? _a3 : "/delete-namespace";
2546
+ var _a2;
2547
+ const endpoint = (_a2 = this.opts.deleteNamespaceEndpoint) != null ? _a2 : "/delete-namespace";
2539
2548
  try {
2540
2549
  await this.http.post(endpoint, { namespace });
2541
2550
  } catch (error) {
@@ -2545,9 +2554,9 @@ var init_UniversalVectorProvider = __esm({
2545
2554
  }
2546
2555
  }
2547
2556
  async ping() {
2548
- var _a3;
2557
+ var _a2;
2549
2558
  try {
2550
- const endpoint = (_a3 = this.opts.pingEndpoint) != null ? _a3 : "/health";
2559
+ const endpoint = (_a2 = this.opts.pingEndpoint) != null ? _a2 : "/health";
2551
2560
  const response = await this.http.get(endpoint, { timeout: 5e3 });
2552
2561
  return response.status >= 200 && response.status < 300;
2553
2562
  } catch (e) {
@@ -2687,13 +2696,13 @@ var LicenseValidationError = class extends RetrivoraError {
2687
2696
  }
2688
2697
  };
2689
2698
  function wrapError(err, defaultCode, defaultMessage) {
2690
- var _a3;
2699
+ var _a2;
2691
2700
  if (err instanceof RetrivoraError) {
2692
2701
  return err;
2693
2702
  }
2694
2703
  const error = err;
2695
2704
  const message = (error == null ? void 0 : error.message) || defaultMessage || String(err);
2696
- const status = (error == null ? void 0 : error.status) || (error == null ? void 0 : error.statusCode) || ((_a3 = error == null ? void 0 : error.response) == null ? void 0 : _a3.status);
2705
+ const status = (error == null ? void 0 : error.status) || (error == null ? void 0 : error.statusCode) || ((_a2 = error == null ? void 0 : error.response) == null ? void 0 : _a2.status);
2697
2706
  const code = error == null ? void 0 : error.code;
2698
2707
  if (status === 429 || /rate[- ]?limit/i.test(message) || code === "RATE_LIMIT_EXCEEDED") {
2699
2708
  return new RateLimitException(message, err);
@@ -2980,8 +2989,8 @@ function getRuntimeConfig() {
2980
2989
  return _runtimeConfig;
2981
2990
  }
2982
2991
  function readString(env, name) {
2983
- var _a3;
2984
- const value = (_a3 = env[name]) == null ? void 0 : _a3.trim();
2992
+ var _a2;
2993
+ const value = (_a2 = env[name]) == null ? void 0 : _a2.trim();
2985
2994
  return value ? value : void 0;
2986
2995
  }
2987
2996
  function readNumber(env, name, fallback) {
@@ -2994,8 +3003,8 @@ function readNumber(env, name, fallback) {
2994
3003
  return parsed;
2995
3004
  }
2996
3005
  function readEnum(env, name, fallback, allowed) {
2997
- var _a3;
2998
- const value = (_a3 = readString(env, name)) != null ? _a3 : fallback;
3006
+ var _a2;
3007
+ const value = (_a2 = readString(env, name)) != null ? _a2 : fallback;
2999
3008
  if (allowed.includes(value)) {
3000
3009
  return value;
3001
3010
  }
@@ -3005,58 +3014,52 @@ function getRagConfig(baseConfig, env = process.env) {
3005
3014
  return getEnvConfig(env, baseConfig);
3006
3015
  }
3007
3016
  function getEnvConfig(env = process.env, base) {
3008
- 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, _Lb, _Mb, _Nb;
3009
- 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;
3010
- const jwtProjectId = (() => {
3011
- if (!licenseKey) return void 0;
3012
- try {
3013
- const parts = licenseKey.split(".");
3014
- if (parts.length >= 2) {
3015
- const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
3016
- return payload == null ? void 0 : payload.projectId;
3017
- }
3018
- } catch (e) {
3019
- }
3020
- return void 0;
3021
- })();
3022
- const projectId = (_i = (_h = (_g2 = (_f = (_e = readString(env, "RAG_PROJECT_ID")) != null ? _e : readString(env, "NEXT_PUBLIC_RAG_PROJECT_ID")) != null ? _f : readString(env, "NEXT_PUBLIC_PROJECT_ID")) != null ? _g2 : base == null ? void 0 : base.projectId) != null ? _h : jwtProjectId) != null ? _i : "default";
3023
- const telemetryEnabled = readString(env, "TELEMETRY_ENABLED") === "true" || readString(env, "NEXT_PUBLIC_TELEMETRY_ENABLED") === "true" || ((_j = base == null ? void 0 : base.telemetry) == null ? void 0 : _j.enabled) || Boolean(licenseKey);
3017
+ var _a2, _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;
3018
+ const licenseKey = (_c = (_b = (_a2 = readString(env, "RAG_LICENSE_KEY")) != null ? _a2 : readString(env, "RETRIVORA_LICENSE_KEY")) != null ? _b : (
3019
+ // Fix SEC-4: NEXT_PUBLIC_RETRIVORA_LICENSE_KEY is NOT included here.
3020
+ // That variable is inlined into the browser bundle by Next.js at build time
3021
+ // and must never be used as a server-side secret source. Developers who
3022
+ // previously relied on this should migrate to RETRIVORA_LICENSE_KEY.
3023
+ readString(env, "LICENSE_KEY")
3024
+ )) != null ? _c : base == null ? void 0 : base.licenseKey;
3025
+ const projectId = (_g2 = (_f = (_e = (_d = readString(env, "RAG_PROJECT_ID")) != null ? _d : readString(env, "NEXT_PUBLIC_RAG_PROJECT_ID")) != null ? _e : readString(env, "NEXT_PUBLIC_PROJECT_ID")) != null ? _f : base == null ? void 0 : base.projectId) != null ? _g2 : "default";
3026
+ const telemetryEnabled = readString(env, "TELEMETRY_ENABLED") === "true" || readString(env, "NEXT_PUBLIC_TELEMETRY_ENABLED") === "true" || ((_h = base == null ? void 0 : base.telemetry) == null ? void 0 : _h.enabled) || Boolean(licenseKey);
3024
3027
  const vectorProvider = readEnum(env, "VECTOR_DB_PROVIDER", "pinecone", VECTOR_DB_PROVIDERS);
3025
3028
  const embeddingDimensions = readNumber(env, "EMBEDDING_DIMENSIONS", 768);
3026
3029
  const vectorDbOptions = {};
3027
3030
  if (vectorProvider === "pinecone") {
3028
- vectorDbOptions.apiKey = (_o = (_n = (_m = readString(env, "PINECONE_API_KEY")) != null ? _m : (_l = (_k = base == null ? void 0 : base.vectorDb) == null ? void 0 : _k.options) == null ? void 0 : _l.apiKey) != null ? _n : process.env.PINECONE_API_KEY) != null ? _o : "";
3029
- vectorDbOptions.indexName = (_v = (_u = (_t = (_q = readString(env, "PINECONE_INDEX")) != null ? _q : (_p = base == null ? void 0 : base.vectorDb) == null ? void 0 : _p.indexName) != null ? _t : (_s = (_r = base == null ? void 0 : base.vectorDb) == null ? void 0 : _r.options) == null ? void 0 : _s.indexName) != null ? _u : process.env.PINECONE_INDEX) != null ? _v : "retrivora-free";
3031
+ vectorDbOptions.apiKey = (_l = (_k = readString(env, "PINECONE_API_KEY")) != null ? _k : (_j = (_i = base == null ? void 0 : base.vectorDb) == null ? void 0 : _i.options) == null ? void 0 : _j.apiKey) != null ? _l : "";
3032
+ vectorDbOptions.indexName = (_r = (_q = (_n = readString(env, "PINECONE_INDEX")) != null ? _n : (_m = base == null ? void 0 : base.vectorDb) == null ? void 0 : _m.indexName) != null ? _q : (_p = (_o = base == null ? void 0 : base.vectorDb) == null ? void 0 : _o.options) == null ? void 0 : _p.indexName) != null ? _r : "retrivora-free";
3030
3033
  } else if (vectorProvider === "pgvector" || vectorProvider === "postgresql") {
3031
- vectorDbOptions.connectionString = (_A = (_z = (_w = readString(env, "PGVECTOR_CONNECTION_STRING")) != null ? _w : readString(env, "POSTGRES_URL")) != null ? _z : (_y = (_x = base == null ? void 0 : base.vectorDb) == null ? void 0 : _x.options) == null ? void 0 : _y.connectionString) != null ? _A : "";
3032
- vectorDbOptions.tables = (_F = (_C = (_B = readString(env, "VECTOR_DB_TABLES")) != null ? _B : readString(env, "POSTGRES_TABLES")) == null ? void 0 : _C.split(",").map((t) => t.trim())) != null ? _F : (_E = (_D = base == null ? void 0 : base.vectorDb) == null ? void 0 : _D.options) == null ? void 0 : _E.tables;
3033
- vectorDbOptions.searchFields = (_J = (_G = readString(env, "POSTGRES_SEARCH_FIELDS")) == null ? void 0 : _G.split(",").map((f) => f.trim())) != null ? _J : (_I = (_H = base == null ? void 0 : base.vectorDb) == null ? void 0 : _H.options) == null ? void 0 : _I.searchFields;
3034
+ vectorDbOptions.connectionString = (_w = (_v = (_s = readString(env, "PGVECTOR_CONNECTION_STRING")) != null ? _s : readString(env, "POSTGRES_URL")) != null ? _v : (_u = (_t = base == null ? void 0 : base.vectorDb) == null ? void 0 : _t.options) == null ? void 0 : _u.connectionString) != null ? _w : "";
3035
+ vectorDbOptions.tables = (_B = (_y = (_x = readString(env, "VECTOR_DB_TABLES")) != null ? _x : readString(env, "POSTGRES_TABLES")) == null ? void 0 : _y.split(",").map((t) => t.trim())) != null ? _B : (_A = (_z = base == null ? void 0 : base.vectorDb) == null ? void 0 : _z.options) == null ? void 0 : _A.tables;
3036
+ vectorDbOptions.searchFields = (_F = (_C = readString(env, "POSTGRES_SEARCH_FIELDS")) == null ? void 0 : _C.split(",").map((f) => f.trim())) != null ? _F : (_E = (_D = base == null ? void 0 : base.vectorDb) == null ? void 0 : _D.options) == null ? void 0 : _E.searchFields;
3034
3037
  vectorDbOptions.dimensions = embeddingDimensions;
3035
3038
  } else if (vectorProvider === "mongodb") {
3036
- vectorDbOptions.uri = (_N = (_M = readString(env, "MONGODB_URI")) != null ? _M : (_L = (_K = base == null ? void 0 : base.vectorDb) == null ? void 0 : _K.options) == null ? void 0 : _L.uri) != null ? _N : "";
3037
- vectorDbOptions.database = (_R = (_Q = readString(env, "MONGODB_DB")) != null ? _Q : (_P = (_O = base == null ? void 0 : base.vectorDb) == null ? void 0 : _O.options) == null ? void 0 : _P.database) != null ? _R : "";
3038
- vectorDbOptions.collection = (_V = (_U = readString(env, "MONGODB_COLLECTION")) != null ? _U : (_T = (_S = base == null ? void 0 : base.vectorDb) == null ? void 0 : _S.options) == null ? void 0 : _T.collection) != null ? _V : "";
3039
- vectorDbOptions.indexName = (_$ = (__ = (_X = readString(env, "MONGODB_INDEX_NAME")) != null ? _X : (_W = base == null ? void 0 : base.vectorDb) == null ? void 0 : _W.indexName) != null ? __ : (_Z = (_Y = base == null ? void 0 : base.vectorDb) == null ? void 0 : _Y.options) == null ? void 0 : _Z.indexName) != null ? _$ : "vector_index";
3039
+ vectorDbOptions.uri = (_J = (_I = readString(env, "MONGODB_URI")) != null ? _I : (_H = (_G = base == null ? void 0 : base.vectorDb) == null ? void 0 : _G.options) == null ? void 0 : _H.uri) != null ? _J : "";
3040
+ vectorDbOptions.database = (_N = (_M = readString(env, "MONGODB_DB")) != null ? _M : (_L = (_K = base == null ? void 0 : base.vectorDb) == null ? void 0 : _K.options) == null ? void 0 : _L.database) != null ? _N : "";
3041
+ vectorDbOptions.collection = (_R = (_Q = readString(env, "MONGODB_COLLECTION")) != null ? _Q : (_P = (_O = base == null ? void 0 : base.vectorDb) == null ? void 0 : _O.options) == null ? void 0 : _P.collection) != null ? _R : "";
3042
+ vectorDbOptions.indexName = (_X = (_W = (_T = readString(env, "MONGODB_INDEX_NAME")) != null ? _T : (_S = base == null ? void 0 : base.vectorDb) == null ? void 0 : _S.indexName) != null ? _W : (_V = (_U = base == null ? void 0 : base.vectorDb) == null ? void 0 : _U.options) == null ? void 0 : _V.indexName) != null ? _X : "vector_index";
3040
3043
  } else if (vectorProvider === "qdrant") {
3041
- vectorDbOptions.baseUrl = (_da = (_ca = readString(env, "QDRANT_URL")) != null ? _ca : (_ba = (_aa = base == null ? void 0 : base.vectorDb) == null ? void 0 : _aa.options) == null ? void 0 : _ba.baseUrl) != null ? _da : "http://localhost:6333";
3042
- vectorDbOptions.apiKey = (_ga = readString(env, "QDRANT_API_KEY")) != null ? _ga : (_fa = (_ea = base == null ? void 0 : base.vectorDb) == null ? void 0 : _ea.options) == null ? void 0 : _fa.apiKey;
3044
+ vectorDbOptions.baseUrl = (_$ = (__ = readString(env, "QDRANT_URL")) != null ? __ : (_Z = (_Y = base == null ? void 0 : base.vectorDb) == null ? void 0 : _Y.options) == null ? void 0 : _Z.baseUrl) != null ? _$ : "http://localhost:6333";
3045
+ vectorDbOptions.apiKey = (_ca = readString(env, "QDRANT_API_KEY")) != null ? _ca : (_ba = (_aa = base == null ? void 0 : base.vectorDb) == null ? void 0 : _aa.options) == null ? void 0 : _ba.apiKey;
3043
3046
  vectorDbOptions.dimensions = embeddingDimensions;
3044
3047
  } else if (vectorProvider === "milvus") {
3045
- vectorDbOptions.baseUrl = (_ha = readString(env, "MILVUS_URL")) != null ? _ha : "http://localhost:19530";
3048
+ vectorDbOptions.baseUrl = (_da = readString(env, "MILVUS_URL")) != null ? _da : "http://localhost:19530";
3046
3049
  vectorDbOptions.apiKey = readString(env, "MILVUS_API_KEY");
3047
3050
  } else if (vectorProvider === "chromadb") {
3048
- vectorDbOptions.baseUrl = (_ia = readString(env, "CHROMADB_URL")) != null ? _ia : "http://localhost:8000";
3051
+ vectorDbOptions.baseUrl = (_ea = readString(env, "CHROMADB_URL")) != null ? _ea : "http://localhost:8000";
3049
3052
  } else if (vectorProvider === "weaviate") {
3050
- vectorDbOptions.baseUrl = (_ja = readString(env, "WEAVIATE_URL")) != null ? _ja : "http://localhost:8080";
3053
+ vectorDbOptions.baseUrl = (_fa = readString(env, "WEAVIATE_URL")) != null ? _fa : "http://localhost:8080";
3051
3054
  vectorDbOptions.apiKey = readString(env, "WEAVIATE_API_KEY");
3052
3055
  } else if (vectorProvider === "redis") {
3053
- vectorDbOptions.baseUrl = (_ka = readString(env, "REDIS_URL")) != null ? _ka : "";
3056
+ vectorDbOptions.baseUrl = (_ga = readString(env, "REDIS_URL")) != null ? _ga : "";
3054
3057
  vectorDbOptions.apiKey = readString(env, "REDIS_API_KEY");
3055
3058
  } else if (vectorProvider === "rest") {
3056
- vectorDbOptions.baseUrl = (_la = readString(env, "VECTOR_DB_REST_URL")) != null ? _la : "";
3059
+ vectorDbOptions.baseUrl = (_ha = readString(env, "VECTOR_DB_REST_URL")) != null ? _ha : "";
3057
3060
  vectorDbOptions.headers = readString(env, "VECTOR_DB_REST_API_KEY") ? { "api-key": readString(env, "VECTOR_DB_REST_API_KEY") } : {};
3058
3061
  } else if (vectorProvider === "universal_rest") {
3059
- vectorDbOptions.baseUrl = (_na = (_ma = readString(env, "VECTOR_BASE_URL")) != null ? _ma : readString(env, "VECTOR_DB_REST_URL")) != null ? _na : "";
3062
+ vectorDbOptions.baseUrl = (_ja = (_ia = readString(env, "VECTOR_BASE_URL")) != null ? _ia : readString(env, "VECTOR_DB_REST_URL")) != null ? _ja : "";
3060
3063
  vectorDbOptions.profile = readString(env, "VECTOR_UNIVERSAL_PROFILE");
3061
3064
  vectorDbOptions.headers = readString(env, "VECTOR_DB_REST_API_KEY") ? { Authorization: `Bearer ${readString(env, "VECTOR_DB_REST_API_KEY")}` } : {};
3062
3065
  }
@@ -3075,8 +3078,8 @@ function getEnvConfig(env = process.env, base) {
3075
3078
  // Anthropic needs a separate embedding provider; key kept for completeness
3076
3079
  gemini: readString(env, "GEMINI_API_KEY"),
3077
3080
  ollama: void 0,
3078
- universal_rest: (_oa = readString(env, "EMBEDDING_API_KEY")) != null ? _oa : readString(env, "OPENAI_API_KEY"),
3079
- custom: (_pa = readString(env, "EMBEDDING_API_KEY")) != null ? _pa : readString(env, "OPENAI_API_KEY")
3081
+ universal_rest: (_ka = readString(env, "EMBEDDING_API_KEY")) != null ? _ka : readString(env, "OPENAI_API_KEY"),
3082
+ custom: (_la = readString(env, "EMBEDDING_API_KEY")) != null ? _la : readString(env, "OPENAI_API_KEY")
3080
3083
  };
3081
3084
  const DEFAULT_MODEL_BY_PROVIDER = {
3082
3085
  openai: "gpt-4o",
@@ -3098,27 +3101,27 @@ function getEnvConfig(env = process.env, base) {
3098
3101
  })();
3099
3102
  const tierBasedLLMModel = isFreeTier2 ? "llama-3.1-8b-instant" : "llama-3.3-70b-versatile";
3100
3103
  const tierBasedEmbeddingModel = isFreeTier2 ? "text-embedding-004" : "text-embedding-004";
3101
- const controlPlaneUrl = (_qa = readString(env, "RETRIVORA_CONTROL_PLANE_URL")) != null ? _qa : readString(env, "NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL");
3104
+ const controlPlaneUrl = (_ma = readString(env, "RETRIVORA_CONTROL_PLANE_URL")) != null ? _ma : readString(env, "NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL");
3102
3105
  const defaultGatewayUrl = controlPlaneUrl ? `${controlPlaneUrl.replace(/\/$/, "")}/api/v1` : "https://llm.retrivora.com/api/v1";
3103
3106
  const rt = _runtimeConfig;
3104
3107
  const defaultLlmProvider = "universal_rest";
3105
- const llmProvider = (_ta = (_sa = readEnum(env, "LLM_PROVIDER", defaultLlmProvider, LLM_PROVIDERS)) != null ? _sa : (_ra = base == null ? void 0 : base.llm) == null ? void 0 : _ra.provider) != null ? _ta : defaultLlmProvider;
3106
- const llmBaseUrl = (_ya = (_xa = (_wa = (_ua = readString(env, "LITELLM_BASE_URL")) != null ? _ua : readString(env, "LLM_BASE_URL")) != null ? _wa : (_va = base == null ? void 0 : base.llm) == null ? void 0 : _va.baseUrl) != null ? _xa : rt == null ? void 0 : rt.llmBaseUrl) != null ? _ya : defaultGatewayUrl;
3107
- const llmModel = (_Ca = (_Ba = (_Aa = readString(env, "LLM_MODEL")) != null ? _Aa : (_za = base == null ? void 0 : base.llm) == null ? void 0 : _za.model) != null ? _Ba : rt == null ? void 0 : rt.llmModel) != null ? _Ca : tierBasedLLMModel;
3108
- const llmApiKey = (_Ga = (_Fa = (_Da = readString(env, "LITELLM_MASTER_KEY")) != null ? _Da : rt == null ? void 0 : rt.litellmApiKey) != null ? _Fa : (_Ea = base == null ? void 0 : base.llm) == null ? void 0 : _Ea.apiKey) != null ? _Ga : licenseKey;
3109
- const llmProfile = (_Ka = (_Ja = readString(env, "LLM_UNIVERSAL_PROFILE")) != null ? _Ja : (_Ia = (_Ha = base == null ? void 0 : base.llm) == null ? void 0 : _Ha.options) == null ? void 0 : _Ia.profile) != null ? _Ka : "litellm";
3108
+ const llmProvider = (_pa = (_oa = readEnum(env, "LLM_PROVIDER", defaultLlmProvider, LLM_PROVIDERS)) != null ? _oa : (_na = base == null ? void 0 : base.llm) == null ? void 0 : _na.provider) != null ? _pa : defaultLlmProvider;
3109
+ const llmBaseUrl = (_ua = (_ta = (_sa = (_qa = readString(env, "LITELLM_BASE_URL")) != null ? _qa : readString(env, "LLM_BASE_URL")) != null ? _sa : (_ra = base == null ? void 0 : base.llm) == null ? void 0 : _ra.baseUrl) != null ? _ta : rt == null ? void 0 : rt.llmBaseUrl) != null ? _ua : defaultGatewayUrl;
3110
+ const llmModel = (_ya = (_xa = (_wa = readString(env, "LLM_MODEL")) != null ? _wa : (_va = base == null ? void 0 : base.llm) == null ? void 0 : _va.model) != null ? _xa : rt == null ? void 0 : rt.llmModel) != null ? _ya : tierBasedLLMModel;
3111
+ const llmApiKey = (_Ca = (_Ba = (_za = readString(env, "LITELLM_MASTER_KEY")) != null ? _za : rt == null ? void 0 : rt.litellmApiKey) != null ? _Ba : (_Aa = base == null ? void 0 : base.llm) == null ? void 0 : _Aa.apiKey) != null ? _Ca : licenseKey;
3112
+ const llmProfile = (_Ga = (_Fa = readString(env, "LLM_UNIVERSAL_PROFILE")) != null ? _Fa : (_Ea = (_Da = base == null ? void 0 : base.llm) == null ? void 0 : _Da.options) == null ? void 0 : _Ea.profile) != null ? _Ga : "litellm";
3110
3113
  const defaultEmbeddingProvider = "universal_rest";
3111
- const embeddingProvider = (_Na = (_Ma = readEnum(env, "EMBEDDING_PROVIDER", defaultEmbeddingProvider, EMBEDDING_PROVIDERS)) != null ? _Ma : (_La = base == null ? void 0 : base.embedding) == null ? void 0 : _La.provider) != null ? _Na : defaultEmbeddingProvider;
3112
- const embeddingBaseUrl = (_Ua = (_Ta = (_Sa = (_Ra = (_Pa = (_Oa = readString(env, "LITELLM_BASE_URL")) != null ? _Oa : readString(env, "EMBEDDING_BASE_URL")) != null ? _Pa : readString(env, "LLM_BASE_URL")) != null ? _Ra : (_Qa = base == null ? void 0 : base.embedding) == null ? void 0 : _Qa.baseUrl) != null ? _Sa : rt == null ? void 0 : rt.embeddingBaseUrl) != null ? _Ta : rt == null ? void 0 : rt.llmBaseUrl) != null ? _Ua : defaultGatewayUrl;
3113
- const embeddingModel = (_Ya = (_Xa = (_Wa = readString(env, "EMBEDDING_MODEL")) != null ? _Wa : (_Va = base == null ? void 0 : base.embedding) == null ? void 0 : _Va.model) != null ? _Xa : rt == null ? void 0 : rt.embeddingModel) != null ? _Ya : tierBasedEmbeddingModel;
3114
- const embeddingApiKey = (_ab = (_$a = (_Za = readString(env, "LITELLM_MASTER_KEY")) != null ? _Za : rt == null ? void 0 : rt.litellmApiKey) != null ? _$a : (__a = base == null ? void 0 : base.embedding) == null ? void 0 : __a.apiKey) != null ? _ab : licenseKey;
3115
- const embeddingProfile = (_eb = (_db = readString(env, "EMBEDDING_UNIVERSAL_PROFILE")) != null ? _db : (_cb = (_bb = base == null ? void 0 : base.embedding) == null ? void 0 : _bb.options) == null ? void 0 : _cb.profile) != null ? _eb : "litellm";
3114
+ const embeddingProvider = (_Ja = (_Ia = readEnum(env, "EMBEDDING_PROVIDER", defaultEmbeddingProvider, EMBEDDING_PROVIDERS)) != null ? _Ia : (_Ha = base == null ? void 0 : base.embedding) == null ? void 0 : _Ha.provider) != null ? _Ja : defaultEmbeddingProvider;
3115
+ const embeddingBaseUrl = (_Qa = (_Pa = (_Oa = (_Na = (_La = (_Ka = readString(env, "LITELLM_BASE_URL")) != null ? _Ka : readString(env, "EMBEDDING_BASE_URL")) != null ? _La : readString(env, "LLM_BASE_URL")) != null ? _Na : (_Ma = base == null ? void 0 : base.embedding) == null ? void 0 : _Ma.baseUrl) != null ? _Oa : rt == null ? void 0 : rt.embeddingBaseUrl) != null ? _Pa : rt == null ? void 0 : rt.llmBaseUrl) != null ? _Qa : defaultGatewayUrl;
3116
+ const embeddingModel = (_Ua = (_Ta = (_Sa = readString(env, "EMBEDDING_MODEL")) != null ? _Sa : (_Ra = base == null ? void 0 : base.embedding) == null ? void 0 : _Ra.model) != null ? _Ta : rt == null ? void 0 : rt.embeddingModel) != null ? _Ua : tierBasedEmbeddingModel;
3117
+ const embeddingApiKey = (_Ya = (_Xa = (_Va = readString(env, "LITELLM_MASTER_KEY")) != null ? _Va : rt == null ? void 0 : rt.litellmApiKey) != null ? _Xa : (_Wa = base == null ? void 0 : base.embedding) == null ? void 0 : _Wa.apiKey) != null ? _Ya : licenseKey;
3118
+ const embeddingProfile = (_ab = (_$a = readString(env, "EMBEDDING_UNIVERSAL_PROFILE")) != null ? _$a : (__a = (_Za = base == null ? void 0 : base.embedding) == null ? void 0 : _Za.options) == null ? void 0 : __a.profile) != null ? _ab : "litellm";
3116
3119
  return __spreadProps(__spreadValues({
3117
3120
  projectId,
3118
3121
  licenseKey,
3119
3122
  vectorDb: {
3120
3123
  provider: vectorProvider,
3121
- indexName: (_gb = (_fb = readString(env, "VECTOR_DB_INDEX")) != null ? _fb : vectorDbOptions.indexName) != null ? _gb : "rag-index",
3124
+ indexName: (_cb = (_bb = readString(env, "VECTOR_DB_INDEX")) != null ? _bb : vectorDbOptions.indexName) != null ? _cb : "rag-index",
3122
3125
  options: vectorDbOptions
3123
3126
  },
3124
3127
  llm: {
@@ -3126,8 +3129,8 @@ function getEnvConfig(env = process.env, base) {
3126
3129
  model: llmModel,
3127
3130
  apiKey: llmApiKey,
3128
3131
  baseUrl: llmBaseUrl,
3129
- systemPrompt: (_hb = readString(env, "LLM_SYSTEM_PROMPT")) != null ? _hb : rt == null ? void 0 : rt.systemPrompt,
3130
- maxTokens: readNumber(env, "LLM_MAX_TOKENS", (_ib = rt == null ? void 0 : rt.maxTokens) != null ? _ib : 4096),
3132
+ systemPrompt: (_db = readString(env, "LLM_SYSTEM_PROMPT")) != null ? _db : rt == null ? void 0 : rt.systemPrompt,
3133
+ maxTokens: readNumber(env, "LLM_MAX_TOKENS", (_eb = rt == null ? void 0 : rt.maxTokens) != null ? _eb : 4096),
3131
3134
  temperature: readNumber(env, "LLM_TEMPERATURE", 0.7),
3132
3135
  options: {
3133
3136
  profile: llmProfile,
@@ -3148,30 +3151,30 @@ function getEnvConfig(env = process.env, base) {
3148
3151
  }
3149
3152
  },
3150
3153
  ui: {
3151
- title: (_kb = (_jb = readString(env, "NEXT_PUBLIC_UI_TITLE")) != null ? _jb : readString(env, "UI_TITLE")) != null ? _kb : "AI Assistant",
3152
- subtitle: (_mb = (_lb = readString(env, "NEXT_PUBLIC_UI_SUBTITLE")) != null ? _lb : readString(env, "UI_SUBTITLE")) != null ? _mb : "Powered by RAG",
3153
- primaryColor: (_ob = (_nb = readString(env, "NEXT_PUBLIC_PRIMARY_COLOR")) != null ? _nb : readString(env, "UI_PRIMARY_COLOR")) != null ? _ob : "#10b981",
3154
- accentColor: (_qb = (_pb = readString(env, "NEXT_PUBLIC_ACCENT_COLOR")) != null ? _pb : readString(env, "UI_ACCENT_COLOR")) != null ? _qb : "#3b82f6",
3155
- logoUrl: (_rb = readString(env, "NEXT_PUBLIC_LOGO_URL")) != null ? _rb : readString(env, "UI_LOGO_URL"),
3156
- placeholder: (_tb = (_sb = readString(env, "NEXT_PUBLIC_PLACEHOLDER")) != null ? _sb : readString(env, "UI_PLACEHOLDER")) != null ? _tb : "Ask me anything\u2026",
3157
- showSources: ((_vb = (_ub = readString(env, "NEXT_PUBLIC_SHOW_SOURCES")) != null ? _ub : readString(env, "UI_SHOW_SOURCES")) != null ? _vb : "true") !== "false",
3158
- 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.",
3159
- visualStyle: (_zb = (_yb = readString(env, "NEXT_PUBLIC_UI_VISUAL_STYLE")) != null ? _yb : readString(env, "UI_VISUAL_STYLE")) != null ? _zb : "glass",
3160
- borderRadius: (_Bb = (_Ab = readString(env, "NEXT_PUBLIC_UI_BORDER_RADIUS")) != null ? _Ab : readString(env, "UI_BORDER_RADIUS")) != null ? _Bb : "xl",
3161
- allowUpload: ((_Db = (_Cb = readString(env, "NEXT_PUBLIC_ALLOW_UPLOAD")) != null ? _Cb : readString(env, "UI_ALLOW_UPLOAD")) != null ? _Db : "false") === "true"
3154
+ title: (_gb = (_fb = readString(env, "NEXT_PUBLIC_UI_TITLE")) != null ? _fb : readString(env, "UI_TITLE")) != null ? _gb : "AI Assistant",
3155
+ subtitle: (_ib = (_hb = readString(env, "NEXT_PUBLIC_UI_SUBTITLE")) != null ? _hb : readString(env, "UI_SUBTITLE")) != null ? _ib : "Powered by RAG",
3156
+ primaryColor: (_kb = (_jb = readString(env, "NEXT_PUBLIC_PRIMARY_COLOR")) != null ? _jb : readString(env, "UI_PRIMARY_COLOR")) != null ? _kb : "#10b981",
3157
+ accentColor: (_mb = (_lb = readString(env, "NEXT_PUBLIC_ACCENT_COLOR")) != null ? _lb : readString(env, "UI_ACCENT_COLOR")) != null ? _mb : "#3b82f6",
3158
+ logoUrl: (_nb = readString(env, "NEXT_PUBLIC_LOGO_URL")) != null ? _nb : readString(env, "UI_LOGO_URL"),
3159
+ placeholder: (_pb = (_ob = readString(env, "NEXT_PUBLIC_PLACEHOLDER")) != null ? _ob : readString(env, "UI_PLACEHOLDER")) != null ? _pb : "Ask me anything\u2026",
3160
+ showSources: ((_rb = (_qb = readString(env, "NEXT_PUBLIC_SHOW_SOURCES")) != null ? _qb : readString(env, "UI_SHOW_SOURCES")) != null ? _rb : "true") !== "false",
3161
+ welcomeMessage: (_tb = (_sb = readString(env, "NEXT_PUBLIC_WELCOME_MESSAGE")) != null ? _sb : readString(env, "UI_WELCOME_MESSAGE")) != null ? _tb : "Hello! I'm your AI assistant. Ask me anything about your documents.",
3162
+ visualStyle: (_vb = (_ub = readString(env, "NEXT_PUBLIC_UI_VISUAL_STYLE")) != null ? _ub : readString(env, "UI_VISUAL_STYLE")) != null ? _vb : "glass",
3163
+ borderRadius: (_xb = (_wb = readString(env, "NEXT_PUBLIC_UI_BORDER_RADIUS")) != null ? _wb : readString(env, "UI_BORDER_RADIUS")) != null ? _xb : "xl",
3164
+ allowUpload: ((_zb = (_yb = readString(env, "NEXT_PUBLIC_ALLOW_UPLOAD")) != null ? _yb : readString(env, "UI_ALLOW_UPLOAD")) != null ? _zb : "false") === "true"
3162
3165
  },
3163
3166
  rag: {
3164
- topK: readNumber(env, "RAG_TOP_K", (_Eb = rt == null ? void 0 : rt.topK) != null ? _Eb : 5),
3167
+ topK: readNumber(env, "RAG_TOP_K", (_Ab = rt == null ? void 0 : rt.topK) != null ? _Ab : 5),
3165
3168
  scoreThreshold: readNumber(env, "RAG_SCORE_THRESHOLD", 0),
3166
- chunkSize: readNumber(env, "RAG_CHUNK_SIZE", (_Fb = rt == null ? void 0 : rt.chunkSize) != null ? _Fb : 1e3),
3167
- chunkOverlap: readNumber(env, "RAG_CHUNK_OVERLAP", (_Gb = rt == null ? void 0 : rt.chunkOverlap) != null ? _Gb : 200),
3168
- filterableFields: (_Hb = readString(env, "RAG_FILTERABLE_FIELDS")) == null ? void 0 : _Hb.split(",").map((f) => f.trim()),
3169
+ chunkSize: readNumber(env, "RAG_CHUNK_SIZE", (_Bb = rt == null ? void 0 : rt.chunkSize) != null ? _Bb : 1e3),
3170
+ chunkOverlap: readNumber(env, "RAG_CHUNK_OVERLAP", (_Cb = rt == null ? void 0 : rt.chunkOverlap) != null ? _Cb : 200),
3171
+ filterableFields: (_Db = readString(env, "RAG_FILTERABLE_FIELDS")) == null ? void 0 : _Db.split(",").map((f) => f.trim()),
3169
3172
  // Query pipeline toggles — read from .env.local
3170
3173
  useQueryTransformation: readString(env, "RAG_USE_QUERY_TRANSFORMATION") === "true",
3171
3174
  useReranking: readString(env, "RAG_USE_RERANKING") === "true",
3172
3175
  useGraphRetrieval: readString(env, "RAG_USE_GRAPH_RETRIEVAL") === "true",
3173
- architecture: (_Ib = readString(env, "RAG_ARCHITECTURE")) != null ? _Ib : "simple",
3174
- chunkingStrategy: (_Jb = readString(env, "RAG_CHUNKING_STRATEGY")) != null ? _Jb : "recursive",
3176
+ architecture: (_Eb = readString(env, "RAG_ARCHITECTURE")) != null ? _Eb : "simple",
3177
+ chunkingStrategy: (_Fb = readString(env, "RAG_CHUNKING_STRATEGY")) != null ? _Fb : "recursive",
3175
3178
  uiMapping: (() => {
3176
3179
  const raw = readString(env, "RAG_UI_MAPPING");
3177
3180
  if (!raw) return void 0;
@@ -3184,7 +3187,7 @@ function getEnvConfig(env = process.env, base) {
3184
3187
  },
3185
3188
  telemetry: {
3186
3189
  enabled: telemetryEnabled,
3187
- url: (_Nb = (_Mb = (_Kb = readString(env, "TELEMETRY_URL")) != null ? _Kb : readString(env, "NEXT_PUBLIC_TELEMETRY_URL")) != null ? _Mb : (_Lb = base == null ? void 0 : base.telemetry) == null ? void 0 : _Lb.url) != null ? _Nb : "https://www.retrivora.com/api/telemetry"
3190
+ url: (_Jb = (_Ib = (_Gb = readString(env, "TELEMETRY_URL")) != null ? _Gb : readString(env, "NEXT_PUBLIC_TELEMETRY_URL")) != null ? _Ib : (_Hb = base == null ? void 0 : base.telemetry) == null ? void 0 : _Hb.url) != null ? _Jb : "https://www.retrivora.com/api/telemetry"
3188
3191
  }
3189
3192
  }, readString(env, "GRAPH_DB_PROVIDER") ? {
3190
3193
  graphDb: {
@@ -3197,8 +3200,8 @@ function getEnvConfig(env = process.env, base) {
3197
3200
  }
3198
3201
  } : {}), {
3199
3202
  mcpServers: (() => {
3200
- var _a4;
3201
- const raw = (_a4 = readString(env, "MCP_SERVERS")) != null ? _a4 : readString(env, "NEXT_PUBLIC_MCP_SERVERS");
3203
+ var _a3;
3204
+ const raw = (_a3 = readString(env, "MCP_SERVERS")) != null ? _a3 : readString(env, "NEXT_PUBLIC_MCP_SERVERS");
3202
3205
  if (!raw) return void 0;
3203
3206
  try {
3204
3207
  return JSON.parse(raw);
@@ -3244,10 +3247,10 @@ var ConfigResolver = class {
3244
3247
  * fallback behavior.
3245
3248
  */
3246
3249
  static resolveUniversal(hostConfig, env = process.env) {
3247
- var _a3;
3250
+ var _a2;
3248
3251
  if (!hostConfig) return this.resolve(void 0, env);
3249
3252
  const normalized = __spreadProps(__spreadValues({}, hostConfig), {
3250
- vectorDb: (_a3 = hostConfig.vectorDb) != null ? _a3 : hostConfig.vectorDatabase,
3253
+ vectorDb: (_a2 = hostConfig.vectorDb) != null ? _a2 : hostConfig.vectorDatabase,
3251
3254
  rag: this.mergeRetrievalWorkflow(hostConfig.rag, hostConfig.retrieval, hostConfig.workflow)
3252
3255
  });
3253
3256
  return this.resolve(normalized, env);
@@ -3267,11 +3270,11 @@ var ConfigResolver = class {
3267
3270
  }
3268
3271
  }
3269
3272
  static mergeRetrievalWorkflow(rag, retrieval, workflow) {
3270
- var _a3, _b, _c, _d, _e, _f;
3273
+ var _a2, _b, _c, _d, _e, _f;
3271
3274
  if (!rag && !retrieval && !workflow) return void 0;
3272
3275
  const normalized = __spreadValues({}, rag != null ? rag : {});
3273
3276
  if (retrieval) {
3274
- normalized.topK = (_a3 = retrieval.topK) != null ? _a3 : normalized.topK;
3277
+ normalized.topK = (_a2 = retrieval.topK) != null ? _a2 : normalized.topK;
3275
3278
  normalized.scoreThreshold = (_b = retrieval.scoreThreshold) != null ? _b : normalized.scoreThreshold;
3276
3279
  normalized.useReranking = (_c = retrieval.useReranking) != null ? _c : normalized.useReranking;
3277
3280
  if (retrieval.strategy === "hybrid") normalized.architecture = (_d = normalized.architecture) != null ? _d : "hybrid";
@@ -3399,8 +3402,8 @@ var OpenAIProvider = class {
3399
3402
  };
3400
3403
  }
3401
3404
  async chat(messages, context, options) {
3402
- var _a3, _b, _c, _d, _e, _f, _g2, _h, _i;
3403
- const basePrompt = (_b = (_a3 = options == null ? void 0 : options.systemPrompt) != null ? _a3 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Answer questions based on the provided context.";
3405
+ var _a2, _b, _c, _d, _e, _f, _g2, _h, _i;
3406
+ const basePrompt = (_b = (_a2 = options == null ? void 0 : options.systemPrompt) != null ? _a2 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Answer questions based on the provided context.";
3404
3407
  const systemMessage = {
3405
3408
  role: "system",
3406
3409
  content: buildSystemContent(basePrompt, context)
@@ -3424,8 +3427,8 @@ var OpenAIProvider = class {
3424
3427
  }
3425
3428
  chatStream(messages, context, options) {
3426
3429
  return __asyncGenerator(this, null, function* () {
3427
- var _a3, _b, _c, _d, _e, _f, _g2, _h;
3428
- const basePrompt = (_b = (_a3 = options == null ? void 0 : options.systemPrompt) != null ? _a3 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Answer questions based on the provided context.";
3430
+ var _a2, _b, _c, _d, _e, _f, _g2, _h;
3431
+ const basePrompt = (_b = (_a2 = options == null ? void 0 : options.systemPrompt) != null ? _a2 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Answer questions based on the provided context.";
3429
3432
  const systemMessage = {
3430
3433
  role: "system",
3431
3434
  content: buildSystemContent(basePrompt, context)
@@ -3472,8 +3475,8 @@ var OpenAIProvider = class {
3472
3475
  return results[0];
3473
3476
  }
3474
3477
  async batchEmbed(texts, options) {
3475
- var _a3, _b, _c, _d, _e;
3476
- const model = (_c = (_b = options == null ? void 0 : options.model) != null ? _b : (_a3 = this.embeddingConfig) == null ? void 0 : _a3.model) != null ? _c : "text-embedding-3-small";
3478
+ var _a2, _b, _c, _d, _e;
3479
+ const model = (_c = (_b = options == null ? void 0 : options.model) != null ? _b : (_a2 = this.embeddingConfig) == null ? void 0 : _a2.model) != null ? _c : "text-embedding-3-small";
3477
3480
  const apiKey = (_e = (_d = this.embeddingConfig) == null ? void 0 : _d.apiKey) != null ? _e : this.llmConfig.apiKey;
3478
3481
  const client = apiKey !== this.llmConfig.apiKey ? new OpenAI({ apiKey }) : this.client;
3479
3482
  const response = await client.embeddings.create({ model, input: texts });
@@ -3532,11 +3535,7 @@ var AnthropicProvider = class {
3532
3535
  try {
3533
3536
  const { default: Anthropic2 } = await import("@anthropic-ai/sdk");
3534
3537
  const client = new Anthropic2({ apiKey });
3535
- await client.messages.create({
3536
- model: modelName,
3537
- max_tokens: 10,
3538
- messages: [{ role: "user", content: "ping" }]
3539
- });
3538
+ await client.models.list();
3540
3539
  return { healthy: true, provider: "anthropic", capabilities: { model: modelName }, timestamp };
3541
3540
  } catch (error) {
3542
3541
  return {
@@ -3550,8 +3549,8 @@ var AnthropicProvider = class {
3550
3549
  };
3551
3550
  }
3552
3551
  async chat(messages, context, options) {
3553
- var _a3, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k;
3554
- const basePrompt = (_b = (_a3 = options == null ? void 0 : options.systemPrompt) != null ? _a3 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Use the context below to answer the user's question accurately.";
3552
+ var _a2, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k;
3553
+ const basePrompt = (_b = (_a2 = options == null ? void 0 : options.systemPrompt) != null ? _a2 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Use the context below to answer the user's question accurately.";
3555
3554
  const system = buildSystemContent(basePrompt, context);
3556
3555
  const anthropicMessages = messages.map((m) => ({
3557
3556
  role: m.role === "assistant" ? "assistant" : "user",
@@ -3589,8 +3588,8 @@ var AnthropicProvider = class {
3589
3588
  }
3590
3589
  chatStream(messages, context, options) {
3591
3590
  return __asyncGenerator(this, null, function* () {
3592
- var _a3, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k;
3593
- const basePrompt = (_b = (_a3 = options == null ? void 0 : options.systemPrompt) != null ? _a3 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Use the context below to answer the user's question accurately.";
3591
+ var _a2, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k;
3592
+ const basePrompt = (_b = (_a2 = options == null ? void 0 : options.systemPrompt) != null ? _a2 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Use the context below to answer the user's question accurately.";
3594
3593
  const system = buildSystemContent(basePrompt, context);
3595
3594
  const anthropicMessages = messages.map((m) => ({
3596
3595
  role: m.role === "assistant" ? "assistant" : "user",
@@ -3674,8 +3673,8 @@ var AnthropicProvider = class {
3674
3673
  import axios from "axios";
3675
3674
  var OllamaProvider = class {
3676
3675
  constructor(llmConfig, embeddingConfig) {
3677
- var _a3, _b, _c;
3678
- const rawBaseURL = ((_a3 = llmConfig.baseUrl) != null ? _a3 : "http://localhost:11434").replace(/\/+$/, "");
3676
+ var _a2, _b, _c;
3677
+ const rawBaseURL = ((_a2 = llmConfig.baseUrl) != null ? _a2 : "http://localhost:11434").replace(/\/+$/, "");
3679
3678
  const baseURL = rawBaseURL.replace(/\/(?:api\/v1|v1|api)$/i, "");
3680
3679
  const timeout = Number((_b = llmConfig.options) == null ? void 0 : _b.timeout) || 3e5;
3681
3680
  const headers = ((_c = llmConfig.options) == null ? void 0 : _c.headers) || {};
@@ -3708,8 +3707,8 @@ var OllamaProvider = class {
3708
3707
  const baseUrl = config.baseUrl || "http://localhost:11434";
3709
3708
  const modelName = config.model;
3710
3709
  try {
3711
- const axios11 = (await import("axios")).default;
3712
- const { data } = await axios11.get(`${baseUrl}/api/tags`);
3710
+ const axios10 = (await import("axios")).default;
3711
+ const { data } = await axios10.get(`${baseUrl}/api/tags`);
3713
3712
  const models = data.models || [];
3714
3713
  const hasModel = models.some((m) => m.name === modelName || m.name.startsWith(`${modelName}:`));
3715
3714
  return {
@@ -3735,8 +3734,8 @@ var OllamaProvider = class {
3735
3734
  };
3736
3735
  }
3737
3736
  async chat(messages, context, options) {
3738
- var _a3, _b, _c, _d, _e, _f;
3739
- const basePrompt = (_b = (_a3 = options == null ? void 0 : options.systemPrompt) != null ? _a3 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Use the provided context to answer the user's question.";
3737
+ var _a2, _b, _c, _d, _e, _f;
3738
+ const basePrompt = (_b = (_a2 = options == null ? void 0 : options.systemPrompt) != null ? _a2 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Use the provided context to answer the user's question.";
3740
3739
  const system = buildSystemContent(basePrompt, context);
3741
3740
  const { data } = await this.http.post("/api/chat", {
3742
3741
  model: this.llmConfig.model,
@@ -3754,8 +3753,8 @@ var OllamaProvider = class {
3754
3753
  }
3755
3754
  chatStream(messages, context, options) {
3756
3755
  return __asyncGenerator(this, null, function* () {
3757
- var _a3, _b, _c, _d, _e, _f, _g2, _h;
3758
- const basePrompt = (_b = (_a3 = options == null ? void 0 : options.systemPrompt) != null ? _a3 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Use the provided context to answer the user's question.";
3756
+ var _a2, _b, _c, _d, _e, _f, _g2, _h;
3757
+ const basePrompt = (_b = (_a2 = options == null ? void 0 : options.systemPrompt) != null ? _a2 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Use the provided context to answer the user's question.";
3759
3758
  const system = buildSystemContent(basePrompt, context);
3760
3759
  const response = yield new __await(this.http.post("/api/chat", {
3761
3760
  model: this.llmConfig.model,
@@ -3813,8 +3812,8 @@ var OllamaProvider = class {
3813
3812
  });
3814
3813
  }
3815
3814
  async embed(text, options) {
3816
- var _a3, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k;
3817
- const model = (_c = (_b = options == null ? void 0 : options.model) != null ? _b : (_a3 = this.embeddingConfig) == null ? void 0 : _a3.model) != null ? _c : "nomic-embed-text";
3815
+ var _a2, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k;
3816
+ const model = (_c = (_b = options == null ? void 0 : options.model) != null ? _b : (_a2 = this.embeddingConfig) == null ? void 0 : _a2.model) != null ? _c : "nomic-embed-text";
3818
3817
  const baseURL = (_f = (_e = (_d = this.embeddingConfig) == null ? void 0 : _d.baseUrl) != null ? _e : this.llmConfig.baseUrl) != null ? _f : "http://localhost:11434";
3819
3818
  const client = baseURL !== ((_g2 = this.llmConfig.baseUrl) != null ? _g2 : "http://localhost:11434") ? axios.create({ baseURL, timeout: 6e4 }) : this.http;
3820
3819
  let prompt = text;
@@ -3915,9 +3914,9 @@ var GeminiProvider = class {
3915
3914
  static getHealthChecker() {
3916
3915
  return {
3917
3916
  async check(config) {
3918
- var _a3, _b;
3917
+ var _a2, _b;
3919
3918
  const timestamp = Date.now();
3920
- const apiKey = (_b = (_a3 = config.apiKey) != null ? _a3 : process.env.GOOGLE_GENAI_API_KEY) != null ? _b : "";
3919
+ const apiKey = (_b = (_a2 = config.apiKey) != null ? _a2 : process.env.GOOGLE_GENAI_API_KEY) != null ? _b : "";
3921
3920
  const modelName = sanitizeModel(config.model);
3922
3921
  try {
3923
3922
  const { GoogleGenerativeAI: GoogleGenerativeAI2 } = await import("@google/generative-ai");
@@ -3947,16 +3946,16 @@ var GeminiProvider = class {
3947
3946
  /** Resolve the embedding client — uses a separate client when the embedding
3948
3947
  * API key differs from the LLM API key. */
3949
3948
  get embeddingClient() {
3950
- var _a3;
3951
- if (((_a3 = this.embeddingConfig) == null ? void 0 : _a3.apiKey) && this.embeddingConfig.apiKey !== this.llmConfig.apiKey) {
3949
+ var _a2;
3950
+ if (((_a2 = this.embeddingConfig) == null ? void 0 : _a2.apiKey) && this.embeddingConfig.apiKey !== this.llmConfig.apiKey) {
3952
3951
  return buildClient(this.embeddingConfig.apiKey);
3953
3952
  }
3954
3953
  return this.client;
3955
3954
  }
3956
3955
  /** Resolve the embedding model to use, in order of specificity. */
3957
3956
  resolveEmbeddingModel(optionsModel) {
3958
- var _a3, _b;
3959
- return sanitizeModel((_b = optionsModel != null ? optionsModel : (_a3 = this.embeddingConfig) == null ? void 0 : _a3.model) != null ? _b : DEFAULT_EMBEDDING_MODEL);
3957
+ var _a2, _b;
3958
+ return sanitizeModel((_b = optionsModel != null ? optionsModel : (_a2 = this.embeddingConfig) == null ? void 0 : _a2.model) != null ? _b : DEFAULT_EMBEDDING_MODEL);
3960
3959
  }
3961
3960
  /**
3962
3961
  * Convert ChatMessage[] to the Gemini contents format.
@@ -3976,8 +3975,8 @@ var GeminiProvider = class {
3976
3975
  // ILLMProvider — chat
3977
3976
  // -------------------------------------------------------------------------
3978
3977
  async chat(messages, context, options) {
3979
- var _a3, _b, _c, _d, _e, _f;
3980
- const basePrompt = (_b = (_a3 = options == null ? void 0 : options.systemPrompt) != null ? _a3 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Answer questions based on the provided context.";
3978
+ var _a2, _b, _c, _d, _e, _f;
3979
+ const basePrompt = (_b = (_a2 = options == null ? void 0 : options.systemPrompt) != null ? _a2 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Answer questions based on the provided context.";
3981
3980
  const model = this.client.getGenerativeModel({
3982
3981
  model: this.llmConfig.model,
3983
3982
  systemInstruction: buildSystemContent(basePrompt, context)
@@ -3994,8 +3993,8 @@ var GeminiProvider = class {
3994
3993
  }
3995
3994
  chatStream(messages, context, options) {
3996
3995
  return __asyncGenerator(this, null, function* () {
3997
- var _a3, _b, _c, _d, _e, _f;
3998
- const basePrompt = (_b = (_a3 = options == null ? void 0 : options.systemPrompt) != null ? _a3 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Answer questions based on the provided context.";
3996
+ var _a2, _b, _c, _d, _e, _f;
3997
+ const basePrompt = (_b = (_a2 = options == null ? void 0 : options.systemPrompt) != null ? _a2 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Answer questions based on the provided context.";
3999
3998
  const model = this.client.getGenerativeModel({
4000
3999
  model: this.llmConfig.model,
4001
4000
  systemInstruction: buildSystemContent(basePrompt, context)
@@ -4030,11 +4029,11 @@ var GeminiProvider = class {
4030
4029
  // ILLMProvider — embeddings
4031
4030
  // -------------------------------------------------------------------------
4032
4031
  async embed(text, options) {
4033
- var _a3, _b;
4032
+ var _a2, _b;
4034
4033
  const content = applyPrefix(
4035
4034
  text,
4036
4035
  options == null ? void 0 : options.taskType,
4037
- (_a3 = this.embeddingConfig) == null ? void 0 : _a3.queryPrefix,
4036
+ (_a2 = this.embeddingConfig) == null ? void 0 : _a2.queryPrefix,
4038
4037
  (_b = this.embeddingConfig) == null ? void 0 : _b.documentPrefix
4039
4038
  );
4040
4039
  const modelName = this.resolveEmbeddingModel(options == null ? void 0 : options.model);
@@ -4051,7 +4050,7 @@ var GeminiProvider = class {
4051
4050
  const modelName = this.resolveEmbeddingModel(options == null ? void 0 : options.model);
4052
4051
  const model = this.embeddingClient.getGenerativeModel({ model: modelName });
4053
4052
  const requests = texts.map((text) => {
4054
- var _a3, _b;
4053
+ var _a2, _b;
4055
4054
  return {
4056
4055
  content: {
4057
4056
  role: "user",
@@ -4059,7 +4058,7 @@ var GeminiProvider = class {
4059
4058
  text: applyPrefix(
4060
4059
  text,
4061
4060
  options == null ? void 0 : options.taskType,
4062
- (_a3 = this.embeddingConfig) == null ? void 0 : _a3.queryPrefix,
4061
+ (_a2 = this.embeddingConfig) == null ? void 0 : _a2.queryPrefix,
4063
4062
  (_b = this.embeddingConfig) == null ? void 0 : _b.documentPrefix
4064
4063
  )
4065
4064
  }]
@@ -4076,8 +4075,8 @@ var GeminiProvider = class {
4076
4075
  throw err;
4077
4076
  });
4078
4077
  return response.embeddings.map((e) => {
4079
- var _a3;
4080
- return (_a3 = e.values) != null ? _a3 : [];
4078
+ var _a2;
4079
+ return (_a2 = e.values) != null ? _a2 : [];
4081
4080
  });
4082
4081
  }
4083
4082
  // -------------------------------------------------------------------------
@@ -4166,8 +4165,8 @@ var GroqProvider = class {
4166
4165
  };
4167
4166
  }
4168
4167
  async chat(messages, context, options) {
4169
- var _a3, _b, _c, _d, _e, _f, _g2, _h, _i;
4170
- const basePrompt = (_b = (_a3 = options == null ? void 0 : options.systemPrompt) != null ? _a3 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Answer questions based on the provided context.";
4168
+ var _a2, _b, _c, _d, _e, _f, _g2, _h, _i;
4169
+ const basePrompt = (_b = (_a2 = options == null ? void 0 : options.systemPrompt) != null ? _a2 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Answer questions based on the provided context.";
4171
4170
  const systemMessage = {
4172
4171
  role: "system",
4173
4172
  content: buildSystemContent(basePrompt, context)
@@ -4191,8 +4190,8 @@ var GroqProvider = class {
4191
4190
  }
4192
4191
  chatStream(messages, context, options) {
4193
4192
  return __asyncGenerator(this, null, function* () {
4194
- var _a3, _b, _c, _d, _e, _f, _g2, _h;
4195
- const basePrompt = (_b = (_a3 = options == null ? void 0 : options.systemPrompt) != null ? _a3 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Answer questions based on the provided context.";
4193
+ var _a2, _b, _c, _d, _e, _f, _g2, _h;
4194
+ const basePrompt = (_b = (_a2 = options == null ? void 0 : options.systemPrompt) != null ? _a2 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Answer questions based on the provided context.";
4196
4195
  const systemMessage = {
4197
4196
  role: "system",
4198
4197
  content: buildSystemContent(basePrompt, context)
@@ -4326,8 +4325,8 @@ var QwenProvider = class {
4326
4325
  };
4327
4326
  }
4328
4327
  async chat(messages, context, options) {
4329
- var _a3, _b, _c, _d, _e, _f, _g2, _h, _i;
4330
- const basePrompt = (_b = (_a3 = options == null ? void 0 : options.systemPrompt) != null ? _a3 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Answer questions based on the provided context.";
4328
+ var _a2, _b, _c, _d, _e, _f, _g2, _h, _i;
4329
+ const basePrompt = (_b = (_a2 = options == null ? void 0 : options.systemPrompt) != null ? _a2 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Answer questions based on the provided context.";
4331
4330
  const systemMessage = {
4332
4331
  role: "system",
4333
4332
  content: buildSystemContent(basePrompt, context)
@@ -4351,8 +4350,8 @@ var QwenProvider = class {
4351
4350
  }
4352
4351
  chatStream(messages, context, options) {
4353
4352
  return __asyncGenerator(this, null, function* () {
4354
- var _a3, _b, _c, _d, _e, _f, _g2, _h;
4355
- const basePrompt = (_b = (_a3 = options == null ? void 0 : options.systemPrompt) != null ? _a3 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Answer questions based on the provided context.";
4353
+ var _a2, _b, _c, _d, _e, _f, _g2, _h;
4354
+ const basePrompt = (_b = (_a2 = options == null ? void 0 : options.systemPrompt) != null ? _a2 : this.llmConfig.systemPrompt) != null ? _b : "You are a helpful assistant. Answer questions based on the provided context.";
4356
4355
  const systemMessage = {
4357
4356
  role: "system",
4358
4357
  content: buildSystemContent(basePrompt, context)
@@ -4399,8 +4398,8 @@ var QwenProvider = class {
4399
4398
  return results[0];
4400
4399
  }
4401
4400
  async batchEmbed(texts, options) {
4402
- var _a3, _b, _c, _d, _e, _f;
4403
- const model = (_c = (_b = options == null ? void 0 : options.model) != null ? _b : (_a3 = this.embeddingConfig) == null ? void 0 : _a3.model) != null ? _c : "text-embedding-v1";
4401
+ var _a2, _b, _c, _d, _e, _f;
4402
+ const model = (_c = (_b = options == null ? void 0 : options.model) != null ? _b : (_a2 = this.embeddingConfig) == null ? void 0 : _a2.model) != null ? _c : "text-embedding-v1";
4404
4403
  const apiKey = (_e = (_d = this.embeddingConfig) == null ? void 0 : _d.apiKey) != null ? _e : this.llmConfig.apiKey;
4405
4404
  const client = apiKey !== this.llmConfig.apiKey ? new OpenAI3({
4406
4405
  apiKey,
@@ -4500,9 +4499,9 @@ var VECTOR_PROFILES = {
4500
4499
 
4501
4500
  // src/llm/providers/UniversalLLMAdapter.ts
4502
4501
  function extractContent(obj) {
4503
- var _a3, _b, _c;
4502
+ var _a2, _b, _c;
4504
4503
  if (!obj || typeof obj !== "object") return void 0;
4505
- const choice = (_a3 = obj.choices) == null ? void 0 : _a3[0];
4504
+ const choice = (_a2 = obj.choices) == null ? void 0 : _a2[0];
4506
4505
  if (!choice) return void 0;
4507
4506
  if (typeof ((_b = choice.message) == null ? void 0 : _b.content) === "string") return choice.message.content;
4508
4507
  if (typeof ((_c = choice.delta) == null ? void 0 : _c.content) === "string") return choice.delta.content;
@@ -4512,10 +4511,10 @@ function extractContent(obj) {
4512
4511
  }
4513
4512
  var UniversalLLMAdapter = class {
4514
4513
  constructor(config) {
4515
- var _a3, _b, _c, _d, _e, _f, _g2, _h;
4514
+ var _a2, _b, _c, _d, _e, _f, _g2, _h;
4516
4515
  this.model = config.model;
4517
4516
  const llmConfig = config;
4518
- const options = (_a3 = llmConfig.options) != null ? _a3 : {};
4517
+ const options = (_a2 = llmConfig.options) != null ? _a2 : {};
4519
4518
  let profile = {};
4520
4519
  if (typeof options.profile === "string") {
4521
4520
  profile = LLM_PROFILES[options.profile] || {};
@@ -4541,8 +4540,8 @@ var UniversalLLMAdapter = class {
4541
4540
  });
4542
4541
  }
4543
4542
  async chat(messages, context) {
4544
- var _a3, _b, _c, _d, _e, _f, _g2, _h, _i, _j;
4545
- const path2 = (_a3 = this.opts.chatPath) != null ? _a3 : "/chat/completions";
4543
+ var _a2, _b, _c, _d, _e, _f, _g2, _h, _i, _j;
4544
+ const path2 = (_a2 = this.opts.chatPath) != null ? _a2 : "/chat/completions";
4546
4545
  const safeMessages = (Array.isArray(messages) ? messages : []).filter((m) => Boolean(m && typeof m === "object")).map((m) => ({
4547
4546
  role: m.role || "user",
4548
4547
  content: typeof m.content === "string" ? m.content : m.content != null ? String(m.content) : ""
@@ -4619,8 +4618,8 @@ ${context != null ? context : "None"}` },
4619
4618
  */
4620
4619
  chatStream(messages, context) {
4621
4620
  return __asyncGenerator(this, null, function* () {
4622
- var _a3, _b, _c, _d, _e, _f;
4623
- const path2 = (_a3 = this.opts.chatPath) != null ? _a3 : "/chat/completions";
4621
+ var _a2, _b, _c, _d, _e, _f;
4622
+ const path2 = (_a2 = this.opts.chatPath) != null ? _a2 : "/chat/completions";
4624
4623
  const url = `${this.baseUrl.replace(/\/$/, "")}${path2}`;
4625
4624
  const extractPath = ((_b = this.opts.responseExtractPath) != null ? _b : "choices[0].message.content").replace("message.content", "delta.content");
4626
4625
  const safeMessages = (Array.isArray(messages) ? messages : []).filter((m) => Boolean(m && typeof m === "object")).map((m) => ({
@@ -4746,8 +4745,8 @@ ${context != null ? context : "None"}` },
4746
4745
  });
4747
4746
  }
4748
4747
  async embed(text) {
4749
- var _a3, _b, _c, _d, _e, _f, _g2, _h;
4750
- const path2 = (_a3 = this.opts.embedPath) != null ? _a3 : "/embeddings";
4748
+ var _a2, _b, _c, _d, _e, _f, _g2, _h;
4749
+ const path2 = (_a2 = this.opts.embedPath) != null ? _a2 : "/embeddings";
4751
4750
  const payload = this.opts.embedPayloadTemplate ? buildPayload(this.opts.embedPayloadTemplate, { input: text, model: this.model }) : { input: text, model: this.model };
4752
4751
  try {
4753
4752
  const { data } = await this.http.post(path2, payload);
@@ -4871,7 +4870,7 @@ var LLMFactory = class _LLMFactory {
4871
4870
  ];
4872
4871
  }
4873
4872
  static create(llmConfig, embeddingConfig) {
4874
- var _a3, _b, _c;
4873
+ var _a2, _b, _c;
4875
4874
  switch (llmConfig.provider) {
4876
4875
  case "openai":
4877
4876
  return new OpenAIProvider(llmConfig, embeddingConfig);
@@ -4890,7 +4889,7 @@ var LLMFactory = class _LLMFactory {
4890
4889
  case "custom":
4891
4890
  return new UniversalLLMAdapter(llmConfig);
4892
4891
  default: {
4893
- const providerName = String((_a3 = llmConfig.provider) != null ? _a3 : "").toLowerCase();
4892
+ const providerName = String((_a2 = llmConfig.provider) != null ? _a2 : "").toLowerCase();
4894
4893
  const customFactory = customProviders.get(providerName);
4895
4894
  if (customFactory) {
4896
4895
  return customFactory(llmConfig);
@@ -4992,7 +4991,7 @@ var ProviderRegistry = class {
4992
4991
  return null;
4993
4992
  }
4994
4993
  static async loadVectorProviderClass(provider) {
4995
- var _a3;
4994
+ var _a2;
4996
4995
  if (this.vectorProviders[provider]) return this.vectorProviders[provider];
4997
4996
  switch (provider) {
4998
4997
  case "pinecone": {
@@ -5001,7 +5000,7 @@ var ProviderRegistry = class {
5001
5000
  }
5002
5001
  case "pgvector":
5003
5002
  case "postgresql": {
5004
- const postgresMode = ((_a3 = process.env.POSTGRES_MODE) != null ? _a3 : "multi").toLowerCase();
5003
+ const postgresMode = ((_a2 = process.env.POSTGRES_MODE) != null ? _a2 : "multi").toLowerCase();
5005
5004
  if (postgresMode === "single") {
5006
5005
  const { PostgreSQLProvider: PostgreSQLProvider2 } = await Promise.resolve().then(() => (init_PostgreSQLProvider(), PostgreSQLProvider_exports));
5007
5006
  return PostgreSQLProvider2;
@@ -5293,13 +5292,15 @@ var DocumentChunker = class {
5293
5292
  }
5294
5293
  }
5295
5294
  const parts = text.split(separator);
5296
- for (const part of parts) {
5297
- if (part.length <= chunkSize) {
5298
- finalSplits.push(part + (part === parts[parts.length - 1] ? "" : separator));
5295
+ for (let i = 0; i < parts.length; i++) {
5296
+ const part = parts[i];
5297
+ const splitVal = (i === 0 ? "" : separator) + part;
5298
+ if (splitVal.length <= chunkSize) {
5299
+ finalSplits.push(splitVal);
5299
5300
  } else if (nextSeparators.length > 0) {
5300
- finalSplits.push(...this.recursiveSplit(part, nextSeparators, chunkSize));
5301
+ finalSplits.push(...this.recursiveSplit(splitVal, nextSeparators, chunkSize));
5301
5302
  } else {
5302
- finalSplits.push(part);
5303
+ finalSplits.push(splitVal);
5303
5304
  }
5304
5305
  }
5305
5306
  return finalSplits;
@@ -5378,74 +5379,108 @@ Text to extract from:
5378
5379
  };
5379
5380
 
5380
5381
  // src/rag/Reranker.ts
5382
+ var MAX_RERANK_CONTENT_CHARS = 64e3;
5381
5383
  var Reranker = class {
5382
5384
  /**
5383
5385
  * Re-ranks matches based on a secondary relevance score using an LLM.
5386
+ *
5387
+ * Fix RAG-2: keyword re-ranking no longer mutates the original `score`
5388
+ * field (which consumers interpret as the raw vector similarity). A new
5389
+ * `rerankScore` field is added so both the original similarity and the
5390
+ * boosted rank signal are available to callers.
5384
5391
  */
5385
5392
  async rerank(matches, query, limit = 5, llm) {
5386
5393
  if (!llm || matches.length <= 1) {
5387
- const keywords = query.toLowerCase().replace(/[^\w\s]/g, "").split(/\s+/).filter((w) => w.length > 2);
5388
- if (keywords.length === 0) {
5389
- return matches.sort((a, b) => b.score - a.score).slice(0, limit);
5390
- }
5391
- const scoredMatches = matches.map((match) => {
5392
- var _a3;
5393
- const contentLower = ((_a3 = match == null ? void 0 : match.content) != null ? _a3 : "").toLowerCase();
5394
- let keywordScore = 0;
5395
- keywords.forEach((keyword) => {
5396
- if (contentLower.includes(keyword)) {
5397
- keywordScore += 1;
5398
- }
5399
- });
5400
- const normalizedKeywordScore = keywordScore / keywords.length;
5401
- const combinedScore = match.score + normalizedKeywordScore * 0.5;
5402
- return __spreadProps(__spreadValues({}, match), {
5403
- score: combinedScore
5404
- });
5405
- });
5406
- return scoredMatches.sort((a, b) => b.score - a.score).slice(0, limit);
5394
+ return this.keywordRerank(matches, query, limit);
5407
5395
  }
5408
5396
  try {
5409
- const topN = matches.slice(0, 10);
5410
- const response = await llm.chat(
5411
- [{ role: "user", content: `Query: "${query}"
5397
+ return await this.llmRerank(matches, query, limit, llm);
5398
+ } catch (error) {
5399
+ console.warn("[Reranker] LLM re-ranking failed, falling back to keyword sorting:", error);
5400
+ return this.keywordRerank(matches, query, limit);
5401
+ }
5402
+ }
5403
+ /**
5404
+ * Keyword-based re-ranking fallback.
5405
+ *
5406
+ * Fix RAG-2: `rerankScore` is a separate field; `score` (the original
5407
+ * vector similarity) is never mutated. Callers that display `score` to
5408
+ * end-users receive the canonical cosine similarity value.
5409
+ */
5410
+ keywordRerank(matches, query, limit) {
5411
+ const keywords = query.toLowerCase().replace(/[^\w\s]/g, "").split(/\s+/).filter((w) => w.length > 2);
5412
+ if (keywords.length === 0) {
5413
+ return matches.sort((a, b) => b.score - a.score).slice(0, limit);
5414
+ }
5415
+ const scoredMatches = matches.map((match) => {
5416
+ var _a2;
5417
+ const contentLower = ((_a2 = match == null ? void 0 : match.content) != null ? _a2 : "").toLowerCase();
5418
+ let keywordHits = 0;
5419
+ keywords.forEach((keyword) => {
5420
+ if (contentLower.includes(keyword)) {
5421
+ keywordHits++;
5422
+ }
5423
+ });
5424
+ const normalizedKeywordScore = keywordHits / keywords.length;
5425
+ return __spreadProps(__spreadValues({}, match), {
5426
+ rerankScore: match.score + normalizedKeywordScore * 0.5
5427
+ });
5428
+ });
5429
+ return scoredMatches.sort((a, b) => {
5430
+ var _a2, _b;
5431
+ return ((_a2 = b.rerankScore) != null ? _a2 : b.score) - ((_b = a.rerankScore) != null ? _b : a.score);
5432
+ }).slice(0, limit);
5433
+ }
5434
+ /**
5435
+ * LLM-based re-ranking.
5436
+ *
5437
+ * Fix RAG-1: total document content is now budgeted against
5438
+ * MAX_RERANK_CONTENT_CHARS to prevent silent truncation or failures
5439
+ * on models with small context windows.
5440
+ */
5441
+ async llmRerank(matches, query, limit, llm) {
5442
+ const candidates = matches.slice(0, 10);
5443
+ let charsUsed = 0;
5444
+ const budgetedCandidates = candidates.filter((m) => {
5445
+ const len = (m.content || "").length;
5446
+ if (charsUsed + len > MAX_RERANK_CONTENT_CHARS) return false;
5447
+ charsUsed += len;
5448
+ return true;
5449
+ });
5450
+ const docList = budgetedCandidates.map((m, i) => {
5451
+ var _a2;
5452
+ return `[${i}] ${((_a2 = m == null ? void 0 : m.content) != null ? _a2 : "").replace(/\n/g, " ")}`;
5453
+ }).join("\n");
5454
+ const response = await llm.chat(
5455
+ [{ role: "user", content: `Query: "${query}"
5412
5456
 
5413
5457
  Documents:
5414
- ${topN.map((m, i) => {
5415
- var _a3;
5416
- return `[${i}] ${((_a3 = m == null ? void 0 : m.content) != null ? _a3 : "").replace(/\n/g, " ")}`;
5417
- }).join("\n")}` }],
5418
- "",
5419
- {
5420
- systemPrompt: 'You are a relevance ranking expert. Given the user query and a list of retrieved document chunks, rank the chunks by relevance to the query. Return the result as a comma-separated list of document indices in order of relevance, from most relevant to least relevant. Use the indices provided in brackets like [0], [1], etc. Only return the indices (e.g., "2,0,1"), nothing else. Do not include brackets in the output.',
5421
- temperature: 0,
5422
- maxTokens: 50
5423
- }
5424
- );
5425
- const cleanedResponse = response.trim().replace(/[\[\]\s]/g, "");
5426
- const rankedIndices = cleanedResponse.split(",").map(Number).filter((n) => !isNaN(n));
5427
- if (rankedIndices.length > 0) {
5428
- const rankedMatches = [];
5429
- const usedIndices = /* @__PURE__ */ new Set();
5430
- for (const index of rankedIndices) {
5431
- if (index >= 0 && index < topN.length && !usedIndices.has(index)) {
5432
- rankedMatches.push(topN[index]);
5433
- usedIndices.add(index);
5434
- }
5435
- }
5436
- for (let i = 0; i < topN.length; i++) {
5437
- if (!usedIndices.has(i)) {
5438
- rankedMatches.push(topN[i]);
5439
- }
5440
- }
5441
- const rest = matches.slice(10);
5442
- rankedMatches.push(...rest);
5443
- return rankedMatches.slice(0, limit);
5458
+ ${docList}` }],
5459
+ "",
5460
+ {
5461
+ systemPrompt: 'You are a relevance ranking expert. Given the user query and a list of retrieved document chunks, rank the chunks by relevance to the query. Return the result as a comma-separated list of document indices in order of relevance, from most relevant to least relevant. Use the indices provided in brackets like [0], [1], etc. Only return the indices (e.g., "2,0,1"), nothing else. Do not include brackets in the output.',
5462
+ temperature: 0,
5463
+ maxTokens: 50
5444
5464
  }
5445
- } catch (error) {
5446
- console.warn("[Reranker] LLM re-ranking failed, falling back to score-based sorting:", error);
5465
+ );
5466
+ const cleanedResponse = response.trim().replace(/[\[\]\s]/g, "");
5467
+ const rankedIndices = cleanedResponse.split(",").map(Number).filter((n) => !isNaN(n));
5468
+ if (rankedIndices.length === 0) {
5469
+ return matches.sort((a, b) => b.score - a.score).slice(0, limit);
5447
5470
  }
5448
- return matches.sort((a, b) => b.score - a.score).slice(0, limit);
5471
+ const rankedMatches = [];
5472
+ const usedIndices = /* @__PURE__ */ new Set();
5473
+ for (const index of rankedIndices) {
5474
+ if (index >= 0 && index < budgetedCandidates.length && !usedIndices.has(index)) {
5475
+ rankedMatches.push(budgetedCandidates[index]);
5476
+ usedIndices.add(index);
5477
+ }
5478
+ }
5479
+ for (let i = 0; i < budgetedCandidates.length; i++) {
5480
+ if (!usedIndices.has(i)) rankedMatches.push(budgetedCandidates[i]);
5481
+ }
5482
+ rankedMatches.push(...matches.slice(10));
5483
+ return rankedMatches.slice(0, limit);
5449
5484
  }
5450
5485
  };
5451
5486
 
@@ -5457,11 +5492,11 @@ var LlamaIndexIngestor = class {
5457
5492
  * than standard character-count splitting.
5458
5493
  */
5459
5494
  async chunk(text, options = {}) {
5460
- var _a3, _b;
5495
+ var _a2, _b;
5461
5496
  try {
5462
5497
  const { Document, SentenceSplitter, MetadataMode } = await import(`${"llamaindex"}`);
5463
5498
  const splitter = new SentenceSplitter({
5464
- chunkSize: (_a3 = options.chunkSize) != null ? _a3 : 1e3,
5499
+ chunkSize: (_a2 = options.chunkSize) != null ? _a2 : 1e3,
5465
5500
  chunkOverlap: (_b = options.chunkOverlap) != null ? _b : 200
5466
5501
  });
5467
5502
  const doc = new Document({ text, metadata: options.metadata || {} });
@@ -5569,7 +5604,7 @@ ${error instanceof Error ? error.message : String(error)}`
5569
5604
  * The agent returns `{ messages: [...] }` — the last message is the final answer.
5570
5605
  */
5571
5606
  async run(input, chatHistory = []) {
5572
- var _a3, _b, _c;
5607
+ var _a2, _b, _c;
5573
5608
  if (!this.agent) {
5574
5609
  throw new Error("[LangChainAgent] Agent not initialized. Call initialize() first.");
5575
5610
  }
@@ -5580,7 +5615,7 @@ ${error instanceof Error ? error.message : String(error)}`
5580
5615
  const response = await this.agent.invoke({
5581
5616
  messages: [...historyMessages, new HumanMessage(input)]
5582
5617
  });
5583
- const lastMessage = (_a3 = response == null ? void 0 : response.messages) == null ? void 0 : _a3.at(-1);
5618
+ const lastMessage = (_a2 = response == null ? void 0 : response.messages) == null ? void 0 : _a2.at(-1);
5584
5619
  if (lastMessage && typeof lastMessage.content === "string") {
5585
5620
  return lastMessage.content;
5586
5621
  }
@@ -5631,7 +5666,7 @@ var MCPClient = class {
5631
5666
  }
5632
5667
  }
5633
5668
  async connectStdio() {
5634
- var _a3;
5669
+ var _a2;
5635
5670
  const cmd = this.config.command;
5636
5671
  if (!cmd) {
5637
5672
  throw new Error(`[MCPClient] Command option is required for stdio transport on "${this.config.name}"`);
@@ -5646,7 +5681,7 @@ var MCPClient = class {
5646
5681
  this.stdioBuffer += data.toString("utf-8");
5647
5682
  this.processStdioLines();
5648
5683
  });
5649
- (_a3 = this.childProcess.stderr) == null ? void 0 : _a3.on("data", (data) => {
5684
+ (_a2 = this.childProcess.stderr) == null ? void 0 : _a2.on("data", (data) => {
5650
5685
  console.warn(`[MCPClient] [stderr] [${this.config.name}]:`, data.toString("utf-8"));
5651
5686
  });
5652
5687
  this.childProcess.on("close", (code) => {
@@ -5720,14 +5755,14 @@ var MCPClient = class {
5720
5755
  }
5721
5756
  }
5722
5757
  async sendNotification(method, params) {
5723
- var _a3;
5758
+ var _a2;
5724
5759
  const notification = {
5725
5760
  jsonrpc: "2.0",
5726
5761
  method,
5727
5762
  params
5728
5763
  };
5729
5764
  if (this.config.transport === "stdio") {
5730
- if ((_a3 = this.childProcess) == null ? void 0 : _a3.stdin) {
5765
+ if ((_a2 = this.childProcess) == null ? void 0 : _a2.stdin) {
5731
5766
  this.childProcess.stdin.write(JSON.stringify(notification) + "\n", "utf-8");
5732
5767
  }
5733
5768
  } else if (this.sseUrl) {
@@ -5805,11 +5840,11 @@ var MCPRegistry = class {
5805
5840
  // src/core/MultiAgentCoordinator.ts
5806
5841
  var MultiAgentCoordinator = class {
5807
5842
  constructor(options) {
5808
- var _a3;
5843
+ var _a2;
5809
5844
  this.llmProvider = options.llmProvider;
5810
5845
  this.mcpRegistry = options.mcpRegistry;
5811
5846
  this.documentSearch = options.documentSearch;
5812
- this.maxIterations = (_a3 = options.maxIterations) != null ? _a3 : 5;
5847
+ this.maxIterations = (_a2 = options.maxIterations) != null ? _a2 : 5;
5813
5848
  }
5814
5849
  /**
5815
5850
  * Run the multi-agent coordination loop synchronously and return the final response.
@@ -5861,8 +5896,8 @@ Available Tools:
5861
5896
 
5862
5897
  ${mcpTools.length > 0 ? "MCP Server Tools:" : ""}
5863
5898
  ${mcpTools.map((mt) => {
5864
- var _a3;
5865
- return `- ${mt.tool.name}(${JSON.stringify(((_a3 = mt.tool.inputSchema) == null ? void 0 : _a3.properties) || {})}): ${mt.tool.description || "No description provided."}`;
5899
+ var _a2;
5900
+ return `- ${mt.tool.name}(${JSON.stringify(((_a2 = mt.tool.inputSchema) == null ? void 0 : _a2.properties) || {})}): ${mt.tool.description || "No description provided."}`;
5866
5901
  }).join("\n")}
5867
5902
 
5868
5903
  Tool Calling Protocol:
@@ -6020,100 +6055,6 @@ ${toolResultText}`
6020
6055
  }
6021
6056
  };
6022
6057
 
6023
- // src/core/CircuitBreaker.ts
6024
- var CircuitBreaker = class {
6025
- constructor(options = {}) {
6026
- this.state = "closed";
6027
- this.failureCount = 0;
6028
- this.successCount = 0;
6029
- this.lastFailureAt = 0;
6030
- this.halfOpenCalls = 0;
6031
- var _a3, _b, _c;
6032
- this.failureThreshold = (_a3 = options.failureThreshold) != null ? _a3 : 5;
6033
- this.resetTimeoutMs = (_b = options.resetTimeoutMs) != null ? _b : 3e4;
6034
- this.halfOpenMaxCalls = (_c = options.halfOpenMaxCalls) != null ? _c : 1;
6035
- }
6036
- record(success) {
6037
- const now = Date.now();
6038
- if (success) {
6039
- this.successCount++;
6040
- if (this.state === "half-open") {
6041
- this.state = "closed";
6042
- this.failureCount = 0;
6043
- this.halfOpenCalls = 0;
6044
- this.successCount = 1;
6045
- } else if (this.state === "closed") {
6046
- if (this.successCount >= this.failureThreshold) {
6047
- this.failureCount = Math.max(0, this.failureCount - 1);
6048
- this.successCount = 0;
6049
- }
6050
- }
6051
- } else {
6052
- this.failureCount++;
6053
- this.lastFailureAt = now;
6054
- this.successCount = 0;
6055
- if (this.state === "half-open") {
6056
- this.state = "open";
6057
- this.halfOpenCalls = 0;
6058
- } else if (this.state === "closed" && this.failureCount >= this.failureThreshold) {
6059
- this.state = "open";
6060
- }
6061
- }
6062
- }
6063
- canExecute() {
6064
- const now = Date.now();
6065
- if (this.state === "closed") {
6066
- return true;
6067
- }
6068
- if (this.state === "open") {
6069
- if (now - this.lastFailureAt >= this.resetTimeoutMs) {
6070
- this.state = "half-open";
6071
- this.halfOpenCalls = 0;
6072
- return true;
6073
- }
6074
- return false;
6075
- }
6076
- if (this.state === "half-open") {
6077
- return this.halfOpenCalls < this.halfOpenMaxCalls;
6078
- }
6079
- return true;
6080
- }
6081
- async wrap(fn) {
6082
- if (!this.canExecute()) {
6083
- const retryAfterSec = Math.ceil(
6084
- Math.max(0, this.resetTimeoutMs - (Date.now() - this.lastFailureAt)) / 1e3
6085
- );
6086
- throw new Error(
6087
- `Circuit breaker is open. Try again in ${retryAfterSec}s. Failed ${this.failureCount}/${this.failureThreshold} consecutive calls.`
6088
- );
6089
- }
6090
- if (this.state === "half-open") {
6091
- this.halfOpenCalls++;
6092
- }
6093
- try {
6094
- const result = await fn();
6095
- this.record(true);
6096
- return result;
6097
- } catch (err) {
6098
- this.record(false);
6099
- throw err;
6100
- }
6101
- }
6102
- getState() {
6103
- return this.state;
6104
- }
6105
- getFailureCount() {
6106
- return this.failureCount;
6107
- }
6108
- reset() {
6109
- this.state = "closed";
6110
- this.failureCount = 0;
6111
- this.successCount = 0;
6112
- this.lastFailureAt = 0;
6113
- this.halfOpenCalls = 0;
6114
- }
6115
- };
6116
-
6117
6058
  // src/core/BatchProcessor.ts
6118
6059
  function isTransientError(error) {
6119
6060
  if (!(error instanceof Error)) return false;
@@ -6137,30 +6078,34 @@ function calculateBackoffDelay(attempt, initialDelayMs, maxDelayMs, multiplier)
6137
6078
  function sleep(ms) {
6138
6079
  return new Promise((resolve) => setTimeout(resolve, ms));
6139
6080
  }
6140
- var _BatchProcessor = class _BatchProcessor {
6081
+ var BatchProcessor = class _BatchProcessor {
6141
6082
  /**
6142
- * Execute a processor call through the circuit breaker.
6143
- * Only transient failures count toward opening the circuit.
6083
+ * Execute a processor call, optionally through a caller-provided circuit
6084
+ * breaker. Only transient failures count toward opening the circuit.
6085
+ *
6086
+ * Fix ARCH-3: removed the static module-level `cb` field. Callers must
6087
+ * supply their own CircuitBreaker via BatchOptions.circuitBreaker.
6088
+ * Fix TYPE-1: uses the public retryAfterMs() and incrementHalfOpen()
6089
+ * API instead of accessing private fields via `as any`.
6144
6090
  */
6145
- static async executeWithCircuitBreaker(processor) {
6146
- if (!this.cb.canExecute()) {
6147
- const retryAfterSec = Math.ceil(
6148
- Math.max(0, 3e4 - (Date.now() - this.cb.lastFailureAt || 0)) / 1e3
6149
- );
6091
+ static async executeWithCircuitBreaker(processor, cb) {
6092
+ if (!cb) {
6093
+ return processor();
6094
+ }
6095
+ if (!cb.canExecute()) {
6096
+ const retryAfterSec = Math.ceil(cb.retryAfterMs() / 1e3);
6150
6097
  throw new Error(
6151
6098
  `[BatchProcessor] Circuit breaker is open. Try again in ${retryAfterSec}s.`
6152
6099
  );
6153
6100
  }
6154
- if (this.cb.state === "half-open") {
6155
- this.cb.halfOpenCalls++;
6156
- }
6101
+ cb.incrementHalfOpen();
6157
6102
  try {
6158
6103
  const result = await processor();
6159
- this.cb.record(true);
6104
+ cb.record(true);
6160
6105
  return result;
6161
6106
  } catch (err) {
6162
6107
  if (isTransientError(err)) {
6163
- this.cb.record(false);
6108
+ cb.record(false);
6164
6109
  }
6165
6110
  throw err;
6166
6111
  }
@@ -6205,7 +6150,10 @@ var _BatchProcessor = class _BatchProcessor {
6205
6150
  let lastError;
6206
6151
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
6207
6152
  try {
6208
- const result = await _BatchProcessor.executeWithCircuitBreaker(() => processor(batch));
6153
+ const result = await _BatchProcessor.executeWithCircuitBreaker(
6154
+ () => processor(batch),
6155
+ options == null ? void 0 : options.circuitBreaker
6156
+ );
6209
6157
  results.push(result);
6210
6158
  success = true;
6211
6159
  break;
@@ -6263,7 +6211,10 @@ ${errorMessages}`
6263
6211
  let lastError;
6264
6212
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
6265
6213
  try {
6266
- const result = await _BatchProcessor.executeWithCircuitBreaker(() => processor(item));
6214
+ const result = await _BatchProcessor.executeWithCircuitBreaker(
6215
+ () => processor(item),
6216
+ options == null ? void 0 : options.circuitBreaker
6217
+ );
6267
6218
  results.push(result);
6268
6219
  success = true;
6269
6220
  break;
@@ -6336,7 +6287,10 @@ ${errorMessages}`
6336
6287
  }));
6337
6288
  const chunkPromises = chunk.map(async ({ item, originalIndex }) => {
6338
6289
  try {
6339
- const result = await _BatchProcessor.executeWithCircuitBreaker(() => processor(item));
6290
+ const result = await _BatchProcessor.executeWithCircuitBreaker(
6291
+ () => processor(item),
6292
+ options == null ? void 0 : options.circuitBreaker
6293
+ );
6340
6294
  return { success: true, result, index: originalIndex };
6341
6295
  } catch (err) {
6342
6296
  const error = err instanceof Error ? err : new Error(String(err));
@@ -6364,12 +6318,6 @@ ${errorMessages}`
6364
6318
  return { results, errors, totalProcessed, totalFailed };
6365
6319
  }
6366
6320
  };
6367
- _BatchProcessor.cb = new CircuitBreaker({
6368
- failureThreshold: 5,
6369
- resetTimeoutMs: 3e4,
6370
- halfOpenMaxCalls: 1
6371
- });
6372
- var BatchProcessor = _BatchProcessor;
6373
6321
 
6374
6322
  // src/config/EmbeddingStrategy.ts
6375
6323
  var EmbeddingStrategy = /* @__PURE__ */ ((EmbeddingStrategy2) => {
@@ -6473,7 +6421,7 @@ var QueryProcessor = class {
6473
6421
  * @param validFields Optional list of known filterable fields to look for
6474
6422
  */
6475
6423
  static extractQueryFieldHints(question, validFields = []) {
6476
- var _a3, _b, _c, _d;
6424
+ var _a2, _b, _c, _d, _e, _f, _g2, _h;
6477
6425
  if (!question.trim()) return [];
6478
6426
  const hints = /* @__PURE__ */ new Map();
6479
6427
  const addHint = (value, field) => {
@@ -6518,11 +6466,11 @@ var QueryProcessor = class {
6518
6466
  if (name) addHint(name, "name");
6519
6467
  }
6520
6468
  }
6521
- const genericPattern = /\b([a-z][a-z0-9_]{1,30})\s*[:=]\s*["']?([^"'\n?.!,]{1,60})["']?/gi;
6469
+ const genericPattern = /\b([a-z][a-z0-9_]{1,30})\s*[:=]\s*(?:"([^"\n?.!,]{1,60})"|'([^'\n?.!,]{1,60})'|([^\s\n?.!,:=]{1,60}))/gi;
6522
6470
  for (const match of question.matchAll(genericPattern)) {
6523
6471
  const field = match[1];
6524
- const value = match[2];
6525
- if (field && !this.isLikelyPromptPhrase(field)) {
6472
+ const value = (_b = (_a2 = match[2]) != null ? _a2 : match[3]) != null ? _b : match[4];
6473
+ if (field && value && !this.isLikelyPromptPhrase(field)) {
6526
6474
  const resolvedField = resolveValidField(field);
6527
6475
  if (resolvedField) {
6528
6476
  addHint(value, resolvedField);
@@ -6553,7 +6501,7 @@ var QueryProcessor = class {
6553
6501
  ];
6554
6502
  for (const p of universalPatterns) {
6555
6503
  for (const match of question.matchAll(p.regex)) {
6556
- const val = p.group ? (_a3 = match[p.group]) != null ? _a3 : match[0] : match[0];
6504
+ const val = p.group ? (_c = match[p.group]) != null ? _c : match[0] : match[0];
6557
6505
  if (!val) continue;
6558
6506
  if (p.field) addHint(val, p.field);
6559
6507
  else addHint(val);
@@ -6561,22 +6509,23 @@ var QueryProcessor = class {
6561
6509
  }
6562
6510
  for (const pattern of naturalQuestionPatterns) {
6563
6511
  for (const match of question.matchAll(pattern)) {
6564
- const value = (_b = match[2]) != null ? _b : match[1];
6512
+ const value = (_d = match[2]) != null ? _d : match[1];
6565
6513
  if (value) addHint(value);
6566
6514
  }
6567
6515
  }
6568
6516
  const fieldPattern = `([^\\n:=?.!,]{1,60}?)`;
6569
- const valuePattern = `([^\\n?.!,]{1,120}?)`;
6517
+ const valuePattern = `(?:"([^"\\n?.!,]{1,120})"|'([^'\\n?.!,]{1,120})'|([^\\s\\n?.!,:=]{1,120}))`;
6570
6518
  const fieldValuePatterns = [
6571
- new RegExp(`\\b${fieldPattern}\\s*(?:=|:)\\s*["']?${valuePattern}["']?(?=[?.!,]|$)`, "gi"),
6572
- new RegExp(`\\b${fieldPattern}\\s+(?:is|are|was|were|equals?|equal to|named|called)\\s+["']?${valuePattern}["']?(?=[?.!,]|$)`, "gi"),
6573
- new RegExp(`\\bwith\\s+${fieldPattern}\\s+["']?${valuePattern}["']?(?=[?.!,]|$)`, "gi"),
6574
- new RegExp(`\\b(?:under|in|for|from|of)\\s+${fieldPattern}\\s+["']?${valuePattern}["']?(?=[?.!,]|$)`, "gi")
6519
+ new RegExp(`\\b${fieldPattern}\\s*(?:=|:)\\s*${valuePattern}`, "gi"),
6520
+ new RegExp(`\\b${fieldPattern}\\s+(?:is|are|was|were|equals?|equal to|named|called)\\s+${valuePattern}`, "gi"),
6521
+ new RegExp(`\\bwith\\s+${fieldPattern}\\s+${valuePattern}`, "gi"),
6522
+ new RegExp(`\\b(?:under|in|for|from|of)\\s+${fieldPattern}\\s+${valuePattern}`, "gi")
6575
6523
  ];
6576
6524
  for (const pattern of fieldValuePatterns) {
6577
6525
  for (const match of question.matchAll(pattern)) {
6578
- const field = (_c = match[1]) != null ? _c : "";
6579
- const value = (_d = match[2]) != null ? _d : "";
6526
+ const field = (_e = match[1]) != null ? _e : "";
6527
+ const value = (_h = (_g2 = (_f = match[2]) != null ? _f : match[3]) != null ? _g2 : match[4]) != null ? _h : "";
6528
+ if (!value) continue;
6580
6529
  const resolvedField = resolveValidField(field);
6581
6530
  if (resolvedField) {
6582
6531
  addHint(value, resolvedField);
@@ -6646,10 +6595,10 @@ var QueryProcessor = class {
6646
6595
  }
6647
6596
  static normalizeNumericOperator(operator) {
6648
6597
  const op = operator.toLowerCase().trim();
6649
- if (op === ">" || /\b(greater than|more than|above|over)\b/.test(op)) return "gt";
6650
6598
  if (op === ">=" || /\b(greater than or equal to|more than or equal to|at least)\b/.test(op)) return "gte";
6651
- if (op === "<" || /\b(less than|below|under)\b/.test(op)) return "lt";
6652
6599
  if (op === "<=" || /\b(less than or equal to|at most)\b/.test(op)) return "lte";
6600
+ if (op === ">" || /\b(greater than|more than|above|over)\b/.test(op)) return "gt";
6601
+ if (op === "<" || /\b(less than|below|under)\b/.test(op)) return "lt";
6653
6602
  return "eq";
6654
6603
  }
6655
6604
  static normalizePredicateField(field, validFields) {
@@ -6777,11 +6726,11 @@ var LLMRouter = class {
6777
6726
  * When provided it is used directly as the 'default' role without re-constructing.
6778
6727
  */
6779
6728
  async initialize(prebuiltDefault) {
6780
- var _a3;
6729
+ var _a2;
6781
6730
  const defaultModel = prebuiltDefault != null ? prebuiltDefault : LLMFactory.create(this.config.llm, this.config.embedding);
6782
6731
  this.models.set("default", defaultModel);
6783
6732
  const envFastModel = process.env.FAST_LLM_MODEL;
6784
- const providerFastDefault = (_a3 = FAST_MODEL_DEFAULTS[this.config.llm.provider]) != null ? _a3 : "";
6733
+ const providerFastDefault = (_a2 = FAST_MODEL_DEFAULTS[this.config.llm.provider]) != null ? _a2 : "";
6785
6734
  const fastModelName = envFastModel || providerFastDefault;
6786
6735
  if (fastModelName && fastModelName !== this.config.llm.model) {
6787
6736
  const fastConfig = __spreadProps(__spreadValues({}, this.config.llm), {
@@ -6798,8 +6747,8 @@ var LLMRouter = class {
6798
6747
  * Falls back to 'default' if the requested role is not registered.
6799
6748
  */
6800
6749
  get(role) {
6801
- var _a3;
6802
- const provider = (_a3 = this.models.get(role)) != null ? _a3 : this.models.get("default");
6750
+ var _a2;
6751
+ const provider = (_a2 = this.models.get(role)) != null ? _a2 : this.models.get("default");
6803
6752
  if (!provider) {
6804
6753
  throw new Error(`[LLMRouter] No provider registered for role: "${role}". Did you call initialize()?`);
6805
6754
  }
@@ -6885,8 +6834,8 @@ var IntentClassifier = class {
6885
6834
  numericFieldCount = numericKeys.size;
6886
6835
  categoricalFieldCount = catKeys.size;
6887
6836
  if (productKeyMatches >= 2 || docs.some((d) => {
6888
- var _a3, _b;
6889
- return ((_a3 = d == null ? void 0 : d.content) != null ? _a3 : "").toLowerCase().includes("price") || ((_b = d == null ? void 0 : d.content) != null ? _b : "").toLowerCase().includes("brand");
6837
+ var _a2, _b;
6838
+ return ((_a2 = d == null ? void 0 : d.content) != null ? _a2 : "").toLowerCase().includes("price") || ((_b = d == null ? void 0 : d.content) != null ? _b : "").toLowerCase().includes("brand");
6890
6839
  })) {
6891
6840
  isProductLike = true;
6892
6841
  }
@@ -7076,7 +7025,7 @@ var Rule6SmallResultSetRule = class {
7076
7025
  var Rule7LargeTableRule = class {
7077
7026
  constructor() {
7078
7027
  this.name = "Rule7LargeTable";
7079
- this.priority = 75;
7028
+ this.priority = 82;
7080
7029
  }
7081
7030
  evaluate(context, intent) {
7082
7031
  const docs = context.retrievedDocuments || [];
@@ -7119,8 +7068,8 @@ var RuleEngine = class {
7119
7068
  this.registerRule(new Rule5MixedResponseRule());
7120
7069
  this.registerRule(new Rule2ComparisonRule());
7121
7070
  this.registerRule(new Rule3ProductDiscoveryRule());
7122
- this.registerRule(new Rule4AnalyticalRule());
7123
7071
  this.registerRule(new Rule7LargeTableRule());
7072
+ this.registerRule(new Rule4AnalyticalRule());
7124
7073
  }
7125
7074
  /**
7126
7075
  * Add or replace a rule in the engine.
@@ -7168,8 +7117,8 @@ var TextRendererStrategy = class {
7168
7117
  }
7169
7118
  const docs = Array.isArray(data) ? data : [];
7170
7119
  const text = docs.map((d) => {
7171
- var _a3;
7172
- return (_a3 = d == null ? void 0 : d.content) != null ? _a3 : "";
7120
+ var _a2;
7121
+ return (_a2 = d == null ? void 0 : d.content) != null ? _a2 : "";
7173
7122
  }).join("\n\n");
7174
7123
  return { type: "text", title, data: { content: text || "No detailed content available." } };
7175
7124
  }
@@ -7312,9 +7261,9 @@ var LRUDecisionCache = class {
7312
7261
  this.maxSize = maxSize;
7313
7262
  }
7314
7263
  generateKey(context) {
7315
- var _a3, _b;
7264
+ var _a2, _b;
7316
7265
  const q = (context.userQuery || "").toLowerCase().trim();
7317
- const docCount = (_b = (_a3 = context.retrievedDocuments) == null ? void 0 : _a3.length) != null ? _b : 0;
7266
+ const docCount = (_b = (_a2 = context.retrievedDocuments) == null ? void 0 : _a2.length) != null ? _b : 0;
7318
7267
  return `${q}::docs:${docCount}`;
7319
7268
  }
7320
7269
  get(context) {
@@ -7423,7 +7372,7 @@ var UITransformer = class _UITransformer {
7423
7372
  * Prefer `analyzeAndDecide()` in production.
7424
7373
  */
7425
7374
  static transform(userQuery, retrievedData, config, trainedSchema, intent) {
7426
- var _a3, _b, _c;
7375
+ var _a2, _b, _c;
7427
7376
  if (!retrievedData || retrievedData.length === 0) {
7428
7377
  return this.createTextResponse("No data available", "No relevant data found for your query.");
7429
7378
  }
@@ -7443,7 +7392,7 @@ var UITransformer = class _UITransformer {
7443
7392
  return this.transformToBarChart(filteredData, profile, userQuery, resolvedIntent.visualizationHint === "ranking");
7444
7393
  }
7445
7394
  if (resolvedIntent.visualizationHint === "distribution") {
7446
- return (_a3 = this.transformToHistogram(profile, userQuery)) != null ? _a3 : this.transformToBarChart(filteredData, profile, userQuery);
7395
+ return (_a2 = this.transformToHistogram(profile, userQuery)) != null ? _a2 : this.transformToBarChart(filteredData, profile, userQuery);
7447
7396
  }
7448
7397
  if (resolvedIntent.visualizationHint === "correlation") {
7449
7398
  return (_b = this.transformToScatterPlot(profile, userQuery)) != null ? _b : this.transformToBarChart(filteredData, profile, userQuery);
@@ -7776,11 +7725,11 @@ ${schemaProfileText}` : ""}`;
7776
7725
  };
7777
7726
  }
7778
7727
  static transformToPieChart(data, profile, query = "") {
7779
- var _a3;
7728
+ var _a2;
7780
7729
  const dimension = profile ? this.selectDimensionField(profile, query) : void 0;
7781
7730
  const categories = dimension ? Array.from(new Set(profile.records.map((record) => {
7782
- var _a4;
7783
- return String((_a4 = record.fields[dimension.key]) != null ? _a4 : "");
7731
+ var _a3;
7732
+ return String((_a3 = record.fields[dimension.key]) != null ? _a3 : "");
7784
7733
  }).filter(Boolean))) : this.detectCategories(data);
7785
7734
  if (categories.length === 0) return null;
7786
7735
  const categoryData = dimension && profile ? this.aggregateProfileByDimension(profile, dimension.key) : this.aggregateByCategory(data, categories);
@@ -7790,7 +7739,7 @@ ${schemaProfileText}` : ""}`;
7790
7739
  });
7791
7740
  return {
7792
7741
  type: "pie_chart",
7793
- title: `Distribution by ${(_a3 = dimension == null ? void 0 : dimension.label) != null ? _a3 : "Category"}`,
7742
+ title: `Distribution by ${(_a2 = dimension == null ? void 0 : dimension.label) != null ? _a2 : "Category"}`,
7794
7743
  description: `Showing breakdown across ${pieData.length} categories`,
7795
7744
  data: pieData
7796
7745
  };
@@ -7800,8 +7749,8 @@ ${schemaProfileText}` : ""}`;
7800
7749
  const valueField = profile.numericFields[0];
7801
7750
  const buckets = /* @__PURE__ */ new Map();
7802
7751
  profile.records.forEach((record) => {
7803
- var _a3, _b, _c;
7804
- const timestamp = String((_a3 = record.fields[dateField.key]) != null ? _a3 : "");
7752
+ var _a2, _b, _c;
7753
+ const timestamp = String((_a2 = record.fields[dateField.key]) != null ? _a2 : "");
7805
7754
  const value = (_b = this.toFiniteNumber(record.fields[valueField.key])) != null ? _b : 0;
7806
7755
  buckets.set(timestamp, ((_c = buckets.get(timestamp)) != null ? _c : 0) + value);
7807
7756
  });
@@ -7814,23 +7763,23 @@ ${schemaProfileText}` : ""}`;
7814
7763
  };
7815
7764
  }
7816
7765
  static transformToBarChart(data, profile, query = "", horizontal = false) {
7817
- var _a3;
7766
+ var _a2;
7818
7767
  const dimension = profile ? this.selectDimensionField(profile, query) : void 0;
7819
7768
  const measure = profile ? this.selectNumericField(profile, query) : void 0;
7820
7769
  const aggregate = dimension && profile ? this.aggregateProfileByDimension(profile, dimension.key, measure == null ? void 0 : measure.key) : this.aggregateByCategory(data, this.detectCategories(data));
7821
7770
  const barData = Object.entries(aggregate).map(([category, value]) => ({ category, value: Number(value) })).sort((a, b) => horizontal ? b.value - a.value : 0).slice(0, 12);
7822
7771
  const fallbackData = barData.length > 0 ? barData : data.slice(0, 12).map((item, index) => {
7823
- var _a4, _b, _c, _d, _e;
7772
+ var _a3, _b, _c, _d, _e;
7824
7773
  const meta = item.metadata || {};
7825
7774
  const label = String(
7826
- (_c = (_b = (_a4 = this.getDynamicVal(meta, "name")) != null ? _a4 : meta.label) != null ? _b : meta.title) != null ? _c : `Result ${index + 1}`
7775
+ (_c = (_b = (_a3 = this.getDynamicVal(meta, "name")) != null ? _a3 : meta.label) != null ? _b : meta.title) != null ? _c : `Result ${index + 1}`
7827
7776
  );
7828
7777
  const value = (_e = (_d = this.extractNumericValue(meta)) != null ? _d : item.score) != null ? _e : 0;
7829
7778
  return { category: label, value: Number(value) };
7830
7779
  });
7831
7780
  return {
7832
7781
  type: horizontal ? "horizontal_bar" : "bar_chart",
7833
- title: dimension ? `${(_a3 = measure == null ? void 0 : measure.label) != null ? _a3 : "Count"} by ${dimension.label}` : "Comparison",
7782
+ title: dimension ? `${(_a2 = measure == null ? void 0 : measure.label) != null ? _a2 : "Count"} by ${dimension.label}` : "Comparison",
7834
7783
  description: `Showing ${fallbackData.length} comparable values`,
7835
7784
  data: fallbackData
7836
7785
  };
@@ -7865,11 +7814,11 @@ ${schemaProfileText}` : ""}`;
7865
7814
  if (fields.length < 2) return null;
7866
7815
  const [xField, yField] = fields;
7867
7816
  const points = profile.records.map((record) => {
7868
- var _a3;
7817
+ var _a2;
7869
7818
  const x = this.toFiniteNumber(record.fields[xField.key]);
7870
7819
  const y = this.toFiniteNumber(record.fields[yField.key]);
7871
7820
  if (x === null || y === null) return null;
7872
- return { x, y, label: String((_a3 = this.getRecordLabel(record)) != null ? _a3 : record.id) };
7821
+ return { x, y, label: String((_a2 = this.getRecordLabel(record)) != null ? _a2 : record.id) };
7873
7822
  }).filter((point) => point !== null).slice(0, 100);
7874
7823
  if (points.length === 0) return null;
7875
7824
  return {
@@ -7899,9 +7848,9 @@ ${schemaProfileText}` : ""}`;
7899
7848
  static transformToRadarChart(data) {
7900
7849
  const attributeMap = {};
7901
7850
  data.forEach((item) => {
7902
- var _a3, _b, _c;
7851
+ var _a2, _b, _c;
7903
7852
  const meta = item.metadata || {};
7904
- const seriesName = String((_c = (_b = (_a3 = meta.name) != null ? _a3 : meta.product) != null ? _b : item.id) != null ? _c : "Item");
7853
+ const seriesName = String((_c = (_b = (_a2 = meta.name) != null ? _a2 : meta.product) != null ? _b : item.id) != null ? _c : "Item");
7905
7854
  Object.entries(meta).forEach(([key, val]) => {
7906
7855
  if (typeof val === "number" && !["price", "id"].includes(key.toLowerCase())) {
7907
7856
  if (!attributeMap[key]) attributeMap[key] = {};
@@ -7917,8 +7866,8 @@ ${schemaProfileText}` : ""}`;
7917
7866
  title: "Product Comparison",
7918
7867
  description: `Comparing ${data.length} items across ${radarData.length} attributes`,
7919
7868
  data: radarData.length > 0 ? radarData : data.map((d) => {
7920
- var _a3;
7921
- return { attribute: ((_a3 = d == null ? void 0 : d.content) != null ? _a3 : "").substring(0, 40) };
7869
+ var _a2;
7870
+ return { attribute: ((_a2 = d == null ? void 0 : d.content) != null ? _a2 : "").substring(0, 40) };
7922
7871
  })
7923
7872
  };
7924
7873
  }
@@ -7937,8 +7886,8 @@ ${schemaProfileText}` : ""}`;
7937
7886
  return this.createTextResponse(
7938
7887
  "Retrieved Context",
7939
7888
  data.map((item) => {
7940
- var _a3;
7941
- return (_a3 = item == null ? void 0 : item.content) != null ? _a3 : "";
7889
+ var _a2;
7890
+ return (_a2 = item == null ? void 0 : item.content) != null ? _a2 : "";
7942
7891
  }).join("\n\n"),
7943
7892
  `Found ${data.length} relevant results`
7944
7893
  );
@@ -7989,11 +7938,11 @@ ${schemaProfileText}` : ""}`;
7989
7938
  return null;
7990
7939
  }
7991
7940
  static normalizeTransformation(payload) {
7992
- var _a3, _b, _c, _d, _e, _f, _g2, _h, _i, _j;
7941
+ var _a2, _b, _c, _d, _e, _f, _g2, _h, _i, _j;
7993
7942
  if (!payload || typeof payload !== "object") return null;
7994
7943
  const p = payload;
7995
7944
  const type = this.normalizeVisualizationType(
7996
- String((_c = (_b = (_a3 = p.type) != null ? _a3 : p.view) != null ? _b : p.chartType) != null ? _c : "")
7945
+ String((_c = (_b = (_a2 = p.type) != null ? _a2 : p.view) != null ? _b : p.chartType) != null ? _c : "")
7997
7946
  );
7998
7947
  if (!type) return null;
7999
7948
  const title = String((_e = (_d = p.title) != null ? _d : p.heading) != null ? _e : "Visualization");
@@ -8004,7 +7953,7 @@ ${schemaProfileText}` : ""}`;
8004
7953
  return this.validateTransformation(transformation) ? transformation : null;
8005
7954
  }
8006
7955
  static normalizeVisualizationType(type) {
8007
- var _a3;
7956
+ var _a2;
8008
7957
  const mapping = {
8009
7958
  pie: "pie_chart",
8010
7959
  pie_chart: "pie_chart",
@@ -8032,7 +7981,7 @@ ${schemaProfileText}` : ""}`;
8032
7981
  product_carousel: "product_carousel",
8033
7982
  carousel: "carousel"
8034
7983
  };
8035
- return (_a3 = mapping[type.toLowerCase()]) != null ? _a3 : null;
7984
+ return (_a2 = mapping[type.toLowerCase()]) != null ? _a2 : null;
8036
7985
  }
8037
7986
  static validateTransformation(t) {
8038
7987
  const { type, data } = t;
@@ -8148,7 +8097,7 @@ ${schemaProfileText}` : ""}`;
8148
8097
  }
8149
8098
  static profileData(data) {
8150
8099
  const records = (data || []).filter((item) => Boolean(item && typeof item === "object")).map((item) => {
8151
- var _a3, _b;
8100
+ var _a2, _b;
8152
8101
  const fields2 = {};
8153
8102
  Object.entries(item.metadata || {}).forEach(([key, value]) => {
8154
8103
  const primitive = this.toPrimitive(value);
@@ -8157,7 +8106,7 @@ ${schemaProfileText}` : ""}`;
8157
8106
  if (!fields2.content && item.content) fields2.content = item.content.substring(0, 500);
8158
8107
  return {
8159
8108
  id: item.id,
8160
- content: (_a3 = item.content) != null ? _a3 : "",
8109
+ content: (_a2 = item.content) != null ? _a2 : "",
8161
8110
  score: (_b = item.score) != null ? _b : 0,
8162
8111
  fields: fields2,
8163
8112
  source: item
@@ -8238,16 +8187,16 @@ ${schemaProfileText}` : ""}`;
8238
8187
  return null;
8239
8188
  }
8240
8189
  static selectDimensionField(profile, query) {
8241
- var _a3, _b;
8190
+ var _a2, _b;
8242
8191
  const productCategory = profile.categoricalFields.find(
8243
8192
  (field) => /category|department|collection|type|group|segment|region|country|state|city/i.test(field.key)
8244
8193
  );
8245
8194
  const ranked = this.rankFieldsByQuery(profile.categoricalFields, query);
8246
- return (_b = (_a3 = ranked[0]) != null ? _a3 : productCategory) != null ? _b : profile.categoricalFields[0];
8195
+ return (_b = (_a2 = ranked[0]) != null ? _a2 : productCategory) != null ? _b : profile.categoricalFields[0];
8247
8196
  }
8248
8197
  static selectNumericField(profile, query) {
8249
- var _a3;
8250
- return (_a3 = this.rankFieldsByQuery(profile.numericFields, query)[0]) != null ? _a3 : profile.numericFields[0];
8198
+ var _a2;
8199
+ return (_a2 = this.rankFieldsByQuery(profile.numericFields, query)[0]) != null ? _a2 : profile.numericFields[0];
8251
8200
  }
8252
8201
  static rankFieldsByQuery(fields, query) {
8253
8202
  const q = query.toLowerCase();
@@ -8276,8 +8225,8 @@ ${schemaProfileText}` : ""}`;
8276
8225
  static aggregateProfileByDimension(profile, dimensionKey, measureKey) {
8277
8226
  const result = {};
8278
8227
  profile.records.forEach((record) => {
8279
- var _a3, _b, _c;
8280
- const category = String((_a3 = record.fields[dimensionKey]) != null ? _a3 : "Other").trim() || "Other";
8228
+ var _a2, _b, _c;
8229
+ const category = String((_a2 = record.fields[dimensionKey]) != null ? _a2 : "Other").trim() || "Other";
8281
8230
  const value = measureKey ? (_b = this.toFiniteNumber(record.fields[measureKey])) != null ? _b : 0 : 1;
8282
8231
  result[category] = ((_c = result[category]) != null ? _c : 0) + value;
8283
8232
  });
@@ -8357,8 +8306,8 @@ ${schemaProfileText}` : ""}`;
8357
8306
  static aggregateByCategory(data, categories) {
8358
8307
  const result = Object.fromEntries(categories.map((c) => [c, 0]));
8359
8308
  data.forEach((item) => {
8360
- var _a3;
8361
- const cat = (_a3 = this.getProductCategory(item)) != null ? _a3 : "Other";
8309
+ var _a2;
8310
+ const cat = (_a2 = this.getProductCategory(item)) != null ? _a2 : "Other";
8362
8311
  if (Object.prototype.hasOwnProperty.call(result, cat)) result[cat]++;
8363
8312
  else result["Other"] = (result["Other"] || 0) + 1;
8364
8313
  });
@@ -8366,17 +8315,17 @@ ${schemaProfileText}` : ""}`;
8366
8315
  }
8367
8316
  static extractTimeSeriesData(data) {
8368
8317
  return data.map((item) => {
8369
- var _a3, _b, _c, _d, _e, _f;
8318
+ var _a2, _b, _c, _d, _e, _f;
8370
8319
  const meta = item.metadata || {};
8371
8320
  return {
8372
- timestamp: (_b = (_a3 = meta.timestamp) != null ? _a3 : meta.date) != null ? _b : (/* @__PURE__ */ new Date()).toISOString(),
8321
+ timestamp: (_b = (_a2 = meta.timestamp) != null ? _a2 : meta.date) != null ? _b : (/* @__PURE__ */ new Date()).toISOString(),
8373
8322
  value: (_d = (_c = meta.value) != null ? _c : item.score) != null ? _d : 0,
8374
8323
  label: (_f = meta.label) != null ? _f : ((_e = item == null ? void 0 : item.content) != null ? _e : "").substring(0, 50)
8375
8324
  };
8376
8325
  });
8377
8326
  }
8378
8327
  static extractNumericValue(meta) {
8379
- var _a3;
8328
+ var _a2;
8380
8329
  const preferredKeys = [
8381
8330
  "value",
8382
8331
  "count",
@@ -8391,7 +8340,7 @@ ${schemaProfileText}` : ""}`;
8391
8340
  "price"
8392
8341
  ];
8393
8342
  for (const key of preferredKeys) {
8394
- const raw = (_a3 = resolveMetadataValue(meta, key)) != null ? _a3 : meta[key];
8343
+ const raw = (_a2 = resolveMetadataValue(meta, key)) != null ? _a2 : meta[key];
8395
8344
  const value = typeof raw === "number" ? raw : Number(String(raw != null ? raw : "").replace(/[$,% ,]/g, ""));
8396
8345
  if (Number.isFinite(value)) return value;
8397
8346
  }
@@ -8486,8 +8435,8 @@ ${schemaProfileText}` : ""}`;
8486
8435
  }, query.includes(normalizedField) ? 3 : 0);
8487
8436
  }
8488
8437
  static resolveTableCellValue(item, column) {
8489
- var _a3, _b, _c;
8490
- if (column === "Content") return ((_a3 = item == null ? void 0 : item.content) != null ? _a3 : "").substring(0, 100);
8438
+ var _a2, _b, _c;
8439
+ if (column === "Content") return ((_a2 = item == null ? void 0 : item.content) != null ? _a2 : "").substring(0, 100);
8491
8440
  const meta = item.metadata || {};
8492
8441
  const normalizedColumn = this.normalizeComparableField(column);
8493
8442
  const exactMetadata = Object.entries(meta).find(
@@ -8539,8 +8488,8 @@ ${schemaProfileText}` : ""}`;
8539
8488
  let inStock = 0;
8540
8489
  let outOfStock = 0;
8541
8490
  data.forEach((d) => {
8542
- var _a3, _b;
8543
- const cat = (_a3 = this.getProductCategory(d)) != null ? _a3 : "Other";
8491
+ var _a2, _b;
8492
+ const cat = (_a2 = this.getProductCategory(d)) != null ? _a2 : "Other";
8544
8493
  if (cat === category) {
8545
8494
  const quantity = (_b = this.extractStockQuantity(d)) != null ? _b : 1;
8546
8495
  if (this.determineStockStatus(d)) inStock += quantity;
@@ -8586,9 +8535,9 @@ ${schemaProfileText}` : ""}`;
8586
8535
  }
8587
8536
  // ─── Product Extraction ───────────────────────────────────────────────────
8588
8537
  static getDynamicVal(meta, uiKey, config, trainedSchema) {
8589
- var _a3;
8538
+ var _a2;
8590
8539
  if (!meta) return void 0;
8591
- const mapping = (_a3 = config == null ? void 0 : config.rag) == null ? void 0 : _a3.uiMapping;
8540
+ const mapping = (_a2 = config == null ? void 0 : config.rag) == null ? void 0 : _a2.uiMapping;
8592
8541
  if ((mapping == null ? void 0 : mapping[uiKey]) && meta[mapping[uiKey]] !== void 0) return meta[mapping[uiKey]];
8593
8542
  if (trainedSchema && typeof trainedSchema === "object") {
8594
8543
  const trainedKey = trainedSchema[uiKey];
@@ -8597,7 +8546,7 @@ ${schemaProfileText}` : ""}`;
8597
8546
  return resolveMetadataValue(meta, uiKey);
8598
8547
  }
8599
8548
  static extractProductInfo(item, config, trainedSchema) {
8600
- var _a3, _b;
8549
+ var _a2, _b;
8601
8550
  if (!item) return null;
8602
8551
  const meta = item.metadata || {};
8603
8552
  const content = item.content || "";
@@ -8605,7 +8554,7 @@ ${schemaProfileText}` : ""}`;
8605
8554
  const price = this.getDynamicVal(meta, "price", config, trainedSchema);
8606
8555
  const brand = this.getDynamicVal(meta, "brand", config, trainedSchema);
8607
8556
  const description = this.cleanProductDescription(
8608
- (_a3 = this.extractProductDescriptionFromContent(content)) != null ? _a3 : this.getProductDescriptionValue(meta, config, trainedSchema)
8557
+ (_a2 = this.extractProductDescriptionFromContent(content)) != null ? _a2 : this.getProductDescriptionValue(meta, config, trainedSchema)
8609
8558
  );
8610
8559
  if (name || this.isProductData(item)) {
8611
8560
  let finalName = name ? String(name) : void 0;
@@ -8740,10 +8689,10 @@ RULES:
8740
8689
  }
8741
8690
  static buildContextSummary(sources, maxChars = 6e3) {
8742
8691
  const items = (sources || []).filter(Boolean).map((s, i) => {
8743
- var _a3, _b, _c, _d;
8692
+ var _a2, _b, _c, _d;
8744
8693
  return {
8745
8694
  index: i + 1,
8746
- content: (_b = (_a3 = s == null ? void 0 : s.content) == null ? void 0 : _a3.substring(0, 400)) != null ? _b : "",
8695
+ content: (_b = (_a2 = s == null ? void 0 : s.content) == null ? void 0 : _a2.substring(0, 400)) != null ? _b : "",
8747
8696
  metadata: (_c = s == null ? void 0 : s.metadata) != null ? _c : {},
8748
8697
  score: (_d = s == null ? void 0 : s.score) != null ? _d : 0
8749
8698
  };
@@ -8783,7 +8732,7 @@ var SchemaMapper = class {
8783
8732
  return promise;
8784
8733
  }
8785
8734
  static async _doTrain(llm, cacheKey, keys) {
8786
- var _a3, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k;
8735
+ var _a2, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k;
8787
8736
  const propertyList = Object.entries(this.TARGET_PROPERTIES).map(([prop, desc]) => `- ${prop} (${desc})`).join("\n");
8788
8737
  const messages = [
8789
8738
  { role: "system", content: "You are a database schema expert. Respond ONLY with valid JSON." },
@@ -8798,7 +8747,7 @@ Return a JSON object like {"name":"Title","price":"Price",...}. Omit unmapped pr
8798
8747
  }
8799
8748
  ];
8800
8749
  try {
8801
- const baseUrl = (_a3 = llm == null ? void 0 : llm.baseUrl) != null ? _a3 : "";
8750
+ const baseUrl = (_a2 = llm == null ? void 0 : llm.baseUrl) != null ? _a2 : "";
8802
8751
  const apiKey = (_b = llm == null ? void 0 : llm.apiKey) != null ? _b : "";
8803
8752
  const model = (_c = llm == null ? void 0 : llm.model) != null ? _c : "llama-3.1-8b-instant";
8804
8753
  let responseText;
@@ -8973,9 +8922,9 @@ var Pipeline = class {
8973
8922
  this.initialised = false;
8974
8923
  /** Namespace-specific static cold context cache for CAG */
8975
8924
  this.coldContexts = /* @__PURE__ */ new Map();
8976
- var _a3, _b, _c, _d, _e;
8925
+ var _a2, _b, _c, _d, _e;
8977
8926
  this.chunker = new DocumentChunker(
8978
- (_b = (_a3 = config.rag) == null ? void 0 : _a3.chunkSize) != null ? _b : 1e3,
8927
+ (_b = (_a2 = config.rag) == null ? void 0 : _a2.chunkSize) != null ? _b : 1e3,
8979
8928
  (_d = (_c = config.rag) == null ? void 0 : _c.chunkOverlap) != null ? _d : 200
8980
8929
  );
8981
8930
  if (((_e = config.rag) == null ? void 0 : _e.chunkingStrategy) === "llamaindex") {
@@ -8991,7 +8940,7 @@ var Pipeline = class {
8991
8940
  return this.initialised ? this.llmProvider : void 0;
8992
8941
  }
8993
8942
  async initialize() {
8994
- var _a3, _b, _c, _d;
8943
+ var _a2, _b, _c, _d;
8995
8944
  if (this.initialised) return;
8996
8945
  const chartInstruction = `You are a helpful assistant. Use the provided context to answer questions accurately.
8997
8946
 
@@ -9034,7 +8983,7 @@ var Pipeline = class {
9034
8983
  this.entityExtractor = new EntityExtractor(this.llmProvider);
9035
8984
  }
9036
8985
  await this.vectorDB.initialize();
9037
- if (((_a3 = this.config.rag) == null ? void 0 : _a3.architecture) === "agentic" || ((_b = this.config.rag) == null ? void 0 : _b.architecture) === "multi-agent" || this.config.mcpServers && this.config.mcpServers.length > 0) {
8986
+ if (((_a2 = this.config.rag) == null ? void 0 : _a2.architecture) === "agentic" || ((_b = this.config.rag) == null ? void 0 : _b.architecture) === "multi-agent" || this.config.mcpServers && this.config.mcpServers.length > 0) {
9038
8987
  this.mcpRegistry = new MCPRegistry(this.config.mcpServers || []);
9039
8988
  this.multiAgentCoordinator = new MultiAgentCoordinator({
9040
8989
  llmProvider: this.llmProvider,
@@ -9052,8 +9001,8 @@ var Pipeline = class {
9052
9001
  this.initialised = true;
9053
9002
  }
9054
9003
  async loadColdContext(ns) {
9055
- var _a3, _b;
9056
- const cagConfig = (_a3 = this.config.rag) == null ? void 0 : _a3.cag;
9004
+ var _a2, _b;
9005
+ const cagConfig = (_a2 = this.config.rag) == null ? void 0 : _a2.cag;
9057
9006
  if (!cagConfig || !cagConfig.enabled) return;
9058
9007
  try {
9059
9008
  const coldNs = cagConfig.coldNamespace || ns;
@@ -9106,12 +9055,12 @@ ${m.content}`).join("\n\n---\n\n");
9106
9055
  }
9107
9056
  /** Step 1: Chunk the document content. */
9108
9057
  async prepareChunks(doc) {
9109
- var _a3, _b;
9058
+ var _a2, _b;
9110
9059
  if (this.llamaIngestor) {
9111
9060
  return this.llamaIngestor.chunk(doc.content, {
9112
9061
  docId: doc.docId,
9113
9062
  metadata: doc.metadata,
9114
- chunkSize: (_a3 = this.config.rag) == null ? void 0 : _a3.chunkSize,
9063
+ chunkSize: (_a2 = this.config.rag) == null ? void 0 : _a2.chunkSize,
9115
9064
  chunkOverlap: (_b = this.config.rag) == null ? void 0 : _b.chunkOverlap
9116
9065
  });
9117
9066
  }
@@ -9209,9 +9158,9 @@ ${m.content}`).join("\n\n---\n\n");
9209
9158
  return { reply, sources };
9210
9159
  }
9211
9160
  async ask(question, history = [], namespace) {
9212
- var _a3, _b;
9161
+ var _a2, _b;
9213
9162
  await this.initialize();
9214
- if ((((_a3 = this.config.rag) == null ? void 0 : _a3.architecture) === "agentic" || ((_b = this.config.rag) == null ? void 0 : _b.architecture) === "multi-agent" || this.config.mcpServers && this.config.mcpServers.length > 0) && this.multiAgentCoordinator) {
9163
+ if ((((_a2 = this.config.rag) == null ? void 0 : _a2.architecture) === "agentic" || ((_b = this.config.rag) == null ? void 0 : _b.architecture) === "multi-agent" || this.config.mcpServers && this.config.mcpServers.length > 0) && this.multiAgentCoordinator) {
9215
9164
  return await this.multiAgentCoordinator.run(question, history);
9216
9165
  }
9217
9166
  const stream = this.askStream(question, history, namespace);
@@ -9246,9 +9195,9 @@ ${m.content}`).join("\n\n---\n\n");
9246
9195
  }
9247
9196
  askStream(_0) {
9248
9197
  return __asyncGenerator(this, arguments, function* (question, history = [], namespace) {
9249
- var _a3, _b;
9198
+ var _a2, _b;
9250
9199
  yield new __await(this.initialize());
9251
- if ((((_a3 = this.config.rag) == null ? void 0 : _a3.architecture) === "agentic" || ((_b = this.config.rag) == null ? void 0 : _b.architecture) === "multi-agent" || this.config.mcpServers && this.config.mcpServers.length > 0) && this.multiAgentCoordinator) {
9200
+ if ((((_a2 = this.config.rag) == null ? void 0 : _a2.architecture) === "agentic" || ((_b = this.config.rag) == null ? void 0 : _b.architecture) === "multi-agent" || this.config.mcpServers && this.config.mcpServers.length > 0) && this.multiAgentCoordinator) {
9252
9201
  const stream2 = this.multiAgentCoordinator.runStream(question, history);
9253
9202
  try {
9254
9203
  for (var iter = __forAwait(stream2), more, temp, error; more = !(temp = yield new __await(iter.next())).done; more = false) {
@@ -9297,10 +9246,10 @@ ${m.content}`).join("\n\n---\n\n");
9297
9246
  */
9298
9247
  askStreamInternal(_0) {
9299
9248
  return __asyncGenerator(this, arguments, function* (question, history = [], namespace) {
9300
- 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;
9249
+ var _a2, _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;
9301
9250
  yield new __await(this.initialize());
9302
9251
  const ns = formatNamespace(namespace != null ? namespace : this.config.projectId);
9303
- const topK = (_b = (_a3 = this.config.rag) == null ? void 0 : _a3.topK) != null ? _b : 5;
9252
+ const topK = (_b = (_a2 = this.config.rag) == null ? void 0 : _a2.topK) != null ? _b : 5;
9304
9253
  const scoreThreshold = (_d = (_c = this.config.rag) == null ? void 0 : _c.scoreThreshold) != null ? _d : 0.3;
9305
9254
  const requestId = `req_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
9306
9255
  const requestStart = performance.now();
@@ -9349,8 +9298,8 @@ ${m.content}`).join("\n\n---\n\n");
9349
9298
  const rerankStart = performance.now();
9350
9299
  const structuredSources = this.applyStructuredFilters(rawSources, filter).filter((s) => Boolean(s && typeof s === "object"));
9351
9300
  let fullSources = hasNumericPredicates ? structuredSources : structuredSources.filter((m) => {
9352
- var _a4;
9353
- return ((_a4 = m == null ? void 0 : m.score) != null ? _a4 : 0) >= scoreThreshold;
9301
+ var _a3;
9302
+ return ((_a3 = m == null ? void 0 : m.score) != null ? _a3 : 0) >= scoreThreshold;
9354
9303
  });
9355
9304
  const rerankLimit = Math.max(retrievalLimit, fullSources.length);
9356
9305
  const useReranking = arch !== "naive" && (arch === "retrieve-and-rerank" || ((_m = this.config.rag) == null ? void 0 : _m.useReranking));
@@ -9363,13 +9312,13 @@ ${m.content}`).join("\n\n---\n\n");
9363
9312
  let context = promptSources.length ? `[SEARCH SUMMARY: Found ${totalCount} matching record(s) out of ${rawSources.length} total resources searched in database. Context includes top ${promptSources.length} relevant records]
9364
9313
 
9365
9314
  ` + promptSources.map((m, i) => {
9366
- var _a4;
9315
+ var _a3;
9367
9316
  return `[Source ${i + 1}]
9368
- ${(_a4 = m == null ? void 0 : m.content) != null ? _a4 : ""}`;
9317
+ ${(_a3 = m == null ? void 0 : m.content) != null ? _a3 : ""}`;
9369
9318
  }).join("\n\n---\n\n") : "No relevant context found.";
9370
9319
  const sources = [...fullSources].filter((s) => Boolean(s && typeof s === "object")).sort((a, b) => {
9371
- var _a4, _b2;
9372
- return ((_a4 = b == null ? void 0 : b.score) != null ? _a4 : 0) - ((_b2 = a == null ? void 0 : a.score) != null ? _b2 : 0);
9320
+ var _a3, _b2;
9321
+ return ((_a3 = b == null ? void 0 : b.score) != null ? _a3 : 0) - ((_b2 = a == null ? void 0 : a.score) != null ? _b2 : 0);
9373
9322
  });
9374
9323
  if (graphData && graphData.nodes.length > 0) {
9375
9324
  const graphContext = graphData.nodes.map(
@@ -9397,10 +9346,10 @@ ${context}`;
9397
9346
  yield {
9398
9347
  reply: "",
9399
9348
  sources: (sources || []).filter((s) => Boolean(s && typeof s === "object")).map((s) => {
9400
- var _a4, _b2, _c2;
9349
+ var _a3, _b2, _c2;
9401
9350
  return {
9402
9351
  id: s.id,
9403
- score: (_a4 = s.score) != null ? _a4 : 0,
9352
+ score: (_a3 = s.score) != null ? _a3 : 0,
9404
9353
  content: (_b2 = s == null ? void 0 : s.content) != null ? _b2 : "",
9405
9354
  metadata: (_c2 = s == null ? void 0 : s.metadata) != null ? _c2 : {},
9406
9355
  namespace: ns
@@ -9593,11 +9542,11 @@ ${context}`;
9593
9542
  systemPrompt,
9594
9543
  userPrompt: question + finalRestrictionSuffix,
9595
9544
  chunks: (sources || []).filter(Boolean).map((s) => {
9596
- var _a4, _b2;
9545
+ var _a3, _b2;
9597
9546
  return {
9598
9547
  id: s.id,
9599
9548
  score: s.score,
9600
- content: (_a4 = s == null ? void 0 : s.content) != null ? _a4 : "",
9549
+ content: (_a3 = s == null ? void 0 : s.content) != null ? _a3 : "",
9601
9550
  metadata: (_b2 = s == null ? void 0 : s.metadata) != null ? _b2 : {},
9602
9551
  namespace: ns
9603
9552
  };
@@ -9616,7 +9565,7 @@ ${context}`;
9616
9565
  const telemetryUrl = ((_B = this.config.telemetry) == null ? void 0 : _B.url) || process.env.TELEMETRY_URL || process.env.NEXT_PUBLIC_TELEMETRY_URL || defaultUrl;
9617
9566
  const absoluteUrl = telemetryUrl.startsWith("http") ? telemetryUrl : "https://www.retrivora.com" + (telemetryUrl.startsWith("/") ? telemetryUrl : "/" + telemetryUrl);
9618
9567
  (async () => {
9619
- var _a4, _b2, _c2, _d2, _e2;
9568
+ var _a3, _b2, _c2, _d2, _e2;
9620
9569
  try {
9621
9570
  let finalTrace = trace;
9622
9571
  if (!awaitHallucination && runHallucination) {
@@ -9625,7 +9574,7 @@ ${context}`;
9625
9574
  finalTrace = buildTrace(backgroundScoreResult);
9626
9575
  }
9627
9576
  }
9628
- const modelName = (finalTrace == null ? void 0 : finalTrace.model) || ((_a4 = this.config.llm) == null ? void 0 : _a4.model) || "llama-3.1-8b-instant";
9577
+ const modelName = (finalTrace == null ? void 0 : finalTrace.model) || ((_a3 = this.config.llm) == null ? void 0 : _a3.model) || "llama-3.1-8b-instant";
9629
9578
  const providerName = (finalTrace == null ? void 0 : finalTrace.provider) || ((_b2 = this.config.llm) == null ? void 0 : _b2.provider) || "groq";
9630
9579
  const tokenCount = Number(((_c2 = finalTrace == null ? void 0 : finalTrace.tokens) == null ? void 0 : _c2.totalTokens) || 0);
9631
9580
  const costEst = Number(((_d2 = finalTrace == null ? void 0 : finalTrace.tokens) == null ? void 0 : _d2.estimatedCostUsd) || 0);
@@ -9679,7 +9628,7 @@ ${context}`;
9679
9628
  * Uses an LRU-bounded embedding cache to avoid re-embedding the same query.
9680
9629
  */
9681
9630
  async generateUiTransformation(question, sources, cachedSchema, forceDeterministic = false) {
9682
- var _a3;
9631
+ var _a2;
9683
9632
  if (!sources || sources.length === 0) {
9684
9633
  return UITransformer.transform(question, sources, this.config, cachedSchema);
9685
9634
  }
@@ -9692,7 +9641,7 @@ ${context}`;
9692
9641
  { visualizationHint: "product_browse", recommendedChart: "text", filterInStockOnly: false, wantsExplicitTable: false, isTemporal: false, isComparison: false, language: "en" }
9693
9642
  );
9694
9643
  }
9695
- const enableLlmUiTransform = ((_a3 = this.config.llm.options) == null ? void 0 : _a3.enableLlmUiTransform) === true;
9644
+ const enableLlmUiTransform = ((_a2 = this.config.llm.options) == null ? void 0 : _a2.enableLlmUiTransform) === true;
9696
9645
  if (forceDeterministic || !enableLlmUiTransform) {
9697
9646
  return UITransformer.transform(question, sources, this.config, cachedSchema);
9698
9647
  }
@@ -9710,15 +9659,15 @@ ${context}`;
9710
9659
  const value = this.resolveNumericPredicateValue(source, predicate);
9711
9660
  return value !== null && this.matchesNumericPredicate(value, predicate);
9712
9661
  })).sort((a, b) => {
9713
- var _a3, _b;
9662
+ var _a2, _b;
9714
9663
  const primary = predicates[0];
9715
- const aValue = (_a3 = this.resolveNumericPredicateValue(a, primary)) != null ? _a3 : 0;
9664
+ const aValue = (_a2 = this.resolveNumericPredicateValue(a, primary)) != null ? _a2 : 0;
9716
9665
  const bValue = (_b = this.resolveNumericPredicateValue(b, primary)) != null ? _b : 0;
9717
9666
  return primary.operator === "lt" || primary.operator === "lte" ? aValue - bValue : bValue - aValue;
9718
9667
  });
9719
9668
  }
9720
9669
  resolveNumericPredicateValue(source, predicate) {
9721
- var _a3;
9670
+ var _a2;
9722
9671
  if (!source) return null;
9723
9672
  const meta = source.metadata || {};
9724
9673
  const field = predicate.field;
@@ -9731,7 +9680,7 @@ ${context}`;
9731
9680
  const value = this.toFiniteNumber(Array.isArray(fuzzy) ? fuzzy[1] : fuzzy.value);
9732
9681
  if (value !== null) return value;
9733
9682
  }
9734
- const contentValue = this.extractNumericValueFromContent((_a3 = source.content) != null ? _a3 : "", field);
9683
+ const contentValue = this.extractNumericValueFromContent((_a2 = source.content) != null ? _a2 : "", field);
9735
9684
  if (contentValue !== null) return contentValue;
9736
9685
  }
9737
9686
  for (const [key, value] of entries) {
@@ -9787,8 +9736,8 @@ ${context}`;
9787
9736
  return Number.isFinite(numeric) ? numeric : null;
9788
9737
  }
9789
9738
  async retrieve(query, options) {
9790
- var _a3, _b, _c, _d, _e, _f, _g2;
9791
- const ns = formatNamespace((_a3 = options.namespace) != null ? _a3 : this.config.projectId);
9739
+ var _a2, _b, _c, _d, _e, _f, _g2;
9740
+ const ns = formatNamespace((_a2 = options.namespace) != null ? _a2 : this.config.projectId);
9792
9741
  const topK = (_b = options.topK) != null ? _b : 5;
9793
9742
  const cacheKey = `${ns}::${query}`;
9794
9743
  let queryVector = this.embeddingCache.get(cacheKey);
@@ -9833,11 +9782,11 @@ ${context}`;
9833
9782
  namespace: ns,
9834
9783
  count: resolvedSources.length,
9835
9784
  sample: resolvedSources.slice(0, 2).map((s) => {
9836
- var _a4;
9785
+ var _a3;
9837
9786
  return {
9838
9787
  id: s == null ? void 0 : s.id,
9839
9788
  score: s == null ? void 0 : s.score,
9840
- contentSnippet: String((_a4 = s == null ? void 0 : s.content) != null ? _a4 : "").substring(0, 150),
9789
+ contentSnippet: String((_a3 = s == null ? void 0 : s.content) != null ? _a3 : "").substring(0, 150),
9841
9790
  metadata: s == null ? void 0 : s.metadata
9842
9791
  };
9843
9792
  })
@@ -9851,8 +9800,8 @@ Focus on extracting the core intent and entities. Do not answer the question, ju
9851
9800
 
9852
9801
  History:
9853
9802
  ${(history || []).map((m) => {
9854
- var _a3;
9855
- return `${(m == null ? void 0 : m.role) || "user"}: ${(_a3 = m == null ? void 0 : m.content) != null ? _a3 : ""}`;
9803
+ var _a2;
9804
+ return `${(m == null ? void 0 : m.role) || "user"}: ${(_a2 = m == null ? void 0 : m.content) != null ? _a2 : ""}`;
9856
9805
  }).join("\n")}
9857
9806
 
9858
9807
  New Question: ${question}
@@ -9879,8 +9828,8 @@ Optimized Search Query:`;
9879
9828
  const { sources } = await this.retrieve(query, { namespace: ns, topK: 5 });
9880
9829
  if (!sources || sources.length === 0) return [];
9881
9830
  const context = sources.map((s) => {
9882
- var _a3;
9883
- return (_a3 = s == null ? void 0 : s.content) != null ? _a3 : "";
9831
+ var _a2;
9832
+ return (_a2 = s == null ? void 0 : s.content) != null ? _a2 : "";
9884
9833
  }).join("\n\n---\n\n");
9885
9834
  const prompt = `Based on the following snippets from a document, what are at least 5 short, relevant questions a user might ask?
9886
9835
  Focus on questions that can be answered by the context.
@@ -9922,13 +9871,13 @@ var Retrivora = class {
9922
9871
  this.pipeline = new Pipeline(this.config);
9923
9872
  }
9924
9873
  async initialize() {
9925
- var _a3;
9874
+ var _a2;
9926
9875
  try {
9927
9876
  await ConfigValidator.validateAndThrow(this.config);
9928
9877
  await LicenseVerifier.verifyAsync(
9929
9878
  this.config.licenseKey,
9930
9879
  this.config.projectId,
9931
- (_a3 = this.config.vectorDb) == null ? void 0 : _a3.provider
9880
+ (_a2 = this.config.vectorDb) == null ? void 0 : _a2.provider
9932
9881
  );
9933
9882
  await LicenseVerifier.verifyIP(this.config.licenseKey);
9934
9883
  } catch (err) {
@@ -10102,186 +10051,9 @@ var ProviderHealthCheck = class {
10102
10051
  };
10103
10052
 
10104
10053
  // src/core/FreeTierLimitsGuard.ts
10105
- var FREE_TIER_QUOTAS = {
10106
- MAX_DOCUMENTS: 25,
10107
- MAX_FILE_SIZE_BYTES: 20 * 1024 * 1024,
10108
- MAX_STORAGE_BYTES: 250 * 1024 * 1024,
10109
- MAX_TRIAL_REQUEST_UNITS: 500,
10110
- MAX_DAILY_REQUEST_UNITS: 50,
10111
- TRIAL_DURATION_DAYS: 14,
10112
- GRACE_PERIOD_DAYS: 2,
10113
- MAX_RPM: 10,
10114
- MAX_RPH: 100,
10115
- MAX_RPD: 500,
10116
- MAX_CONCURRENT_REQUESTS: 2,
10117
- MAX_INPUT_TOKENS: 2e4,
10118
- MAX_OUTPUT_TOKENS: 4e3,
10119
- UPGRADE_REMINDER_DAYS: [7, 12, 14],
10120
- MAX_USERS: 1,
10121
- MAX_NAMESPACES: 1,
10122
- MAX_PROJECTS: 1
10123
- };
10124
- var FreeTierLimitsGuard = class {
10125
- static calculateTrialTimestamps(startedAt) {
10126
- const startDate = startedAt ? new Date(startedAt) : /* @__PURE__ */ new Date();
10127
- const trialStartedAtMs = startDate.getTime();
10128
- const trialExpiresAtMs = trialStartedAtMs + FREE_TIER_QUOTAS.TRIAL_DURATION_DAYS * 24 * 60 * 60 * 1e3;
10129
- const gracePeriodExpiresAtMs = trialStartedAtMs + (FREE_TIER_QUOTAS.TRIAL_DURATION_DAYS + FREE_TIER_QUOTAS.GRACE_PERIOD_DAYS) * 24 * 60 * 60 * 1e3;
10130
- return {
10131
- trial_started_at: new Date(trialStartedAtMs).toISOString(),
10132
- trial_expires_at: new Date(trialExpiresAtMs).toISOString(),
10133
- grace_period_expires_at: new Date(gracePeriodExpiresAtMs).toISOString()
10134
- };
10135
- }
10136
- static calculateRequestUnits(operationType, options) {
10137
- var _a3;
10138
- const op = operationType.toLowerCase().trim();
10139
- if (op.includes("suggestion") || op.includes("template") || op.includes("history") || op.includes("model") || op.includes("health") || op.includes("auth") || op.includes("license") || op.includes("usage") || op.includes("feedback") || op.includes("analytic")) {
10140
- return 0;
10141
- }
10142
- if (op.includes("image")) {
10143
- return 10;
10144
- }
10145
- if (op.includes("embedding")) {
10146
- const chunks = (_a3 = options == null ? void 0 : options.chunkCount) != null ? _a3 : 1;
10147
- return Math.max(1, Math.ceil(chunks / 1e3));
10148
- }
10149
- return 1;
10150
- }
10151
- static checkTrialStatus(startedAt, totalUnitsUsed = 0, nowServerTime = /* @__PURE__ */ new Date()) {
10152
- const timestamps = this.calculateTrialTimestamps(startedAt);
10153
- const startMs = new Date(timestamps.trial_started_at).getTime();
10154
- const expireMs = new Date(timestamps.trial_expires_at).getTime();
10155
- const graceExpireMs = new Date(timestamps.grace_period_expires_at).getTime();
10156
- const nowMs = nowServerTime.getTime();
10157
- const daysElapsed = Math.floor(Math.max(0, nowMs - startMs) / (1e3 * 60 * 60 * 24));
10158
- const daysRemaining = Math.max(0, Math.ceil((expireMs - nowMs) / (1e3 * 60 * 60 * 24)));
10159
- const isConsumedUnits = totalUnitsUsed >= FREE_TIER_QUOTAS.MAX_TRIAL_REQUEST_UNITS;
10160
- const isExpiredTime = nowMs > expireMs;
10161
- const isPastGraceTime = nowMs > graceExpireMs;
10162
- let status = "active";
10163
- let reason;
10164
- if (isPastGraceTime || isConsumedUnits && isExpiredTime) {
10165
- status = "expired";
10166
- reason = "Trial period and grace period have expired. Upgrade your plan.";
10167
- } else if (isExpiredTime || isConsumedUnits) {
10168
- status = "grace_period";
10169
- reason = isConsumedUnits ? "Total trial request quota (500 units) consumed. Grace period active (dashboard access only)." : "14-day trial period expired. 2-day grace period active (dashboard access only).";
10170
- }
10171
- let upgradeReminderDue;
10172
- if (FREE_TIER_QUOTAS.UPGRADE_REMINDER_DAYS.includes(daysElapsed)) {
10173
- upgradeReminderDue = daysElapsed;
10174
- }
10175
- let usageReminderDue;
10176
- const usagePercent = totalUnitsUsed / FREE_TIER_QUOTAS.MAX_TRIAL_REQUEST_UNITS * 100;
10177
- if (usagePercent >= 100) {
10178
- usageReminderDue = "100%";
10179
- } else if (usagePercent >= 90) {
10180
- usageReminderDue = "90%";
10181
- } else if (usagePercent >= 80) {
10182
- usageReminderDue = "80%";
10183
- }
10184
- return {
10185
- status,
10186
- daysElapsed,
10187
- daysRemaining,
10188
- isGracePeriod: status === "grace_period",
10189
- isExpired: status === "expired",
10190
- upgradeReminderDue,
10191
- usageReminderDue,
10192
- reason
10193
- };
10194
- }
10195
- static checkIngestionAllowed(stats, incomingSizeBytes = 0) {
10196
- var _a3, _b;
10197
- const docs = (_a3 = stats.documentCount) != null ? _a3 : 0;
10198
- const storage = (_b = stats.totalStorageBytes) != null ? _b : 0;
10199
- if (incomingSizeBytes > FREE_TIER_QUOTAS.MAX_FILE_SIZE_BYTES) {
10200
- const mbSize = (incomingSizeBytes / (1024 * 1024)).toFixed(1);
10201
- return {
10202
- allowed: false,
10203
- reason: `[FreeTierIngestor] File size (${mbSize}MB) exceeds maximum allowed size of 20MB under Free Tier rules.`
10204
- };
10205
- }
10206
- if (docs >= FREE_TIER_QUOTAS.MAX_DOCUMENTS) {
10207
- return {
10208
- allowed: false,
10209
- reason: `Document limit reached (${docs}/${FREE_TIER_QUOTAS.MAX_DOCUMENTS}). Upgrade to Pro to ingest more documents.`
10210
- };
10211
- }
10212
- if (storage + incomingSizeBytes > FREE_TIER_QUOTAS.MAX_STORAGE_BYTES) {
10213
- const mbUsed = (storage / (1024 * 1024)).toFixed(1);
10214
- return {
10215
- allowed: false,
10216
- reason: `Storage quota exceeded (${mbUsed}MB / 250MB). Upgrade for unlimited storage.`
10217
- };
10218
- }
10219
- return { allowed: true };
10220
- }
10221
- static checkRequestAllowed(params) {
10222
- var _a3, _b, _c;
10223
- const op = (_a3 = params.operationType) != null ? _a3 : "chat";
10224
- const costUnits = this.calculateRequestUnits(op, { chunkCount: params.chunkCount });
10225
- if (costUnits === 0) {
10226
- return { allowed: true, costUnits: 0 };
10227
- }
10228
- if (params.inputTokens && params.inputTokens > FREE_TIER_QUOTAS.MAX_INPUT_TOKENS) {
10229
- return {
10230
- allowed: false,
10231
- reason: "Token limit exceeded. Upgrade your plan.",
10232
- costUnits
10233
- };
10234
- }
10235
- if (params.outputTokens && params.outputTokens > FREE_TIER_QUOTAS.MAX_OUTPUT_TOKENS) {
10236
- return {
10237
- allowed: false,
10238
- reason: "Token limit exceeded. Upgrade your plan.",
10239
- costUnits
10240
- };
10241
- }
10242
- if (params.concurrentRequests && params.concurrentRequests > FREE_TIER_QUOTAS.MAX_CONCURRENT_REQUESTS) {
10243
- return {
10244
- allowed: false,
10245
- reason: `Concurrent limit exceeded (max ${FREE_TIER_QUOTAS.MAX_CONCURRENT_REQUESTS} active requests). Please wait for active streams to finish.`,
10246
- costUnits
10247
- };
10248
- }
10249
- const totalUnits = (_b = params.totalUnitsUsed) != null ? _b : 0;
10250
- const trialStatus = this.checkTrialStatus(params.trialStartedAt, totalUnits, params.nowServerTime);
10251
- if (trialStatus.status === "expired" || trialStatus.status === "grace_period") {
10252
- return {
10253
- allowed: false,
10254
- reason: trialStatus.reason || "Trial limit reached. Upgrade your plan.",
10255
- costUnits
10256
- };
10257
- }
10258
- if (totalUnits + costUnits > FREE_TIER_QUOTAS.MAX_TRIAL_REQUEST_UNITS) {
10259
- return {
10260
- allowed: false,
10261
- reason: `Total trial request unit limit reached (${totalUnits}/${FREE_TIER_QUOTAS.MAX_TRIAL_REQUEST_UNITS}). Upgrade your plan.`,
10262
- costUnits
10263
- };
10264
- }
10265
- const dailyUnits = (_c = params.dailyUnitsUsed) != null ? _c : 0;
10266
- if (dailyUnits + costUnits > FREE_TIER_QUOTAS.MAX_DAILY_REQUEST_UNITS) {
10267
- return {
10268
- allowed: false,
10269
- reason: `Daily request quota limit reached (${dailyUnits}/${FREE_TIER_QUOTAS.MAX_DAILY_REQUEST_UNITS} units/day). Quota resets tomorrow.`,
10270
- costUnits
10271
- };
10272
- }
10273
- return { allowed: true, costUnits };
10274
- }
10275
- static checkQueryAllowed(dailyQueriesCount = 0) {
10276
- if (dailyQueriesCount >= FREE_TIER_QUOTAS.MAX_DAILY_REQUEST_UNITS) {
10277
- return {
10278
- allowed: false,
10279
- reason: `Daily query limit reached (${FREE_TIER_QUOTAS.MAX_DAILY_REQUEST_UNITS}/day). Quota resets tomorrow.`
10280
- };
10281
- }
10282
- return { allowed: true };
10283
- }
10284
- };
10054
+ var FreeTierLimitsGuard_exports = {};
10055
+ __reExport(FreeTierLimitsGuard_exports, billing_guards_star);
10056
+ import * as billing_guards_star from "@retrivora-ai/billing-guards";
10285
10057
 
10286
10058
  // src/core/VectorPlugin.ts
10287
10059
  var VectorPlugin = class {
@@ -10289,12 +10061,12 @@ var VectorPlugin = class {
10289
10061
  const resolvedConfig = ConfigResolver.resolve(hostConfig);
10290
10062
  this.config = resolvedConfig;
10291
10063
  this.validationPromise = (async () => {
10292
- var _a3;
10064
+ var _a2;
10293
10065
  await ConfigValidator.validateAndThrow(resolvedConfig);
10294
10066
  await LicenseVerifier.verifyAsync(
10295
10067
  resolvedConfig.licenseKey,
10296
10068
  resolvedConfig.projectId,
10297
- (_a3 = resolvedConfig.vectorDb) == null ? void 0 : _a3.provider
10069
+ (_a2 = resolvedConfig.vectorDb) == null ? void 0 : _a2.provider
10298
10070
  );
10299
10071
  })();
10300
10072
  this.validationPromise.catch(() => {
@@ -10330,8 +10102,8 @@ var VectorPlugin = class {
10330
10102
  }
10331
10103
  estimateInputTokens(message, history = []) {
10332
10104
  const allContent = message.length + history.reduce((acc, m) => {
10333
- var _a3, _b;
10334
- return acc + (((_a3 = m == null ? void 0 : m.content) == null ? void 0 : _a3.length) || ((_b = m == null ? void 0 : m.text) == null ? void 0 : _b.length) || 0);
10105
+ var _a2, _b;
10106
+ return acc + (((_a2 = m == null ? void 0 : m.content) == null ? void 0 : _a2.length) || ((_b = m == null ? void 0 : m.text) == null ? void 0 : _b.length) || 0);
10335
10107
  }, 0);
10336
10108
  return Math.ceil(allContent / 4);
10337
10109
  }
@@ -10339,7 +10111,7 @@ var VectorPlugin = class {
10339
10111
  * Run a chat query.
10340
10112
  */
10341
10113
  async chat(message, history = [], namespace) {
10342
- var _a3;
10114
+ var _a2;
10343
10115
  try {
10344
10116
  await this.validationPromise;
10345
10117
  } catch (err) {
@@ -10347,11 +10119,11 @@ var VectorPlugin = class {
10347
10119
  }
10348
10120
  try {
10349
10121
  const inputTokens = this.estimateInputTokens(message, history);
10350
- const tokenCheck = FreeTierLimitsGuard.checkRequestAllowed({
10122
+ const tokenCheck = FreeTierLimitsGuard_exports.FreeTierLimitsGuard.checkRequestAllowed({
10351
10123
  operationType: "chat",
10352
10124
  inputTokens
10353
10125
  });
10354
- if (!tokenCheck.allowed && ((_a3 = tokenCheck.reason) == null ? void 0 : _a3.toLowerCase().includes("token"))) {
10126
+ if (!tokenCheck.allowed && ((_a2 = tokenCheck.reason) == null ? void 0 : _a2.toLowerCase().includes("token"))) {
10355
10127
  throw wrapError(new Error(tokenCheck.reason), "RATE_LIMITED");
10356
10128
  }
10357
10129
  return await this.pipeline.ask(message, history, namespace);
@@ -10372,7 +10144,7 @@ var VectorPlugin = class {
10372
10144
  */
10373
10145
  chatStream(_0) {
10374
10146
  return __asyncGenerator(this, arguments, function* (message, history = [], namespace) {
10375
- var _a3;
10147
+ var _a2;
10376
10148
  try {
10377
10149
  yield new __await(this.validationPromise);
10378
10150
  } catch (err) {
@@ -10380,11 +10152,11 @@ var VectorPlugin = class {
10380
10152
  }
10381
10153
  try {
10382
10154
  const inputTokens = this.estimateInputTokens(message, history);
10383
- const tokenCheck = FreeTierLimitsGuard.checkRequestAllowed({
10155
+ const tokenCheck = FreeTierLimitsGuard_exports.FreeTierLimitsGuard.checkRequestAllowed({
10384
10156
  operationType: "chat_stream",
10385
10157
  inputTokens
10386
10158
  });
10387
- if (!tokenCheck.allowed && ((_a3 = tokenCheck.reason) == null ? void 0 : _a3.toLowerCase().includes("token"))) {
10159
+ if (!tokenCheck.allowed && ((_a2 = tokenCheck.reason) == null ? void 0 : _a2.toLowerCase().includes("token"))) {
10388
10160
  throw wrapError(new Error(tokenCheck.reason), "RATE_LIMITED");
10389
10161
  }
10390
10162
  const stream = this.pipeline.askStream(message, history, namespace);
@@ -10471,13 +10243,13 @@ var ConfigBuilder = class {
10471
10243
  * Configure the vector database provider
10472
10244
  */
10473
10245
  vectorDb(provider, options) {
10474
- var _a3;
10246
+ var _a2;
10475
10247
  if (provider === "auto") {
10476
10248
  this._vectorDb = this._autoDetectVectorDb();
10477
10249
  } else {
10478
10250
  this._vectorDb = {
10479
10251
  provider,
10480
- indexName: (_a3 = options == null ? void 0 : options.indexName) != null ? _a3 : "default",
10252
+ indexName: (_a2 = options == null ? void 0 : options.indexName) != null ? _a2 : "default",
10481
10253
  options: __spreadValues({}, options)
10482
10254
  };
10483
10255
  }
@@ -10487,7 +10259,7 @@ var ConfigBuilder = class {
10487
10259
  * Configure the LLM provider for chat
10488
10260
  */
10489
10261
  llm(provider, model, apiKey, options) {
10490
- var _a3, _b;
10262
+ var _a2, _b;
10491
10263
  if (provider === "auto") {
10492
10264
  this._llm = this._autoDetectLLM();
10493
10265
  } else {
@@ -10496,7 +10268,7 @@ var ConfigBuilder = class {
10496
10268
  model: model != null ? model : "default-model",
10497
10269
  apiKey,
10498
10270
  systemPrompt: options == null ? void 0 : options.systemPrompt,
10499
- maxTokens: (_a3 = options == null ? void 0 : options.maxTokens) != null ? _a3 : 1024,
10271
+ maxTokens: (_a2 = options == null ? void 0 : options.maxTokens) != null ? _a2 : 1024,
10500
10272
  temperature: (_b = options == null ? void 0 : options.temperature) != null ? _b : 0.7,
10501
10273
  baseUrl: options == null ? void 0 : options.baseUrl,
10502
10274
  options
@@ -10539,8 +10311,8 @@ var ConfigBuilder = class {
10539
10311
  * Set RAG-specific pipeline parameters
10540
10312
  */
10541
10313
  rag(options) {
10542
- var _a3;
10543
- this._rag = __spreadValues(__spreadValues({}, (_a3 = this._rag) != null ? _a3 : {}), options);
10314
+ var _a2;
10315
+ this._rag = __spreadValues(__spreadValues({}, (_a2 = this._rag) != null ? _a2 : {}), options);
10544
10316
  return this;
10545
10317
  }
10546
10318
  /**
@@ -10556,7 +10328,7 @@ var ConfigBuilder = class {
10556
10328
  * Throws if required fields (projectId, vectorDb, llm, embedding) are not set.
10557
10329
  */
10558
10330
  build() {
10559
- var _a3;
10331
+ var _a2;
10560
10332
  const missing = [];
10561
10333
  if (!this._projectId) missing.push('projectId (call .projectId("my-app"))');
10562
10334
  if (!this._vectorDb) missing.push('vectorDb (call .vectorDb("pinecone", { ... }))');
@@ -10568,7 +10340,7 @@ var ConfigBuilder = class {
10568
10340
  ${missing.join("\n ")}`
10569
10341
  );
10570
10342
  }
10571
- const ragConfig = (_a3 = this._rag) != null ? _a3 : { chunkSize: 1e3, chunkOverlap: 200, topK: 5 };
10343
+ const ragConfig = (_a2 = this._rag) != null ? _a2 : { chunkSize: 1e3, chunkOverlap: 200, topK: 5 };
10572
10344
  if (process.env.RAG_USE_GRAPH_RETRIEVAL === "true") {
10573
10345
  ragConfig.useGraphRetrieval = true;
10574
10346
  }
@@ -10664,8 +10436,8 @@ var DocumentParser = class {
10664
10436
  * Extract text from a File or Buffer based on its type.
10665
10437
  */
10666
10438
  static async parse(file, fileName, mimeType) {
10667
- var _a3;
10668
- const extension = ((_a3 = fileName.split(".").pop()) == null ? void 0 : _a3.toLowerCase()) || "";
10439
+ var _a2;
10440
+ const extension = ((_a2 = fileName.split(".").pop()) == null ? void 0 : _a2.toLowerCase()) || "";
10669
10441
  if (extension === "txt" || extension === "md" || mimeType === "text/plain" || mimeType === "text/markdown") {
10670
10442
  return this.readAsText(file);
10671
10443
  }
@@ -10760,7 +10532,17 @@ import { NextResponse } from "next/server";
10760
10532
  import * as fs from "fs";
10761
10533
  import * as path from "path";
10762
10534
  import * as os from "os";
10763
- var DatabaseStorage = class {
10535
+ function validateTableName(name) {
10536
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/.test(name)) {
10537
+ throw new Error(
10538
+ `[DatabaseStorage] Invalid table name "${name}". Table names must start with a letter or underscore and contain only alphanumeric characters and underscores (max 63 chars).`
10539
+ );
10540
+ }
10541
+ return name;
10542
+ }
10543
+ var _pgInitPromises = /* @__PURE__ */ new Map();
10544
+ var _DatabaseStorage = class _DatabaseStorage {
10545
+ // 5 minutes
10764
10546
  constructor(config) {
10765
10547
  // Dynamic PG Pool
10766
10548
  this.pgPool = null;
@@ -10772,36 +10554,50 @@ var DatabaseStorage = class {
10772
10554
  this.fallbackDir = this.isServerless ? path.join(os.tmpdir(), ".retrivora") : path.join(process.cwd(), ".retrivora");
10773
10555
  this.historyFile = path.join(this.fallbackDir, "history.json");
10774
10556
  this.feedbackFile = path.join(this.fallbackDir, "feedback.json");
10775
- var _a3, _b, _c, _d, _e;
10557
+ /** Subscription check result cache (Fix PERF-1). */
10558
+ this.subscriptionCheckedAt = 0;
10559
+ var _a2, _b, _c, _d, _e;
10776
10560
  this.config = config;
10777
- this.provider = ((_a3 = config.vectorDb) == null ? void 0 : _a3.provider) || "fs";
10561
+ this.provider = ((_a2 = config.vectorDb) == null ? void 0 : _a2.provider) || "fs";
10778
10562
  const rawHistoryTable = ((_c = (_b = config.rag) == null ? void 0 : _b.history) == null ? void 0 : _c.tableName) || "retrivora_history";
10779
10563
  const rawFeedbackTable = ((_e = (_d = config.rag) == null ? void 0 : _d.feedback) == null ? void 0 : _e.tableName) || "retrivora_feedback";
10780
- this.historyTableName = rawHistoryTable.replace(/[^a-zA-Z0-9_]/g, "_");
10781
- this.feedbackTableName = rawFeedbackTable.replace(/[^a-zA-Z0-9_]/g, "_");
10564
+ this.historyTableName = validateTableName(rawHistoryTable);
10565
+ this.feedbackTableName = validateTableName(rawFeedbackTable);
10782
10566
  }
10783
10567
  /**
10784
- * Asserts the user is running a valid Premium/Enterprise license in production.
10785
- * In non-production (development / test) environments this is a complete no-op —
10786
- * all History and Feedback features are freely accessible for local development.
10568
+ * Checks that the caller holds a valid paid-tier license in production.
10569
+ *
10570
+ * Fix PERF-1: result is cached for 5 minutes so we don't call
10571
+ * LicenseVerifier.verifyAsync() on every DB operation (saveMessage,
10572
+ * getHistory, etc.).
10573
+ *
10574
+ * Fix PERF-2: renamed from `checkPremiumSubscription` to clarify intent.
10575
+ * The previous allowlist admitted all free tiers, defeating the gate.
10576
+ * The new allowlist only passes paid tiers. Free-tier access to history
10577
+ * and feedback is a product decision — update the constant below if the
10578
+ * policy changes.
10579
+ *
10580
+ * In non-production environments this is a complete no-op so local
10581
+ * development works without a license key.
10787
10582
  */
10788
- async checkPremiumSubscription() {
10789
- if (process.env.NODE_ENV !== "production") {
10790
- return;
10791
- }
10583
+ async checkPaidSubscription() {
10584
+ if (process.env.NODE_ENV !== "production") return;
10585
+ if (Date.now() - this.subscriptionCheckedAt < _DatabaseStorage.SUBSCRIPTION_CACHE_TTL_MS) return;
10792
10586
  if (!this.config.licenseKey) {
10793
10587
  throw new Error(
10794
- "[Retrivora SDK] Chat History and Feedback features require a Premium or Enterprise license key in production."
10588
+ "[Retrivora SDK] Chat History and Feedback features require a paid license key in production."
10795
10589
  );
10796
10590
  }
10797
10591
  try {
10798
10592
  const payload = await LicenseVerifier.verifyAsync(this.config.licenseKey, this.config.projectId);
10799
10593
  const tier = (payload.tier || "").toLowerCase();
10800
- if (tier !== "premium" && tier !== "enterprise" && tier !== "growth" && tier !== "pro" && tier !== "developer_pro" && tier !== "free_trial" && tier !== "free_tier" && tier !== "free" && tier !== "hobby") {
10594
+ const PAID_TIERS = /* @__PURE__ */ new Set(["premium", "enterprise", "growth", "pro", "developer_pro"]);
10595
+ if (!PAID_TIERS.has(tier)) {
10801
10596
  throw new Error(
10802
10597
  `[Retrivora SDK] Chat History and Feedback features are not available on the "${tier}" tier. Please upgrade to a Developer Pro or Enterprise plan.`
10803
10598
  );
10804
10599
  }
10600
+ this.subscriptionCheckedAt = Date.now();
10805
10601
  } catch (err) {
10806
10602
  throw new Error(
10807
10603
  `[Retrivora SDK] Subscription check failed: ${err instanceof Error ? err.message : String(err)}`
@@ -10809,34 +10605,45 @@ var DatabaseStorage = class {
10809
10605
  }
10810
10606
  }
10811
10607
  async checkHistoryEnabled() {
10812
- var _a3, _b;
10813
- await this.checkPremiumSubscription();
10814
- if (((_b = (_a3 = this.config.rag) == null ? void 0 : _a3.history) == null ? void 0 : _b.enabled) === false) {
10608
+ var _a2, _b;
10609
+ await this.checkPaidSubscription();
10610
+ if (((_b = (_a2 = this.config.rag) == null ? void 0 : _a2.history) == null ? void 0 : _b.enabled) === false) {
10815
10611
  throw new Error("[Retrivora SDK] Chat History is disabled in RagConfig.");
10816
10612
  }
10817
10613
  }
10818
10614
  async checkFeedbackEnabled() {
10819
- var _a3, _b;
10820
- await this.checkPremiumSubscription();
10821
- if (((_b = (_a3 = this.config.rag) == null ? void 0 : _a3.feedback) == null ? void 0 : _b.enabled) === false) {
10615
+ var _a2, _b;
10616
+ await this.checkPaidSubscription();
10617
+ if (((_b = (_a2 = this.config.rag) == null ? void 0 : _a2.feedback) == null ? void 0 : _b.enabled) === false) {
10822
10618
  throw new Error("[Retrivora SDK] User Feedback is disabled in RagConfig.");
10823
10619
  }
10824
10620
  }
10825
- async getPGPool() {
10826
- const globalKey = `__retrivora_pg_pool_${this.config.projectId}`;
10827
- const _g2 = global;
10828
- if (_g2[globalKey]) {
10829
- this.pgPool = _g2[globalKey];
10830
- return this.pgPool;
10621
+ /**
10622
+ * Returns (or lazily creates) the PostgreSQL connection pool for this project.
10623
+ *
10624
+ * Fix ERR-2: the previous implementation had a double-initialization race
10625
+ * condition — two concurrent requests would both find _g[globalKey] missing,
10626
+ * both create a Pool, and the second Pool would be orphaned, leaking
10627
+ * database connections. This version stores a single Promise in the module-
10628
+ * level _pgInitPromises map so all concurrent callers await the same
10629
+ * initialization without creating duplicate pools.
10630
+ */
10631
+ getPGPool() {
10632
+ const globalKey = `pg:${this.config.projectId}`;
10633
+ if (!_pgInitPromises.has(globalKey)) {
10634
+ _pgInitPromises.set(globalKey, this.createPGPool());
10831
10635
  }
10636
+ return _pgInitPromises.get(globalKey);
10637
+ }
10638
+ async createPGPool() {
10832
10639
  const opts = this.config.vectorDb.options;
10833
10640
  if (!opts.connectionString) {
10834
10641
  throw new Error("[DatabaseStorage] pg connectionString option is missing.");
10835
10642
  }
10836
10643
  const { Pool: Pool3 } = await import("pg");
10837
- this.pgPool = new Pool3({ connectionString: opts.connectionString });
10838
- _g2[globalKey] = this.pgPool;
10839
- const client = await this.pgPool.connect();
10644
+ const pool = new Pool3({ connectionString: opts.connectionString });
10645
+ this.pgPool = pool;
10646
+ const client = await pool.connect();
10840
10647
  try {
10841
10648
  await client.query(`
10842
10649
  CREATE TABLE IF NOT EXISTS ${this.historyTableName} (
@@ -10863,7 +10670,7 @@ var DatabaseStorage = class {
10863
10670
  } finally {
10864
10671
  client.release();
10865
10672
  }
10866
- return this.pgPool;
10673
+ return pool;
10867
10674
  }
10868
10675
  async getMongoClient() {
10869
10676
  const globalKey = `__retrivora_mongo_client_${this.config.projectId}`;
@@ -11043,17 +10850,21 @@ var DatabaseStorage = class {
11043
10850
  }
11044
10851
  }
11045
10852
  /**
11046
- * Return true when `sessionId` falls into the allowed `projectIds` scope.
11047
- * When `projectIds` is empty / undefined we allow the call (legacy behavior
11048
- * for non-multi-tenant consumers). Session ids typically begin with the
11049
- * project id they were created for, so we prefix-match as well as contains-match
11050
- * to catch sharded / suffix-style ids used by some integrations.
10853
+ * Returns true when `sessionId` is in scope for the given `projectIds`.
10854
+ *
10855
+ * Fix RAG-5: the previous implementation used `sessionId.includes(pid)` which
10856
+ * allows cross-tenant data leakage. If a project ID "abc" is a substring of
10857
+ * another tenant's session ID (e.g., "xyz-abc-user-123"), the check would
10858
+ * incorrectly return true. We now only allow exact match or strict delimiter-
10859
+ * separated prefix match to prevent this attack.
11051
10860
  */
11052
10861
  sessionInScope(sessionId, projectIds) {
11053
10862
  if (!projectIds || projectIds.length === 0) return true;
11054
- return projectIds.some(
11055
- (pid) => pid && (sessionId === pid || sessionId.startsWith(pid) || sessionId.includes(pid))
11056
- );
10863
+ return projectIds.some((pid) => {
10864
+ if (!pid) return false;
10865
+ if (sessionId === pid) return true;
10866
+ return sessionId.startsWith(`${pid}-`) || sessionId.startsWith(`${pid}_`) || sessionId.startsWith(`${pid}/`);
10867
+ });
11057
10868
  }
11058
10869
  async listSessions(projectIds) {
11059
10870
  await this.checkHistoryEnabled();
@@ -11202,9 +11013,12 @@ var DatabaseStorage = class {
11202
11013
  }
11203
11014
  }
11204
11015
  };
11016
+ _DatabaseStorage.SUBSCRIPTION_CACHE_TTL_MS = 5 * 60 * 1e3;
11017
+ var DatabaseStorage = _DatabaseStorage;
11205
11018
 
11206
11019
  // src/handlers/index.ts
11207
11020
  init_version();
11021
+ import { createHash } from "crypto";
11208
11022
  async function checkAuth(req, onAuthorize) {
11209
11023
  if (!onAuthorize) return null;
11210
11024
  try {
@@ -11226,6 +11040,17 @@ var RateLimiter = class {
11226
11040
  this.hits = /* @__PURE__ */ new Map();
11227
11041
  this.windowMs = windowMs;
11228
11042
  this.max = max;
11043
+ this.pruneTimer = setInterval(() => this.prune(), windowMs);
11044
+ if (typeof this.pruneTimer === "object" && "unref" in this.pruneTimer) {
11045
+ this.pruneTimer.unref();
11046
+ }
11047
+ }
11048
+ /** Prune entries whose timestamps are all outside the window. */
11049
+ prune() {
11050
+ const cutoff = Date.now() - this.windowMs;
11051
+ for (const [k, timestamps] of this.hits.entries()) {
11052
+ if (timestamps.every((t) => t <= cutoff)) this.hits.delete(k);
11053
+ }
11229
11054
  }
11230
11055
  /** Returns true if the request should be allowed, false if rate-limited. */
11231
11056
  allow(key) {
@@ -11234,11 +11059,6 @@ var RateLimiter = class {
11234
11059
  const existing = (this.hits.get(key) || []).filter((t) => t > cutoff);
11235
11060
  existing.push(now);
11236
11061
  this.hits.set(key, existing);
11237
- if (this.hits.size > 5e3) {
11238
- for (const [k, timestamps] of this.hits.entries()) {
11239
- if (timestamps.every((t) => t <= cutoff)) this.hits.delete(k);
11240
- }
11241
- }
11242
11062
  return existing.length <= this.max;
11243
11063
  }
11244
11064
  retryAfterSec(key) {
@@ -11253,8 +11073,8 @@ var _g = global;
11253
11073
  var _a;
11254
11074
  var rateLimiter = (_a = _g.__retrivoraRateLimiter) != null ? _a : _g.__retrivoraRateLimiter = new RateLimiter(6e4, 30);
11255
11075
  function getRateLimitKey(req) {
11256
- var _a3, _b;
11257
- const ip = ((_b = (_a3 = req.headers.get("x-forwarded-for")) == null ? void 0 : _a3.split(",")[0]) == null ? void 0 : _b.trim()) || req.headers.get("x-real-ip") || "127.0.0.1";
11076
+ var _a2, _b;
11077
+ const ip = ((_b = (_a2 = req.headers.get("x-forwarded-for")) == null ? void 0 : _a2.split(",")[0]) == null ? void 0 : _b.trim()) || req.headers.get("x-real-ip") || "127.0.0.1";
11258
11078
  return `ip:${ip}`;
11259
11079
  }
11260
11080
  function checkRateLimit(req) {
@@ -11281,8 +11101,6 @@ function isFreeTier(tier) {
11281
11101
  if (!tier) return true;
11282
11102
  return FREE_TIER_NAMES.has(tier.toLowerCase().trim());
11283
11103
  }
11284
- var _a2;
11285
- var _freeTierGuardInstance = (_a2 = _g.__retrivoraFreeTierGuard) != null ? _a2 : _g.__retrivoraFreeTierGuard = new FreeTierLimitsGuard();
11286
11104
  function createPaymentRequiredResponse(reason, details) {
11287
11105
  const body = __spreadProps(__spreadValues({
11288
11106
  type: "https://retrivora.com/docs/errors/payment-required",
@@ -11293,10 +11111,10 @@ function createPaymentRequiredResponse(reason, details) {
11293
11111
  instance: void 0
11294
11112
  }, details != null ? details : {}), {
11295
11113
  quota: {
11296
- maxDailyRequestUnits: FREE_TIER_QUOTAS.MAX_DAILY_REQUEST_UNITS,
11297
- maxTrialRequestUnits: FREE_TIER_QUOTAS.MAX_TRIAL_REQUEST_UNITS,
11298
- maxDocuments: FREE_TIER_QUOTAS.MAX_DOCUMENTS,
11299
- maxStorageBytes: FREE_TIER_QUOTAS.MAX_STORAGE_BYTES,
11114
+ maxDailyRequestUnits: FreeTierLimitsGuard_exports.FREE_TIER_QUOTAS.MAX_DAILY_REQUEST_UNITS,
11115
+ maxTrialRequestUnits: FreeTierLimitsGuard_exports.FREE_TIER_QUOTAS.MAX_TRIAL_REQUEST_UNITS,
11116
+ maxDocuments: FreeTierLimitsGuard_exports.FREE_TIER_QUOTAS.MAX_DOCUMENTS,
11117
+ maxStorageBytes: FreeTierLimitsGuard_exports.FREE_TIER_QUOTAS.MAX_STORAGE_BYTES,
11300
11118
  upgradeUrl: "https://retrivora.com/pricing"
11301
11119
  }
11302
11120
  });
@@ -11308,17 +11126,17 @@ function createPaymentRequiredResponse(reason, details) {
11308
11126
  });
11309
11127
  }
11310
11128
  function resolveLicenseKey(req, config, bodyLicenseKey) {
11311
- var _a3;
11312
- return req.headers.get("x-license-key") || bodyLicenseKey || ((_a3 = req.headers.get("authorization")) == null ? void 0 : _a3.replace(/^Bearer\s+/i, "")) || config.licenseKey || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY || process.env.RETRIVORA_LICENSE_KEY || process.env.RAG_LICENSE_KEY || "";
11129
+ return req.headers.get("x-license-key") || bodyLicenseKey || config.licenseKey || process.env.RETRIVORA_LICENSE_KEY || process.env.RAG_LICENSE_KEY || "";
11313
11130
  }
11314
11131
  async function enforceLicense(req, config, bodyLicenseKey) {
11315
11132
  const rawKey = resolveLicenseKey(req, config, bodyLicenseKey);
11316
11133
  const licenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
11317
- const projectId = config.projectId || "";
11134
+ const url = new URL(req.url);
11135
+ const requestedProjectId = url.searchParams.get("projectId") || url.searchParams.get("project-id") || req.headers.get("x-project-id") || req.headers.get("X-Project-Id") || config.projectId || "";
11318
11136
  try {
11319
11137
  let payload;
11320
11138
  try {
11321
- payload = await LicenseVerifier.verifyAsync(licenseKey, projectId);
11139
+ payload = await LicenseVerifier.verifyAsync(licenseKey, requestedProjectId);
11322
11140
  } catch (err) {
11323
11141
  return {
11324
11142
  ok: false,
@@ -11330,7 +11148,7 @@ async function enforceLicense(req, config, bodyLicenseKey) {
11330
11148
  }
11331
11149
  return { ok: true, payload };
11332
11150
  } catch (err) {
11333
- const message = err instanceof Error ? err.message : "Missing or invalid RETRIVORA_LICENSE_KEY. Set NEXT_PUBLIC_RETRIVORA_LICENSE_KEY in your environment or contact your administrator.";
11151
+ const message = err instanceof Error ? err.message : "Missing or invalid RETRIVORA_LICENSE_KEY. Set RETRIVORA_LICENSE_KEY in your environment or contact your administrator.";
11334
11152
  const body = {
11335
11153
  error: {
11336
11154
  code: "LICENSE_REVOKED",
@@ -11388,38 +11206,59 @@ function sanitizeInput(raw) {
11388
11206
  }
11389
11207
  return { ok: true, value: trimmed };
11390
11208
  }
11209
+ var _pluginCache = /* @__PURE__ */ new Map();
11210
+ var PLUGIN_CACHE_TTL_MS = 10 * 60 * 1e3;
11211
+ function configHash(config) {
11212
+ return createHash("sha1").update(JSON.stringify(config != null ? config : {})).digest("hex").slice(0, 16);
11213
+ }
11391
11214
  function getOrCreatePlugin(configOrPlugin) {
11392
11215
  if (configOrPlugin instanceof VectorPlugin) return configOrPlugin;
11393
- const cacheKey = "__retrivoraPlugin_" + JSON.stringify(configOrPlugin != null ? configOrPlugin : {}).slice(0, 64);
11394
- if (!_g[cacheKey]) {
11395
- _g[cacheKey] = new VectorPlugin(configOrPlugin);
11216
+ const key = configHash(configOrPlugin);
11217
+ const cached = _pluginCache.get(key);
11218
+ if (cached && Date.now() - cached.createdAt < PLUGIN_CACHE_TTL_MS) return cached.plugin;
11219
+ const plugin = new VectorPlugin(configOrPlugin);
11220
+ _pluginCache.set(key, { plugin, createdAt: Date.now() });
11221
+ return plugin;
11222
+ }
11223
+ var TELEMETRY_ALLOWED_HOSTS = /* @__PURE__ */ new Set([
11224
+ "retrivora.com",
11225
+ "www.retrivora.com"
11226
+ ]);
11227
+ function sanitizeTelemetryUrl(raw) {
11228
+ if (process.env.NODE_ENV !== "production") return raw;
11229
+ try {
11230
+ const parsed = new URL(raw);
11231
+ const hostname = parsed.hostname.toLowerCase().replace(/^www\./, "");
11232
+ if (!TELEMETRY_ALLOWED_HOSTS.has(`www.${hostname}`) && !TELEMETRY_ALLOWED_HOSTS.has(hostname)) {
11233
+ console.warn(
11234
+ `[Retrivora SDK Telemetry] Blocked non-allowlisted telemetry URL: ${parsed.hostname}. Only retrivora.com endpoints are permitted in production.`
11235
+ );
11236
+ return null;
11237
+ }
11238
+ return parsed.toString();
11239
+ } catch (e) {
11240
+ return null;
11396
11241
  }
11397
- return _g[cacheKey];
11398
11242
  }
11399
11243
  function reportTelemetry(req, plugin, action, status, details, trace) {
11400
- var _a3, _b, _c, _d, _e, _f, _g2;
11244
+ var _a2, _b, _c, _d, _e, _f, _g2;
11401
11245
  try {
11402
11246
  const config = plugin.getConfig();
11403
- const licenseKey = config.licenseKey || process.env.RAG_LICENSE_KEY || process.env.RETRIVORA_LICENSE_KEY || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY;
11247
+ const licenseKey = config.licenseKey || process.env.RETRIVORA_LICENSE_KEY || process.env.RAG_LICENSE_KEY;
11404
11248
  const telemetryConfig = config.telemetry;
11405
- const host = req.headers.get("host") || "localhost";
11406
11249
  const defaultUrl = "https://www.retrivora.com/api/telemetry";
11407
- const telemetryUrl = (telemetryConfig == null ? void 0 : telemetryConfig.url) || process.env.TELEMETRY_URL || process.env.NEXT_PUBLIC_TELEMETRY_URL || defaultUrl;
11250
+ const rawTelemetryUrl = (telemetryConfig == null ? void 0 : telemetryConfig.url) || process.env.TELEMETRY_URL || process.env.NEXT_PUBLIC_TELEMETRY_URL || defaultUrl;
11251
+ const telemetryUrl = sanitizeTelemetryUrl(rawTelemetryUrl);
11252
+ if (!telemetryUrl) return;
11408
11253
  const userAgent = req.headers.get("user-agent") || `Retrivora-SDK/${SDK_VERSION}`;
11409
- let absoluteUrl = telemetryUrl;
11410
- if (!telemetryUrl.startsWith("http")) {
11411
- const proto = req.headers.get("x-forwarded-proto") || "http";
11412
- absoluteUrl = `${proto}://${host}${telemetryUrl}`;
11413
- }
11414
11254
  const projectId = config.projectId || "default";
11415
- const model = (trace == null ? void 0 : trace.model) || ((_a3 = config.llm) == null ? void 0 : _a3.model) || ((_b = config.embedding) == null ? void 0 : _b.model) || "llama-3.1-8b-instant";
11255
+ const model = (trace == null ? void 0 : trace.model) || ((_a2 = config.llm) == null ? void 0 : _a2.model) || ((_b = config.embedding) == null ? void 0 : _b.model) || "llama-3.1-8b-instant";
11416
11256
  const provider = (trace == null ? void 0 : trace.provider) || ((_c = config.llm) == null ? void 0 : _c.provider) || ((_d = config.embedding) == null ? void 0 : _d.provider) || "groq";
11417
11257
  const tokens = Number(((_e = trace == null ? void 0 : trace.tokens) == null ? void 0 : _e.totalTokens) || (trace == null ? void 0 : trace.totalTokens) || 0);
11418
11258
  const costUsd = Number(((_f = trace == null ? void 0 : trace.tokens) == null ? void 0 : _f.estimatedCostUsd) || (trace == null ? void 0 : trace.costUsd) || 0);
11419
11259
  const latencyMs = Number(((_g2 = trace == null ? void 0 : trace.latency) == null ? void 0 : _g2.totalMs) || (trace == null ? void 0 : trace.latencyMs) || 0);
11420
11260
  const payload = {
11421
11261
  trace,
11422
- licenseKey,
11423
11262
  projectId,
11424
11263
  organization: process.env.RETRIVORA_ORGANIZATION || "default-org",
11425
11264
  sdkVersion: SDK_VERSION,
@@ -11436,14 +11275,13 @@ function reportTelemetry(req, plugin, action, status, details, trace) {
11436
11275
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
11437
11276
  details
11438
11277
  };
11439
- fetch(absoluteUrl, {
11278
+ fetch(telemetryUrl, {
11440
11279
  method: "POST",
11441
- headers: {
11442
- "Content-Type": "application/json",
11443
- "x-forwarded-for": req.headers.get("x-forwarded-for") || "",
11444
- "x-real-ip": req.headers.get("x-real-ip") || "",
11280
+ headers: __spreadProps(__spreadValues({
11281
+ "Content-Type": "application/json"
11282
+ }, licenseKey ? { "x-license-key": licenseKey } : {}), {
11445
11283
  "user-agent": userAgent
11446
- },
11284
+ }),
11447
11285
  body: JSON.stringify(payload)
11448
11286
  }).catch((err) => {
11449
11287
  console.warn("[Retrivora SDK Telemetry] Async report warning:", err.message);
@@ -11493,7 +11331,7 @@ function createChatHandler(configOrPlugin, options) {
11493
11331
  const storage = new DatabaseStorage(plugin.getConfig());
11494
11332
  const onAuthorize = options == null ? void 0 : options.onAuthorize;
11495
11333
  return async function POST(req, context) {
11496
- var _a3, _b, _c, _d, _e, _f;
11334
+ var _a2, _b, _c, _d, _e, _f;
11497
11335
  const authResult = await checkAuth(req, onAuthorize);
11498
11336
  if (authResult) return authResult;
11499
11337
  const rateLimited = checkRateLimit(req);
@@ -11506,18 +11344,17 @@ function createChatHandler(configOrPlugin, options) {
11506
11344
  if (!licenseCheck.ok) return licenseCheck.response;
11507
11345
  if (isFreeTier(licenseCheck.payload.tier)) {
11508
11346
  const estimatedInputTokens = Math.ceil(
11509
- ((((_a3 = bodyObj.message) == null ? void 0 : _a3.length) || 0) + (Array.isArray(bodyObj.messages) ? bodyObj.messages.reduce((a, m) => {
11510
- var _a4, _b2;
11511
- return a + (((_a4 = m == null ? void 0 : m.content) == null ? void 0 : _a4.length) || ((_b2 = m == null ? void 0 : m.text) == null ? void 0 : _b2.length) || 0);
11347
+ ((((_a2 = bodyObj.message) == null ? void 0 : _a2.length) || 0) + (Array.isArray(bodyObj.messages) ? bodyObj.messages.reduce((a, m) => {
11348
+ var _a3, _b2;
11349
+ return a + (((_a3 = m == null ? void 0 : m.content) == null ? void 0 : _a3.length) || ((_b2 = m == null ? void 0 : m.text) == null ? void 0 : _b2.length) || 0);
11512
11350
  }, 0) : 0) + (((_b = bodyObj.history) == null ? void 0 : _b.reduce((a, m) => {
11513
- var _a4, _b2;
11514
- return a + (((_a4 = m == null ? void 0 : m.content) == null ? void 0 : _a4.length) || ((_b2 = m == null ? void 0 : m.text) == null ? void 0 : _b2.length) || 0);
11351
+ var _a3, _b2;
11352
+ return a + (((_a3 = m == null ? void 0 : m.content) == null ? void 0 : _a3.length) || ((_b2 = m == null ? void 0 : m.text) == null ? void 0 : _b2.length) || 0);
11515
11353
  }, 0)) || 0)) / 4
11516
11354
  );
11517
- const chatCheck = FreeTierLimitsGuard.checkRequestAllowed({
11355
+ const chatCheck = FreeTierLimitsGuard_exports.FreeTierLimitsGuard.checkRequestAllowed({
11518
11356
  operationType: "chat",
11519
- inputTokens: estimatedInputTokens,
11520
- projectId: licenseCheck.payload.projectId
11357
+ inputTokens: estimatedInputTokens
11521
11358
  });
11522
11359
  if (!chatCheck.allowed) {
11523
11360
  return createPaymentRequiredResponse(
@@ -11576,7 +11413,7 @@ function createStreamHandler(configOrPlugin, options) {
11576
11413
  const storage = new DatabaseStorage(plugin.getConfig());
11577
11414
  const onAuthorize = options == null ? void 0 : options.onAuthorize;
11578
11415
  return async function POST(req, context) {
11579
- var _a3, _b, _c;
11416
+ var _a2, _b;
11580
11417
  const authResult = await checkAuth(req, onAuthorize);
11581
11418
  if (authResult) return authResult;
11582
11419
  const rateLimited = checkRateLimit(req);
@@ -11584,10 +11421,6 @@ function createStreamHandler(configOrPlugin, options) {
11584
11421
  const config = plugin.getConfig();
11585
11422
  let body;
11586
11423
  try {
11587
- if ((_a3 = req.headers.get("content-type")) == null ? void 0 : _a3.includes("multipart/form-data")) {
11588
- const uploader = createUploadHandler(plugin, { onAuthorize });
11589
- return uploader(req);
11590
- }
11591
11424
  body = await req.json();
11592
11425
  } catch (e) {
11593
11426
  return new Response(JSON.stringify({ error: { code: "INVALID_JSON", message: "Invalid JSON body" } }), {
@@ -11600,15 +11433,15 @@ function createStreamHandler(configOrPlugin, options) {
11600
11433
  if (!licenseCheck.ok) return licenseCheck.response;
11601
11434
  if (isFreeTier(licenseCheck.payload.tier)) {
11602
11435
  const estimatedInputTokens = Math.ceil(
11603
- ((((_b = bodyObj.message) == null ? void 0 : _b.length) || 0) + (Array.isArray(bodyObj.messages) ? bodyObj.messages.reduce((a, m) => {
11604
- var _a4, _b2;
11605
- return a + (((_a4 = m == null ? void 0 : m.content) == null ? void 0 : _a4.length) || ((_b2 = m == null ? void 0 : m.text) == null ? void 0 : _b2.length) || 0);
11606
- }, 0) : 0) + (((_c = bodyObj.history) == null ? void 0 : _c.reduce((a, m) => {
11607
- var _a4, _b2;
11608
- return a + (((_a4 = m == null ? void 0 : m.content) == null ? void 0 : _a4.length) || ((_b2 = m == null ? void 0 : m.text) == null ? void 0 : _b2.length) || 0);
11436
+ ((((_a2 = bodyObj.message) == null ? void 0 : _a2.length) || 0) + (Array.isArray(bodyObj.messages) ? bodyObj.messages.reduce((a, m) => {
11437
+ var _a3, _b2;
11438
+ return a + (((_a3 = m == null ? void 0 : m.content) == null ? void 0 : _a3.length) || ((_b2 = m == null ? void 0 : m.text) == null ? void 0 : _b2.length) || 0);
11439
+ }, 0) : 0) + (((_b = bodyObj.history) == null ? void 0 : _b.reduce((a, m) => {
11440
+ var _a3, _b2;
11441
+ return a + (((_a3 = m == null ? void 0 : m.content) == null ? void 0 : _a3.length) || ((_b2 = m == null ? void 0 : m.text) == null ? void 0 : _b2.length) || 0);
11609
11442
  }, 0)) || 0)) / 4
11610
11443
  );
11611
- const chatCheck = FreeTierLimitsGuard.checkRequestAllowed({
11444
+ const chatCheck = FreeTierLimitsGuard_exports.FreeTierLimitsGuard.checkRequestAllowed({
11612
11445
  operationType: "chat_stream",
11613
11446
  inputTokens: estimatedInputTokens,
11614
11447
  projectId: licenseCheck.payload.projectId
@@ -11651,7 +11484,7 @@ function createStreamHandler(configOrPlugin, options) {
11651
11484
  let isActive = true;
11652
11485
  const stream = new ReadableStream({
11653
11486
  async start(controller) {
11654
- var _a4, _b2, _c2, _d, _e;
11487
+ var _a3, _b2, _c, _d, _e;
11655
11488
  const enqueue = (text) => {
11656
11489
  if (!isActive) return;
11657
11490
  try {
@@ -11684,7 +11517,7 @@ function createStreamHandler(configOrPlugin, options) {
11684
11517
  let uiTransformation = responseChunk == null ? void 0 : responseChunk.ui_transformation;
11685
11518
  if (sources.length > 0) {
11686
11519
  try {
11687
- uiTransformation = (_a4 = responseChunk == null ? void 0 : responseChunk.ui_transformation) != null ? _a4 : UITransformer.transform(message, sources, plugin.getConfig());
11520
+ uiTransformation = (_a3 = responseChunk == null ? void 0 : responseChunk.ui_transformation) != null ? _a3 : UITransformer.transform(message, sources, plugin.getConfig());
11688
11521
  if (uiTransformation) {
11689
11522
  enqueue(sseUIFrame(uiTransformation));
11690
11523
  }
@@ -11708,7 +11541,7 @@ function createStreamHandler(configOrPlugin, options) {
11708
11541
  uiTransformation,
11709
11542
  trace: responseChunk == null ? void 0 : responseChunk.trace
11710
11543
  }).catch((err) => console.warn("[createStreamHandler] Failed to save assistant message:", err));
11711
- reportTelemetry(req, plugin, "QUERY_GENERATION", "success", `Tokens: ${((_c2 = (_b2 = responseChunk == null ? void 0 : responseChunk.trace) == null ? void 0 : _b2.tokens) == null ? void 0 : _c2.totalTokens) || 0}, Latency: ${((_e = (_d = responseChunk == null ? void 0 : responseChunk.trace) == null ? void 0 : _d.latency) == null ? void 0 : _e.totalMs) || 0}ms`, responseChunk == null ? void 0 : responseChunk.trace);
11544
+ reportTelemetry(req, plugin, "QUERY_GENERATION", "success", `Tokens: ${((_c = (_b2 = responseChunk == null ? void 0 : responseChunk.trace) == null ? void 0 : _b2.tokens) == null ? void 0 : _c.totalTokens) || 0}, Latency: ${((_e = (_d = responseChunk == null ? void 0 : responseChunk.trace) == null ? void 0 : _d.latency) == null ? void 0 : _e.totalMs) || 0}ms`, responseChunk == null ? void 0 : responseChunk.trace);
11712
11545
  }
11713
11546
  }
11714
11547
  } catch (temp) {
@@ -11773,7 +11606,7 @@ function createIngestHandler(configOrPlugin, options) {
11773
11606
  (sum, d) => sum + Buffer.byteLength(d.content || "", "utf8"),
11774
11607
  0
11775
11608
  );
11776
- const ingestCheck = FreeTierLimitsGuard.checkIngestionAllowed(
11609
+ const ingestCheck = FreeTierLimitsGuard_exports.FreeTierLimitsGuard.checkIngestionAllowed(
11777
11610
  { documentCount: documents.length },
11778
11611
  totalIncomingBytes
11779
11612
  );
@@ -11825,7 +11658,6 @@ function createLicenseHandler(configOrPlugin, options) {
11825
11658
  const plugin = getOrCreatePlugin(configOrPlugin);
11826
11659
  const onAuthorize = options == null ? void 0 : options.onAuthorize;
11827
11660
  return async function POST(req) {
11828
- var _a3;
11829
11661
  if (req) {
11830
11662
  const authResult = await checkAuth(req, onAuthorize);
11831
11663
  if (authResult) return authResult;
@@ -11833,7 +11665,17 @@ function createLicenseHandler(configOrPlugin, options) {
11833
11665
  try {
11834
11666
  const body = await req.json().catch(() => ({}));
11835
11667
  const config = plugin.getConfig();
11836
- const rawKey = req.headers.get("x-license-key") || (body == null ? void 0 : body.licenseKey) || ((_a3 = req.headers.get("authorization")) == null ? void 0 : _a3.replace(/^Bearer\s+/i, "")) || config.licenseKey || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY || process.env.RETRIVORA_LICENSE_KEY || "";
11668
+ const authHeader = req.headers.get("authorization");
11669
+ let authHeaderKey = "";
11670
+ if (authHeader && authHeader.toLowerCase().startsWith("bearer ")) {
11671
+ authHeaderKey = authHeader.replace(/^Bearer\s+/i, "");
11672
+ if (authHeaderKey) {
11673
+ console.warn(
11674
+ '[Retrivora SDK] DEPRECATION WARNING (SEC-7): Repurposing the standard "Authorization: Bearer" header to carry the license key is deprecated and will be removed in a future release. Please use the custom "x-license-key" header instead.'
11675
+ );
11676
+ }
11677
+ }
11678
+ const rawKey = req.headers.get("x-license-key") || (body == null ? void 0 : body.licenseKey) || authHeaderKey || config.licenseKey || process.env.RETRIVORA_LICENSE_KEY || "";
11837
11679
  const licenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
11838
11680
  const projectId = (body == null ? void 0 : body.projectId) || config.projectId || "";
11839
11681
  const payload = await LicenseVerifier.verifyAsync(licenseKey, projectId);
@@ -11884,7 +11726,7 @@ function createUploadHandler(configOrPlugin, options) {
11884
11726
  }
11885
11727
  if (isFreeTier(licenseCheck.payload.tier)) {
11886
11728
  const totalUploadBytes = files.reduce((sum, f) => sum + (f.size || 0), 0);
11887
- const uploadCheck = FreeTierLimitsGuard.checkIngestionAllowed(
11729
+ const uploadCheck = FreeTierLimitsGuard_exports.FreeTierLimitsGuard.checkIngestionAllowed(
11888
11730
  { documentCount: files.length },
11889
11731
  totalUploadBytes
11890
11732
  );
@@ -11896,8 +11738,8 @@ function createUploadHandler(configOrPlugin, options) {
11896
11738
  projectId: licenseCheck.payload.projectId,
11897
11739
  fileCount: files.length,
11898
11740
  totalUploadBytes,
11899
- maxFileSizeBytes: FREE_TIER_QUOTAS.MAX_FILE_SIZE_BYTES,
11900
- maxStorageBytes: FREE_TIER_QUOTAS.MAX_STORAGE_BYTES
11741
+ maxFileSizeBytes: FreeTierLimitsGuard_exports.FREE_TIER_QUOTAS.MAX_FILE_SIZE_BYTES,
11742
+ maxStorageBytes: FreeTierLimitsGuard_exports.FREE_TIER_QUOTAS.MAX_STORAGE_BYTES
11901
11743
  }
11902
11744
  );
11903
11745
  }
@@ -12211,7 +12053,7 @@ function createRagHandler(configOrPlugin, options) {
12211
12053
  }
12212
12054
  }
12213
12055
  async function getSegment(req, context) {
12214
- var _a3, _b, _c;
12056
+ var _a2, _b, _c;
12215
12057
  const contentType = req.headers.get("content-type") || "";
12216
12058
  if (contentType.includes("multipart/form-data")) {
12217
12059
  return "upload";
@@ -12230,7 +12072,7 @@ function createRagHandler(configOrPlugin, options) {
12230
12072
  if (pathname.endsWith("/sessions")) return "sessions";
12231
12073
  } catch (e) {
12232
12074
  }
12233
- const resolvedParams = typeof ((_a3 = context == null ? void 0 : context.params) == null ? void 0 : _a3.then) === "function" ? await context.params : context == null ? void 0 : context.params;
12075
+ const resolvedParams = typeof ((_a2 = context == null ? void 0 : context.params) == null ? void 0 : _a2.then) === "function" ? await context.params : context == null ? void 0 : context.params;
12234
12076
  const segments = (resolvedParams == null ? void 0 : resolvedParams.retrivora) || ((_b = resolvedParams == null ? void 0 : resolvedParams.params) == null ? void 0 : _b.retrivora) || (resolvedParams == null ? void 0 : resolvedParams.rag) || ((_c = resolvedParams == null ? void 0 : resolvedParams.params) == null ? void 0 : _c.rag) || [];
12235
12077
  const joined = segments.join("/");
12236
12078
  return joined || "chat";
@@ -12308,7 +12150,6 @@ var _LicenseValidator = class _LicenseValidator {
12308
12150
  * lock the chat widget.
12309
12151
  */
12310
12152
  async validate(request) {
12311
- var _a3;
12312
12153
  const {
12313
12154
  licenseKey,
12314
12155
  projectId,
@@ -12327,7 +12168,17 @@ var _LicenseValidator = class _LicenseValidator {
12327
12168
  }
12328
12169
  return void 0;
12329
12170
  };
12330
- 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 : "") || "";
12171
+ const authHeader = getHeader("authorization");
12172
+ let authHeaderKey = "";
12173
+ if (authHeader && authHeader.toLowerCase().startsWith("bearer ")) {
12174
+ authHeaderKey = authHeader.replace(/^Bearer\s+/i, "");
12175
+ if (authHeaderKey) {
12176
+ console.warn(
12177
+ '[Retrivora SDK] DEPRECATION WARNING (SEC-7): Repurposing the standard "Authorization: Bearer" header to carry the license key is deprecated and will be removed in a future release. Please use the custom "x-license-key" header instead.'
12178
+ );
12179
+ }
12180
+ }
12181
+ const rawKey = licenseKey || getHeader("x-license-key") || authHeaderKey || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY || process.env.RETRIVORA_LICENSE_KEY : "") || "";
12331
12182
  const effectiveLicenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
12332
12183
  if (!effectiveLicenseKey) {
12333
12184
  this.purgeCache(effectiveLicenseKey);
@@ -12599,7 +12450,6 @@ LicenseConfigResolver.CACHE_TTL_MS = 36e5;
12599
12450
  LicenseConfigResolver.configCache = /* @__PURE__ */ new Map();
12600
12451
 
12601
12452
  // src/telemetry/TelemetryService.ts
12602
- import axios10 from "axios";
12603
12453
  var EventType = /* @__PURE__ */ ((EventType2) => {
12604
12454
  EventType2["EMBEDDING_GENERATED"] = "embedding_generated";
12605
12455
  EventType2["LLM_CHAT_COMPLETION"] = "llm_chat_completion";
@@ -12619,14 +12469,11 @@ var _TelemetryService = class _TelemetryService {
12619
12469
  this.projectId = projectId;
12620
12470
  this.licenseKey = licenseKey;
12621
12471
  this.userTelemetryUrl = userTelemetryUrl || process.env[_TelemetryService.USER_TELEMETRY_URL_ENV_KEY];
12622
- this.http = axios10.create({
12623
- timeout: 5e3,
12624
- headers: {
12625
- "Content-Type": "application/json",
12626
- "X-License-Key": licenseKey,
12627
- "X-Project-ID": projectId
12628
- }
12629
- });
12472
+ this.baseHeaders = {
12473
+ "Content-Type": "application/json",
12474
+ "X-License-Key": licenseKey,
12475
+ "X-Project-ID": projectId
12476
+ };
12630
12477
  this.startAutoFlush();
12631
12478
  }
12632
12479
  /**
@@ -12634,7 +12481,7 @@ var _TelemetryService = class _TelemetryService {
12634
12481
  */
12635
12482
  recordEvent(event) {
12636
12483
  if (!this.enabled) return;
12637
- const _a3 = event, { licenseKey } = _a3, safeEvent = __objRest(_a3, ["licenseKey"]);
12484
+ const _a2 = event, { licenseKey } = _a2, safeEvent = __objRest(_a2, ["licenseKey"]);
12638
12485
  const completeEvent = __spreadValues({
12639
12486
  eventType: event.eventType || "error_occurred" /* ERROR_OCCURRED */,
12640
12487
  projectId: this.projectId,
@@ -12719,26 +12566,33 @@ var _TelemetryService = class _TelemetryService {
12719
12566
  if (this.eventQueue.length === 0) return;
12720
12567
  const events = this.eventQueue.splice(0, this.batchSize);
12721
12568
  const payload = {
12722
- events: events.map((e) => {
12723
- const eventWithoutKey = __objRest(e, []);
12724
- return eventWithoutKey;
12725
- }),
12569
+ events: events.map((e) => __spreadValues({}, e)),
12726
12570
  batchId: `${this.projectId}_${Date.now()}`
12727
12571
  };
12728
12572
  try {
12729
- await this.http.post(_TelemetryService.RETRIVORA_TELEMETRY_URL, payload);
12573
+ const res = await fetch(_TelemetryService.RETRIVORA_TELEMETRY_URL, {
12574
+ method: "POST",
12575
+ headers: this.baseHeaders,
12576
+ body: JSON.stringify(payload),
12577
+ signal: AbortSignal.timeout(5e3)
12578
+ });
12579
+ if (!res.ok) {
12580
+ throw new Error(`HTTP ${res.status}`);
12581
+ }
12730
12582
  } catch (err) {
12731
12583
  console.warn("[TelemetryService] Failed to send telemetry to Retrivora:", err.message);
12732
12584
  this.eventQueue.unshift(...events);
12733
12585
  }
12734
12586
  if (this.userTelemetryUrl) {
12735
12587
  try {
12736
- await axios10.post(this.userTelemetryUrl, payload, {
12737
- timeout: 5e3,
12588
+ await fetch(this.userTelemetryUrl, {
12589
+ method: "POST",
12738
12590
  headers: {
12739
12591
  "Content-Type": "application/json",
12740
12592
  "X-Project-ID": this.projectId
12741
- }
12593
+ },
12594
+ body: JSON.stringify(payload),
12595
+ signal: AbortSignal.timeout(5e3)
12742
12596
  });
12743
12597
  } catch (err) {
12744
12598
  console.warn("[TelemetryService] Failed to send telemetry to user endpoint:", err.message);
@@ -12813,7 +12667,9 @@ var LicensedRetrivora = class {
12813
12667
  }
12814
12668
  }
12815
12669
  /**
12816
- * Initialize the SDK by validating license and fetching config
12670
+ * Generates a unique ID for correlating telemetry events.
12671
+ * Format: `{timestamp}-{random}` — not cryptographically secure, used for
12672
+ * tracing only.
12817
12673
  */
12818
12674
  generateId() {
12819
12675
  return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
@@ -12919,7 +12775,7 @@ var LicensedRetrivora = class {
12919
12775
  * Returns only the response text and sources (abstracted from underlying models)
12920
12776
  */
12921
12777
  async query(queryText, options) {
12922
- var _a3;
12778
+ var _a2;
12923
12779
  if (!this.initialized || !this.pipeline) {
12924
12780
  throw new Error("[LicensedRetrivora] SDK not initialized. Call initialize() first.");
12925
12781
  }
@@ -12927,19 +12783,21 @@ var LicensedRetrivora = class {
12927
12783
  const telemetry = getTelemetryService();
12928
12784
  const startTime = Date.now();
12929
12785
  try {
12930
- const response = await this.pipeline.runNormalQuery(queryText);
12786
+ const response = await this.pipeline.ask(queryText);
12931
12787
  const durationMs = Date.now() - startTime;
12932
12788
  if (telemetry) {
12933
12789
  telemetry.recordQueryExecuted({
12934
12790
  queryText,
12935
- resultCount: ((_a3 = response.sources) == null ? void 0 : _a3.length) || 0,
12791
+ resultCount: ((_a2 = response.sources) == null ? void 0 : _a2.length) || 0,
12936
12792
  durationMs,
12937
12793
  operationId
12938
12794
  });
12939
12795
  }
12940
12796
  return {
12941
12797
  reply: response.reply,
12942
- sources: response.sources
12798
+ sources: response.sources,
12799
+ trace: response.trace,
12800
+ ui_transformation: response.ui_transformation
12943
12801
  };
12944
12802
  } catch (error) {
12945
12803
  const durationMs = Date.now() - startTime;
@@ -12978,9 +12836,17 @@ var LicensedRetrivora = class {
12978
12836
  return this.initialized;
12979
12837
  }
12980
12838
  /**
12981
- * Get current RAG configuration (for debugging)
12839
+ * Get current RAG configuration (for debugging).
12840
+ *
12841
+ * Fix DX-3: throws when called before `initialize()` so callers receive a
12842
+ * clear, actionable error instead of a silent `undefined` that causes a
12843
+ * confusing null-reference error downstream. Consistent with the behavior
12844
+ * of `query()` and `ingest()`.
12982
12845
  */
12983
12846
  getConfig() {
12847
+ if (!this.ragConfig) {
12848
+ throw new Error("[LicensedRetrivora] SDK not initialized. Call initialize() first.");
12849
+ }
12984
12850
  return this.ragConfig;
12985
12851
  }
12986
12852
  };