@retrivora-ai/rag-engine 2.0.4 → 2.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
  }
@@ -3570,7 +3872,7 @@ var UniversalLLMAdapter = class {
3570
3872
  });
3571
3873
  }
3572
3874
  async chat(messages, context) {
3573
- var _a2, _b;
3875
+ var _a2, _b, _c, _d, _e, _f;
3574
3876
  const path2 = (_a2 = this.opts.chatPath) != null ? _a2 : "/chat/completions";
3575
3877
  const formattedMessages = [
3576
3878
  { role: "system", content: `${this.systemPrompt}
@@ -3595,8 +3897,26 @@ ${context != null ? context : "None"}` },
3595
3897
  temperature: this.temperature
3596
3898
  };
3597
3899
  }
3900
+ const isSelfHost = this.baseUrl.includes("retrivora.com") || this.baseUrl.includes("localhost");
3901
+ if (isSelfHost || Boolean(process.env.VERCEL)) {
3902
+ try {
3903
+ const _g2 = globalThis;
3904
+ if (typeof _g2.__retrivoraDispatchChat === "function") {
3905
+ const res = await _g2.__retrivoraDispatchChat({
3906
+ model: this.model,
3907
+ messages: formattedMessages,
3908
+ max_tokens: this.maxTokens,
3909
+ temperature: this.temperature
3910
+ }, this.apiKey);
3911
+ if ((_e = (_d = (_c = (_b = res == null ? void 0 : res.response) == null ? void 0 : _b.choices) == null ? void 0 : _c[0]) == null ? void 0 : _d.message) == null ? void 0 : _e.content) {
3912
+ return res.response.choices[0].message.content;
3913
+ }
3914
+ }
3915
+ } catch (e) {
3916
+ }
3917
+ }
3598
3918
  const { data } = await this.http.post(path2, payload);
3599
- const extractPath = (_b = this.opts.responseExtractPath) != null ? _b : "choices[0].message.content";
3919
+ const extractPath = (_f = this.opts.responseExtractPath) != null ? _f : "choices[0].message.content";
3600
3920
  const result = resolvePath(data, extractPath);
3601
3921
  if (result === void 0) {
3602
3922
  throw new Error(`[UniversalLLMAdapter] Could not extract text from path '${extractPath}' in response.`);
@@ -3610,7 +3930,7 @@ ${context != null ? context : "None"}` },
3610
3930
  */
3611
3931
  chatStream(messages, context) {
3612
3932
  return __asyncGenerator(this, null, function* () {
3613
- var _a2, _b, _c;
3933
+ var _a2, _b, _c, _d, _e, _f, _g2;
3614
3934
  const path2 = (_a2 = this.opts.chatPath) != null ? _a2 : "/chat/completions";
3615
3935
  const url = `${this.baseUrl.replace(/\/$/, "")}${path2}`;
3616
3936
  const extractPath = ((_b = this.opts.responseExtractPath) != null ? _b : "choices[0].message.content").replace("message.content", "delta.content");
@@ -3641,19 +3961,45 @@ ${context != null ? context : "None"}` },
3641
3961
  stream: true
3642
3962
  };
3643
3963
  }
