@retrivora-ai/rag-engine 2.0.4 → 2.0.5

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.
@@ -1239,7 +1239,7 @@ __export(QdrantProvider_exports, {
1239
1239
  QdrantProvider: () => QdrantProvider
1240
1240
  });
1241
1241
  import axios4 from "axios";
1242
- import crypto from "crypto";
1242
+ import crypto2 from "crypto";
1243
1243
  var QdrantProvider;
1244
1244
  var init_QdrantProvider = __esm({
1245
1245
  "src/providers/vectordb/QdrantProvider.ts"() {
@@ -1471,7 +1471,7 @@ var init_QdrantProvider = __esm({
1471
1471
  if (typeof id === "number") return id;
1472
1472
  const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1473
1473
  if (uuidRegex.test(id)) return id.toLowerCase();
1474
- const hash = crypto.createHash("md5").update(id).digest("hex");
1474
+ const hash = crypto2.createHash("md5").update(id).digest("hex");
1475
1475
  return `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20, 32)}`;
1476
1476
  }
1477
1477
  async disconnect() {
@@ -2058,6 +2058,285 @@ import { NextResponse } from "next/server";
2058
2058
  // src/core/ConfigResolver.ts
2059
2059
  init_templateUtils();
2060
2060
 
2061
+ // src/core/LicenseVerifier.ts
2062
+ import * as crypto from "crypto";
2063
+
2064
+ // src/exceptions/index.ts
2065
+ var RetrivoraError = class extends Error {
2066
+ constructor(message, code, details) {
2067
+ super(message);
2068
+ this.name = new.target.name;
2069
+ this.code = code;
2070
+ this.details = details;
2071
+ }
2072
+ };
2073
+ var ProviderNotFoundException = class extends RetrivoraError {
2074
+ constructor(providerType, provider, details) {
2075
+ super(`Unsupported ${providerType} provider: ${provider}`, "PROVIDER_NOT_FOUND", details);
2076
+ }
2077
+ };
2078
+ var EmbeddingFailedException = class extends RetrivoraError {
2079
+ constructor(message = "Embedding generation failed", details) {
2080
+ super(message, "EMBEDDING_FAILED", details);
2081
+ }
2082
+ };
2083
+ var RetrievalException = class extends RetrivoraError {
2084
+ constructor(message = "Retrieval failed", details) {
2085
+ super(message, "RETRIEVAL_FAILED", details);
2086
+ }
2087
+ };
2088
+ var RateLimitException = class extends RetrivoraError {
2089
+ constructor(message = "Provider rate limit exceeded", details) {
2090
+ super(message, "RATE_LIMITED", details);
2091
+ }
2092
+ };
2093
+ var ConfigurationException = class extends RetrivoraError {
2094
+ constructor(message, details) {
2095
+ super(message, "CONFIGURATION_ERROR", details);
2096
+ }
2097
+ };
2098
+ var AuthenticationException = class extends RetrivoraError {
2099
+ constructor(message = "Provider authentication failed", details) {
2100
+ super(message, "AUTHENTICATION_ERROR", details);
2101
+ }
2102
+ };
2103
+ function wrapError(err, defaultCode, defaultMessage) {
2104
+ var _a2;
2105
+ if (err instanceof RetrivoraError) {
2106
+ return err;
2107
+ }
2108
+ const error = err;
2109
+ const message = (error == null ? void 0 : error.message) || defaultMessage || String(err);
2110
+ const status = (error == null ? void 0 : error.status) || (error == null ? void 0 : error.statusCode) || ((_a2 = error == null ? void 0 : error.response) == null ? void 0 : _a2.status);
2111
+ const code = error == null ? void 0 : error.code;
2112
+ if (status === 429 || /rate[- ]?limit/i.test(message) || code === "RATE_LIMIT_EXCEEDED") {
2113
+ return new RateLimitException(message, err);
2114
+ }
2115
+ if (status === 401 || status === 403 || /unauthorized|auth|api[- ]?key/i.test(message) || code === "INVALID_API_KEY") {
2116
+ return new AuthenticationException(message, err);
2117
+ }
2118
+ switch (defaultCode) {
2119
+ case "PROVIDER_NOT_FOUND":
2120
+ return new ProviderNotFoundException("provider", message, err);
2121
+ case "EMBEDDING_FAILED":
2122
+ return new EmbeddingFailedException(message, err);
2123
+ case "RETRIEVAL_FAILED":
2124
+ return new RetrievalException(message, err);
2125
+ case "RATE_LIMITED":
2126
+ return new RateLimitException(message, err);
2127
+ case "CONFIGURATION_ERROR":
2128
+ return new ConfigurationException(message, err);
2129
+ case "AUTHENTICATION_ERROR":
2130
+ return new AuthenticationException(message, err);
2131
+ default:
2132
+ return new RetrivoraError(message, defaultCode, err);
2133
+ }
2134
+ }
2135
+
2136
+ // src/core/LicenseVerifier.ts
2137
+ var LicenseVerifier = class {
2138
+ /**
2139
+ * Decodes, verifies signature, and checks metadata of a license key.
2140
+ *
2141
+ * @param licenseKey - Base64url signed JWT license key.
2142
+ * @param currentProjectId - Project namespace ID.
2143
+ * @param publicKeyOverride - Optional override for unit/integration tests.
2144
+ */
2145
+ static verify(licenseKey, currentProjectId, provider, publicKeyOverride) {
2146
+ const isProduction = process.env.NODE_ENV === "production";
2147
+ const now = Date.now();
2148
+ if (licenseKey) {
2149
+ const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
2150
+ const cached = this.cache.get(cacheKey);
2151
+ if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
2152
+ const currentTimestampSec = Math.floor(now / 1e3);
2153
+ if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
2154
+ this.cache.delete(cacheKey);
2155
+ } else {
2156
+ return cached.payload;
2157
+ }
2158
+ }
2159
+ }
2160
+ if (!licenseKey) {
2161
+ if (isProduction) {
2162
+ throw new ConfigurationException(
2163
+ "[Retrivora SDK] License key (licenseKey) is required in production environments."
2164
+ );
2165
+ }
2166
+ console.warn(
2167
+ `\x1B[33m[Retrivora SDK] WARNING: Running without a license key. This namespace (${currentProjectId}) is permitted for local development only.\x1B[0m`
2168
+ );
2169
+ return {
2170
+ projectId: currentProjectId,
2171
+ expiresAt: Math.floor(Date.now() / 1e3) + 86400,
2172
+ // Valid for 24h
2173
+ tier: "hobby"
2174
+ };
2175
+ }
2176
+ try {
2177
+ const parts = licenseKey.split(".");
2178
+ if (parts.length !== 3) {
2179
+ throw new Error("Malformed token structure (expected 3 parts).");
2180
+ }
2181
+ const [headerB64, payloadB64, signatureB64] = parts;
2182
+ const dataToVerify = `${headerB64}.${payloadB64}`;
2183
+ const publicKey = publicKeyOverride != null ? publicKeyOverride : this.PUBLIC_KEY;
2184
+ const signature = Buffer.from(signatureB64, "base64url");
2185
+ const data = Buffer.from(dataToVerify);
2186
+ const isValid = crypto.verify(
2187
+ "sha256",
2188
+ data,
2189
+ publicKey,
2190
+ signature
2191
+ );
2192
+ if (!isValid) {
2193
+ throw new Error("Signature verification failed.");
2194
+ }
2195
+ const payload = JSON.parse(
2196
+ Buffer.from(payloadB64, "base64url").toString("utf8")
2197
+ );
2198
+ if (!payload.projectId) {
2199
+ throw new Error('License payload is missing "projectId".');
2200
+ }
2201
+ if (payload.projectId !== currentProjectId) {
2202
+ throw new Error(
2203
+ `Project ID mismatch. License is bound to project namespace "${payload.projectId}" but configuration has "${currentProjectId}".`
2204
+ );
2205
+ }
2206
+ if (!payload.expiresAt) {
2207
+ throw new Error('License payload is missing expiration ("expiresAt").');
2208
+ }
2209
+ const currentTimestampSec = Math.floor(Date.now() / 1e3);
2210
+ if (currentTimestampSec > payload.expiresAt) {
2211
+ throw new Error(
2212
+ `License key has expired. Expiration: ${new Date(
2213
+ payload.expiresAt * 1e3
2214
+ ).toDateString()}`
2215
+ );
2216
+ }
2217
+ if (isProduction && provider) {
2218
+ const tier = (payload.tier || "").toLowerCase();
2219
+ const normalizedProvider = provider.toLowerCase();
2220
+ if (tier === "hobby") {
2221
+ const allowedHobby = ["postgresql", "pgvector", "supabase"];
2222
+ if (!allowedHobby.includes(normalizedProvider)) {
2223
+ throw new Error(
2224
+ `The database provider "${provider}" is not allowed on the Hobby tier. Hobby tier is restricted to PostgreSQL and Supabase. Please upgrade to a Developer Pro or Enterprise plan.`
2225
+ );
2226
+ }
2227
+ } else if (tier === "pro" || tier === "developer_pro" || tier === "premium" || tier === "growth" || tier === "free_trial" || tier === "free_tier" || tier === "free") {
2228
+ const allowedPro = [
2229
+ "postgresql",
2230
+ "pgvector",
2231
+ "supabase",
2232
+ "pinecone",
2233
+ "qdrant",
2234
+ "mongodb",
2235
+ "milvus",
2236
+ "chroma",
2237
+ "chromadb"
2238
+ ];
2239
+ if (!allowedPro.includes(normalizedProvider)) {
2240
+ throw new Error(
2241
+ `The database provider "${provider}" is not allowed on the Developer Pro tier. Please upgrade to an Enterprise plan.`
2242
+ );
2243
+ }
2244
+ }
2245
+ }
2246
+ if (licenseKey) {
2247
+ const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
2248
+ this.cache.set(cacheKey, { payload, cachedAt: now });
2249
+ }
2250
+ return payload;
2251
+ } catch (err) {
2252
+ const message = err instanceof Error ? err.message : String(err);
2253
+ throw new ConfigurationException(
2254
+ `[Retrivora SDK] License key validation failed: ${message}`
2255
+ );
2256
+ }
2257
+ }
2258
+ static async verifyIP(licenseKey) {
2259
+ if (!licenseKey) return;
2260
+ try {
2261
+ const parts = licenseKey.split(".");
2262
+ if (parts.length !== 3) return;
2263
+ const [, payloadB64] = parts;
2264
+ const payload = JSON.parse(
2265
+ Buffer.from(payloadB64, "base64url").toString("utf8")
2266
+ );
2267
+ const tier = (payload.tier || "").toLowerCase();
2268
+ if (tier === "enterprise" || tier === "custom") {
2269
+ return;
2270
+ }
2271
+ if (payload.ipv4 || payload.ipv6) {
2272
+ let currentIpv4 = "";
2273
+ let currentIpv6 = "";
2274
+ try {
2275
+ const res = await fetch("https://api4.ipify.org?format=json", { signal: AbortSignal.timeout(3e3) });
2276
+ const data = await res.json();
2277
+ currentIpv4 = data.ip;
2278
+ } catch (e) {
2279
+ }
2280
+ try {
2281
+ const res = await fetch("https://api6.ipify.org?format=json", { signal: AbortSignal.timeout(3e3) });
2282
+ const data = await res.json();
2283
+ currentIpv6 = data.ip;
2284
+ } catch (e) {
2285
+ }
2286
+ const localIps = [];
2287
+ try {
2288
+ const osModule = __require("os");
2289
+ const interfaces = osModule.networkInterfaces();
2290
+ for (const name of Object.keys(interfaces)) {
2291
+ for (const iface of interfaces[name] || []) {
2292
+ if (!iface.internal) {
2293
+ localIps.push(iface.address);
2294
+ }
2295
+ }
2296
+ }
2297
+ } catch (e) {
2298
+ }
2299
+ const isIpv4Match = payload.ipv4 && (currentIpv4 === payload.ipv4 || localIps.includes(payload.ipv4));
2300
+ const isIpv6Match = payload.ipv6 && (currentIpv6 === payload.ipv6 || localIps.includes(payload.ipv6));
2301
+ if (payload.ipv4 && payload.ipv6) {
2302
+ if (!isIpv4Match && !isIpv6Match) {
2303
+ throw new Error(
2304
+ `License key access restricted. This license key was created for a different system (authorized IPv4: ${payload.ipv4}, IPv6: ${payload.ipv6}) and cannot be used on this machine.`
2305
+ );
2306
+ }
2307
+ } else if (payload.ipv4 && !isIpv4Match) {
2308
+ throw new Error(
2309
+ `License key access restricted. This license key was created for a different system (authorized IPv4: ${payload.ipv4}) and cannot be used on this machine.`
2310
+ );
2311
+ } else if (payload.ipv6 && !isIpv6Match) {
2312
+ throw new Error(
2313
+ `License key access restricted. This license key was created for a different system (authorized IPv6: ${payload.ipv6}) and cannot be used on this machine.`
2314
+ );
2315
+ }
2316
+ }
2317
+ } catch (err) {
2318
+ if (err.message.includes("License key access restricted")) {
2319
+ throw new ConfigurationException(`[Retrivora SDK] ${err.message}`);
2320
+ }
2321
+ }
2322
+ }
2323
+ };
2324
+ // A simple in-memory cache to save CPU overhead of cryptographic signature checks.
2325
+ LicenseVerifier.cache = /* @__PURE__ */ new Map();
2326
+ LicenseVerifier.CACHE_TTL_MS = 60 * 1e3;
2327
+ // Cache verified license for 60 seconds
2328
+ // Retrivora's Public Key used to verify the license key signature.
2329
+ // In production, this matches the private key held by Retrivora SaaS.
2330
+ LicenseVerifier.PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
2331
+ MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArMieCkCBtTfByRNOserm
2332
+ XM4T0Am29JyNzB4XQPe+WJJ56CN73H1HLXx9n1ByFcxkEJ9po+SURj5DnvUXwEy+
2333
+ xstx33wDPpVmcMQe33j5CRYS0S4gICiNqIRN7XkTlJtrcXqrmh1/hdOAwfRbjO1T
2334
+ NVtORHwUwWfI/lBLyxUPGtKPed+0fQ7NtcW4o00JXxs3EjCB5BV9CbnXoTjQb/4h
2335
+ iwZof4l8rb7oaNzOsVg0RSyxsETX7Ex5sI0CjBz1p2mYp4oVhw/A/h8Ls7H0XzjC
2336
+ +Eb6BLtsytt5JHoSp0jExLlCpDmpys2L+kETcBVx+IqiXtdN1n6KbkksvEDUVzLI
2337
+ MwIDAQAB
2338
+ -----END PUBLIC KEY-----`;
2339
+
2061
2340
  // src/config/constants.ts
2062
2341
  var VECTOR_DB_PROVIDERS = [
2063
2342
  "pinecone",
@@ -2127,14 +2406,12 @@ function readEnum(env, name, fallback, allowed) {
2127
2406
  throw new Error(`[getRagConfig] ${name} must be one of: ${allowed.join(", ")}`);
2128
2407
  }
2129
2408
  function getEnvConfig(env = process.env, base) {
2130
- var _a2, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S, _T, _U, _V, _W, _X, _Y, _Z, __, _$, _aa, _ba, _ca, _da, _ea, _fa, _ga, _ha, _ia, _ja, _ka, _la, _ma, _na, _oa, _pa, _qa, _ra, _sa, _ta, _ua, _va, _wa, _xa, _ya, _za, _Aa, _Ba, _Ca, _Da, _Ea, _Fa, _Ga, _Ha, _Ia, _Ja, _Ka, _La, _Ma, _Na, _Oa, _Pa, _Qa, _Ra, _Sa, _Ta, _Ua;
2409
+ var _a2, _b, _c, _d, _e, _f, _g2, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S, _T, _U, _V, _W, _X, _Y, _Z, __, _$, _aa, _ba, _ca, _da, _ea, _fa, _ga, _ha, _ia, _ja, _ka, _la, _ma, _na, _oa, _pa, _qa, _ra, _sa, _ta, _ua, _va, _wa, _xa, _ya, _za, _Aa, _Ba, _Ca, _Da, _Ea, _Fa, _Ga, _Ha, _Ia, _Ja, _Ka, _La, _Ma, _Na, _Oa, _Pa, _Qa, _Ra, _Sa, _Ta, _Ua, _Va, _Wa, _Xa, _Ya, _Za, __a, _$a, _ab, _bb, _cb, _db, _eb, _fb, _gb, _hb, _ib, _jb, _kb, _lb, _mb, _nb, _ob, _pb, _qb, _rb, _sb, _tb, _ub, _vb, _wb;
2131
2410
  const projectId = (_c = (_b = (_a2 = readString(env, "RAG_PROJECT_ID")) != null ? _a2 : readString(env, "NEXT_PUBLIC_PROJECT_ID")) != null ? _b : base == null ? void 0 : base.projectId) != null ? _c : "__default__";
2132
2411
  const licenseKey = (_g2 = (_f = (_e = (_d = readString(env, "RAG_LICENSE_KEY")) != null ? _d : readString(env, "RETRIVORA_LICENSE_KEY")) != null ? _e : readString(env, "NEXT_PUBLIC_RETRIVORA_LICENSE_KEY")) != null ? _f : readString(env, "LICENSE_KEY")) != null ? _g2 : base == null ? void 0 : base.licenseKey;
2133
2412
  const telemetryEnabled = readString(env, "TELEMETRY_ENABLED") === "true" || readString(env, "NEXT_PUBLIC_TELEMETRY_ENABLED") === "true" || ((_h = base == null ? void 0 : base.telemetry) == null ? void 0 : _h.enabled) || Boolean(licenseKey);
2134
2413
  const vectorProvider = readEnum(env, "VECTOR_DB_PROVIDER", "pinecone", VECTOR_DB_PROVIDERS);
2135
- const llmProvider = readEnum(env, "LLM_PROVIDER", "openai", LLM_PROVIDERS);
2136
- const embeddingProvider = readEnum(env, "EMBEDDING_PROVIDER", "openai", EMBEDDING_PROVIDERS);
2137
- const embeddingDimensions = readNumber(env, "EMBEDDING_DIMENSIONS", 1536);
2414
+ const embeddingDimensions = readNumber(env, "EMBEDDING_DIMENSIONS", 768);
2138
2415
  const vectorDbOptions = {};
2139
2416
  if (vectorProvider === "pinecone") {
2140
2417
  vectorDbOptions.apiKey = (_l = (_k = readString(env, "PINECONE_API_KEY")) != null ? _k : (_j = (_i = base == null ? void 0 : base.vectorDb) == null ? void 0 : _i.options) == null ? void 0 : _j.apiKey) != null ? _l : "";
@@ -2199,65 +2476,88 @@ function getEnvConfig(env = process.env, base) {
2199
2476
  rest: "default",
2200
2477
  custom: "default"
2201
2478
  };
2479
+ const isFreeTier = (() => {
2480
+ if (!licenseKey) return true;
2481
+ try {
2482
+ const payload = LicenseVerifier.verify(licenseKey, projectId);
2483
+ const tier = (payload.tier || "").toLowerCase();
2484
+ return tier === "free_trial" || tier === "free_tier" || tier === "free" || tier === "hobby";
2485
+ } catch (e) {
2486
+ return true;
2487
+ }
2488
+ })();
2489
+ const DEFAULT_FREE_GATEWAY = "https://llm.retrivora.com/api/v1";
2490
+ const defaultLlmProvider = isFreeTier ? "universal_rest" : "universal_rest";
2491
+ const llmProvider = (_na = (_ma = readEnum(env, "LLM_PROVIDER", defaultLlmProvider, LLM_PROVIDERS)) != null ? _ma : (_la = base == null ? void 0 : base.llm) == null ? void 0 : _la.provider) != null ? _na : defaultLlmProvider;
2492
+ const llmBaseUrl = (_qa = (_pa = readString(env, "LLM_BASE_URL")) != null ? _pa : (_oa = base == null ? void 0 : base.llm) == null ? void 0 : _oa.baseUrl) != null ? _qa : DEFAULT_FREE_GATEWAY;
2493
+ const llmModel = (_ua = (_sa = readString(env, "LLM_MODEL")) != null ? _sa : (_ra = base == null ? void 0 : base.llm) == null ? void 0 : _ra.model) != null ? _ua : isFreeTier ? "llama-3.1-8b-instant" : (_ta = DEFAULT_MODEL_BY_PROVIDER[llmProvider]) != null ? _ta : "gpt-4o";
2494
+ const llmApiKey = (_ya = (_xa = (_va = llmApiKeyByProvider[llmProvider]) != null ? _va : readString(env, "LLM_API_KEY")) != null ? _xa : (_wa = base == null ? void 0 : base.llm) == null ? void 0 : _wa.apiKey) != null ? _ya : "sk-retrivora-cancer-280590";
2495
+ const llmProfile = (_Ca = (_Ba = readString(env, "LLM_UNIVERSAL_PROFILE")) != null ? _Ba : (_Aa = (_za = base == null ? void 0 : base.llm) == null ? void 0 : _za.options) == null ? void 0 : _Aa.profile) != null ? _Ca : "litellm";
2496
+ const defaultEmbeddingProvider = isFreeTier ? "universal_rest" : "universal_rest";
2497
+ const embeddingProvider = (_Fa = (_Ea = readEnum(env, "EMBEDDING_PROVIDER", defaultEmbeddingProvider, EMBEDDING_PROVIDERS)) != null ? _Ea : (_Da = base == null ? void 0 : base.embedding) == null ? void 0 : _Da.provider) != null ? _Fa : defaultEmbeddingProvider;
2498
+ const embeddingBaseUrl = (_Ia = (_Ha = readString(env, "EMBEDDING_BASE_URL")) != null ? _Ha : (_Ga = base == null ? void 0 : base.embedding) == null ? void 0 : _Ga.baseUrl) != null ? _Ia : DEFAULT_FREE_GATEWAY;
2499
+ const embeddingModel = (_La = (_Ka = readString(env, "EMBEDDING_MODEL")) != null ? _Ka : (_Ja = base == null ? void 0 : base.embedding) == null ? void 0 : _Ja.model) != null ? _La : "text-embedding-004";
2500
+ const embeddingApiKey = (_Qa = (_Pa = (_Na = (_Ma = embeddingApiKeyByProvider[embeddingProvider]) != null ? _Ma : readString(env, "EMBEDDING_API_KEY")) != null ? _Na : readString(env, "LLM_API_KEY")) != null ? _Pa : (_Oa = base == null ? void 0 : base.embedding) == null ? void 0 : _Oa.apiKey) != null ? _Qa : "sk-retrivora-cancer-280590";
2501
+ const embeddingProfile = (_Ua = (_Ta = readString(env, "EMBEDDING_UNIVERSAL_PROFILE")) != null ? _Ta : (_Sa = (_Ra = base == null ? void 0 : base.embedding) == null ? void 0 : _Ra.options) == null ? void 0 : _Sa.profile) != null ? _Ua : "litellm";
2202
2502
  return __spreadProps(__spreadValues({
2203
2503
  projectId,
2204
- licenseKey: (_ma = (_la = readString(env, "RETRIVORA_LICENSE_KEY")) != null ? _la : readString(env, "LICENSE_KEY")) != null ? _ma : base == null ? void 0 : base.licenseKey,
2504
+ licenseKey,
2205
2505
  vectorDb: {
2206
2506
  provider: vectorProvider,
2207
- indexName: (_oa = (_na = readString(env, "VECTOR_DB_INDEX")) != null ? _na : vectorDbOptions.indexName) != null ? _oa : "rag-index",
2507
+ indexName: (_Wa = (_Va = readString(env, "VECTOR_DB_INDEX")) != null ? _Va : vectorDbOptions.indexName) != null ? _Wa : "rag-index",
2208
2508
  options: vectorDbOptions
2209
2509
  },
2210
2510
  llm: {
2211
2511
  provider: llmProvider,
2212
- model: (_qa = (_pa = readString(env, "LLM_MODEL")) != null ? _pa : DEFAULT_MODEL_BY_PROVIDER[llmProvider]) != null ? _qa : "gpt-4o",
2213
- apiKey: (_ra = llmApiKeyByProvider[llmProvider]) != null ? _ra : "",
2214
- baseUrl: readString(env, "LLM_BASE_URL"),
2512
+ model: llmModel,
2513
+ apiKey: llmApiKey,
2514
+ baseUrl: llmBaseUrl,
2215
2515
  systemPrompt: readString(env, "LLM_SYSTEM_PROMPT"),
2216
2516
  maxTokens: readNumber(env, "LLM_MAX_TOKENS", 4096),
2217
2517
  temperature: readNumber(env, "LLM_TEMPERATURE", 0.7),
2218
2518
  options: {
2219
- profile: readString(env, "LLM_UNIVERSAL_PROFILE"),
2519
+ profile: llmProfile,
2220
2520
  thinking: readString(env, "LLM_THINKING") === "true" || readString(env, "LLM_THINKING") === "enabled" ? true : readString(env, "LLM_THINKING") === "false" ? false : void 0,
2221
2521
  thinkingBudget: env.LLM_THINKING_BUDGET ? parseInt(env.LLM_THINKING_BUDGET, 10) : void 0
2222
2522
  }
2223
2523
  },
2224
2524
  embedding: {
2225
2525
  provider: embeddingProvider,
2226
- model: (_sa = readString(env, "EMBEDDING_MODEL")) != null ? _sa : "text-embedding-3-small",
2227
- apiKey: embeddingApiKeyByProvider[embeddingProvider],
2228
- baseUrl: readString(env, "EMBEDDING_BASE_URL"),
2526
+ model: embeddingModel,
2527
+ apiKey: embeddingApiKey,
2528
+ baseUrl: embeddingBaseUrl,
2229
2529
  dimensions: embeddingDimensions,
2230
2530
  queryPrefix: readString(env, "EMBEDDING_QUERY_PREFIX"),
2231
2531
  documentPrefix: readString(env, "EMBEDDING_DOCUMENT_PREFIX"),
2232
2532
  options: {
2233
- profile: readString(env, "EMBEDDING_UNIVERSAL_PROFILE")
2533
+ profile: embeddingProfile
2234
2534
  }
2235
2535
  },
2236
2536
  ui: {
2237
- title: (_ua = (_ta = readString(env, "NEXT_PUBLIC_UI_TITLE")) != null ? _ta : readString(env, "UI_TITLE")) != null ? _ua : "AI Assistant",
2238
- subtitle: (_wa = (_va = readString(env, "NEXT_PUBLIC_UI_SUBTITLE")) != null ? _va : readString(env, "UI_SUBTITLE")) != null ? _wa : "Powered by RAG",
2239
- primaryColor: (_ya = (_xa = readString(env, "NEXT_PUBLIC_PRIMARY_COLOR")) != null ? _xa : readString(env, "UI_PRIMARY_COLOR")) != null ? _ya : "#10b981",
2240
- accentColor: (_Aa = (_za = readString(env, "NEXT_PUBLIC_ACCENT_COLOR")) != null ? _za : readString(env, "UI_ACCENT_COLOR")) != null ? _Aa : "#3b82f6",
2241
- logoUrl: (_Ba = readString(env, "NEXT_PUBLIC_LOGO_URL")) != null ? _Ba : readString(env, "UI_LOGO_URL"),
2242
- placeholder: (_Da = (_Ca = readString(env, "NEXT_PUBLIC_PLACEHOLDER")) != null ? _Ca : readString(env, "UI_PLACEHOLDER")) != null ? _Da : "Ask me anything\u2026",
2243
- showSources: ((_Fa = (_Ea = readString(env, "NEXT_PUBLIC_SHOW_SOURCES")) != null ? _Ea : readString(env, "UI_SHOW_SOURCES")) != null ? _Fa : "true") !== "false",
2244
- welcomeMessage: (_Ha = (_Ga = readString(env, "NEXT_PUBLIC_WELCOME_MESSAGE")) != null ? _Ga : readString(env, "UI_WELCOME_MESSAGE")) != null ? _Ha : "Hello! I'm your AI assistant. Ask me anything about your documents.",
2245
- visualStyle: (_Ja = (_Ia = readString(env, "NEXT_PUBLIC_UI_VISUAL_STYLE")) != null ? _Ia : readString(env, "UI_VISUAL_STYLE")) != null ? _Ja : "glass",
2246
- borderRadius: (_La = (_Ka = readString(env, "NEXT_PUBLIC_UI_BORDER_RADIUS")) != null ? _Ka : readString(env, "UI_BORDER_RADIUS")) != null ? _La : "xl",
2247
- allowUpload: ((_Na = (_Ma = readString(env, "NEXT_PUBLIC_ALLOW_UPLOAD")) != null ? _Ma : readString(env, "UI_ALLOW_UPLOAD")) != null ? _Na : "false") === "true"
2537
+ title: (_Ya = (_Xa = readString(env, "NEXT_PUBLIC_UI_TITLE")) != null ? _Xa : readString(env, "UI_TITLE")) != null ? _Ya : "AI Assistant",
2538
+ subtitle: (__a = (_Za = readString(env, "NEXT_PUBLIC_UI_SUBTITLE")) != null ? _Za : readString(env, "UI_SUBTITLE")) != null ? __a : "Powered by RAG",
2539
+ primaryColor: (_ab = (_$a = readString(env, "NEXT_PUBLIC_PRIMARY_COLOR")) != null ? _$a : readString(env, "UI_PRIMARY_COLOR")) != null ? _ab : "#10b981",
2540
+ accentColor: (_cb = (_bb = readString(env, "NEXT_PUBLIC_ACCENT_COLOR")) != null ? _bb : readString(env, "UI_ACCENT_COLOR")) != null ? _cb : "#3b82f6",
2541
+ logoUrl: (_db = readString(env, "NEXT_PUBLIC_LOGO_URL")) != null ? _db : readString(env, "UI_LOGO_URL"),
2542
+ placeholder: (_fb = (_eb = readString(env, "NEXT_PUBLIC_PLACEHOLDER")) != null ? _eb : readString(env, "UI_PLACEHOLDER")) != null ? _fb : "Ask me anything\u2026",
2543
+ showSources: ((_hb = (_gb = readString(env, "NEXT_PUBLIC_SHOW_SOURCES")) != null ? _gb : readString(env, "UI_SHOW_SOURCES")) != null ? _hb : "true") !== "false",
2544
+ welcomeMessage: (_jb = (_ib = readString(env, "NEXT_PUBLIC_WELCOME_MESSAGE")) != null ? _ib : readString(env, "UI_WELCOME_MESSAGE")) != null ? _jb : "Hello! I'm your AI assistant. Ask me anything about your documents.",
2545
+ visualStyle: (_lb = (_kb = readString(env, "NEXT_PUBLIC_UI_VISUAL_STYLE")) != null ? _kb : readString(env, "UI_VISUAL_STYLE")) != null ? _lb : "glass",
2546
+ borderRadius: (_nb = (_mb = readString(env, "NEXT_PUBLIC_UI_BORDER_RADIUS")) != null ? _mb : readString(env, "UI_BORDER_RADIUS")) != null ? _nb : "xl",
2547
+ allowUpload: ((_pb = (_ob = readString(env, "NEXT_PUBLIC_ALLOW_UPLOAD")) != null ? _ob : readString(env, "UI_ALLOW_UPLOAD")) != null ? _pb : "false") === "true"
2248
2548
  },
2249
2549
  rag: {
2250
2550
  topK: readNumber(env, "RAG_TOP_K", 5),
2251
2551
  scoreThreshold: readNumber(env, "RAG_SCORE_THRESHOLD", 0),
2252
2552
  chunkSize: readNumber(env, "RAG_CHUNK_SIZE", 1e3),
2253
2553
  chunkOverlap: readNumber(env, "RAG_CHUNK_OVERLAP", 200),
2254
- filterableFields: (_Oa = readString(env, "RAG_FILTERABLE_FIELDS")) == null ? void 0 : _Oa.split(",").map((f) => f.trim()),
2554
+ filterableFields: (_qb = readString(env, "RAG_FILTERABLE_FIELDS")) == null ? void 0 : _qb.split(",").map((f) => f.trim()),
2255
2555
  // Query pipeline toggles — read from .env.local
2256
2556
  useQueryTransformation: readString(env, "RAG_USE_QUERY_TRANSFORMATION") === "true",
2257
2557
  useReranking: readString(env, "RAG_USE_RERANKING") === "true",
2258
2558
  useGraphRetrieval: readString(env, "RAG_USE_GRAPH_RETRIEVAL") === "true",
2259
- architecture: (_Pa = readString(env, "RAG_ARCHITECTURE")) != null ? _Pa : "simple",
2260
- chunkingStrategy: (_Qa = readString(env, "RAG_CHUNKING_STRATEGY")) != null ? _Qa : "recursive",
2559
+ architecture: (_rb = readString(env, "RAG_ARCHITECTURE")) != null ? _rb : "simple",
2560
+ chunkingStrategy: (_sb = readString(env, "RAG_CHUNKING_STRATEGY")) != null ? _sb : "recursive",
2261
2561
  uiMapping: (() => {
2262
2562
  const raw = readString(env, "RAG_UI_MAPPING");
2263
2563
  if (!raw) return void 0;
@@ -2270,7 +2570,7 @@ function getEnvConfig(env = process.env, base) {
2270
2570
  },
2271
2571
  telemetry: {
2272
2572
  enabled: telemetryEnabled,
2273
- url: (_Ua = (_Ta = (_Ra = readString(env, "TELEMETRY_URL")) != null ? _Ra : readString(env, "NEXT_PUBLIC_TELEMETRY_URL")) != null ? _Ta : (_Sa = base == null ? void 0 : base.telemetry) == null ? void 0 : _Sa.url) != null ? _Ua : process.env.NODE_ENV === "development" ? "http://localhost:3001/api/telemetry" : "https://retrivora.com/api/telemetry"
2573
+ url: (_wb = (_vb = (_tb = readString(env, "TELEMETRY_URL")) != null ? _tb : readString(env, "NEXT_PUBLIC_TELEMETRY_URL")) != null ? _vb : (_ub = base == null ? void 0 : base.telemetry) == null ? void 0 : _ub.url) != null ? _wb : process.env.NODE_ENV === "development" ? "http://localhost:3001/api/telemetry" : "https://retrivora.com/api/telemetry"
2274
2574
  }
2275
2575
  }, readString(env, "GRAPH_DB_PROVIDER") ? {
2276
2576
  graphDb: {
@@ -2757,10 +3057,12 @@ var AnthropicProvider = class {
2757
3057
  import axios from "axios";
2758
3058
  var OllamaProvider = class {
2759
3059
  constructor(llmConfig, embeddingConfig) {
2760
- var _a2, _b;
2761
- const baseURL = (_a2 = llmConfig.baseUrl) != null ? _a2 : "http://localhost:11434";
3060
+ var _a2, _b, _c;
3061
+ const rawBaseURL = ((_a2 = llmConfig.baseUrl) != null ? _a2 : "http://localhost:11434").replace(/\/+$/, "");
3062
+ const baseURL = rawBaseURL.replace(/\/(?:api\/v1|v1|api)$/i, "");
2762
3063
  const timeout = Number((_b = llmConfig.options) == null ? void 0 : _b.timeout) || 3e5;
2763
- this.http = axios.create({ baseURL, timeout });
3064
+ const headers = ((_c = llmConfig.options) == null ? void 0 : _c.headers) || {};
3065
+ this.http = axios.create({ baseURL, timeout, headers });
2764
3066
  this.llmConfig = llmConfig;
2765
3067
  this.embeddingConfig = embeddingConfig;
2766
3068
  }
@@ -3697,112 +3999,40 @@ ${context != null ? context : "None"}` },
3697
3999
  payload = buildPayload(this.opts.embedPayloadTemplate, {
3698
4000
  model: this.model,
3699
4001
  input: text
3700
- });
3701
- } else {
3702
- payload = {
3703
- model: this.model,
3704
- input: text
3705
- };
3706
- }
3707
- const { data } = await this.http.post(path2, payload);
3708
- const extractPath = (_b = this.opts.embedExtractPath) != null ? _b : "data[0].embedding";
3709
- const vector = resolvePath(data, extractPath);
3710
- if (!Array.isArray(vector)) {
3711
- throw new Error(`[UniversalLLMAdapter] Expected a number array at '${extractPath}' for embeddings.`);
3712
- }
3713
- return vector;
3714
- }
3715
- async batchEmbed(texts) {
3716
- const vectors = [];
3717
- for (const text of texts) {
3718
- vectors.push(await this.embed(text));
3719
- }
3720
- return vectors;
3721
- }
3722
- async ping() {
3723
- try {
3724
- if (this.opts.pingPath) {
3725
- await this.http.get(this.opts.pingPath);
3726
- }
3727
- return true;
3728
- } catch (err) {
3729
- console.error("[UniversalLLMAdapter] Ping failed:", err);
3730
- return false;
3731
- }
3732
- }
3733
- };
3734
-
3735
- // src/exceptions/index.ts
3736
- var RetrivoraError = class extends Error {
3737
- constructor(message, code, details) {
3738
- super(message);
3739
- this.name = new.target.name;
3740
- this.code = code;
3741
- this.details = details;
3742
- }
3743
- };
3744
- var ProviderNotFoundException = class extends RetrivoraError {
3745
- constructor(providerType, provider, details) {
3746
- super(`Unsupported ${providerType} provider: ${provider}`, "PROVIDER_NOT_FOUND", details);
3747
- }
3748
- };
3749
- var EmbeddingFailedException = class extends RetrivoraError {
3750
- constructor(message = "Embedding generation failed", details) {
3751
- super(message, "EMBEDDING_FAILED", details);
3752
- }
3753
- };
3754
- var RetrievalException = class extends RetrivoraError {
3755
- constructor(message = "Retrieval failed", details) {
3756
- super(message, "RETRIEVAL_FAILED", details);
3757
- }
3758
- };
3759
- var RateLimitException = class extends RetrivoraError {
3760
- constructor(message = "Provider rate limit exceeded", details) {
3761
- super(message, "RATE_LIMITED", details);
3762
- }
3763
- };
3764
- var ConfigurationException = class extends RetrivoraError {
3765
- constructor(message, details) {
3766
- super(message, "CONFIGURATION_ERROR", details);
3767
- }
3768
- };
3769
- var AuthenticationException = class extends RetrivoraError {
3770
- constructor(message = "Provider authentication failed", details) {
3771
- super(message, "AUTHENTICATION_ERROR", details);
3772
- }
3773
- };
3774
- function wrapError(err, defaultCode, defaultMessage) {
3775
- var _a2;
3776
- if (err instanceof RetrivoraError) {
3777
- return err;
3778
- }
3779
- const error = err;
3780
- const message = (error == null ? void 0 : error.message) || defaultMessage || String(err);
3781
- const status = (error == null ? void 0 : error.status) || (error == null ? void 0 : error.statusCode) || ((_a2 = error == null ? void 0 : error.response) == null ? void 0 : _a2.status);
3782
- const code = error == null ? void 0 : error.code;
3783
- if (status === 429 || /rate[- ]?limit/i.test(message) || code === "RATE_LIMIT_EXCEEDED") {
3784
- return new RateLimitException(message, err);
4002
+ });
4003
+ } else {
4004
+ payload = {
4005
+ model: this.model,
4006
+ input: text
4007
+ };
4008
+ }
4009
+ const { data } = await this.http.post(path2, payload);
4010
+ const extractPath = (_b = this.opts.embedExtractPath) != null ? _b : "data[0].embedding";
4011
+ const vector = resolvePath(data, extractPath);
4012
+ if (!Array.isArray(vector)) {
4013
+ throw new Error(`[UniversalLLMAdapter] Expected a number array at '${extractPath}' for embeddings.`);
4014
+ }
4015
+ return vector;
3785
4016
  }
