@retrivora-ai/rag-engine 2.3.6 → 2.3.8

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 (34) hide show
  1. package/dist/{BatchProcessor-Dfn23VAd.d.mts → BatchProcessor-BhLczWj5.d.mts} +100 -2
  2. package/dist/{BatchProcessor-ByBl-1MA.d.ts → BatchProcessor-C42_RVWO.d.ts} +100 -2
  3. package/dist/handlers/index.d.mts +1 -1
  4. package/dist/handlers/index.d.ts +1 -1
  5. package/dist/handlers/index.js +340 -172
  6. package/dist/handlers/index.mjs +342 -174
  7. package/dist/{index-ejOWsaqb.d.ts → index-BQd6Bax0.d.ts} +1 -1
  8. package/dist/{index-xxQOFx-u.d.mts → index-C7aHK7_g.d.mts} +1 -1
  9. package/dist/index.d.mts +2 -2
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.js +114 -87
  12. package/dist/index.mjs +114 -87
  13. package/dist/server.d.mts +263 -37
  14. package/dist/server.d.ts +263 -37
  15. package/dist/server.js +957 -178
  16. package/dist/server.mjs +949 -180
  17. package/package.json +1 -1
  18. package/src/LicensedRetrivora.ts +273 -0
  19. package/src/components/ChatWidget.tsx +0 -1
  20. package/src/components/ConfigProvider.tsx +2 -1
  21. package/src/config/LicenseConfigResolver.ts +296 -0
  22. package/src/config/serverConfig.ts +75 -16
  23. package/src/core/ConfigFetcher.ts +36 -3
  24. package/src/core/DatabaseStorage.ts +13 -13
  25. package/src/core/LicenseValidator.ts +5 -3
  26. package/src/core/LicenseVerifier.ts +85 -120
  27. package/src/core/Retrivora.ts +1 -1
  28. package/src/core/VectorPlugin.ts +1 -1
  29. package/src/handlers/index.ts +25 -11
  30. package/src/index.ts +9 -0
  31. package/src/llm/providers/UniversalLLMAdapter.ts +67 -12
  32. package/src/providers/vectordb/PineconeProvider.ts +69 -2
  33. package/src/server.ts +23 -1
  34. package/src/telemetry/TelemetryService.ts +330 -0