3644
- const response = yield new __await(fetch(url, {
3645
- method: "POST",
3646
- headers: this.resolvedHeaders,
3647
- body: JSON.stringify(payload)
3648
- }));
3649
- if (!response.ok) {
3650
- const errorText = yield new __await(response.text().catch(() => response.statusText));
3651
- throw new Error(`[UniversalLLMAdapter] Streaming request failed (${response.status}): ${errorText}`);
3964
+ const isSelfHost = this.baseUrl.includes("retrivora.com") || this.baseUrl.includes("localhost");
3965
+ let streamBody = null;
3966
+ if (isSelfHost || Boolean(process.env.VERCEL)) {
3967
+ try {
3968
+ const _g3 = globalThis;
3969
+ if (typeof _g3.__retrivoraDispatchChat === "function") {
3970
+ const res = yield new __await(_g3.__retrivoraDispatchChat({
3971
+ model: this.model,
3972
+ messages: formattedMessages,
3973
+ max_tokens: this.maxTokens,
3974
+ temperature: this.temperature,
3975
+ stream: true
3976
+ }, this.apiKey));
3977
+ if (res == null ? void 0 : res.stream) {
3978
+ streamBody = res.stream;
3979
+ } else if ((_f = (_e = (_d = (_c = res == null ? void 0 : res.response) == null ? void 0 : _c.choices) == null ? void 0 : _d[0]) == null ? void 0 : _e.message) == null ? void 0 : _f.content) {
3980
+ yield res.response.choices[0].message.content;
3981
+ return;
3982
+ }
3983
+ }
3984
+ } catch (e) {
3985
+ }
3652
3986
  }
3653
- if (!response.body) {
3654
- throw new Error("[UniversalLLMAdapter] Response body is null \u2014 server did not send a streaming response.");
3987
+ if (!streamBody) {
3988
+ const response = yield new __await(fetch(url, {
3989
+ method: "POST",
3990
+ headers: this.resolvedHeaders,
3991
+ body: JSON.stringify(payload)
3992
+ }));
3993
+ if (!response.ok) {
3994
+ const errorText = yield new __await(response.text().catch(() => response.statusText));
3995
+ throw new Error(`[UniversalLLMAdapter] Streaming request failed (${response.status}): ${errorText}`);
3996
+ }
3997
+ if (!response.body) {
3998
+ throw new Error("[UniversalLLMAdapter] Response body is null \u2014 server did not send a streaming response.");
3999
+ }
4000
+ streamBody = response.body;
3655
4001
  }
3656
- const reader = response.body.getReader();
4002
+ const reader = streamBody.getReader();
3657
4003
  const decoder = new TextDecoder("utf-8");
3658
4004
  let buffer = "";
3659
4005
  try {
@@ -3662,7 +4008,7 @@ ${context != null ? context : "None"}` },
3662
4008
  if (done) break;
3663
4009
  buffer += decoder.decode(value, { stream: true });
3664
4010
  const lines = buffer.split("\n");
3665
- buffer = (_c = lines.pop()) != null ? _c : "";
4011
+ buffer = (_g2 = lines.pop()) != null ? _g2 : "";
3666
4012
  for (const line of lines) {
3667
4013
  const trimmed = line.trim();
3668
4014
  if (!trimmed || trimmed === "data: [DONE]") continue;
@@ -3690,7 +4036,7 @@ ${context != null ? context : "None"}` },
3690
4036
  });
3691
4037
  }
3692
4038
  async embed(text) {
3693
- var _a2, _b;
4039
+ var _a2, _b, _c, _d;
3694
4040
  const path2 = (_a2 = this.opts.embedPath) != null ? _a2 : "/embeddings";
3695
4041
  let payload;
3696
4042
  if (this.opts.embedPayloadTemplate) {
@@ -3704,105 +4050,49 @@ ${context != null ? context : "None"}` },
3704
4050
  input: text
3705
4051
  };
3706
4052
  }
4053
+ const isSelfHost = this.baseUrl.includes("retrivora.com") || this.baseUrl.includes("localhost");
4054
+ if (isSelfHost || Boolean(process.env.VERCEL)) {
4055
+ try {
4056
+ const _g2 = globalThis;
4057
+ if (typeof _g2.__retrivoraDispatchEmbedding === "function") {
4058
+ const res = await _g2.__retrivoraDispatchEmbedding({
4059
+ model: this.model,
4060
+ input: text
4061
+ }, this.apiKey);
4062
+ if ((_c = (_b = res == null ? void 0 : res.data) == null ? void 0 : _b[0]) == null ? void 0 : _c.embedding) {
4063
+ return res.data[0].embedding;
4064
+ }
4065
+ }
4066
+ } catch (e) {
4067
+ }
4068
+ }
3707
4069
  const { data } = await this.http.post(path2, payload);
3708
- const extractPath = (_b = this.opts.embedExtractPath) != null ? _b : "data[0].embedding";
4070
+ const extractPath = (_d = this.opts.embedExtractPath) != null ? _d : "data[0].embedding";
3709
4071
  const vector = resolvePath(data, extractPath);
3710
4072
  if (!Array.isArray(vector)) {
3711
4073
  throw new Error(`[UniversalLLMAdapter] Expected a number array at '${extractPath}' for embeddings.`);
3712
4074
  }
3713
4075
  return vector;
3714
4076
  }
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);
3785
- }
3786
- if (status === 401 || status === 403 || /unauthorized|auth|api[- ]?key/i.test(message) || code === "INVALID_API_KEY") {
3787
- return new AuthenticationException(message, err);
4077
+ async batchEmbed(texts) {
4078
+ const vectors = [];
4079
+ for (const text of texts) {
4080
+ vectors.push(await this.embed(text));
4081
+ }
4082
+ return vectors;
3788
4083
  }
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);
4084
+ async ping() {
4085
+ try {
4086
+ if (this.opts.pingPath) {
4087
+ await this.http.get(this.opts.pingPath);
4088
+ }
4089
+ return true;
4090
+ } catch (err) {
4091
+ console.error("[UniversalLLMAdapter] Ping failed:", err);
4092
+ return false;
4093
+ }
3804
4094
  }
3805
- }
4095
+ };
3806
4096
 
3807
4097
  // src/llm/LLMFactory.ts
3808
4098
  var customProviders = /* @__PURE__ */ new Map();
@@ -8113,8 +8403,11 @@ ${m.content}`).join("\n\n---\n\n");
8113
8403
  fullSources = fullSources.slice(0, topK);
8114
8404
  }