3786
- if (status === 401 || status === 403 || /unauthorized|auth|api[- ]?key/i.test(message) || code === "INVALID_API_KEY") {
3787
- return new AuthenticationException(message, err);
4017
+ async batchEmbed(texts) {
4018
+ const vectors = [];
4019
+ for (const text of texts) {
4020
+ vectors.push(await this.embed(text));
4021
+ }
4022
+ return vectors;
3788
4023
  }
3789
- switch (defaultCode) {
3790
- case "PROVIDER_NOT_FOUND":
3791
- return new ProviderNotFoundException("provider", message, err);
3792
- case "EMBEDDING_FAILED":
3793
- return new EmbeddingFailedException(message, err);
3794
- case "RETRIEVAL_FAILED":
3795
- return new RetrievalException(message, err);
3796
- case "RATE_LIMITED":
3797
- return new RateLimitException(message, err);
3798
- case "CONFIGURATION_ERROR":
3799
- return new ConfigurationException(message, err);
3800
- case "AUTHENTICATION_ERROR":
3801
- return new AuthenticationException(message, err);
3802
- default:
3803
- return new RetrivoraError(message, defaultCode, err);
4024
+ async ping() {
4025
+ try {
4026
+ if (this.opts.pingPath) {
4027
+ await this.http.get(this.opts.pingPath);
4028
+ }
4029
+ return true;
4030
+ } catch (err) {
4031
+ console.error("[UniversalLLMAdapter] Ping failed:", err);
4032
+ return false;
4033
+ }
3804
4034
  }
3805
- }
4035
+ };
3806
4036
 
