@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
package/dist/index.mjs CHANGED
@@ -307,7 +307,7 @@ function projectSettingsToUiConfig(settings) {
307
307
  // package.json
308
308
  var package_default = {
309
309
  name: "@retrivora-ai/rag-engine",
310
- version: "2.3.6",
310
+ version: "2.3.8",
311
311
  description: "Retrivora AI is a plug-and-play AI engine for RAG chat experiences \u2014 generic vector DB + LLM provider, embeddable or standalone.",
312
312
  author: "Abhinav Alkuchi",
313
313
  license: "UNLICENSED",
@@ -478,7 +478,12 @@ var ConfigFetcher = class {
478
478
  process.env.RETRIVORA_CONTROL_PLANE_URL,
479
479
  process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL,
480
480
  CONTROL_PLANE_URL
481
- ].filter((url) => Boolean(url) && !url.includes("localhost") && !url.includes("127.0.0.1")).map((url) => url.replace(/\/$/, ""));
481
+ ].filter((url) => {
482
+ if (!url) return false;
483
+ const isEnvVar = url === process.env.RETRIVORA_CONTROL_PLANE_URL || url === process.env.NEXT_PUBLIC_RETRIVORA_CONTROL_PLANE_URL;
484
+ if (!isEnvVar && (url.includes("localhost") || url.includes("127.0.0.1"))) return false;
485
+ return true;
486
+ }).map((url) => url.replace(/\/$/, ""));
482
487
  for (const baseUrl of controlPlaneUrls) {
483
488
  try {
484
489
  const url = `${baseUrl}/api/v1/config?projectId=${encodeURIComponent(projectId)}`;
@@ -499,8 +504,7 @@ var ConfigFetcher = class {
499
504
  isActive: data.isActive,
500
505
  expiresAt: data.expiresAt,
501
506
  vectorDb: {
502
- // apiKey is not returned by the config API — it's a server-only secret.
503
- // The SDK uses local PINECONE_API_KEY if available.
507
+ // Fetch apiKey from credentials API if available, else fallback to empty
504
508
  apiKey: data.vectorDb.apiKey || "",
505
509
  indexName: data.vectorDb.indexName || "retrivora-free",
506
510
  provider: data.vectorDb.provider || "pinecone",
@@ -532,6 +536,32 @@ var ConfigFetcher = class {
532
536
  data.projectSettings || data.settings
533
537
  )
534
538
  };
539
+ if (licenseKey) {
540
+ try {
541
+ const credUrl = `${baseUrl}/api/v1/credentials`;
542
+ const credRes = await fetch(credUrl, {
543
+ method: "POST",
544
+ headers: {
545
+ "Content-Type": "application/json"
546
+ },
547
+ body: JSON.stringify({ licenseKey, projectId: fetchedProjectId })
548
+ });
549
+ if (credRes.ok) {
550
+ const credData = await credRes.json();
551
+ if ((credData == null ? void 0 : credData.success) && (credData == null ? void 0 : credData.credentials)) {
552
+ if (credData.credentials.pineconeApiKey && !config.vectorDb.apiKey) {
553
+ config.vectorDb.apiKey = credData.credentials.pineconeApiKey;
554
+ }
555
+ if (credData.credentials.litellmApiKey) {
556
+ config.llm.apiKey = credData.credentials.litellmApiKey;
557
+ config.embedding.apiKey = credData.credentials.litellmApiKey;
558
+ }
559
+ }
560
+ }
561
+ } catch (e) {
562
+ console.warn("[ConfigFetcher] Failed to fetch credentials:", e);
563
+ }
564
+ }
535
565
  this.cache.set(cacheKey, { config, cachedAt: now });
536
566
  return config;
537
567
  }
@@ -566,7 +596,8 @@ function ConfigProvider({
566
596
  config,
567
597
  children
568
598
  }) {
569
- const projectId = (config == null ? void 0 : config.projectId) || DEFAULT_CONFIG.projectId;
599
+ const envProjectId = typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_PROJECT_ID || process.env.RETRIVORA_PROJECT_ID : "";
600
+ const projectId = (config == null ? void 0 : config.projectId) || envProjectId || DEFAULT_CONFIG.projectId;
570
601
  const projectSettingsInput = config == null ? void 0 : config.projectSettings;
571
602
  const autoLoadProjectSettings = config == null ? void 0 : config.autoLoadProjectSettings;
572
603
  const licenseKeyInput = config == null ? void 0 : config.licenseKey;
@@ -3573,30 +3604,18 @@ var LicenseValidationError = class extends RetrivoraError {
3573
3604
  };
3574
3605
 
3575
3606
  // src/core/LicenseVerifier.ts
3576
- import * as crypto from "crypto";
3577
- var LicenseVerifier = class {
3607
+ var _LicenseVerifier = class _LicenseVerifier {
3608
+ // Cache verified license for 5 minutes
3578
3609
  /**
3579
- * Decodes, verifies signature, and checks metadata of a license key.
3610
+ * Validates the license key asynchronously by calling the Retrivora backend.
3580
3611
  *
3581
3612
  * @param licenseKey - Base64url signed JWT license key.
3582
3613
  * @param currentProjectId - Project namespace ID.
3583
- * @param publicKeyOverride - Optional override for unit/integration tests.
3614
+ * @param provider - Optional provider for tier checks.
3584
3615
  */
3585
- static verify(licenseKey, currentProjectId, provider, publicKeyOverride) {
3616
+ static async verifyAsync(licenseKey, currentProjectId, provider) {
3586
3617
  const isProduction = process.env.NODE_ENV === "production";
3587
3618
  const now = Date.now();
3588
- if (licenseKey) {
3589
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
3590
- const cached = this.cache.get(cacheKey);
3591
- if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
3592
- const currentTimestampSec = Math.floor(now / 1e3);
3593
- if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
3594
- this.cache.delete(cacheKey);
3595
- } else {
3596
- return cached.payload;
3597
- }
3598
- }
3599
- }
3600
3619
  if (!licenseKey) {
3601
3620
  if (isProduction) {
3602
3621
  throw new ConfigurationException(
@@ -3613,52 +3632,61 @@ var LicenseVerifier = class {
3613
3632
  tier: "hobby"
3614
3633
  };
3615
3634
  }
3616
- try {
3617
- const sanitizedKey = (licenseKey || "").trim().replace(/^["']|["']$/g, "").trim();
3618
- const rawToken = sanitizedKey.replace(/^rtv_/i, "").trim();
3619
- const parts = rawToken.split(".");
3620
- if (parts.length !== 3) {
3621
- throw new Error("Malformed token structure (expected 3 parts).");
3622
- }
3623
- const [headerB64, payloadB64, signatureB64] = parts;
3624
- const dataToVerify = `${headerB64}.${payloadB64}`;
3625
- const publicKey = publicKeyOverride != null ? publicKeyOverride : this.PUBLIC_KEY;
3626
- const signature = Buffer.from(signatureB64, "base64url");
3627
- const data = Buffer.from(dataToVerify);
3628
- const isValid = crypto.verify(
3629
- "sha256",
3630
- data,
3631
- publicKey,
3632
- signature
3633
- );
3634
- if (!isValid) {
3635
- throw new Error("Signature verification failed.");
3635
+ const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}`;
3636
+ const cached = this.cache.get(cacheKey);
3637
+ if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
3638
+ const currentTimestampSec = Math.floor(now / 1e3);
3639
+ if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
3640
+ this.cache.delete(cacheKey);
3641
+ } else {
3642
+ return cached.payload;
3636
3643
  }
3637
- const payload = JSON.parse(
3638
- Buffer.from(payloadB64, "base64url").toString("utf8")
3639
- );
3640
- if (!payload.projectId) {
3641
- throw new Error('License payload is missing "projectId".');
3644
+ }
3645
+ try {
3646
+ let baseUrl = typeof process !== "undefined" && process.env.RETRIVORA_CONTROL_PLANE_URL ? process.env.RETRIVORA_CONTROL_PLANE_URL : "https://retrivora.com";
3647
+ if (typeof process !== "undefined" && process.env.TELEMETRY_URL) {
3648
+ baseUrl = process.env.TELEMETRY_URL.replace(/\/api\/telemetry\/?$/, "");
3642
3649
  }
3643
- const isProjectMatch = payload.projectId === currentProjectId || payload.projectId === `retrivora-${currentProjectId}` || `retrivora-${payload.projectId}` === currentProjectId;
3644
- if (!isProjectMatch) {
3645
- throw new Error(
3646
- `Project ID mismatch. License is bound to project namespace "${payload.projectId}" but configuration has "${currentProjectId}".`
3647
- );
3650
+ const endpoint = `${baseUrl}/api/v1/license/validate`;
3651
+ const response = await fetch(endpoint, {
3652
+ method: "POST",
3653
+ headers: {
3654
+ "Content-Type": "application/json",
3655
+ "x-license-key": licenseKey
3656
+ },
3657
+ body: JSON.stringify({
3658
+ licenseKey,
3659
+ projectId: currentProjectId,
3660
+ provider
3661
+ })
3662
+ });
3663
+ if (!response.ok) {
3664
+ let errMessage = `HTTP ${response.status}`;
3665
+ try {
3666
+ const body = await response.json();
3667
+ if (body.message) errMessage = body.message;
3668
+ } catch (e) {
3669
+ }
3670
+ throw new Error(errMessage);
3648
3671
  }
3649
- if (!payload.expiresAt) {
3650
- throw new Error('License payload is missing expiration ("expiresAt").');
3672
+ const data = await response.json();
3673
+ if (!data.valid) {
3674
+ throw new Error(data.message || "License validation failed by server.");
3651
3675
  }
3652
- const currentTimestampSec = Math.floor(Date.now() / 1e3);
3653
- if (currentTimestampSec > payload.expiresAt) {
3654
- throw new Error(
3655
- `License key has expired. Expiration: ${new Date(
3656
- payload.expiresAt * 1e3
3657
- ).toDateString()}`
3658
- );
3676
+ let expiresAtNum = Math.floor(Date.now() / 1e3) + 100 * 365 * 24 * 60 * 60;
3677
+ if (data.expiresAt) {
3678
+ expiresAtNum = Math.floor(new Date(data.expiresAt).getTime() / 1e3);
3659
3679
  }
3680
+ const tier = _LicenseVerifier.extractTier(licenseKey);
3681
+ const payload = {
3682
+ projectId: currentProjectId,
3683
+ expiresAt: expiresAtNum,
3684
+ tier,
3685
+ licenseStatus: data.licenseStatus,
3686
+ minimumSupportedVersion: data.minimumSupportedVersion,
3687
+ forceUpgrade: data.forceUpgrade
3688
+ };
3660
3689
  if (isProduction && provider) {
3661
- const tier = (payload.tier || "").toLowerCase();
3662
3690
  const normalizedProvider = provider.toLowerCase();
3663
3691
  if (tier === "hobby") {
3664
3692
  const allowedHobby = ["postgresql", "pgvector", "supabase"];
@@ -3686,15 +3714,12 @@ var LicenseVerifier = class {
3686
3714
  }
3687
3715
  }
3688
3716
  }
3689
- if (licenseKey) {
3690
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
3691
- this.cache.set(cacheKey, { payload, cachedAt: now });
3692
- }
3717
+ this.cache.set(cacheKey, { payload, cachedAt: now });
3693
3718
  return payload;
3694
3719
  } catch (err) {
3695
3720
  const message = err instanceof Error ? err.message : String(err);
3696
3721
  throw new ConfigurationException(
3697
- `[Retrivora SDK] License key validation failed: ${message}`
3722
+ `[Retrivora SDK] License key validation failed via API: ${message}`
3698
3723
  );
3699
3724
  }
3700
3725
  }
@@ -3763,23 +3788,25 @@ var LicenseVerifier = class {
3763
3788
  }
3764
3789
  }
3765
3790
  }
3791
+ static extractTier(licenseKey) {
3792
+ if (!licenseKey) return "hobby";
3793
+ try {
3794
+ const sanitizedKey = licenseKey.trim().replace(/^["']|["']$/g, "").trim();
3795
+ const rawToken = sanitizedKey.replace(/^rtv_/i, "").trim();
3796
+ const parts = rawToken.split(".");
3797
+ if (parts.length === 3) {
3798
+ const decodedPayload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
3799
+ if (decodedPayload.tier) return decodedPayload.tier;
3800
+ }
3801
+ } catch (e) {
3802
+ }
3803
+ return "hobby";
3804
+ }
3766
3805
  };
3767
- // A simple in-memory cache to save CPU overhead of cryptographic signature checks.
3768
- LicenseVerifier.cache = /* @__PURE__ */ new Map();
3769
- LicenseVerifier.CACHE_TTL_MS = 60 * 1e3;
3770
- // Cache verified license for 60 seconds
3771
- // Retrivora's Public Key used to verify the license key signature.
3772
- // In production, this matches the private key held by Retrivora SaaS.
3773
- // Rotate this key only when the signing private key is replaced.
3774
- LicenseVerifier.PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
3775
- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoOQlmDSKfCZaRy06rxwa
3776
- chuDimlF134xTCitKDTPTPizF23oSn34pGDJakm/0T09JVUX8L/cvhGPe/3lf/g9
3777
- 4Y1q+Gb2KVM17KNGeT1Aj9Ua3BKz/yao/oFhi/r3Zt3cWY13B/Rd6clqY9WshIAV
3778
- NqZNM8ilTl777cMbyym+6D+mzGXgmnJAO5brddIAI9FPLW0T3Znt8vEqDOIljEkC
3779
- HCGHeirKABLbjKSJ4hljCa3vVitWqndhiq8CBSJG6HatiSGYotgMWGRY+0EbdlEv
3780
- OJP4SqafQ3aD6YnL9q1n15QKwxu/uMK+JGM2VxxuyUi9GANtMIkCYy9xya73P4Qc
3781
- gQIDAQAB
3782
- -----END PUBLIC KEY-----`;
3806
+ // In-memory cache to save network overhead on hot paths.
3807
+ _LicenseVerifier.cache = /* @__PURE__ */ new Map();
3808
+ _LicenseVerifier.CACHE_TTL_MS = 5 * 60 * 1e3;
3809
+ var LicenseVerifier = _LicenseVerifier;
3783
3810
 
3784
3811
  // src/core/LicenseValidator.ts
3785
3812
  function canUseLocalValidationFallback(baseUrl, status) {
@@ -3841,6 +3868,7 @@ var _LicenseValidator = class _LicenseValidator {
3841
3868
  retrivoraApiBase,
3842
3869
  headers: customHeaders
3843
3870
  } = request;
3871
+ const effectiveProjectId = projectId || (typeof process !== "undefined" ? process.env.NEXT_PUBLIC_RETRIVORA_PROJECT_ID || process.env.RETRIVORA_PROJECT_ID : "") || "";
3844
3872
  const getHeader = (name) => {
3845
3873
  if (!customHeaders) return void 0;
3846
3874
  const target = name.toLowerCase();
@@ -3878,7 +3906,7 @@ var _LicenseValidator = class _LicenseValidator {
3878
3906
  }, customHeaders || {}),
3879
3907
  body: JSON.stringify({
3880
3908
  licenseKey: effectiveLicenseKey,
3881
- projectId,
3909
+ projectId: effectiveProjectId,
3882
3910
  sdkVersion,
3883
3911
  sdk,
3884
3912
  platform
@@ -3889,7 +3917,7 @@ var _LicenseValidator = class _LicenseValidator {
3889
3917
  if (!canUseLocalValidationFallback(base)) {
3890
3918
  throw err;
3891
3919
  }
3892
- const payload = LicenseVerifier.verify(effectiveLicenseKey, projectId || "");
3920
+ const payload = await LicenseVerifier.verifyAsync(effectiveLicenseKey, effectiveProjectId);
3893
3921
  const fallbackResp = {
3894
3922
  valid: true,
3895
3923
  licenseStatus: "ACTIVE",
@@ -3908,7 +3936,7 @@ var _LicenseValidator = class _LicenseValidator {
3908
3936
  }
3909
3937
  if (res && !res.ok && canUseLocalValidationFallback(base, res.status)) {
3910
3938
  try {
3911
- const payload = LicenseVerifier.verify(effectiveLicenseKey, projectId || "");
3939
+ const payload = await LicenseVerifier.verifyAsync(effectiveLicenseKey, effectiveProjectId);
3912
3940
  const fallbackResp = {
3913
3941
  valid: true,
3914
3942
  licenseStatus: "ACTIVE",
@@ -4690,7 +4718,6 @@ function ChatWidget({ position, onAddToCart, apiUrl, retrivoraApiBase, licenseKe
4690
4718
  "button",
4691
4719
  {
4692
4720
  onClick: isOpen ? () => setIsOpen(false) : handleOpen,
4693
- disabled: isWidgetLocked && !isOpen,
4694
4721
  "aria-label": isWidgetLocked ? "Chat unavailable - invalid or missing license key" : isOpen ? "Close chat" : "Open chat",
4695
4722
  "aria-disabled": isWidgetLocked && !isOpen,
4696
4723
  className: `group fixed z-[9999] w-14 h-14 drop-shadow-2xl flex items-center justify-center transition-all duration-300 ${positionClass} ${isWidgetLocked && !isOpen ? "grayscale opacity-60 cursor-not-allowed" : "cursor-pointer hover:scale-110 active:scale-95"}`,
package/dist/server.d.mts CHANGED
@@ -1,62 +1,40 @@
1
- import { V as VectorDBConfig, L as LLMConfig, d as EmbeddingConfig, n as RagConfig, t as UniversalRagConfig, u as UpsertDocument, w as VectorMatch, G as GraphDBConfig, D as GraphNode, F as Edge, H as GraphSearchResult, I as ILLMProvider, v as VectorDBProvider, g as LLMProvider, e as EmbeddingProvider, R as RAGConfig, s as UIConfig, J as UITransformationResponse, C as ChatMessage, b as ChatOptions, E as EmbedOptions } from './ILLMProvider-B8TAVx3j.mjs';
2
- export { A as AuthMode, K as BarChartData, M as CarouselProduct, c as ChatResponse, N as IRetriever, f as IngestDocument, h as LatencyBreakdown, Q as LineChartDataPoint, S as MessageRole, X as MetricCardData, O as ObservabilityTrace, Y as PieChartData, Z as Product, i as ProjectAiSettings, j as ProjectAuthSettings, k as ProjectBrandingSettings, P as ProjectChatSettings, l as ProjectTelemetrySettings, m as ProjectWidgetSettings, o as RagMessage, p as RetrievalConfig, _ as RetrievalResult, q as RetrievedChunk, $ as RetrivoraChunkMetadata, a0 as RetrivoraIngestedDocument, a1 as ScatterPlotDataPoint, a2 as SuggestionsResponse, a3 as TableData, T as ThemeMode, r as TokenUsage, U as UseRagChatOptions, a as UseRagChatReturn, a4 as VisualizationType, W as WidgetPosition, x as WorkflowConfig, y as createDefaultProjectSettings, z as normalizeProjectSettings, B as projectSettingsToUiConfig } from './ILLMProvider-B8TAVx3j.mjs';
3
- import { l as DecisionContext, n as IntentCategory, I as IRenderRule, w as RenderDecision, m as IRendererStrategy } from './BatchProcessor-Dfn23VAd.mjs';
4
- export { N as ArchitectureCardProps, A as AuthenticationException, B as BatchOptions, e as BatchProcessor, f as BatchResult, g as ChartType, O as ChatViewportSize, C as ChatWidgetProps, a as ChatWindowProps, h as Chunk, i as ChunkOptions, c as ClientConfig, j as ConfigFetcher, b as ConfigProviderProps, k as ConfigurationException, Q as DocumentChunker, D as DocumentUploadProps, E as EmbeddingFailedException, L as LicenseValidationError, o as LicenseValidationRequest, p as LicenseValidationResponse, q as LicenseValidator, M as MessageBubbleProps, T as Pipeline, U as PipelineStep, P as ProductCardProps, d as ProductCarouselProps, r as ProviderNotFoundException, V as ProviderPill, s as RateLimitException, R as RemoteConfig, t as RemoteEmbeddingConfig, u as RemoteLLMConfig, v as RemoteVectorConfig, W as RenderSectionDecision, x as RenderType, y as RetrievalException, z as Retrivora, F as RetrivoraError, G as RetrivoraErrorCode, H as SDKVersionUnsupportedError, J as SDK_VERSION, X as Snippet, S as SourceCardProps, Y as wrapError } from './BatchProcessor-Dfn23VAd.mjs';
5
- import { H as HealthCheckResult, I as IProviderValidator, a as IProviderHealthChecker } from './index-xxQOFx-u.mjs';
6
- export { C as ConfigValidator, b as HandlerOptions, V as ValidationError, c as VectorPlugin, d as createChatHandler, e as createFeedbackHandler, f as createHealthHandler, g as createHistoryHandler, h as createIngestHandler, i as createRagHandler, j as createSessionsHandler, k as createStreamHandler, l as createUploadHandler, s as sseErrorFrame, m as sseFrame, n as sseMetaFrame, o as sseTextFrame } from './index-xxQOFx-u.mjs';
1
+ import { V as VectorDBConfig, L as LLMConfig, d as EmbeddingConfig, n as RagConfig, t as UniversalRagConfig, u as UpsertDocument, w as VectorMatch, G as GraphDBConfig, D as GraphNode, F as Edge, H as GraphSearchResult, I as ILLMProvider, v as VectorDBProvider, g as LLMProvider, e as EmbeddingProvider, R as RAGConfig, s as UIConfig, J as UITransformationResponse, C as ChatMessage, b as ChatOptions, E as EmbedOptions, f as IngestDocument, c as ChatResponse } from './ILLMProvider-B8TAVx3j.mjs';
2
+ export { A as AuthMode, K as BarChartData, M as CarouselProduct, N as IRetriever, h as LatencyBreakdown, Q as LineChartDataPoint, S as MessageRole, X as MetricCardData, O as ObservabilityTrace, Y as PieChartData, Z as Product, i as ProjectAiSettings, j as ProjectAuthSettings, k as ProjectBrandingSettings, P as ProjectChatSettings, l as ProjectTelemetrySettings, m as ProjectWidgetSettings, o as RagMessage, p as RetrievalConfig, _ as RetrievalResult, q as RetrievedChunk, $ as RetrivoraChunkMetadata, a0 as RetrivoraIngestedDocument, a1 as ScatterPlotDataPoint, a2 as SuggestionsResponse, a3 as TableData, T as ThemeMode, r as TokenUsage, U as UseRagChatOptions, a as UseRagChatReturn, a4 as VisualizationType, W as WidgetPosition, x as WorkflowConfig, y as createDefaultProjectSettings, z as normalizeProjectSettings, B as projectSettingsToUiConfig } from './ILLMProvider-B8TAVx3j.mjs';
3
+ import { l as DecisionContext, n as IntentCategory, I as IRenderRule, y as RenderDecision, m as IRendererStrategy } from './BatchProcessor-BhLczWj5.mjs';
4
+ export { Q as ArchitectureCardProps, A as AuthenticationException, B as BatchOptions, e as BatchProcessor, f as BatchResult, g as ChartType, T as ChatViewportSize, C as ChatWidgetProps, a as ChatWindowProps, h as Chunk, i as ChunkOptions, c as ClientConfig, j as ConfigFetcher, b as ConfigProviderProps, k as ConfigurationException, U as DocumentChunker, D as DocumentUploadProps, E as EmbeddingFailedException, V as LicenseConfigResolver, L as LicenseTierConfig, o as LicenseValidationError, p as LicenseValidationRequest, q as LicenseValidationResponse, r as LicenseValidator, M as MessageBubbleProps, W as Pipeline, X as PipelineStep, P as ProductCardProps, d as ProductCarouselProps, s as ProviderCredentials, t as ProviderNotFoundException, Y as ProviderPill, u as RateLimitException, R as RemoteConfig, v as RemoteEmbeddingConfig, w as RemoteLLMConfig, x as RemoteVectorConfig, Z as RenderSectionDecision, z as RenderType, F as RetrievalException, G as Retrivora, H as RetrivoraError, J as RetrivoraErrorCode, K as SDKVersionUnsupportedError, N as SDK_VERSION, _ as Snippet, S as SourceCardProps, $ as wrapError } from './BatchProcessor-BhLczWj5.mjs';
5
+ import { H as HealthCheckResult, I as IProviderValidator, a as IProviderHealthChecker } from './index-C7aHK7_g.mjs';
6
+ export { C as ConfigValidator, b as HandlerOptions, V as ValidationError, c as VectorPlugin, d as createChatHandler, e as createFeedbackHandler, f as createHealthHandler, g as createHistoryHandler, h as createIngestHandler, i as createRagHandler, j as createSessionsHandler, k as createStreamHandler, l as createUploadHandler, s as sseErrorFrame, m as sseFrame, n as sseMetaFrame, o as sseTextFrame } from './index-C7aHK7_g.mjs';
7
7
  import 'react';
8
8
  import 'next/server';
9
9
 
10
10
  /**
11
11
  * Decoded payload of a Retrivora license JWT.
12
- *
13
- * Retrivora licenses are signed with RS256 using a key held exclusively by
14
- * Retrivora SaaS. They carry the project binding, the expiration time, and
15
- * the customer tier, which the SDK uses to enforce per-tier feature limits
16
- * (vector DB provider whitelist).
17
12
  */
18
13
  interface LicensePayload {
19
- /** Project ID this license is bound to — used to prevent cross-tenant reuse. */
20
14
  projectId: string;
21
- /** UNIX timestamp in seconds after which the license must be considered expired. */
22
15
  expiresAt: number;
23
- /** Customer tier (hobby | pro | enterprise). */
24
16
  tier: string;
25
- /** Optional: License lifecycle status propagated by the server validator (ACTIVE/TERMINATED/etc). */
26
17
  licenseStatus?: string;
18
+ minimumSupportedVersion?: string;
19
+ forceUpgrade?: boolean;
27
20
  }
28
21
  /**
29
- * Zero-latency cryptographic license verifier.
30
- *
31
- * Responsibilities:
32
- * 1. Parse the `rtv_`-prefixed JWT (base64url header.payload.signature)
33
- * 2. Verify the RS256 signature against Retrivora's embedded PUBLIC_KEY
34
- * 3. Match the license's projectId to the currently configured projectId
35
- * 4. Enforce expiration (current UNIX seconds > expiresAt)
36
- * 5. Enforce per-tier vector DB provider whitelist in production
37
- *
38
- * Fail-open policy: In non-production environments a missing license key
39
- * produces a console-warning and a synthetic 24h "hobby" payload so that
40
- * local development continues to work without signing up. In production
41
- * any missing/invalid key throws `ConfigurationException`.
42
- *
43
- * Caching: Cryptographic verification is CPU-expensive — successful results
44
- * are cached for 60 seconds keyed by (licenseKey, projectId, provider,
45
- * publicKeyOverride). Cache hits still re-verify expiresAt.
22
+ * Validates licenses against the central Retrivora API.
23
+ * Replaces the old zero-latency local cryptographic verifier.
46
24
  */
47
25
  declare class LicenseVerifier {
48
26
  private static readonly cache;
49
27
  private static readonly CACHE_TTL_MS;
50
- private static readonly PUBLIC_KEY;
51
28
  /**
52
- * Decodes, verifies signature, and checks metadata of a license key.
29
+ * Validates the license key asynchronously by calling the Retrivora backend.
53
30
  *
54
31
  * @param licenseKey - Base64url signed JWT license key.
55
32
  * @param currentProjectId - Project namespace ID.
56
- * @param publicKeyOverride - Optional override for unit/integration tests.
33
+ * @param provider - Optional provider for tier checks.
57
34
  */
58
- static verify(licenseKey: string | undefined, currentProjectId: string, provider?: string, publicKeyOverride?: string): LicensePayload;
35
+ static verifyAsync(licenseKey: string | undefined, currentProjectId: string, provider?: string): Promise<LicensePayload>;
59
36
  static verifyIP(licenseKey: string | undefined): Promise<void>;
37
+ static extractTier(licenseKey: string | undefined): string;
60
38
  }
61
39
 
62
40
  /**
@@ -246,6 +224,32 @@ declare class ProviderRegistry {
246
224
  * universal_rest→ VECTOR_BASE_URL, VECTOR_DB_REST_API_KEY
247
225
  */
248
226
 
227
+ /**
228
+ * Runtime tier configuration injected from the /api/v1/config + /api/v1/credentials
229
+ * API responses at app startup. This overrides static env-var defaults so that
230
+ * the tier-based model selection from the license is applied to all SDK calls.
231
+ */
232
+ interface RuntimeTierConfig {
233
+ llmModel?: string;
234
+ embeddingModel?: string;
235
+ /** LiteLLM master key for authenticating with llm.retrivora.com */
236
+ litellmApiKey?: string;
237
+ /** LiteLLM gateway base URL (defaults to https://llm.retrivora.com/api/v1) */
238
+ llmBaseUrl?: string;
239
+ embeddingBaseUrl?: string;
240
+ maxTokens?: number;
241
+ topK?: number;
242
+ chunkSize?: number;
243
+ chunkOverlap?: number;
244
+ tier?: string;
245
+ }
246
+ /**
247
+ * Inject tier-based config fetched from /api/v1/config + /api/v1/credentials.
248
+ * Call this once after successful license init (e.g. in validate-env.ts).
249
+ */
250
+ declare function injectRuntimeConfig(config: RuntimeTierConfig): void;
251
+ /** Returns the currently injected runtime config, or null if not yet set. */
252
+ declare function getRuntimeConfig(): RuntimeTierConfig | null;
249
253
  declare function getRagConfig(baseConfig?: Partial<RagConfig>, env?: Record<string, string | undefined>): RagConfig;
250
254
 
251
255
  /**
@@ -716,7 +720,9 @@ declare class Rule7LargeTableRule implements IRenderRule {
716
720
  declare class PineconeProvider extends BaseVectorProvider {
717
721
  private client;
718
722
  private apiKey;
723
+ private licenseKey?;
719
724
  constructor(config: VectorDBConfig);
725
+ private getControlPlaneUrl;
720
726
  static getValidator(): IProviderValidator;
721
727
  static getHealthChecker(): IProviderHealthChecker;
722
728
  initialize(): Promise<void>;
@@ -1126,4 +1132,224 @@ declare class UniversalLLMAdapter implements ILLMProvider {
1126
1132
  ping(): Promise<boolean>;
1127
1133
  }
1128
1134
 
1129
- export { AnthropicProvider, BaseVectorProvider, CarouselRendererStrategy, ChartRendererStrategy, ChatMessage, ChatOptions, ChromaDBProvider, ConfigBuilder, ConfigResolver, DecisionContext, DocumentParser, Edge, EmbedOptions, EmbeddingConfig, EmbeddingProvider, EmbeddingStrategy, EmbeddingStrategyResolver, GraphNode, GraphSearchResult, GroqProvider, HealthCheckResult, ILLMProvider, IProviderHealthChecker, IProviderValidator, IRenderRule, IRendererStrategy, IntentCategory, IntentClassifier, LLMConfig, LLMFactory, LLMProvider, LLM_PROFILES, type LicensePayload, LicenseVerifier, MilvusProvider, MixedRendererStrategy, MongoDBProvider, MultiTablePostgresProvider, OllamaProvider, OpenAIProvider, PRESETS, PineconeProvider, PostgreSQLProvider, ProviderHealthCheck, ProviderRegistry, QdrantProvider, QwenProvider, RAGConfig, RagConfig, RedisProvider, RenderDecision, RendererRegistry, Rule1SpecificInfoRule, Rule2ComparisonRule, Rule3ProductDiscoveryRule, Rule4AnalyticalRule, Rule5MixedResponseRule, Rule6SmallResultSetRule, Rule7LargeTableRule, RuleEngine, TableRendererStrategy, TextRendererStrategy, UIConfig, UITransformationResponse, UniversalLLMAdapter, UniversalRagConfig, UniversalVectorProvider, UpsertDocument, VECTOR_PROFILES, VectorDBConfig, VectorDBProvider, VectorMatch, VisualizationDecisionEngine, WeaviateProvider, createFromPreset, decideVisualization, getRagConfig };
1135
+ /**
1136
+ * LicensedRetrivora — End-user facing SDK that only requires:
1137
+ * - License Key (JWT from Retrivora)
1138
+ * - Project ID (workspace identifier)
1139
+ *
1140
+ * Everything else (models, vector DB, embeddings) is resolved from
1141
+ * the Retrivora admin dashboard based on tier.
1142
+ *
1143
+ * NOTE: This is a SERVER-ONLY module. Import from '@retrivora-ai/rag-engine/server'
1144
+ * Do NOT import in client components.
1145
+ */
1146
+
1147
+ interface LicensedRetrivoraOptions {
1148
+ licenseKey: string;
1149
+ projectId: string;
1150
+ userTelemetryUrl?: string;
1151
+ enableTelemetry?: boolean;
1152
+ }
1153
+ /**
1154
+ * End-user facing SDK for Retrivora RAG engine
1155
+ */
1156
+ declare class LicensedRetrivora {
1157
+ private licenseKey;
1158
+ private projectId;
1159
+ private pipeline?;
1160
+ private ragConfig?;
1161
+ private initialized;
1162
+ constructor(options: LicensedRetrivoraOptions);
1163
+ /**
1164
+ * Initialize the SDK by validating license and fetching config
1165
+ */
1166
+ private generateId;
1167
+ /**
1168
+ * Initialize the SDK by validating license and fetching config
1169
+ */
1170
+ initialize(): Promise<void>;
1171
+ /**
1172
+ * Ingest documents (upload files to vector database)
1173
+ * Returns success/failure status to end-user
1174
+ */
1175
+ ingest(documents: IngestDocument[]): Promise<{
1176
+ success: boolean;
1177
+ message: string;
1178
+ documentIds?: string[];
1179
+ }>;
1180
+ /**
1181
+ * Execute a user query and get response
1182
+ * Returns only the response text and sources (abstracted from underlying models)
1183
+ */
1184
+ query(queryText: string, options?: {
1185
+ topK?: number;
1186
+ }): Promise<ChatResponse>;
1187
+ /**
1188
+ * Get license tier information (for UI display if needed)
1189
+ */
1190
+ getTierInfo(): Promise<{
1191
+ tier: string;
1192
+ model: string;
1193
+ embeddingModel: string;
1194
+ }>;
1195
+ /**
1196
+ * Cleanup and shutdown
1197
+ */
1198
+ shutdown(): Promise<void>;
1199
+ /**
1200
+ * Check if SDK is initialized
1201
+ */
1202
+ isInitialized(): boolean;
1203
+ /**
1204
+ * Get current RAG configuration (for debugging)
1205
+ */
1206
+ getConfig(): RagConfig | undefined;
1207
+ }
1208
+ /**
1209
+ * Convenience function to create and initialize SDK in one call
1210
+ */
1211
+ declare function createRetrivora(options: LicensedRetrivoraOptions): Promise<LicensedRetrivora>;
1212
+
1213
+ /**
1214
+ * TelemetryService — Tracks LLM calls, embedding operations, and user interactions
1215
+ * for billing, analytics, and usage monitoring.
1216
+ *
1217
+ * Sends telemetry to both:
1218
+ * - Admin dashboard (retrivora.com)
1219
+ * - User's own dashboard (if configured)
1220
+ */
1221
+ declare enum EventType {
1222
+ EMBEDDING_GENERATED = "embedding_generated",
1223
+ LLM_CHAT_COMPLETION = "llm_chat_completion",
1224
+ DOCUMENT_INGESTED = "document_ingested",
1225
+ QUERY_EXECUTED = "query_executed",
1226
+ ERROR_OCCURRED = "error_occurred",
1227
+ CONFIGURATION_LOADED = "configuration_loaded"
1228
+ }
1229
+ interface TelemetryEvent {
1230
+ eventType: EventType;
1231
+ projectId: string;
1232
+ timestamp: number;
1233
+ operationId?: string;
1234
+ durationMs?: number;
1235
+ model?: string;
1236
+ inputTokens?: number;
1237
+ outputTokens?: number;
1238
+ totalTokens?: number;
1239
+ embeddingModel?: string;
1240
+ vectorDimensions?: number;
1241
+ textLength?: number;
1242
+ documentId?: string;
1243
+ documentName?: string;
1244
+ documentSize?: number;
1245
+ chunksGenerated?: number;
1246
+ queryText?: string;
1247
+ resultCount?: number;
1248
+ errorCode?: string;
1249
+ errorMessage?: string;
1250
+ stackTrace?: string;
1251
+ metadata?: Record<string, unknown>;
1252
+ }
1253
+ /**
1254
+ * Telemetry service for tracking usage, billing, and analytics
1255
+ */
1256
+ declare class TelemetryService {
1257
+ private static readonly RETRIVORA_TELEMETRY_URL;
1258
+ private static readonly USER_TELEMETRY_URL_ENV_KEY;
1259
+ private http;
1260
+ private projectId;
1261
+ private licenseKey;
1262
+ private userTelemetryUrl?;
1263
+ private batchSize;
1264
+ private flushIntervalMs;
1265
+ private eventQueue;
1266
+ private flushTimer?;
1267
+ private enabled;
1268
+ constructor(projectId: string, licenseKey: string, userTelemetryUrl?: string);
1269
+ /**
1270
+ * Record a telemetry event
1271
+ */
1272
+ recordEvent(event: Partial<TelemetryEvent>): void;
1273
+ /**
1274
+ * Record LLM completion event
1275
+ */
1276
+ recordLLMCompletion(data: {
1277
+ model: string;
1278
+ inputTokens: number;
1279
+ outputTokens: number;
1280
+ durationMs: number;
1281
+ operationId?: string;
1282
+ metadata?: Record<string, unknown>;
1283
+ }): void;
1284
+ /**
1285
+ * Record embedding generation event
1286
+ */
1287
+ recordEmbeddingGenerated(data: {
1288
+ embeddingModel: string;
1289
+ vectorDimensions: number;
1290
+ textLength: number;
1291
+ durationMs: number;
1292
+ operationId?: string;
1293
+ }): void;
1294
+ /**
1295
+ * Record document ingestion event
1296
+ */
1297
+ recordDocumentIngested(data: {
1298
+ documentId: string;
1299
+ documentName: string;
1300
+ documentSize: number;
1301
+ chunksGenerated: number;
1302
+ durationMs: number;
1303
+ }): void;
1304
+ /**
1305
+ * Record query execution event
1306
+ */
1307
+ recordQueryExecuted(data: {
1308
+ queryText: string;
1309
+ resultCount: number;
1310
+ durationMs: number;
1311
+ operationId?: string;
1312
+ }): void;
1313
+ /**
1314
+ * Record error event
1315
+ */
1316
+ recordError(error: Error, context?: Record<string, unknown>): void;
1317
+ /**
1318
+ * Flush all queued events to telemetry endpoints
1319
+ */
1320
+ flush(): Promise<void>;
1321
+ /**
1322
+ * Start automatic flush interval
1323
+ */
1324
+ private startAutoFlush;
1325
+ /**
1326
+ * Stop telemetry service and flush remaining events
1327
+ */
1328
+ shutdown(): Promise<void>;
1329
+ /**
1330
+ * Disable telemetry temporarily
1331
+ */
1332
+ disable(): void;
1333
+ /**
1334
+ * Enable telemetry
1335
+ */
1336
+ enable(): void;
1337
+ /**
1338
+ * Get current queue size (for debugging)
1339
+ */
1340
+ getQueueSize(): number;
1341
+ }
1342
+ /**
1343
+ * Get or create global telemetry service instance
1344
+ */
1345
+ declare function getTelemetryService(): TelemetryService | null;
1346
+ /**
1347
+ * Initialize global telemetry service
1348
+ */
1349
+ declare function initializeTelemetryService(projectId: string, licenseKey: string, userTelemetryUrl?: string): TelemetryService;
1350
+ /**
1351
+ * Shutdown global telemetry service
1352
+ */
1353
+ declare function shutdownTelemetryService(): Promise<void>;
1354
+
1355
+ export { AnthropicProvider, BaseVectorProvider, CarouselRendererStrategy, ChartRendererStrategy, ChatMessage, ChatOptions, ChatResponse, ChromaDBProvider, ConfigBuilder, ConfigResolver, DecisionContext, DocumentParser, Edge, EmbedOptions, EmbeddingConfig, EmbeddingProvider, EmbeddingStrategy, EmbeddingStrategyResolver, EventType, GraphNode, GraphSearchResult, GroqProvider, HealthCheckResult, ILLMProvider, IProviderHealthChecker, IProviderValidator, IRenderRule, IRendererStrategy, IngestDocument, IntentCategory, IntentClassifier, LLMConfig, LLMFactory, LLMProvider, LLM_PROFILES, type LicensePayload, LicenseVerifier, LicensedRetrivora, type LicensedRetrivoraOptions, MilvusProvider, MixedRendererStrategy, MongoDBProvider, MultiTablePostgresProvider, OllamaProvider, OpenAIProvider, PRESETS, PineconeProvider, PostgreSQLProvider, ProviderHealthCheck, ProviderRegistry, QdrantProvider, QwenProvider, RAGConfig, RagConfig, RedisProvider, RenderDecision, RendererRegistry, Rule1SpecificInfoRule, Rule2ComparisonRule, Rule3ProductDiscoveryRule, Rule4AnalyticalRule, Rule5MixedResponseRule, Rule6SmallResultSetRule, Rule7LargeTableRule, RuleEngine, type RuntimeTierConfig, TableRendererStrategy, type TelemetryEvent, TelemetryService, TextRendererStrategy, UIConfig, UITransformationResponse, UniversalLLMAdapter, UniversalRagConfig, UniversalVectorProvider, UpsertDocument, VECTOR_PROFILES, VectorDBConfig, VectorDBProvider, VectorMatch, VisualizationDecisionEngine, WeaviateProvider, createFromPreset, createRetrivora, decideVisualization, getRagConfig, getRuntimeConfig, getTelemetryService, initializeTelemetryService, injectRuntimeConfig, shutdownTelemetryService };