@@ -302,7 +302,7 @@ var init_package = __esm({
302
302
  "package.json"() {
303
303
  package_default = {
304
304
  name: "@retrivora-ai/rag-engine",
305
- version: "2.3.6",
305
+ version: "2.3.8",
306
306
  description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
307
307
  author: "Abhinav Alkuchi",
308
308
  license: "UNLICENSED",
@@ -488,7 +488,12 @@ var init_ConfigFetcher = __esm({
488
488
  process.env.RETRIVORA_CONTROL_PLANE_URL,
489
489
  process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
490
490
  CONTROL_PLANE_URL
491
- ].filter((url) => Boolean(url) && !url.includes("localhost") && !url.includes("127.0.0.1")).map((url) => url.replace(/\/$/, ""));
491
+ ].filter((url) => {
492
+ if (!url) return false;
493
+ const isEnvVar = url === process.env.RETRIVORA_CONTROL_PLANE_URL || url === process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL;
494
+ if (!isEnvVar && (url.includes("localhost") || url.includes("127.0.0.1"))) return false;
495
+ return true;
496
+ }).map((url) => url.replace(/\/$/, ""));
492
497
  for (const baseUrl of controlPlaneUrls) {
493
498
  try {
494
499
  const url = `${baseUrl}/api/v1/config?projectId=${encodeURIComponent(projectId)}`;
@@ -509,8 +514,7 @@ var init_ConfigFetcher = __esm({
509
514
  isActive: data.isActive,
510
515
  expiresAt: data.expiresAt,
511
516
  vectorDb: {
512
- // apiKey is not returned by the config API — it's a server-only secret.
513
- // The SDK uses local PINECONE_API_KEY if available.
517
+ // Fetch apiKey from credentials API if available, else fallback to empty
514
518
  apiKey: data.vectorDb.apiKey || "",
515
519
  indexName: data.vectorDb.indexName || "retrivora-free",
516
520
  provider: data.vectorDb.provider || "pinecone",
@@ -542,6 +546,32 @@ var init_ConfigFetcher = __esm({
542
546
  data.projectSettings || data.settings
543
547
  )
544
548
  };
549
+ if (licenseKey) {
550
+ try {
551
+ const credUrl = `${baseUrl}/api/v1/credentials`;
552
+ const credRes = await fetch(credUrl, {
553
+ method: "POST",
554
+ headers: {
555
+ "Content-Type": "application/json"
556
+ },
557
+ body: JSON.stringify({ licenseKey, projectId: fetchedProjectId })
558
+ });
559
+ if (credRes.ok) {
560
+ const credData = await credRes.json();
561
+ if ((credData == null ? void 0 : credData.success) && (credData == null ? void 0 : credData.credentials)) {
562
+ if (credData.credentials.pineconeApiKey && !config.vectorDb.apiKey) {
563
+ config.vectorDb.apiKey = credData.credentials.pineconeApiKey;
564
+ }
565
+ if (credData.credentials.litellmApiKey) {
566
+ config.llm.apiKey = credData.credentials.litellmApiKey;
567
+ config.embedding.apiKey = credData.credentials.litellmApiKey;
568
+ }
569
+ }
570
+ }
571
+ } catch (e) {
572
+ console.warn("[ConfigFetcher] Failed to fetch credentials:", e);
573
+ }
574
+ }
545
575
  this.cache.set(cacheKey, { config, cachedAt: now });
546
576
  return config;
547
577
  }
@@ -581,6 +611,14 @@ var init_PineconeProvider = __esm({
581
611
  const opts = config.options || {};
582
612
  this.apiKey = opts.apiKey || process.env.PINECONE_API_KEY || "";
583
613
  }
614
+ getControlPlaneUrl() {
615
+ const urls = [
616
+ process.env.RETRIVORA_CONTROL_PLANE_URL,
617
+ process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
618
+ "https://www.retrivora.com"
619
+ ].filter((url) => Boolean(url));
620
+ return urls[0].replace(/\/$/, "");
621
+ }
584
622
  static getValidator() {
585
623
  return {
586
624
  validate(config) {
@@ -644,6 +682,7 @@ var init_PineconeProvider = __esm({
644
682
  let key = this.apiKey || process.env.PINECONE_API_KEY || "";
645
683
  if (!key) {
646
684
  const licenseKey = process.env.RETRIVORA_LICENSE_KEY || process.env.NEXT_PUBLIC_RETRIVORA_LICENSE_KEY;
685
+ this.licenseKey = licenseKey;
647
686
  const jwtProjectId = (() => {
648
687
  if (!licenseKey) return void 0;
649
688
  try {
@@ -657,6 +696,7 @@ var init_PineconeProvider = __esm({
657
696
  return void 0;
658
697
  })();
659
698
  const projectId = process.env.RAG_PROJECT_ID || process.env.NEXT_PUBLIC_RAG_PROJECT_ID || jwtProjectId || this.projectId || "default";
699
+ this.projectId = projectId;
660
700
  const remoteConfig = await ConfigFetcher.fetchRemoteVectorConfig(projectId, licenseKey);
661
701
  if (remoteConfig) {
662
702
  if (remoteConfig.apiKey) {
@@ -702,19 +742,59 @@ var init_PineconeProvider = __esm({
702
742
  return namespace ? idx.namespace(namespace) : idx.namespace("");
703
743
  }
704
744
  async upsert(doc, namespace) {
705
- var _a3;
745
+ var _a3, _b;
746
+ if (!this.client) {
747
+ if (!this.licenseKey) throw new Error("[PineconeProvider] Cannot execute vector operation: Missing API key and License key.");
748
+ const res = await fetch(`${this.getControlPlaneUrl()}/api/v1/vectors/upsert`, {
749
+ method: "POST",
750
+ headers: { "Content-Type": "application/json", "x-license-key": this.licenseKey },
751
+ body: JSON.stringify({
752
+ projectId: this.projectId,
753
+ indexName: this.indexName,
754
+ namespace: namespace || this.projectId,
755
+ records: [{ id: String(doc.id), values: doc.vector, metadata: __spreadValues({ content: doc.content }, (_a3 = doc.metadata) != null ? _a3 : {}) }]
756
+ })
757
+ });
758
+ if (!res.ok) throw new Error(`[PineconeProvider] Proxy upsert failed: ${await res.text()}`);
759
+ return;
760
+ }
706
761
  const targetIdx = await this.getActiveIndex(namespace);
707
762
  await targetIdx.upsert({
708
763
  records: [{
709
764
  id: String(doc.id),
710
765
  values: doc.vector,
711
- metadata: __spreadValues({ content: doc.content }, (_a3 = doc.metadata) != null ? _a3 : {})
766
+ metadata: __spreadValues({ content: doc.content }, (_b = doc.metadata) != null ? _b : {})
712
767
  }]
713
768
  });
714
769
  }
715
770
  async batchUpsert(docs, namespace) {
716
- const targetIdx = await this.getActiveIndex(namespace);
717
771
  const BATCH = 100;
772
+ if (!this.client) {
773
+ if (!this.licenseKey) throw new Error("[PineconeProvider] Cannot execute vector operation: Missing API key and License key.");
774
+ for (let i = 0; i < docs.length; i += BATCH) {
775
+ const records = docs.slice(i, i + BATCH).map((d) => {
776
+ var _a3;
777
+ return {
778
+ id: String(d.id),
779
+ values: d.vector,
780
+ metadata: __spreadValues({ content: d.content }, (_a3 = d.metadata) != null ? _a3 : {})
781
+ };
782
+ });
783
+ const res = await fetch(`${this.getControlPlaneUrl()}/api/v1/vectors/upsert`, {
784
+ method: "POST",
785
+ headers: { "Content-Type": "application/json", "x-license-key": this.licenseKey },
786
+ body: JSON.stringify({
787
+ projectId: this.projectId,
788
+ indexName: this.indexName,
789
+ namespace: namespace || this.projectId,
790
+ records
791
+ })
792
+ });
793
+ if (!res.ok) throw new Error(`[PineconeProvider] Proxy batch upsert failed: ${await res.text()}`);
794
+ }
795
+ return;
796
+ }
797
+ const targetIdx = await this.getActiveIndex(namespace);
718
798
  for (let i = 0; i < docs.length; i += BATCH) {
719
799
  const records = docs.slice(i, i + BATCH).map((d) => {
720
800
  var _a3;
@@ -728,20 +808,46 @@ var init_PineconeProvider = __esm({
728
808
  }
729
809
  }
730
810
  async query(vector, topK, namespace, filter) {
731
- var _a3;
732
- const targetIdx = await this.getActiveIndex(namespace);
811
+ var _a3, _b;
733
812
  const pineconeFilter = this.sanitizeFilter(filter);
813
+ if (!this.client) {
814
+ if (!this.licenseKey) throw new Error("[PineconeProvider] Cannot execute vector operation: Missing API key and License key.");
815
+ const res = await fetch(`${this.getControlPlaneUrl()}/api/v1/vectors/query`, {
816
+ method: "POST",
817
+ headers: { "Content-Type": "application/json", "x-license-key": this.licenseKey },
818
+ body: JSON.stringify({
819
+ projectId: this.projectId,
820
+ indexName: this.indexName,
821
+ namespace: namespace || this.projectId,
822
+ vector,
823
+ topK,
824
+ filter: pineconeFilter
825
+ })
826
+ });
827
+ if (!res.ok) throw new Error(`[PineconeProvider] Proxy query failed: ${await res.text()}`);
828
+ const data = await res.json();
829
+ return ((_a3 = data.matches) != null ? _a3 : []).map((m) => {
830
+ var _a4, _b2;
831
+ return {
832
+ id: m.id,
833
+ score: (_a4 = m.score) != null ? _a4 : 0,
834
+ content: ((_b2 = m.metadata) == null ? void 0 : _b2.content) || "",
835
+ metadata: m.metadata
836
+ };
837
+ });
838
+ }
839
+ const targetIdx = await this.getActiveIndex(namespace);
734
840
  const result = await targetIdx.query(__spreadValues({
735
841
  vector,
736
842
  topK,
737
843
  includeMetadata: true
738
844
  }, Object.keys(pineconeFilter).length > 0 ? { filter: pineconeFilter } : {}));
739
- return ((_a3 = result.matches) != null ? _a3 : []).map((m) => {
740
- var _a4, _b;
845
+ return ((_b = result.matches) != null ? _b : []).map((m) => {
846
+ var _a4, _b2;
741
847
  return {
742
848
  id: m.id,
743
849
  score: (_a4 = m.score) != null ? _a4 : 0,
744
- content: ((_b = m.metadata) == null ? void 0 : _b.content) || "",
850
+ content: ((_b2 = m.metadata) == null ? void 0 : _b2.content) || "",
745
851
  metadata: m.metadata
746
852
  };
747
853
  });
@@ -1720,7 +1826,7 @@ __export(QdrantProvider_exports, {
1720
1826
  QdrantProvider: () => QdrantProvider
1721
1827
  });
1722
1828
  import axios4 from "axios";
1723
- import crypto2 from "crypto";
1829
+ import crypto from "crypto";
1724
1830
  var QdrantProvider;
1725
1831
  var init_QdrantProvider = __esm({
1726
1832
  "src/providers/vectordb/QdrantProvider.ts"() {
@@ -1952,7 +2058,7 @@ var init_QdrantProvider = __esm({
1952
2058
  if (typeof id === "number") return id;
1953
2059
  const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1954
2060
  if (uuidRegex.test(id)) return id.toLowerCase();
1955
- const hash = crypto2.createHash("md5").update(id).digest("hex");
2061
+ const hash = crypto.createHash("md5").update(id).digest("hex");
1956
2062
  return `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20, 32)}`;
1957
2063
  }
1958
2064
  async disconnect() {
@@ -2537,9 +2643,6 @@ import { NextResponse } from "next/server";
2537
2643
  // src/core/ConfigResolver.ts
2538
2644
  init_templateUtils();
2539
2645
 
2540
- // src/core/LicenseVerifier.ts
2541
- import * as crypto from "crypto";
2542
-
2543
2646
  // src/exceptions/index.ts
2544
2647
  var RetrivoraError = class extends Error {
2545
2648
  constructor(message, code, details) {
@@ -2615,29 +2718,18 @@ function wrapError(err, defaultCode, defaultMessage) {
2615
2718
  }
2616
2719
 
2617
2720
  // src/core/LicenseVerifier.ts
2618
- var LicenseVerifier = class {
2721
+ var _LicenseVerifier = class _LicenseVerifier {
2722
+ // Cache verified license for 5 minutes
2619
2723
  /**
2620
- * Decodes, verifies signature, and checks metadata of a license key.
2724
+ * Validates the license key asynchronously by calling the Retrivora backend.
2621
2725
  *
2622
2726
  * @param licenseKey - Base64url signed JWT license key.
2623
2727
  * @param currentProjectId - Project namespace ID.
2624
- * @param publicKeyOverride - Optional override for unit/integration tests.
2728
+ * @param provider - Optional provider for tier checks.
2625
2729
  */
2626
- static verify(licenseKey, currentProjectId, provider, publicKeyOverride) {
2730
+ static async verifyAsync(licenseKey, currentProjectId, provider) {
2627
2731
  const isProduction = process.env.NODE_ENV === "production";
2628
2732
  const now = Date.now();
2629
- if (licenseKey) {
2630
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
2631
- const cached = this.cache.get(cacheKey);
2632
- if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
2633
- const currentTimestampSec = Math.floor(now / 1e3);
2634
- if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
2635
- this.cache.delete(cacheKey);
2636
- } else {
2637
- return cached.payload;
2638
- }
2639
- }
2640
- }
2641
2733
  if (!licenseKey) {
2642
2734
  if (isProduction) {
2643
2735
  throw new ConfigurationException(
@@ -2654,52 +2746,61 @@ var LicenseVerifier = class {
2654
2746
  tier: "hobby"
2655
2747
  };
2656
2748
  }
2657
- try {
2658
- const sanitizedKey = (licenseKey || "").trim().replace(/^["']|["']$/g, "").trim();
2659
- const rawToken = sanitizedKey.replace(/^rtv_/i, "").trim();
2660
- const parts = rawToken.split(".");
2661
- if (parts.length !== 3) {
2662
- throw new Error("Malformed token structure (expected 3 parts).");
2663
- }
2664
- const [headerB64, payloadB64, signatureB64] = parts;
2665
- const dataToVerify = `${headerB64}.${payloadB64}`;
2666
- const publicKey = publicKeyOverride != null ? publicKeyOverride : this.PUBLIC_KEY;
2667
- const signature = Buffer.from(signatureB64, "base64url");
2668
- const data = Buffer.from(dataToVerify);
2669
- const isValid = crypto.verify(
2670
- "sha256",
2671
- data,
2672
- publicKey,
2673
- signature
2674
- );
2675
- if (!isValid) {
2676
- throw new Error("Signature verification failed.");
2749
+ const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}`;
2750
+ const cached = this.cache.get(cacheKey);
2751
+ if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
2752
+ const currentTimestampSec = Math.floor(now / 1e3);
2753
+ if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
2754
+ this.cache.delete(cacheKey);
2755
+ } else {
2756
+ return cached.payload;
2677
2757
  }
2678
- const payload = JSON.parse(
2679
- Buffer.from(payloadB64, "base64url").toString("utf8")
2680
- );
2681
- if (!payload.projectId) {
2682
- throw new Error('License payload is missing "projectId".');
2758
+ }
2759
+ try {
2760
+ let baseUrl = typeof process !== "undefined" && process.env.RETRIVORA_CONTROL_PLANE_URL ? process.env.RETRIVORA_CONTROL_PLANE_URL : "https://retrivora.com";
2761
+ if (typeof process !== "undefined" && process.env.TELEMETRY_URL) {
2762
+ baseUrl = process.env.TELEMETRY_URL.replace(/\/api\/telemetry\/?$/, "");
2683
2763
  }
2684
- const isProjectMatch = payload.projectId === currentProjectId || payload.projectId === `retrivora-${currentProjectId}` || `retrivora-${payload.projectId}` === currentProjectId;
2685
- if (!isProjectMatch) {
2686
- throw new Error(
2687
- `Project ID mismatch. License is bound to project namespace "${payload.projectId}" but configuration has "${currentProjectId}".`
2688
- );
2764
+ const endpoint = `${baseUrl}/api/v1/license/validate`;
2765
+ const response = await fetch(endpoint, {
2766
+ method: "POST",
2767
+ headers: {
2768
+ "Content-Type": "application/json",
2769
+ "x-license-key": licenseKey
2770
+ },
2771
+ body: JSON.stringify({
2772
+ licenseKey,
2773
+ projectId: currentProjectId,
2774
+ provider
2775
+ })
2776
+ });
2777
+ if (!response.ok) {
2778
+ let errMessage = `HTTP ${response.status}`;
2779
+ try {
2780
+ const body = await response.json();
2781
+ if (body.message) errMessage = body.message;
2782
+ } catch (e) {
2783
+ }
2784
+ throw new Error(errMessage);
2689
2785
  }
2690
- if (!payload.expiresAt) {
2691
- throw new Error('License payload is missing expiration ("expiresAt").');
2786
+ const data = await response.json();
2787
+ if (!data.valid) {
2788
+ throw new Error(data.message || "License validation failed by server.");
2692
2789
  }
2693
- const currentTimestampSec = Math.floor(Date.now() / 1e3);
2694
- if (currentTimestampSec > payload.expiresAt) {
2695
- throw new Error(
2696
- `License key has expired. Expiration: ${new Date(
2697
- payload.expiresAt * 1e3
2698
- ).toDateString()}`
2699
- );
2790
+ let expiresAtNum = Math.floor(Date.now() / 1e3) + 100 * 365 * 24 * 60 * 60;
2791
+ if (data.expiresAt) {
2792
+ expiresAtNum = Math.floor(new Date(data.expiresAt).getTime() / 1e3);
2700
2793
  }
2794
+ const tier = _LicenseVerifier.extractTier(licenseKey);
2795
+ const payload = {
2796
+ projectId: currentProjectId,
2797
+ expiresAt: expiresAtNum,
2798
+ tier,
2799
+ licenseStatus: data.licenseStatus,
2800
+ minimumSupportedVersion: data.minimumSupportedVersion,
2801
+ forceUpgrade: data.forceUpgrade
2802
+ };
2701
2803
  if (isProduction && provider) {
2702
- const tier = (payload.tier || "").toLowerCase();
2703
2804
  const normalizedProvider = provider.toLowerCase();
2704
2805
  if (tier === "hobby") {
2705
2806
  const allowedHobby = ["postgresql", "pgvector", "supabase"];
@@ -2727,15 +2828,12 @@ var LicenseVerifier = class {
2727
2828
  }
2728
2829
  }
2729
2830
  }
2730
- if (licenseKey) {
2731
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
2732
- this.cache.set(cacheKey, { payload, cachedAt: now });
2733
- }
2831
+ this.cache.set(cacheKey, { payload, cachedAt: now });
2734
2832
  return payload;
2735
2833
  } catch (err) {
2736
2834
  const message = err instanceof Error ? err.message : String(err);
2737
2835
  throw new ConfigurationException(
2738
- `[Retrivora SDK] License key validation failed: ${message}`
2836
+ `[Retrivora SDK] License key validation failed via API: ${message}`
2739
2837
  );
2740
2838
  }
2741
2839
  }
@@ -2804,23 +2902,25 @@ var LicenseVerifier = class {
2804
2902
  }
2805
2903
  }
2806
2904
  }
2905
+ static extractTier(licenseKey) {
2906
+ if (!licenseKey) return "hobby";
2907
+ try {
2908
+ const sanitizedKey = licenseKey.trim().replace(/^["']|["']$/g, "").trim();
2909
+ const rawToken = sanitizedKey.replace(/^rtv_/i, "").trim();
2910
+ const parts = rawToken.split(".");
2911
+ if (parts.length === 3) {
2912
+ const decodedPayload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
2913
+ if (decodedPayload.tier) return decodedPayload.tier;
2914
+ }
2915
+ } catch (e) {
2916
+ }
2917
+ return "hobby";
2918
+ }
2807
2919
  };
2808
- // A simple in-memory cache to save CPU overhead of cryptographic signature checks.
2809
- LicenseVerifier.cache = /* @__PURE__ */ new Map();
2810
- LicenseVerifier.CACHE_TTL_MS = 60 * 1e3;
2811
- // Cache verified license for 60 seconds
2812
- // Retrivora's Public Key used to verify the license key signature.
2813
- // In production, this matches the private key held by Retrivora SaaS.
2814
- // Rotate this key only when the signing private key is replaced.
2815
- LicenseVerifier.PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
2816
- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoOQlmDSKfCZaRy06rxwa
2817
- chuDimlF134xTCitKDTPTPizF23oSn34pGDJakm/0T09JVUX8L/cvhGPe/3lf/g9
2818
- 4Y1q+Gb2KVM17KNGeT1Aj9Ua3BKz/yao/oFhi/r3Zt3cWY13B/Rd6clqY9WshIAV
2819
- NqZNM8ilTl777cMbyym+6D+mzGXgmnJAO5brddIAI9FPLW0T3Znt8vEqDOIljEkC
2820
- HCGHeirKABLbjKSJ4hljCa3vVitWqndhiq8CBSJG6HatiSGYotgMWGRY+0EbdlEv
2821
- OJP4SqafQ3aD6YnL9q1n15QKwxu/uMK+JGM2VxxuyUi9GANtMIkCYy9xya73P4Qc
2822
- gQIDAQAB
2823
- -----END PUBLIC KEY-----`;
2920
+ // In-memory cache to save network overhead on hot paths.
2921
+ _LicenseVerifier.cache = /* @__PURE__ */ new Map();
2922
+ _LicenseVerifier.CACHE_TTL_MS = 5 * 60 * 1e3;
2923
+ var LicenseVerifier = _LicenseVerifier;
2824
2924
 
2825
2925
  // src/config/constants.ts
2826
2926
  var VECTOR_DB_PROVIDERS = [
@@ -2868,6 +2968,7 @@ var PROVIDERS_WITH_EMBEDDINGS = [
2868
2968
  var UI_BORDER_RADIUS_OPTIONS = ["none", "sm", "md", "lg", "xl", "full"];
2869
2969
 
2870
2970
  // src/config/serverConfig.ts
2971
+ var _runtimeConfig = null;
2871
2972
  function readString(env, name) {
2872
2973
  var _a3;
2873
2974
  const value = (_a3 = env[name]) == null ? void 0 : _a3.trim();
@@ -2891,7 +2992,7 @@ function readEnum(env, name, fallback, allowed) {
2891
2992
  throw new Error(`[getRagConfig] ${name} must be one of: ${allowed.join(", ")}`);
2892
2993
  }
2893
2994
  function getEnvConfig(env = process.env, base) {
2894
- 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;
2995
+ 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;
2895
2996
  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;
2896
2997
  const jwtProjectId = (() => {
2897
2998
  if (!licenseKey) return void 0;
@@ -2976,32 +3077,41 @@ function getEnvConfig(env = process.env, base) {
2976
3077
  const isFreeTier2 = (() => {
2977
3078
  if (!licenseKey) return true;
2978
3079
  try {
2979
- const payload = LicenseVerifier.verify(licenseKey, projectId);
2980
- const tier = (payload.tier || "").toLowerCase();
3080
+ const tier = LicenseVerifier.extractTier(licenseKey).toLowerCase();
2981
3081
  return tier === "free_trial" || tier === "free_tier" || tier === "free" || tier === "hobby";
2982
3082
  } catch (e) {
2983
3083
  return true;
2984
3084
  }
2985
3085
  })();
2986
- const defaultGatewayUrl = (_ra = (_qa = readString(env, "LITELLM_BASE_URL")) != null ? _qa : readString(env, "LLM_BASE_URL")) != null ? _ra : "https://www.retrivora.com/api/v1";
2987
- const defaultLlmProvider = isFreeTier2 ? "universal_rest" : "universal_rest";
2988
- const llmProvider = (_ua = (_ta = readEnum(env, "LLM_PROVIDER", defaultLlmProvider, LLM_PROVIDERS)) != null ? _ta : (_sa = base == null ? void 0 : base.llm) == null ? void 0 : _sa.provider) != null ? _ua : defaultLlmProvider;
2989
- const llmBaseUrl = (_ya = (_xa = (_va = readString(env, "LITELLM_BASE_URL")) != null ? _va : readString(env, "LLM_BASE_URL")) != null ? _xa : (_wa = base == null ? void 0 : base.llm) == null ? void 0 : _wa.baseUrl) != null ? _ya : defaultGatewayUrl;
2990
- const llmModel = (_Ca = (_Aa = readString(env, "LLM_MODEL")) != null ? _Aa : (_za = base == null ? void 0 : base.llm) == null ? void 0 : _za.model) != null ? _Ca : isFreeTier2 ? "llama-3.1-8b-instant" : (_Ba = DEFAULT_MODEL_BY_PROVIDER[llmProvider]) != null ? _Ba : "gpt-4o";
2991
- const llmApiKey = (_Ia = (_Ha = (_Fa = (_Ea = (_Da = llmApiKeyByProvider[llmProvider]) != null ? _Da : readString(env, "LLM_API_KEY")) != null ? _Ea : readString(env, "LITELLM_MASTER_KEY")) != null ? _Fa : readString(env, "LITELLM_API_KEY")) != null ? _Ha : (_Ga = base == null ? void 0 : base.llm) == null ? void 0 : _Ga.apiKey) != null ? _Ia : licenseKey;
2992
- const llmProfile = (_Ma = (_La = readString(env, "LLM_UNIVERSAL_PROFILE")) != null ? _La : (_Ka = (_Ja = base == null ? void 0 : base.llm) == null ? void 0 : _Ja.options) == null ? void 0 : _Ka.profile) != null ? _Ma : "litellm";
2993
- const defaultEmbeddingProvider = isFreeTier2 ? "universal_rest" : "universal_rest";
2994
- const embeddingProvider = (_Pa = (_Oa = readEnum(env, "EMBEDDING_PROVIDER", defaultEmbeddingProvider, EMBEDDING_PROVIDERS)) != null ? _Oa : (_Na = base == null ? void 0 : base.embedding) == null ? void 0 : _Na.provider) != null ? _Pa : defaultEmbeddingProvider;
2995
- const embeddingBaseUrl = (_Ua = (_Ta = (_Ra = (_Qa = readString(env, "LITELLM_BASE_URL")) != null ? _Qa : readString(env, "EMBEDDING_BASE_URL")) != null ? _Ra : readString(env, "LLM_BASE_URL")) != null ? _Ta : (_Sa = base == null ? void 0 : base.embedding) == null ? void 0 : _Sa.baseUrl) != null ? _Ua : defaultGatewayUrl;
2996
- const embeddingModel = (_Xa = (_Wa = readString(env, "EMBEDDING_MODEL")) != null ? _Wa : (_Va = base == null ? void 0 : base.embedding) == null ? void 0 : _Va.model) != null ? _Xa : "text-embedding-004";
2997
- const embeddingApiKey = (_cb = (_bb = (_$a = (__a = (_Za = (_Ya = embeddingApiKeyByProvider[embeddingProvider]) != null ? _Ya : readString(env, "EMBEDDING_API_KEY")) != null ? _Za : readString(env, "LLM_API_KEY")) != null ? __a : readString(env, "LITELLM_MASTER_KEY")) != null ? _$a : readString(env, "LITELLM_API_KEY")) != null ? _bb : (_ab = base == null ? void 0 : base.embedding) == null ? void 0 : _ab.apiKey) != null ? _cb : licenseKey;
2998
- const embeddingProfile = (_gb = (_fb = readString(env, "EMBEDDING_UNIVERSAL_PROFILE")) != null ? _fb : (_eb = (_db = base == null ? void 0 : base.embedding) == null ? void 0 : _db.options) == null ? void 0 : _eb.profile) != null ? _gb : "litellm";
3086
+ const tierBasedLLMModel = isFreeTier2 ? "llama-3.1-8b-instant" : "llama-3.3-70b-versatile";
3087
+ const tierBasedEmbeddingModel = isFreeTier2 ? "text-embedding-004" : "text-embedding-004";
3088
+ const defaultGatewayUrl = "https://llm.retrivora.com/api/v1";
3089
+ const rt = _runtimeConfig;
3090
+ const defaultLlmProvider = "universal_rest";
3091
+ const llmProvider = (_sa = (_ra = readEnum(env, "LLM_PROVIDER", defaultLlmProvider, LLM_PROVIDERS)) != null ? _ra : (_qa = base == null ? void 0 : base.llm) == null ? void 0 : _qa.provider) != null ? _sa : defaultLlmProvider;
3092
+ const llmBaseUrl = (_xa = (_wa = (_va = (_ta = readString(env, "LITELLM_BASE_URL")) != null ? _ta : readString(env, "LLM_BASE_URL")) != null ? _va : (_ua = base == null ? void 0 : base.llm) == null ? void 0 : _ua.baseUrl) != null ? _wa : rt == null ? void 0 : rt.llmBaseUrl) != null ? _xa : defaultGatewayUrl;
3093
+ const llmModel = (_Ba = (_Aa = (_za = readString(env, "LLM_MODEL")) != null ? _za : (_ya = base == null ? void 0 : base.llm) == null ? void 0 : _ya.model) != null ? _Aa : rt == null ? void 0 : rt.llmModel) != null ? _Ba : tierBasedLLMModel;
3094
+ const llmApiKey = (_Fa = (_Ea = (_Ca = readString(env, "LITELLM_MASTER_KEY")) != null ? _Ca : rt == null ? void 0 : rt.litellmApiKey) != null ? _Ea : (_Da = base == null ? void 0 : base.llm) == null ? void 0 : _Da.apiKey) != null ? _Fa : licenseKey;
3095
+ const llmProfile = (_Ja = (_Ia = readString(env, "LLM_UNIVERSAL_PROFILE")) != null ? _Ia : (_Ha = (_Ga = base == null ? void 0 : base.llm) == null ? void 0 : _Ga.options) == null ? void 0 : _Ha.profile) != null ? _Ja : "litellm";
3096
+ console.log("[serverConfig] \u{1F527} LLM Configuration:", {
3097
+ baseUrl: llmBaseUrl,
3098
+ model: llmModel,
3099
+ provider: llmProvider,
3100
+ hasApiKey: !!llmApiKey,
3101
+ source: (rt == null ? void 0 : rt.llmModel) ? "runtime-injected" : "env/fallback"
3102
+ });
3103
+ const defaultEmbeddingProvider = "universal_rest";
3104
+ const embeddingProvider = (_Ma = (_La = readEnum(env, "EMBEDDING_PROVIDER", defaultEmbeddingProvider, EMBEDDING_PROVIDERS)) != null ? _La : (_Ka = base == null ? void 0 : base.embedding) == null ? void 0 : _Ka.provider) != null ? _Ma : defaultEmbeddingProvider;
3105
+ const embeddingBaseUrl = (_Ta = (_Sa = (_Ra = (_Qa = (_Oa = (_Na = readString(env, "LITELLM_BASE_URL")) != null ? _Na : readString(env, "EMBEDDING_BASE_URL")) != null ? _Oa : readString(env, "LLM_BASE_URL")) != null ? _Qa : (_Pa = base == null ? void 0 : base.embedding) == null ? void 0 : _Pa.baseUrl) != null ? _Ra : rt == null ? void 0 : rt.embeddingBaseUrl) != null ? _Sa : rt == null ? void 0 : rt.llmBaseUrl) != null ? _Ta : defaultGatewayUrl;
3106
+ const embeddingModel = (_Xa = (_Wa = (_Va = readString(env, "EMBEDDING_MODEL")) != null ? _Va : (_Ua = base == null ? void 0 : base.embedding) == null ? void 0 : _Ua.model) != null ? _Wa : rt == null ? void 0 : rt.embeddingModel) != null ? _Xa : tierBasedEmbeddingModel;
3107
+ const embeddingApiKey = (_$a = (__a = (_Ya = readString(env, "LITELLM_MASTER_KEY")) != null ? _Ya : rt == null ? void 0 : rt.litellmApiKey) != null ? __a : (_Za = base == null ? void 0 : base.embedding) == null ? void 0 : _Za.apiKey) != null ? _$a : licenseKey;
3108
+ const embeddingProfile = (_db = (_cb = readString(env, "EMBEDDING_UNIVERSAL_PROFILE")) != null ? _cb : (_bb = (_ab = base == null ? void 0 : base.embedding) == null ? void 0 : _ab.options) == null ? void 0 : _bb.profile) != null ? _db : "litellm";
2999
3109
  return __spreadProps(__spreadValues({
3000
3110
  projectId,
3001
3111
  licenseKey,
3002
3112
  vectorDb: {
3003
3113
  provider: vectorProvider,
3004
- indexName: (_ib = (_hb = readString(env, "VECTOR_DB_INDEX")) != null ? _hb : vectorDbOptions.indexName) != null ? _ib : "rag-index",
3114
+ indexName: (_fb = (_eb = readString(env, "VECTOR_DB_INDEX")) != null ? _eb : vectorDbOptions.indexName) != null ? _fb : "rag-index",
3005
3115
  options: vectorDbOptions
3006
3116
  },
3007
3117
  llm: {
@@ -3031,30 +3141,30 @@ function getEnvConfig(env = process.env, base) {
3031
3141
  }
3032
3142
  },
3033
3143
  ui: {
3034
- title: (_kb = (_jb = readString(env, "NEXT_PUBLIC_UI_TITLE")) != null ? _jb : readString(env, "UI_TITLE")) != null ? _kb : "AI Assistant",
3035
- subtitle: (_mb = (_lb = readString(env, "NEXT_PUBLIC_UI_SUBTITLE")) != null ? _lb : readString(env, "UI_SUBTITLE")) != null ? _mb : "Powered by RAG",
3036
- primaryColor: (_ob = (_nb = readString(env, "NEXT_PUBLIC_PRIMARY_COLOR")) != null ? _nb : readString(env, "UI_PRIMARY_COLOR")) != null ? _ob : "#10b981",
3037
- accentColor: (_qb = (_pb = readString(env, "NEXT_PUBLIC_ACCENT_COLOR")) != null ? _pb : readString(env, "UI_ACCENT_COLOR")) != null ? _qb : "#3b82f6",
3038
- logoUrl: (_rb = readString(env, "NEXT_PUBLIC_LOGO_URL")) != null ? _rb : readString(env, "UI_LOGO_URL"),
3039
- placeholder: (_tb = (_sb = readString(env, "NEXT_PUBLIC_PLACEHOLDER")) != null ? _sb : readString(env, "UI_PLACEHOLDER")) != null ? _tb : "Ask me anything\u2026",
3040
- showSources: ((_vb = (_ub = readString(env, "NEXT_PUBLIC_SHOW_SOURCES")) != null ? _ub : readString(env, "UI_SHOW_SOURCES")) != null ? _vb : "true") !== "false",
3041
- 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.",
3042
- visualStyle: (_zb = (_yb = readString(env, "NEXT_PUBLIC_UI_VISUAL_STYLE")) != null ? _yb : readString(env, "UI_VISUAL_STYLE")) != null ? _zb : "glass",
3043
- borderRadius: (_Bb = (_Ab = readString(env, "NEXT_PUBLIC_UI_BORDER_RADIUS")) != null ? _Ab : readString(env, "UI_BORDER_RADIUS")) != null ? _Bb : "xl",
3044
- allowUpload: ((_Db = (_Cb = readString(env, "NEXT_PUBLIC_ALLOW_UPLOAD")) != null ? _Cb : readString(env, "UI_ALLOW_UPLOAD")) != null ? _Db : "false") === "true"
3144
+ title: (_hb = (_gb = readString(env, "NEXT_PUBLIC_UI_TITLE")) != null ? _gb : readString(env, "UI_TITLE")) != null ? _hb : "AI Assistant",
3145
+ subtitle: (_jb = (_ib = readString(env, "NEXT_PUBLIC_UI_SUBTITLE")) != null ? _ib : readString(env, "UI_SUBTITLE")) != null ? _jb : "Powered by RAG",
3146
+ primaryColor: (_lb = (_kb = readString(env, "NEXT_PUBLIC_PRIMARY_COLOR")) != null ? _kb : readString(env, "UI_PRIMARY_COLOR")) != null ? _lb : "#10b981",
3147
+ accentColor: (_nb = (_mb = readString(env, "NEXT_PUBLIC_ACCENT_COLOR")) != null ? _mb : readString(env, "UI_ACCENT_COLOR")) != null ? _nb : "#3b82f6",
3148
+ logoUrl: (_ob = readString(env, "NEXT_PUBLIC_LOGO_URL")) != null ? _ob : readString(env, "UI_LOGO_URL"),
3149
+ placeholder: (_qb = (_pb = readString(env, "NEXT_PUBLIC_PLACEHOLDER")) != null ? _pb : readString(env, "UI_PLACEHOLDER")) != null ? _qb : "Ask me anything\u2026",
3150
+ showSources: ((_sb = (_rb = readString(env, "NEXT_PUBLIC_SHOW_SOURCES")) != null ? _rb : readString(env, "UI_SHOW_SOURCES")) != null ? _sb : "true") !== "false",
3151
+ welcomeMessage: (_ub = (_tb = readString(env, "NEXT_PUBLIC_WELCOME_MESSAGE")) != null ? _tb : readString(env, "UI_WELCOME_MESSAGE")) != null ? _ub : "Hello! I'm your AI assistant. Ask me anything about your documents.",
3152
+ visualStyle: (_wb = (_vb = readString(env, "NEXT_PUBLIC_UI_VISUAL_STYLE")) != null ? _vb : readString(env, "UI_VISUAL_STYLE")) != null ? _wb : "glass",
3153
+ borderRadius: (_yb = (_xb = readString(env, "NEXT_PUBLIC_UI_BORDER_RADIUS")) != null ? _xb : readString(env, "UI_BORDER_RADIUS")) != null ? _yb : "xl",
3154
+ allowUpload: ((_Ab = (_zb = readString(env, "NEXT_PUBLIC_ALLOW_UPLOAD")) != null ? _zb : readString(env, "UI_ALLOW_UPLOAD")) != null ? _Ab : "false") === "true"
3045
3155
  },
3046
3156
  rag: {
3047
3157
  topK: readNumber(env, "RAG_TOP_K", 5),
3048
3158
  scoreThreshold: readNumber(env, "RAG_SCORE_THRESHOLD", 0),
3049
3159
  chunkSize: readNumber(env, "RAG_CHUNK_SIZE", 1e3),
3050
3160
  chunkOverlap: readNumber(env, "RAG_CHUNK_OVERLAP", 200),
3051
- filterableFields: (_Eb = readString(env, "RAG_FILTERABLE_FIELDS")) == null ? void 0 : _Eb.split(",").map((f) => f.trim()),
3161
+ filterableFields: (_Bb = readString(env, "RAG_FILTERABLE_FIELDS")) == null ? void 0 : _Bb.split(",").map((f) => f.trim()),
3052
3162
  // Query pipeline toggles — read from .env.local
3053
3163
  useQueryTransformation: readString(env, "RAG_USE_QUERY_TRANSFORMATION") === "true",
3054
3164
  useReranking: readString(env, "RAG_USE_RERANKING") === "true",
3055
3165
  useGraphRetrieval: readString(env, "RAG_USE_GRAPH_RETRIEVAL") === "true",
3056
- architecture: (_Fb = readString(env, "RAG_ARCHITECTURE")) != null ? _Fb : "simple",
3057
- chunkingStrategy: (_Gb = readString(env, "RAG_CHUNKING_STRATEGY")) != null ? _Gb : "recursive",
3166
+ architecture: (_Cb = readString(env, "RAG_ARCHITECTURE")) != null ? _Cb : "simple",
3167
+ chunkingStrategy: (_Db = readString(env, "RAG_CHUNKING_STRATEGY")) != null ? _Db : "recursive",
3058
3168
  uiMapping: (() => {
3059
3169
  const raw = readString(env, "RAG_UI_MAPPING");
3060
3170
  if (!raw) return void 0;
@@ -3067,7 +3177,7 @@ function getEnvConfig(env = process.env, base) {
3067
3177
  },
3068
3178
  telemetry: {
3069
3179
  enabled: telemetryEnabled,
3070
- url: (_Kb = (_Jb = (_Hb = readString(env, "TELEMETRY_URL")) != null ? _Hb : readString(env, "NEXT_PUBLIC_TELEMETRY_URL")) != null ? _Jb : (_Ib = base == null ? void 0 : base.telemetry) == null ? void 0 : _Ib.url) != null ? _Kb : "https://www.retrivora.com/api/telemetry"
3180
+ url: (_Hb = (_Gb = (_Eb = readString(env, "TELEMETRY_URL")) != null ? _Eb : readString(env, "NEXT_PUBLIC_TELEMETRY_URL")) != null ? _Gb : (_Fb = base == null ? void 0 : base.telemetry) == null ? void 0 : _Fb.url) != null ? _Hb : "https://www.retrivora.com/api/telemetry"
3071
3181
  }
3072
3182
  }, readString(env, "GRAPH_DB_PROVIDER") ? {
3073
3183
  graphDb: {
@@ -4385,7 +4495,7 @@ var UniversalLLMAdapter = class {
4385
4495
  });
4386
4496
  }
4387
4497
  async chat(messages, context) {
4388
- var _a3, _b, _c, _d, _e;
4498
+ var _a3, _b, _c, _d, _e, _f, _g2, _h, _i, _j;
4389
4499
  const path2 = (_a3 = this.opts.chatPath) != null ? _a3 : "/chat/completions";
4390
4500
  const safeMessages = (Array.isArray(messages) ? messages : []).filter((m) => Boolean(m && typeof m === "object")).map((m) => ({
4391
4501
  role: m.role || "user",
@@ -4415,16 +4525,27 @@ ${context != null ? context : "None"}` },
4415
4525
  };
4416
4526
  }
4417
4527
  try {
4528
+ console.debug(`[UniversalLLMAdapter] POST ${this.baseUrl}${path2}`);
4529
+ console.debug(`[UniversalLLMAdapter] Model: ${this.model}`);
4530
+ console.debug(`[UniversalLLMAdapter] Auth: Bearer ${((_b = this.apiKey) == null ? void 0 : _b.substring(0, 20)) || "none"}...`);
4418
4531
  const { data: data2 } = await this.http.post(path2, payload);
4419
- const extractPath2 = (_b = this.opts.responseExtractPath) != null ? _b : "choices[0].message.content";
4420
- const result2 = (_c = resolvePath(data2, extractPath2)) != null ? _c : extractContent(data2);
4532
+ const extractPath2 = (_c = this.opts.responseExtractPath) != null ? _c : "choices[0].message.content";
4533
+ const result2 = (_d = resolvePath(data2, extractPath2)) != null ? _d : extractContent(data2);
4421
4534
  if (result2 !== void 0) {
4422
4535
  return String(result2);
4423
4536
  }
4424
4537
  } catch (httpErr) {
4425
- const _g2 = globalThis;
4426
- const dispatch = _g2.__retrivoraDispatchChat;
4538
+ console.error("[UniversalLLMAdapter] \u274C HTTP chat request failed:", {
4539
+ status: (_e = httpErr == null ? void 0 : httpErr.response) == null ? void 0 : _e.status,
4540
+ statusText: (_f = httpErr == null ? void 0 : httpErr.response) == null ? void 0 : _f.statusText,
4541
+ url: (_g2 = httpErr == null ? void 0 : httpErr.config) == null ? void 0 : _g2.url,
4542
+ errorData: (_h = httpErr == null ? void 0 : httpErr.response) == null ? void 0 : _h.data,
4543
+ message: httpErr == null ? void 0 : httpErr.message
4544
+ });
4545
+ const _g3 = globalThis;
4546
+ const dispatch = _g3.__retrivoraDispatchChat;
4427
4547
  if (typeof dispatch === "function") {
4548
+ console.debug("[UniversalLLMAdapter] \u{1F504} Attempting in-process fallback dispatch");
4428
4549
  const res = await dispatch({
4429
4550
  model: this.model,
4430
4551
  messages: formattedMessages,
@@ -4439,8 +4560,8 @@ ${context != null ? context : "None"}` },
4439
4560
  throw httpErr;
4440
4561
  }
4441
4562
  const { data } = await this.http.post(path2, payload);
4442
- const extractPath = (_d = this.opts.responseExtractPath) != null ? _d : "choices[0].message.content";
4443
- const result = (_e = resolvePath(data, extractPath)) != null ? _e : extractContent(data);
4563
+ const extractPath = (_i = this.opts.responseExtractPath) != null ? _i : "choices[0].message.content";
4564
+ const result = (_j = resolvePath(data, extractPath)) != null ? _j : extractContent(data);
4444
4565
  if (result === void 0) {
4445
4566
  throw new Error(`[UniversalLLMAdapter] Could not extract text from path '${extractPath}' in response.`);
4446
4567
  }
@@ -4579,36 +4700,70 @@ ${context != null ? context : "None"}` },
4579
4700
  });
4580
4701
  }
4581
4702
  async embed(text) {
4582
- var _a3, _b, _c, _d, _e;
4703
+ var _a3, _b, _c, _d, _e, _f, _g2;
4583
4704
  const path2 = (_a3 = this.opts.embedPath) != null ? _a3 : "/embeddings";
4584
4705
  const payload = this.opts.embedPayloadTemplate ? buildPayload(this.opts.embedPayloadTemplate, { input: text, model: this.model }) : { input: text, model: this.model };
4585
4706
  try {
4586
- const { data: data2 } = await this.http.post(path2, payload);
4587
- const extractPath2 = (_b = this.opts.embedExtractPath) != null ? _b : "data[0].embedding";
4588
- const vector2 = resolvePath(data2, extractPath2);
4589
- if (Array.isArray(vector2)) return vector2;
4590
- } catch (e) {
4591
- const _g2 = globalThis;
4592
- const dispatchEmbed = _g2.__retrivoraDispatchEmbedding;
4707
+ const { data } = await this.http.post(path2, payload);
4708
+ const extractPath = (_b = this.opts.embedExtractPath) != null ? _b : "data[0].embedding";
4709
+ const vector = resolvePath(data, extractPath);
4710
+ if (Array.isArray(vector)) return vector;
4711
+ console.warn(
4712
+ `[UniversalLLMAdapter] Embedding API returned unexpected format for path '${extractPath}'. Response:`,
4713
+ data
4714
+ );
4715
+ } catch (err) {
4716
+ console.warn(
4717
+ `[UniversalLLMAdapter] HTTP embedding request failed: ${(err == null ? void 0 : err.message) || err}`,
4718
+ { path: path2, model: this.model }
4719
+ );
4720
+ const _g3 = globalThis;
4721
+ const dispatchEmbed = _g3.__retrivoraDispatchEmbedding;
4593
4722
  if (typeof dispatchEmbed === "function") {
4594
- const res = await dispatchEmbed({ input: text, model: this.model }, this.apiKey);
4595
- if ((_d = (_c = res == null ? void 0 : res.data) == null ? void 0 : _c[0]) == null ? void 0 : _d.embedding) {
4596
- return res.data[0].embedding;
4723
+ try {
4724
+ const res = await dispatchEmbed({ input: text, model: this.model }, this.apiKey);
4725
+ if ((_d = (_c = res == null ? void 0 : res.data) == null ? void 0 : _c[0]) == null ? void 0 : _d.embedding) {
4726
+ return res.data[0].embedding;
4727
+ }
4728
+ } catch (dispatchErr) {
4729
+ console.warn("[UniversalLLMAdapter] In-process dispatch embedding failed:", dispatchErr);
4597
4730
  }
4598
4731
  }
4599
4732
  }
4600
- const { data } = await this.http.post(path2, payload);
4601
- const extractPath = (_e = this.opts.embedExtractPath) != null ? _e : "data[0].embedding";
4602
- const vector = resolvePath(data, extractPath);
4603
- if (!Array.isArray(vector)) {
4604
- throw new Error(`[UniversalLLMAdapter] Could not extract embedding vector from path '${extractPath}' in response.`);
4733
+ try {
4734
+ const { data } = await this.http.post(path2, payload);
4735
+ const extractPath = (_e = this.opts.embedExtractPath) != null ? _e : "data[0].embedding";
4736
+ const vector = resolvePath(data, extractPath);
4737
+ if (Array.isArray(vector)) {
4738
+ return vector;
4739
+ }
4740
+ console.error(
4741
+ `[UniversalLLMAdapter] Retry embedding failed: unexpected response format for path '${extractPath}'. Response:`,
4742
+ data
4743
+ );
4744
+ throw new Error(
4745
+ `[UniversalLLMAdapter] Could not extract embedding vector. Expected array at '${extractPath}', got: ${typeof vector}. Response keys: ${Object.keys(data || {})}.`
4746
+ );
4747
+ } catch (err) {
4748
+ console.error(
4749
+ `[UniversalLLMAdapter] Both embedding attempts failed. Path: ${path2}, Model: ${this.model}`,
4750
+ { error: err == null ? void 0 : err.message, statusCode: (_f = err == null ? void 0 : err.response) == null ? void 0 : _f.status, response: (_g2 = err == null ? void 0 : err.response) == null ? void 0 : _g2.data }
4751
+ );
4752
+ throw new Error(
4753
+ `[UniversalLLMAdapter] Failed to generate embedding after 2 attempts: ${(err == null ? void 0 : err.message) || err}`
4754
+ );
4605
4755
  }
4606
- return vector;
4607
4756
  }
4608
4757
  async batchEmbed(texts) {
4609
4758
  const results = [];
4610
4759
  for (const text of texts) {
4611
- results.push(await this.embed(text));
4760
+ try {
4761
+ const vector = await this.embed(text);
4762
+ results.push(vector);
4763
+ } catch (err) {
4764
+ console.warn(`[UniversalLLMAdapter] batchEmbed failed for text (first 50 chars): ${text.slice(0, 50)}...`, err);
4765
+ throw err;
4766
+ }
4612
4767
  }
4613
4768
  return results;
4614
4769
  }
@@ -9997,7 +10152,7 @@ var VectorPlugin = class {
9997
10152
  this.validationPromise = (async () => {
9998
10153
  var _a3;
9999
10154
  await ConfigValidator.validateAndThrow(resolvedConfig);
10000
- LicenseVerifier.verify(
10155
+ await LicenseVerifier.verifyAsync(
10001
10156
  resolvedConfig.licenseKey,
10002
10157
  resolvedConfig.projectId,
10003
10158
  (_a3 = resolvedConfig.vectorDb) == null ? void 0 : _a3.provider
@@ -10270,7 +10425,7 @@ var DatabaseStorage = class {
10270
10425
  * In non-production (development / test) environments this is a complete no-op —
10271
10426
  * all History and Feedback features are freely accessible for local development.
10272
10427
  */
10273
- checkPremiumSubscription() {
10428
+ async checkPremiumSubscription() {
10274
10429
  if (process.env.NODE_ENV !== "production") {
10275
10430
  return;
10276
10431
  }
@@ -10280,7 +10435,7 @@ var DatabaseStorage = class {
10280
10435
  );
10281
10436
  }
10282
10437
  try {
10283
- const payload = LicenseVerifier.verify(this.config.licenseKey, this.config.projectId);
10438
+ const payload = await LicenseVerifier.verifyAsync(this.config.licenseKey, this.config.projectId);
10284
10439
  const tier = (payload.tier || "").toLowerCase();
10285
10440
  if (tier !== "premium" && tier !== "enterprise" && tier !== "growth" && tier !== "pro" && tier !== "developer_pro" && tier !== "free_trial" && tier !== "free_tier" && tier !== "free" && tier !== "hobby") {
10286
10441
  throw new Error(
@@ -10293,16 +10448,16 @@ var DatabaseStorage = class {
10293
10448
  );
10294
10449
  }
10295
10450
  }
10296
- checkHistoryEnabled() {
10451
+ async checkHistoryEnabled() {
10297
10452
  var _a3, _b;
10298
- this.checkPremiumSubscription();
10453
+ await this.checkPremiumSubscription();
10299
10454
  if (((_b = (_a3 = this.config.rag) == null ? void 0 : _a3.history) == null ? void 0 : _b.enabled) === false) {
10300
10455
  throw new Error("[Retrivora SDK] Chat History is disabled in RagConfig.");
10301
10456
  }
10302
10457
  }
10303
- checkFeedbackEnabled() {
10458
+ async checkFeedbackEnabled() {
10304
10459
  var _a3, _b;
10305
- this.checkPremiumSubscription();
10460
+ await this.checkPremiumSubscription();
10306
10461
  if (((_b = (_a3 = this.config.rag) == null ? void 0 : _a3.feedback) == null ? void 0 : _b.enabled) === false) {
10307
10462
  throw new Error("[Retrivora SDK] User Feedback is disabled in RagConfig.");
10308
10463
  }
@@ -10408,7 +10563,7 @@ var DatabaseStorage = class {
10408
10563
  }
10409
10564
  // ─── Message History Operations ──────────────────────────────────────────
10410
10565
  async saveMessage(sessionId, message) {
10411
- this.checkHistoryEnabled();
10566
+ await this.checkHistoryEnabled();
10412
10567
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
10413
10568
  const msgId = message.id || `msg_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
10414
10569
  if (this.provider === "postgresql" || this.provider === "pgvector") {
@@ -10471,7 +10626,7 @@ var DatabaseStorage = class {
10471
10626
  }
10472
10627
  }
10473
10628
  async getHistory(sessionId, projectIds) {
10474
- this.checkHistoryEnabled();
10629
+ await this.checkHistoryEnabled();
10475
10630
  if (projectIds && projectIds.length > 0 && !this.sessionInScope(sessionId, projectIds)) {
10476
10631
  return [];
10477
10632
  }
@@ -10505,7 +10660,7 @@ var DatabaseStorage = class {
10505
10660
  }
10506
10661
  }
10507
10662
  async clearHistory(sessionId, projectIds) {
10508
- this.checkHistoryEnabled();
10663
+ await this.checkHistoryEnabled();
10509
10664
  if (projectIds && projectIds.length > 0 && !this.sessionInScope(sessionId, projectIds)) {
10510
10665
  return;
10511
10666
  }
@@ -10541,7 +10696,7 @@ var DatabaseStorage = class {
10541
10696
  );
10542
10697
  }
10543
10698
  async listSessions(projectIds) {
10544
- this.checkHistoryEnabled();
10699
+ await this.checkHistoryEnabled();
10545
10700
  let raw = [];
10546
10701
  if (this.provider === "postgresql" || this.provider === "pgvector") {
10547
10702
  const pool = await this.getPGPool();
@@ -10560,7 +10715,7 @@ var DatabaseStorage = class {
10560
10715
  }
10561
10716
  // ─── Feedback Operations ──────────────────────────────────────────────────
10562
10717
  async saveFeedback(feedback) {
10563
- this.checkFeedbackEnabled();
10718
+ await this.checkFeedbackEnabled();
10564
10719
  const id = `fb_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
10565
10720
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
10566
10721
  if (this.provider === "postgresql" || this.provider === "pgvector") {
@@ -10610,7 +10765,7 @@ var DatabaseStorage = class {
10610
10765
  }
10611
10766
  }
10612
10767
  async getFeedback(messageId, projectIds) {
10613
- this.checkFeedbackEnabled();
10768
+ await this.checkFeedbackEnabled();
10614
10769
  let item = null;
10615
10770
  if (this.provider === "postgresql" || this.provider === "pgvector") {
10616
10771
  const pool = await this.getPGPool();
@@ -10646,7 +10801,7 @@ var DatabaseStorage = class {
10646
10801
  return item;
10647
10802
  }
10648
10803
  async listFeedback(projectIds) {
10649
- this.checkFeedbackEnabled();
10804
+ await this.checkFeedbackEnabled();
10650
10805
  let raw = [];
10651
10806
  if (this.provider === "postgresql" || this.provider === "pgvector") {
10652
10807
  const pool = await this.getPGPool();
@@ -10796,12 +10951,23 @@ function resolveLicenseKey(req, config, bodyLicenseKey) {
10796
10951
  var _a3;
10797
10952
  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 || "";
10798
10953
  }
10799
- function enforceLicense(req, config, bodyLicenseKey) {
10954
+ async function enforceLicense(req, config, bodyLicenseKey) {
10800
10955
  const rawKey = resolveLicenseKey(req, config, bodyLicenseKey);
10801
10956
  const licenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
10802
10957
  const projectId = config.projectId || "";
10803
10958
  try {
10804
- const payload = LicenseVerifier.verify(licenseKey, projectId);
10959
+ let payload;
10960
+ try {
10961
+ payload = await LicenseVerifier.verifyAsync(licenseKey, projectId);
10962
+ } catch (err) {
10963
+ return {
10964
+ ok: false,
10965
+ response: NextResponse.json(
10966
+ { error: `License validation failed: ${err.message}` },
10967
+ { status: 401 }
10968
+ )
10969
+ };
10970
+ }
10805
10971
  return { ok: true, payload };
10806
10972
  } catch (err) {
10807
10973
  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.";
@@ -10976,7 +11142,7 @@ function createChatHandler(configOrPlugin, options) {
10976
11142
  try {
10977
11143
  const body = await req.json();
10978
11144
  const bodyObj = body != null ? body : {};
10979
- const licenseCheck = enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11145
+ const licenseCheck = await enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
10980
11146
  if (!licenseCheck.ok) return licenseCheck.response;
10981
11147
  if (isFreeTier(licenseCheck.payload.tier)) {
10982
11148
  const estimatedInputTokens = Math.ceil(
@@ -11070,7 +11236,7 @@ function createStreamHandler(configOrPlugin, options) {
11070
11236
  });
11071
11237
  }
11072
11238
  const bodyObj = body != null ? body : {};
11073
- const licenseCheck = enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11239
+ const licenseCheck = await enforceLicense(req, config, bodyObj == null ? void 0 : bodyObj.licenseKey);
11074
11240
  if (!licenseCheck.ok) return licenseCheck.response;
11075
11241
  if (isFreeTier(licenseCheck.payload.tier)) {
11076
11242
  const estimatedInputTokens = Math.ceil(
@@ -11235,7 +11401,7 @@ function createIngestHandler(configOrPlugin, options) {
11235
11401
  const config = plugin.getConfig();
11236
11402
  try {
11237
11403
  const body = await req.json();
11238
- const licenseCheck = enforceLicense(req, config, body == null ? void 0 : body.licenseKey);
11404
+ const licenseCheck = await enforceLicense(req, config, body == null ? void 0 : body.licenseKey);
11239
11405
  if (!licenseCheck.ok) return licenseCheck.response;
11240
11406
  const { documents, namespace } = body;
11241
11407
  if (!Array.isArray(documents) || documents.length === 0) {
@@ -11311,7 +11477,7 @@ function createLicenseHandler(configOrPlugin, options) {
11311
11477
  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 || "";
11312
11478
  const licenseKey = (rawKey || "").trim().replace(/^["']|["']$/g, "").trim();
11313
11479
  const projectId = (body == null ? void 0 : body.projectId) || config.projectId || "";
11314
- const payload = LicenseVerifier.verify(licenseKey, projectId);
11480
+ const payload = await LicenseVerifier.verifyAsync(licenseKey, projectId);
11315
11481
  return NextResponse.json({
11316
11482
  valid: true,
11317
11483
  licenseStatus: "ACTIVE",
@@ -11341,14 +11507,16 @@ function createUploadHandler(configOrPlugin, options) {
11341
11507
  const plugin = getOrCreatePlugin(configOrPlugin);
11342
11508
  const onAuthorize = options == null ? void 0 : options.onAuthorize;
11343
11509
  return async function POST(req, context) {
11510
+ console.log("Upload handler invoked");
11344
11511
  const authResult = await checkAuth(req, onAuthorize);
11345
11512
  if (authResult) return authResult;
11346
11513
  const config = plugin.getConfig();
11347
- const licenseCheck = enforceLicense(req, config);
11514
+ const licenseCheck = await enforceLicense(req, config);
11348
11515
  if (!licenseCheck.ok) return licenseCheck.response;
11349
11516
  try {
11350
11517
  const formData = await req.formData();
11351
11518
  const files = formData.getAll("files");
11519
+ console.log("Files received for upload:", files.map((f) => f.name));
11352
11520
  const namespace = formData.get("namespace") || void 0;
11353
11521
  const dimensionRaw = formData.get("dimension");
11354
11522
  const dimension = dimensionRaw ? parseInt(dimensionRaw, 10) : void 0;
@@ -11487,7 +11655,7 @@ function createSuggestionsHandler(configOrPlugin, options) {
11487
11655
  const authResult = await checkAuth(req, onAuthorize);
11488
11656
  if (authResult) return authResult;
11489
11657
  const config = plugin.getConfig();
11490
- const licenseCheck = enforceLicense(req, config);
11658
+ const licenseCheck = await enforceLicense(req, config);
11491
11659
  if (!licenseCheck.ok) return licenseCheck.response;
11492
11660
  let effectiveLicensePayload = licenseCheck.payload;
11493
11661
  try {
@@ -11500,7 +11668,7 @@ function createSuggestionsHandler(configOrPlugin, options) {
11500
11668
  namespace = body.namespace;
11501
11669
  bodyLicenseKey = body.licenseKey;
11502
11670
  if (bodyLicenseKey) {
11503
- const recheck = enforceLicense(req, config, bodyLicenseKey);
11671
+ const recheck = await enforceLicense(req, config, bodyLicenseKey);
11504
11672
  if (!recheck.ok) return recheck.response;
11505
11673
  effectiveLicensePayload = recheck.payload;
11506
11674
  }