8115
8405
  const rerankMs = performance.now() - rerankStart;
8116
- let context = fullSources.length ? fullSources.map((m, i) => `[Source ${i + 1}]
8117
- ${m.content}`).join("\n\n---\n\n") : "No relevant context found.";
8406
+ let context = fullSources.length ? fullSources.map((m, i) => {
8407
+ var _a3;
8408
+ return `[Source ${i + 1}]
8409
+ ${(_a3 = m == null ? void 0 : m.content) != null ? _a3 : ""}`;
8410
+ }).join("\n\n---\n\n") : "No relevant context found.";
8118
8411
  let displayCount = 15;
8119
8412
  if (hasMetadataFilter) {
8120
8413
  displayCount = fullSources.length;
@@ -8198,7 +8491,10 @@ ${context}`;
8198
8491
  if (isSimulatedThinking) {
8199
8492
  finalRestrictionSuffix += "\n\n(IMPORTANT: You must think step-by-step before answering. Write your thinking process inside a `<think>...</think>` block. Write the `<think>` block first, then follow it with your final response. Keep the thinking process thorough and detailed. Example: `<think>Thinking details here...</think>Final answer text here.`)";
8200
8493
  }
8201
- const hardenedHistory = [...history];
8494
+ const hardenedHistory = (Array.isArray(history) ? history : []).filter((m) => Boolean(m && typeof m === "object")).map((m) => ({
8495
+ role: m.role || "user",
8496
+ content: typeof m.content === "string" ? m.content : m.content != null ? String(m.content) : ""
8497
+ }));
8202
8498
  const userQuestion = { role: "user", content: question + finalRestrictionSuffix };
8203
8499
  const messages = [...hardenedHistory, userQuestion];
8204
8500
  const systemPrompt = (_v = this.config.llm.systemPrompt) != null ? _v : "";
@@ -8345,13 +8641,13 @@ ${context}`;
8345
8641
  rewrittenQuery,
8346
8642
  systemPrompt,
8347
8643
  userPrompt: question + finalRestrictionSuffix,
8348
- chunks: sources.map((s) => {
8349
- var _a3;
8644
+ chunks: (sources || []).filter(Boolean).map((s) => {
8645
+ var _a3, _b2;
8350
8646
  return {
8351
8647
  id: s.id,
8352
8648
  score: s.score,
8353
- content: s.content,
8354
- metadata: (_a3 = s.metadata) != null ? _a3 : {},
8649
+ content: (_a3 = s == null ? void 0 : s.content) != null ? _a3 : "",
8650
+ metadata: (_b2 = s == null ? void 0 : s.metadata) != null ? _b2 : {},
8355
8651
  namespace: ns
8356
8652
  };
8357
8653
  }),
@@ -8729,211 +9025,6 @@ var ProviderHealthCheck = class {
8729
9025
  }
8730
9026
  };
8731
9027
 
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
9028
  // src/core/VectorPlugin.ts
8938
9029
  var VectorPlugin = class {
8939
9030
  constructor(hostConfig) {
@@ -9158,6 +9249,7 @@ ${csv.trim()}`);
9158
9249
  // src/core/DatabaseStorage.ts
9159
9250
  import * as fs from "fs";
9160
9251
  import * as path from "path";
9252
+ import * as os from "os";
9161
9253
  var DatabaseStorage = class {
9162
9254
  constructor(config) {
9163
9255
  // Dynamic PG Pool
@@ -9166,7 +9258,8 @@ var DatabaseStorage = class {
9166
9258
  this.mongoClient = null;
9167
9259
  this.mongoDbName = "";
9168
9260
  // Filesystem fallback configuration
9169
- this.fallbackDir = path.join(process.cwd(), ".retrivora");
9261
+ this.isServerless = Boolean(process.env.VERCEL || process.env.AWS_LAMBDA_FUNCTION_NAME || process.env.LAMBDA_TASK_ROOT);
9262
+ this.fallbackDir = this.isServerless ? path.join(os.tmpdir(), ".retrivora") : path.join(process.cwd(), ".retrivora");
9170
9263
  this.historyFile = path.join(this.fallbackDir, "history.json");
9171
9264
  this.feedbackFile = path.join(this.fallbackDir, "feedback.json");
9172
9265
  var _a2, _b, _c, _d, _e;
@@ -9296,10 +9389,27 @@ var DatabaseStorage = class {
9296
9389
  }
9297
9390
  // Helper for FS fallback writes
9298
9391
  writeLocalFile(filePath, data) {
9299
- if (!fs.existsSync(this.fallbackDir)) {
9300
- fs.mkdirSync(this.fallbackDir, { recursive: true });
9392
+ try {
9393
+ const dir = path.dirname(filePath);
9394
+ if (!fs.existsSync(dir)) {
9395
+ fs.mkdirSync(dir, { recursive: true });
9396
+ }
9397
+ fs.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf-8");
9398
+ } catch (err) {
9399
+ if (err.code === "EROFS") {
9400
+ try {
9401
+ const tmpDir = path.join(os.tmpdir(), ".retrivora");
9402
+ if (!fs.existsSync(tmpDir)) {
9403
+ fs.mkdirSync(tmpDir, { recursive: true });
9404
+ }
9405
+ const tmpFilePath = path.join(tmpDir, path.basename(filePath));
9406
+ fs.writeFileSync(tmpFilePath, JSON.stringify(data, null, 2), "utf-8");
9407
+ } catch (e) {
9408
+ }
9409
+ } else {
9410
+ console.warn(`[DatabaseStorage] Failed to write local fallback file: ${err.message}`);
9411
+ }
9301
9412
  }
9302
- fs.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf-8");
9303
9413
  }
9304
9414
  // ─── Message History Operations ──────────────────────────────────────────
9305
9415
  async saveMessage(sessionId, message) {
@@ -9731,7 +9841,17 @@ function createChatHandler(configOrPlugin, options) {
9731
9841
  if (rateLimited) return rateLimited;
9732
9842
  try {
9733
9843
  const body = await req.json();
9734
- const { message: rawMessage, history = [], namespace, sessionId = "default", messageId, userMessageId } = body;
9844
+ const bodyObj = body != null ? body : {};
9845
+ let rawMessage = bodyObj.message;
9846
+ if (!rawMessage && Array.isArray(bodyObj.messages) && bodyObj.messages.length > 0) {
9847
+ const lastMsg = bodyObj.messages[bodyObj.messages.length - 1];
9848
+ rawMessage = typeof lastMsg === "string" ? lastMsg : (lastMsg == null ? void 0 : lastMsg.content) || (lastMsg == null ? void 0 : lastMsg.text);
9849
+ }
9850
+ if (!rawMessage && typeof bodyObj.prompt === "string") {
9851
+ rawMessage = bodyObj.prompt;
9852
+ }
9853
+ const history = bodyObj.history || (Array.isArray(bodyObj.messages) ? bodyObj.messages.slice(0, -1) : []);
9854
+ const { namespace, sessionId = "default", messageId, userMessageId } = bodyObj;
9735
9855
  const sanitized = sanitizeInput(rawMessage != null ? rawMessage : "");
9736
9856
  if (!sanitized.ok) {
9737
9857
  return NextResponse.json({ error: { code: "INVALID_INPUT", message: sanitized.error } }, { status: 400 });
@@ -9783,7 +9903,17 @@ function createStreamHandler(configOrPlugin, options) {
9783
9903
  headers: { "Content-Type": "application/json" }
9784
9904
  });
9785
9905
  }
9786
- const { message: rawMessage, history = [], namespace, sessionId = "default", messageId, userMessageId } = body;
9906
+ const bodyObj = body != null ? body : {};
9907
+ let rawMessage = bodyObj.message;
9908
+ if (!rawMessage && Array.isArray(bodyObj.messages) && bodyObj.messages.length > 0) {
9909
+ const lastMsg = bodyObj.messages[bodyObj.messages.length - 1];
9910
+ rawMessage = typeof lastMsg === "string" ? lastMsg : (lastMsg == null ? void 0 : lastMsg.content) || (lastMsg == null ? void 0 : lastMsg.text);
9911
+ }
9912
+ if (!rawMessage && typeof bodyObj.prompt === "string") {
9913
+ rawMessage = bodyObj.prompt;
9914
+ }
9915
+ const history = bodyObj.history || (Array.isArray(bodyObj.messages) ? bodyObj.messages.slice(0, -1) : []);
9916
+ const { namespace, sessionId = "default", messageId, userMessageId } = bodyObj;
9787
9917
  const sanitized = sanitizeInput(rawMessage != null ? rawMessage : "");
9788
9918
  if (!sanitized.ok) {
9789
9919
  return new Response(