3807
4037
  // src/llm/LLMFactory.ts
3808
4038
  var customProviders = /* @__PURE__ */ new Map();
@@ -8729,211 +8959,6 @@ var ProviderHealthCheck = class {
8729
8959
  }
8730
8960
  };
8731
8961
 
8732
- // src/core/LicenseVerifier.ts
8733
- import * as crypto2 from "crypto";
8734
- var LicenseVerifier = class {
8735
- /**
8736
- * Decodes, verifies signature, and checks metadata of a license key.
8737
- *
8738
- * @param licenseKey - Base64url signed JWT license key.
8739
- * @param currentProjectId - Project namespace ID.
8740
- * @param publicKeyOverride - Optional override for unit/integration tests.
8741
- */
8742
- static verify(licenseKey, currentProjectId, provider, publicKeyOverride) {
8743
- const isProduction = process.env.NODE_ENV === "production";
8744
- const now = Date.now();
8745
- if (licenseKey) {
8746
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
8747
- const cached = this.cache.get(cacheKey);
8748
- if (cached && now - cached.cachedAt < this.CACHE_TTL_MS) {
8749
- const currentTimestampSec = Math.floor(now / 1e3);
8750
- if (cached.payload.expiresAt && currentTimestampSec > cached.payload.expiresAt) {
8751
- this.cache.delete(cacheKey);
8752
- } else {
8753
- return cached.payload;
8754
- }
8755
- }
8756
- }
8757
- if (!licenseKey) {
8758
- if (isProduction) {
8759
- throw new ConfigurationException(
8760
- "[Retrivora SDK] License key (licenseKey) is required in production environments."
8761
- );
8762
- }
8763
- console.warn(
8764
- `\x1B[33m[Retrivora SDK] WARNING: Running without a license key. This namespace (${currentProjectId}) is permitted for local development only.\x1B[0m`
8765
- );
8766
- return {
8767
- projectId: currentProjectId,
8768
- expiresAt: Math.floor(Date.now() / 1e3) + 86400,
8769
- // Valid for 24h
8770
- tier: "hobby"
8771
- };
8772
- }
8773
- try {
8774
- const parts = licenseKey.split(".");
8775
- if (parts.length !== 3) {
8776
- throw new Error("Malformed token structure (expected 3 parts).");
8777
- }
8778
- const [headerB64, payloadB64, signatureB64] = parts;
8779
- const dataToVerify = `${headerB64}.${payloadB64}`;
8780
- const publicKey = publicKeyOverride != null ? publicKeyOverride : this.PUBLIC_KEY;
8781
- const signature = Buffer.from(signatureB64, "base64url");
8782
- const data = Buffer.from(dataToVerify);
8783
- const isValid = crypto2.verify(
8784
- "sha256",
8785
- data,
8786
- publicKey,
8787
- signature
8788
- );
8789
- if (!isValid) {
8790
- throw new Error("Signature verification failed.");
8791
- }
8792
- const payload = JSON.parse(
8793
- Buffer.from(payloadB64, "base64url").toString("utf8")
8794
- );
8795
- if (!payload.projectId) {
8796
- throw new Error('License payload is missing "projectId".');
8797
- }
8798
- if (payload.projectId !== currentProjectId) {
8799
- throw new Error(
8800
- `Project ID mismatch. License is bound to project namespace "${payload.projectId}" but configuration has "${currentProjectId}".`
8801
- );
8802
- }
8803
- if (!payload.expiresAt) {
8804
- throw new Error('License payload is missing expiration ("expiresAt").');
8805
- }
8806
- const currentTimestampSec = Math.floor(Date.now() / 1e3);
8807
- if (currentTimestampSec > payload.expiresAt) {
8808
- throw new Error(
8809
- `License key has expired. Expiration: ${new Date(
8810
- payload.expiresAt * 1e3
8811
- ).toDateString()}`
8812
- );
8813
- }
8814
- if (isProduction && provider) {
8815
- const tier = (payload.tier || "").toLowerCase();
8816
- const normalizedProvider = provider.toLowerCase();
8817
- if (tier === "hobby") {
8818
- const allowedHobby = ["postgresql", "pgvector", "supabase"];
8819
- if (!allowedHobby.includes(normalizedProvider)) {
8820
- throw new Error(
8821
- `The database provider "${provider}" is not allowed on the Hobby tier. Hobby tier is restricted to PostgreSQL and Supabase. Please upgrade to a Developer Pro or Enterprise plan.`
8822
- );
8823
- }
8824
- } else if (tier === "pro" || tier === "developer_pro" || tier === "premium" || tier === "growth" || tier === "free_trial" || tier === "free_tier" || tier === "free") {
8825
- const allowedPro = [
8826
- "postgresql",
8827
- "pgvector",
8828
- "supabase",
8829
- "pinecone",
8830
- "qdrant",
8831
- "mongodb",
8832
- "milvus",
8833
- "chroma",
8834
- "chromadb"
8835
- ];
8836
- if (!allowedPro.includes(normalizedProvider)) {
8837
- throw new Error(
8838
- `The database provider "${provider}" is not allowed on the Developer Pro tier. Please upgrade to an Enterprise plan.`
8839
- );
8840
- }
8841
- }
8842
- }
8843
- if (licenseKey) {
8844
- const cacheKey = `${licenseKey}:${currentProjectId}:${provider || ""}:${publicKeyOverride || ""}`;
8845
- this.cache.set(cacheKey, { payload, cachedAt: now });
8846
- }
8847
- return payload;
8848
- } catch (err) {
8849
- const message = err instanceof Error ? err.message : String(err);
8850
- throw new ConfigurationException(
8851
- `[Retrivora SDK] License key validation failed: ${message}`
8852
- );
8853
- }
8854
- }
8855
- static async verifyIP(licenseKey) {
8856
- if (!licenseKey) return;
8857
- try {
8858
- const parts = licenseKey.split(".");
8859
- if (parts.length !== 3) return;
8860
- const [, payloadB64] = parts;
8861
- const payload = JSON.parse(
8862
- Buffer.from(payloadB64, "base64url").toString("utf8")
8863
- );
8864
- const tier = (payload.tier || "").toLowerCase();
8865
- if (tier === "enterprise" || tier === "custom") {
8866
- return;
8867
- }
8868
- if (payload.ipv4 || payload.ipv6) {
8869
- let currentIpv4 = "";
8870
- let currentIpv6 = "";
8871
- try {
8872
- const res = await fetch("https://api4.ipify.org?format=json", { signal: AbortSignal.timeout(3e3) });
8873
- const data = await res.json();
8874
- currentIpv4 = data.ip;
8875
- } catch (e) {
8876
- }
8877
- try {
8878
- const res = await fetch("https://api6.ipify.org?format=json", { signal: AbortSignal.timeout(3e3) });
8879
- const data = await res.json();
8880
- currentIpv6 = data.ip;
8881
- } catch (e) {
8882
- }
8883
- const localIps = [];
8884
- try {
8885
- const osModule = __require("os");
8886
- const interfaces = osModule.networkInterfaces();
8887
- for (const name of Object.keys(interfaces)) {
8888
- for (const iface of interfaces[name] || []) {
8889
- if (!iface.internal) {
8890
- localIps.push(iface.address);
8891
- }
8892
- }
8893
- }
8894
- } catch (e) {
8895
- }
8896
- const isIpv4Match = payload.ipv4 && (currentIpv4 === payload.ipv4 || localIps.includes(payload.ipv4));
8897
- const isIpv6Match = payload.ipv6 && (currentIpv6 === payload.ipv6 || localIps.includes(payload.ipv6));
8898
- if (payload.ipv4 && payload.ipv6) {
8899
- if (!isIpv4Match && !isIpv6Match) {
8900
- throw new Error(
8901
- `License key access restricted. This license key was created for a different system (authorized IPv4: ${payload.ipv4}, IPv6: ${payload.ipv6}) and cannot be used on this machine.`
8902
- );
8903
- }
8904
- } else if (payload.ipv4 && !isIpv4Match) {
8905
- throw new Error(
8906
- `License key access restricted. This license key was created for a different system (authorized IPv4: ${payload.ipv4}) and cannot be used on this machine.`
8907
- );
8908
- } else if (payload.ipv6 && !isIpv6Match) {
8909
- throw new Error(
8910
- `License key access restricted. This license key was created for a different system (authorized IPv6: ${payload.ipv6}) and cannot be used on this machine.`
8911
- );
8912
- }
8913
- }
8914
- } catch (err) {
8915
- if (err.message.includes("License key access restricted")) {
8916
- throw new ConfigurationException(`[Retrivora SDK] ${err.message}`);
8917
- }
8918
- }
8919
- }
8920
- };
8921
- // A simple in-memory cache to save CPU overhead of cryptographic signature checks.
8922
- LicenseVerifier.cache = /* @__PURE__ */ new Map();
8923
- LicenseVerifier.CACHE_TTL_MS = 60 * 1e3;
8924
- // Cache verified license for 60 seconds
8925
- // Retrivora's Public Key used to verify the license key signature.
8926
- // In production, this matches the private key held by Retrivora SaaS.
8927
- LicenseVerifier.PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
8928
- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArMieCkCBtTfByRNOserm
8929
- XM4T0Am29JyNzB4XQPe+WJJ56CN73H1HLXx9n1ByFcxkEJ9po+SURj5DnvUXwEy+
8930
- xstx33wDPpVmcMQe33j5CRYS0S4gICiNqIRN7XkTlJtrcXqrmh1/hdOAwfRbjO1T
8931
- NVtORHwUwWfI/lBLyxUPGtKPed+0fQ7NtcW4o00JXxs3EjCB5BV9CbnXoTjQb/4h
8932
- iwZof4l8rb7oaNzOsVg0RSyxsETX7Ex5sI0CjBz1p2mYp4oVhw/A/h8Ls7H0XzjC
8933
- +Eb6BLtsytt5JHoSp0jExLlCpDmpys2L+kETcBVx+IqiXtdN1n6KbkksvEDUVzLI
8934
- MwIDAQAB
8935
- -----END PUBLIC KEY-----`;
8936
-
8937
8962
  // src/core/VectorPlugin.ts
8938
8963
  var VectorPlugin = class {
8939
8964
  constructor(hostConfig) {
@@ -9731,7 +9756,17 @@ function createChatHandler(configOrPlugin, options) {
9731
9756
  if (rateLimited) return rateLimited;
9732
9757
  try {
9733
9758
  const body = await req.json();
9734
- const { message: rawMessage, history = [], namespace, sessionId = "default", messageId, userMessageId } = body;
9759
+ const bodyObj = body != null ? body : {};
9760
+ let rawMessage = bodyObj.message;
9761
+ if (!rawMessage && Array.isArray(bodyObj.messages) && bodyObj.messages.length > 0) {
9762
+ const lastMsg = bodyObj.messages[bodyObj.messages.length - 1];
9763
+ rawMessage = typeof lastMsg === "string" ? lastMsg : (lastMsg == null ? void 0 : lastMsg.content) || (lastMsg == null ? void 0 : lastMsg.text);
9764
+ }
9765
+ if (!rawMessage && typeof bodyObj.prompt === "string") {
9766
+ rawMessage = bodyObj.prompt;
9767
+ }
9768
+ const history = bodyObj.history || (Array.isArray(bodyObj.messages) ? bodyObj.messages.slice(0, -1) : []);
9769
+ const { namespace, sessionId = "default", messageId, userMessageId } = bodyObj;
9735
9770
  const sanitized = sanitizeInput(rawMessage != null ? rawMessage : "");
9736
9771
  if (!sanitized.ok) {
9737
9772
  return NextResponse.json({ error: { code: "INVALID_INPUT", message: sanitized.error } }, { status: 400 });
@@ -9783,7 +9818,17 @@ function createStreamHandler(configOrPlugin, options) {
9783
9818
  headers: { "Content-Type": "application/json" }
9784
9819
  });
9785
9820
  }
9786
- const { message: rawMessage, history = [], namespace, sessionId = "default", messageId, userMessageId } = body;
9821
+ const bodyObj = body != null ? body : {};
9822
+ let rawMessage = bodyObj.message;
9823
+ if (!rawMessage && Array.isArray(bodyObj.messages) && bodyObj.messages.length > 0) {
9824
+ const lastMsg = bodyObj.messages[bodyObj.messages.length - 1];
9825
+ rawMessage = typeof lastMsg === "string" ? lastMsg : (lastMsg == null ? void 0 : lastMsg.content) || (lastMsg == null ? void 0 : lastMsg.text);
9826
+ }
9827
+ if (!rawMessage && typeof bodyObj.prompt === "string") {
9828
+ rawMessage = bodyObj.prompt;
9829
+ }
9830
+ const history = bodyObj.history || (Array.isArray(bodyObj.messages) ? bodyObj.messages.slice(0, -1) : []);
9831
+ const { namespace, sessionId = "default", messageId, userMessageId } = bodyObj;
9787
9832
  const sanitized = sanitizeInput(rawMessage != null ? rawMessage : "");
9788
9833
  if (!sanitized.ok) {
9789
9834
  return new Response(