mem0ai 3.0.6 → 3.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/oss/index.js CHANGED
@@ -126,6 +126,7 @@ var OpenAIEmbedder = class {
126
126
  const response = await this.openai.embeddings.create({
127
127
  model: this.model,
128
128
  input: text,
129
+ encoding_format: "float",
129
130
  ...this.embeddingDims !== void 0 && {
130
131
  dimensions: this.embeddingDims
131
132
  }
@@ -140,6 +141,7 @@ var OpenAIEmbedder = class {
140
141
  const response = await this.openai.embeddings.create({
141
142
  model: this.model,
142
143
  input: chunk,
144
+ encoding_format: "float",
143
145
  ...this.embeddingDims !== void 0 && {
144
146
  dimensions: this.embeddingDims
145
147
  }
@@ -226,8 +228,8 @@ var DEFAULT_MODEL = "nomic-ai/nomic-embed-text-v1.5-GGUF/nomic-embed-text-v1.5.f
226
228
  var DEFAULT_LMSTUDIO_API_KEY = "lm-studio";
227
229
  var LMStudioEmbedder = class {
228
230
  constructor(config) {
229
- var _a2, _b;
230
- const baseURL = (_b = (_a2 = config.baseURL) != null ? _a2 : config.url) != null ? _b : DEFAULT_BASE_URL;
231
+ var _a2, _b2;
232
+ const baseURL = (_b2 = (_a2 = config.baseURL) != null ? _a2 : config.url) != null ? _b2 : DEFAULT_BASE_URL;
231
233
  const apiKey = config.apiKey || DEFAULT_LMSTUDIO_API_KEY;
232
234
  this.openai = new import_openai2.default({ apiKey, baseURL: String(baseURL) });
233
235
  this.model = config.model || DEFAULT_MODEL;
@@ -256,7 +258,7 @@ var LMStudioEmbedder = class {
256
258
  input: normalized,
257
259
  encoding_format: "float"
258
260
  });
259
- return response.data.map((item) => item.embedding);
261
+ return response.data.sort((a, b) => a.index - b.index).map((item) => item.embedding);
260
262
  } catch (err) {
261
263
  const message = err instanceof Error ? err.message : String(err);
262
264
  throw new Error(`LM Studio embedder failed: ${message}`);
@@ -1221,7 +1223,7 @@ var Qdrant = class {
1221
1223
  }
1222
1224
  }
1223
1225
  async ensureCollection(name, size) {
1224
- var _a2, _b, _c;
1226
+ var _a2, _b2, _c;
1225
1227
  try {
1226
1228
  await this.client.createCollection(name, {
1227
1229
  vectors: {
@@ -1234,7 +1236,7 @@ var Qdrant = class {
1234
1236
  if (name === this.collectionName) {
1235
1237
  try {
1236
1238
  const collectionInfo = await this.client.getCollection(name);
1237
- const vectorConfig = (_b = (_a2 = collectionInfo.config) == null ? void 0 : _a2.params) == null ? void 0 : _b.vectors;
1239
+ const vectorConfig = (_b2 = (_a2 = collectionInfo.config) == null ? void 0 : _a2.params) == null ? void 0 : _b2.vectors;
1238
1240
  if (vectorConfig && vectorConfig.size !== size) {
1239
1241
  throw new Error(
1240
1242
  `Collection ${name} exists but has wrong vector size. Expected: ${size}, got: ${vectorConfig.size}`
@@ -1321,7 +1323,7 @@ var VectorizeDB = class {
1321
1323
  return null;
1322
1324
  }
1323
1325
  async search(query, topK = 5, filters) {
1324
- var _a2, _b;
1326
+ var _a2, _b2;
1325
1327
  try {
1326
1328
  const result = await ((_a2 = this.client) == null ? void 0 : _a2.vectorize.indexes.query(
1327
1329
  this.indexName,
@@ -1333,7 +1335,7 @@ var VectorizeDB = class {
1333
1335
  topK
1334
1336
  }
1335
1337
  ));
1336
- return ((_b = result == null ? void 0 : result.matches) == null ? void 0 : _b.map((match) => ({
1338
+ return ((_b2 = result == null ? void 0 : result.matches) == null ? void 0 : _b2.map((match) => ({
1337
1339
  id: match.id,
1338
1340
  payload: match.metadata,
1339
1341
  score: match.score
@@ -1428,7 +1430,7 @@ var VectorizeDB = class {
1428
1430
  }
1429
1431
  }
1430
1432
  async list(filters, topK = 20) {
1431
- var _a2, _b;
1433
+ var _a2, _b2;
1432
1434
  try {
1433
1435
  const result = await ((_a2 = this.client) == null ? void 0 : _a2.vectorize.indexes.query(
1434
1436
  this.indexName,
@@ -1441,7 +1443,7 @@ var VectorizeDB = class {
1441
1443
  returnMetadata: "all"
1442
1444
  }
1443
1445
  ));
1444
- const matches = ((_b = result == null ? void 0 : result.matches) == null ? void 0 : _b.map((match) => ({
1446
+ const matches = ((_b2 = result == null ? void 0 : result.matches) == null ? void 0 : _b2.map((match) => ({
1445
1447
  id: match.id,
1446
1448
  payload: match.metadata,
1447
1449
  score: match.score
@@ -1465,7 +1467,7 @@ var VectorizeDB = class {
1465
1467
  );
1466
1468
  }
1467
1469
  async getUserId() {
1468
- var _a2, _b, _c;
1470
+ var _a2, _b2, _c;
1469
1471
  try {
1470
1472
  let found = false;
1471
1473
  for await (const index of this.client.vectorize.indexes.list({
@@ -1485,7 +1487,7 @@ var VectorizeDB = class {
1485
1487
  }
1486
1488
  }));
1487
1489
  }
1488
- const result = await ((_b = this.client) == null ? void 0 : _b.vectorize.indexes.query(
1490
+ const result = await ((_b2 = this.client) == null ? void 0 : _b2.vectorize.indexes.query(
1489
1491
  "memory_migrations",
1490
1492
  {
1491
1493
  account_id: this.accountId,
@@ -1524,7 +1526,7 @@ var VectorizeDB = class {
1524
1526
  }
1525
1527
  }
1526
1528
  async setUserId(userId) {
1527
- var _a2, _b;
1529
+ var _a2, _b2;
1528
1530
  try {
1529
1531
  const result = await ((_a2 = this.client) == null ? void 0 : _a2.vectorize.indexes.query(
1530
1532
  "memory_migrations",
@@ -1547,7 +1549,7 @@ var VectorizeDB = class {
1547
1549
  method: "POST",
1548
1550
  headers: {
1549
1551
  "Content-Type": "application/x-ndjson",
1550
- Authorization: `Bearer ${(_b = this.client) == null ? void 0 : _b.apiToken}`
1552
+ Authorization: `Bearer ${(_b2 = this.client) == null ? void 0 : _b2.apiToken}`
1551
1553
  },
1552
1554
  body: JSON.stringify(data) + "\n"
1553
1555
  // ndjson format
@@ -1567,7 +1569,7 @@ var VectorizeDB = class {
1567
1569
  return this._initPromise;
1568
1570
  }
1569
1571
  async _doInitialize() {
1570
- var _a2, _b, _c, _d, _e;
1572
+ var _a2, _b2, _c, _d, _e;
1571
1573
  try {
1572
1574
  let indexFound = false;
1573
1575
  for await (const idx of this.client.vectorize.indexes.list({
@@ -1590,7 +1592,7 @@ var VectorizeDB = class {
1590
1592
  }));
1591
1593
  const properties2 = ["userId", "agentId", "runId"];
1592
1594
  for (const propertyName of properties2) {
1593
- await ((_b = this.client) == null ? void 0 : _b.vectorize.indexes.metadataIndex.create(
1595
+ await ((_b2 = this.client) == null ? void 0 : _b2.vectorize.indexes.metadataIndex.create(
1594
1596
  this.indexName,
1595
1597
  {
1596
1598
  account_id: this.accountId,
@@ -1943,7 +1945,7 @@ var RedisDB = class {
1943
1945
  return {
1944
1946
  id: doc.value.memory_id,
1945
1947
  payload: toCamelCase(resultPayload),
1946
- score: (_a2 = Number(doc.value.__vector_score)) != null ? _a2 : 0
1948
+ score: Math.max(0, 1 - ((_a2 = Number(doc.value.__vector_score)) != null ? _a2 : 0))
1947
1949
  };
1948
1950
  });
1949
1951
  } catch (error) {
@@ -2643,7 +2645,7 @@ var SQLiteManager = class {
2643
2645
  }
2644
2646
  async batchAddHistory(records) {
2645
2647
  const txn = this.db.transaction(() => {
2646
- var _a2, _b, _c;
2648
+ var _a2, _b2, _c;
2647
2649
  for (const record of records) {
2648
2650
  this.stmtInsert.run(
2649
2651
  record.memoryId,
@@ -2651,7 +2653,7 @@ var SQLiteManager = class {
2651
2653
  record.newValue,
2652
2654
  record.action,
2653
2655
  (_a2 = record.createdAt) != null ? _a2 : null,
2654
- (_b = record.updatedAt) != null ? _b : null,
2656
+ (_b2 = record.updatedAt) != null ? _b2 : null,
2655
2657
  (_c = record.isDeleted) != null ? _c : 0
2656
2658
  );
2657
2659
  }
@@ -3499,12 +3501,12 @@ function truncateContent(text, limit = PAST_MESSAGE_TRUNCATION_LIMIT) {
3499
3501
  return text.slice(0, limit) + "...";
3500
3502
  }
3501
3503
  function formatConversationHistory(messages) {
3502
- var _a2, _b;
3504
+ var _a2, _b2;
3503
3505
  if (!messages || messages.length === 0) return "";
3504
3506
  let result = "";
3505
3507
  for (const msg of messages) {
3506
3508
  const role = (_a2 = msg.role) != null ? _a2 : "";
3507
- const content = (_b = msg.content) != null ? _b : "";
3509
+ const content = (_b2 = msg.content) != null ? _b2 : "";
3508
3510
  if (role && content) {
3509
3511
  result += `${role}: ${truncateContent(content)}
3510
3512
  `;
@@ -3516,10 +3518,10 @@ function serializeMemories(memories) {
3516
3518
  return JSON.stringify(memories != null ? memories : []);
3517
3519
  }
3518
3520
  function generateAdditiveExtractionPrompt(options) {
3519
- var _a2, _b, _c;
3521
+ var _a2, _b2, _c;
3520
3522
  const now = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
3521
3523
  const currentDate = (_a2 = options.currentDate) != null ? _a2 : now;
3522
- const observationDate = (_b = options.observationDate) != null ? _b : currentDate;
3524
+ const observationDate = (_b2 = options.observationDate) != null ? _b2 : currentDate;
3523
3525
  const sections = [];
3524
3526
  sections.push("## Summary\n");
3525
3527
  sections.push(
@@ -3690,14 +3692,14 @@ var LangchainLLM = class {
3690
3692
  this.modelName = this.llmInstance.modelId || this.llmInstance.model || "langchain-model";
3691
3693
  }
3692
3694
  async generateResponse(messages, response_format, tools) {
3693
- var _a2, _b, _c, _d, _e;
3695
+ var _a2, _b2, _c, _d, _e;
3694
3696
  const langchainMessages = convertToLangchainMessages(messages);
3695
3697
  let runnable = this.llmInstance;
3696
3698
  const invokeOptions = {};
3697
3699
  let isStructuredOutput = false;
3698
3700
  let selectedSchema = null;
3699
3701
  const systemPromptContent = ((_a2 = messages.find((m) => m.role === "system")) == null ? void 0 : _a2.content) || "";
3700
- const userPromptContent = ((_b = messages.find((m) => m.role === "user")) == null ? void 0 : _b.content) || "";
3702
+ const userPromptContent = ((_b2 = messages.find((m) => m.role === "user")) == null ? void 0 : _b2.content) || "";
3701
3703
  if (systemPromptContent.includes("Personal Information Organizer") && systemPromptContent.includes("extract relevant pieces of information")) {
3702
3704
  selectedSchema = FactRetrievalSchema;
3703
3705
  } else if (userPromptContent.includes("smart memory manager") && userPromptContent.includes("Compare newly retrieved facts")) {
@@ -3827,7 +3829,7 @@ var LangchainVectorStore = class {
3827
3829
  // Simple in-memory user ID
3828
3830
  constructor(config) {
3829
3831
  this.storeUserId = "anonymous-langchain-user";
3830
- var _a2, _b;
3832
+ var _a2, _b2;
3831
3833
  if (!config.client || typeof config.client !== "object") {
3832
3834
  throw new Error(
3833
3835
  "Langchain vector store provider requires an initialized Langchain VectorStore instance passed via the 'client' field."
@@ -3843,7 +3845,7 @@ var LangchainVectorStore = class {
3843
3845
  if (!this.dimension && ((_a2 = this.lcStore.embeddings) == null ? void 0 : _a2.embeddingDimension)) {
3844
3846
  this.dimension = this.lcStore.embeddings.embeddingDimension;
3845
3847
  }
3846
- if (!this.dimension && ((_b = this.lcStore.embedding) == null ? void 0 : _b.embeddingDimension)) {
3848
+ if (!this.dimension && ((_b2 = this.lcStore.embedding) == null ? void 0 : _b2.embeddingDimension)) {
3847
3849
  this.dimension = this.lcStore.embedding.embeddingDimension;
3848
3850
  }
3849
3851
  if (!this.dimension) {
@@ -4985,13 +4987,13 @@ var DEFAULT_MEMORY_CONFIG = {
4985
4987
  // src/oss/src/config/manager.ts
4986
4988
  var ConfigManager = class {
4987
4989
  static mergeConfig(userConfig = {}) {
4988
- var _a2, _b, _c, _d, _e, _f, _g;
4990
+ var _a2, _b2, _c, _d, _e, _f, _g;
4989
4991
  const mergedConfig = {
4990
4992
  version: userConfig.version || DEFAULT_MEMORY_CONFIG.version,
4991
4993
  embedder: {
4992
4994
  provider: ((_a2 = userConfig.embedder) == null ? void 0 : _a2.provider) || DEFAULT_MEMORY_CONFIG.embedder.provider,
4993
4995
  config: (() => {
4994
- var _a3, _b2, _c2, _d2;
4996
+ var _a3, _b3, _c2, _d2;
4995
4997
  const defaultConf = DEFAULT_MEMORY_CONFIG.embedder.config;
4996
4998
  const userConf = (_a3 = userConfig.embedder) == null ? void 0 : _a3.config;
4997
4999
  let finalModel = defaultConf.model;
@@ -5000,7 +5002,7 @@ var ConfigManager = class {
5000
5002
  } else if ((userConf == null ? void 0 : userConf.model) && typeof userConf.model === "string") {
5001
5003
  finalModel = userConf.model;
5002
5004
  }
5003
- const baseURL = (_c2 = (_b2 = userConf == null ? void 0 : userConf.baseURL) != null ? _b2 : userConf == null ? void 0 : userConf.lmstudio_base_url) != null ? _c2 : userConf == null ? void 0 : userConf.url;
5005
+ const baseURL = (_c2 = (_b3 = userConf == null ? void 0 : userConf.baseURL) != null ? _b3 : userConf == null ? void 0 : userConf.lmstudio_base_url) != null ? _c2 : userConf == null ? void 0 : userConf.url;
5004
5006
  const embeddingDims = (_d2 = userConf == null ? void 0 : userConf.embeddingDims) != null ? _d2 : userConf == null ? void 0 : userConf.embedding_dims;
5005
5007
  return {
5006
5008
  apiKey: (userConf == null ? void 0 : userConf.apiKey) !== void 0 ? userConf.apiKey : defaultConf.apiKey,
@@ -5013,12 +5015,12 @@ var ConfigManager = class {
5013
5015
  })()
5014
5016
  },
5015
5017
  vectorStore: {
5016
- provider: ((_b = userConfig.vectorStore) == null ? void 0 : _b.provider) || DEFAULT_MEMORY_CONFIG.vectorStore.provider,
5018
+ provider: ((_b2 = userConfig.vectorStore) == null ? void 0 : _b2.provider) || DEFAULT_MEMORY_CONFIG.vectorStore.provider,
5017
5019
  config: (() => {
5018
- var _a3, _b2, _c2;
5020
+ var _a3, _b3, _c2;
5019
5021
  const defaultConf = DEFAULT_MEMORY_CONFIG.vectorStore.config;
5020
5022
  const userConf = (_a3 = userConfig.vectorStore) == null ? void 0 : _a3.config;
5021
- const explicitDimension = (userConf == null ? void 0 : userConf.dimension) || ((_c2 = (_b2 = userConfig.embedder) == null ? void 0 : _b2.config) == null ? void 0 : _c2.embeddingDims) || void 0;
5023
+ const explicitDimension = (userConf == null ? void 0 : userConf.dimension) || ((_c2 = (_b3 = userConfig.embedder) == null ? void 0 : _b3.config) == null ? void 0 : _c2.embeddingDims) || void 0;
5022
5024
  if ((userConf == null ? void 0 : userConf.client) && typeof userConf.client === "object") {
5023
5025
  return {
5024
5026
  client: userConf.client,
@@ -5042,7 +5044,7 @@ var ConfigManager = class {
5042
5044
  llm: {
5043
5045
  provider: ((_c = userConfig.llm) == null ? void 0 : _c.provider) || DEFAULT_MEMORY_CONFIG.llm.provider,
5044
5046
  config: (() => {
5045
- var _a3, _b2, _c2, _d2;
5047
+ var _a3, _b3, _c2, _d2;
5046
5048
  const defaultConf = DEFAULT_MEMORY_CONFIG.llm.config;
5047
5049
  const userConf = (_a3 = userConfig.llm) == null ? void 0 : _a3.config;
5048
5050
  let finalModel = defaultConf.model;
@@ -5051,7 +5053,7 @@ var ConfigManager = class {
5051
5053
  } else if ((userConf == null ? void 0 : userConf.model) && typeof userConf.model === "string") {
5052
5054
  finalModel = userConf.model;
5053
5055
  }
5054
- const llmBaseURL = (_d2 = (_c2 = (_b2 = userConf == null ? void 0 : userConf.baseURL) != null ? _b2 : userConf == null ? void 0 : userConf.lmstudio_base_url) != null ? _c2 : userConf == null ? void 0 : userConf.url) != null ? _d2 : defaultConf.baseURL;
5056
+ const llmBaseURL = (_d2 = (_c2 = (_b3 = userConf == null ? void 0 : userConf.baseURL) != null ? _b3 : userConf == null ? void 0 : userConf.lmstudio_base_url) != null ? _c2 : userConf == null ? void 0 : userConf.url) != null ? _d2 : defaultConf.baseURL;
5055
5057
  return {
5056
5058
  baseURL: llmBaseURL,
5057
5059
  url: userConf == null ? void 0 : userConf.url,
@@ -5064,7 +5066,7 @@ var ConfigManager = class {
5064
5066
  historyDbPath: userConfig.historyDbPath || ((_e = (_d = userConfig.historyStore) == null ? void 0 : _d.config) == null ? void 0 : _e.historyDbPath) || ((_g = (_f = DEFAULT_MEMORY_CONFIG.historyStore) == null ? void 0 : _f.config) == null ? void 0 : _g.historyDbPath),
5065
5067
  customInstructions: userConfig.customInstructions,
5066
5068
  historyStore: (() => {
5067
- var _a3, _b2;
5069
+ var _a3, _b3;
5068
5070
  const defaultHistoryStore = DEFAULT_MEMORY_CONFIG.historyStore;
5069
5071
  const historyProvider = ((_a3 = userConfig.historyStore) == null ? void 0 : _a3.provider) || defaultHistoryStore.provider;
5070
5072
  const isSqlite = historyProvider.toLowerCase() === "sqlite";
@@ -5075,7 +5077,7 @@ var ConfigManager = class {
5075
5077
  config: {
5076
5078
  ...isSqlite ? defaultHistoryStore.config : {},
5077
5079
  ...isSqlite && userConfig.historyDbPath ? { historyDbPath: userConfig.historyDbPath } : {},
5078
- ...(_b2 = userConfig.historyStore) == null ? void 0 : _b2.config
5080
+ ...(_b3 = userConfig.historyStore) == null ? void 0 : _b3.config
5079
5081
  }
5080
5082
  };
5081
5083
  })(),
@@ -5123,15 +5125,16 @@ var parse_vision_messages = async (messages) => {
5123
5125
  };
5124
5126
 
5125
5127
  // src/oss/src/utils/telemetry.ts
5126
- var version = true ? "3.0.6" : "dev";
5128
+ var version = true ? "3.0.8" : "dev";
5127
5129
  var MEM0_TELEMETRY = true;
5128
- var _a;
5130
+ var _a, _b;
5129
5131
  try {
5130
- MEM0_TELEMETRY = ((_a = process == null ? void 0 : process.env) == null ? void 0 : _a.MEM0_TELEMETRY) === "false" ? false : true;
5132
+ MEM0_TELEMETRY = ((_b = (_a = process == null ? void 0 : process.env) == null ? void 0 : _a.MEM0_TELEMETRY) == null ? void 0 : _b.toLowerCase()) === "false" ? false : true;
5131
5133
  } catch (error) {
5132
5134
  }
5133
5135
  var POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX";
5134
5136
  var POSTHOG_HOST = "https://us.i.posthog.com/i/v0/e/";
5137
+ var NOTICE_EVENT_NAME = "mem0.notice_displayed";
5135
5138
  var DEFAULT_SAMPLE_RATE = 0.1;
5136
5139
  var MEM0_TELEMETRY_SAMPLE_RATE = (() => {
5137
5140
  var _a2;
@@ -5147,7 +5150,11 @@ var MEM0_TELEMETRY_SAMPLE_RATE = (() => {
5147
5150
  }
5148
5151
  return DEFAULT_SAMPLE_RATE;
5149
5152
  })();
5150
- var LIFECYCLE_EVENTS = /* @__PURE__ */ new Set(["init", "reset"]);
5153
+ var ALWAYS_SEND_EVENTS = /* @__PURE__ */ new Set([
5154
+ "init",
5155
+ "reset",
5156
+ "notice_displayed"
5157
+ ]);
5151
5158
  var UnifiedTelemetry = class {
5152
5159
  constructor(projectApiKey, host) {
5153
5160
  this.apiKey = projectApiKey;
@@ -5187,13 +5194,16 @@ var UnifiedTelemetry = class {
5187
5194
  }
5188
5195
  };
5189
5196
  var telemetry = new UnifiedTelemetry(POSTHOG_API_KEY, POSTHOG_HOST);
5197
+ function isTelemetryEnabled() {
5198
+ return MEM0_TELEMETRY;
5199
+ }
5190
5200
  async function captureClientEvent(eventName, instance, additionalData = {}) {
5191
5201
  if (!instance.telemetryId) {
5192
5202
  console.warn("No telemetry ID found for instance");
5193
5203
  return;
5194
5204
  }
5195
- const isLifecycle = LIFECYCLE_EVENTS.has(eventName);
5196
- if (!isLifecycle && Math.random() >= MEM0_TELEMETRY_SAMPLE_RATE) {
5205
+ const alwaysSend = ALWAYS_SEND_EVENTS.has(eventName);
5206
+ if (!alwaysSend && Math.random() >= MEM0_TELEMETRY_SAMPLE_RATE) {
5197
5207
  return;
5198
5208
  }
5199
5209
  const eventData = {
@@ -5205,7 +5215,7 @@ async function captureClientEvent(eventName, instance, additionalData = {}) {
5205
5215
  client_source: "nodejs",
5206
5216
  ...additionalData,
5207
5217
  // sample_rate set AFTER the spread so callers can never override it
5208
- sample_rate: isLifecycle ? 1 : MEM0_TELEMETRY_SAMPLE_RATE
5218
+ sample_rate: alwaysSend ? 1 : MEM0_TELEMETRY_SAMPLE_RATE
5209
5219
  };
5210
5220
  await telemetry.captureEvent(
5211
5221
  instance.telemetryId,
@@ -5213,6 +5223,1038 @@ async function captureClientEvent(eventName, instance, additionalData = {}) {
5213
5223
  eventData
5214
5224
  );
5215
5225
  }
5226
+ async function captureNoticeEvent(instance, properties = {}) {
5227
+ if (!instance.telemetryId) return;
5228
+ const eventData = {
5229
+ function: `${instance.constructor.name}`,
5230
+ method: "notice_displayed",
5231
+ api_host: instance.host,
5232
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5233
+ client_version: version,
5234
+ client_source: "nodejs",
5235
+ ...properties,
5236
+ sample_rate: 1
5237
+ };
5238
+ await telemetry.captureEvent(
5239
+ instance.telemetryId,
5240
+ NOTICE_EVENT_NAME,
5241
+ eventData
5242
+ );
5243
+ }
5244
+
5245
+ // src/oss/src/utils/notices.ts
5246
+ var fs4 = __toESM(require("fs"));
5247
+ var os2 = __toESM(require("os"));
5248
+ var path3 = __toESM(require("path"));
5249
+ var NOTICE_FLAG_KEY = "mem0-oss-notices";
5250
+ var NOTICE_STATE_SECTION = "notice_state";
5251
+ var FIRST_RUN_NOTICE_ID = "first_run";
5252
+ var TEMPORAL_FEATURE_NOTICE_ID = "temporal_stub";
5253
+ var TEMPORAL_USAGE_NOTICE_ID = "temporal_usage";
5254
+ var DECAY_FEATURE_NOTICE_ID = "decay_stub";
5255
+ var DECAY_USAGE_NOTICE_ID = "decay_usage";
5256
+ var SCALE_THRESHOLD_NOTICE_ID = "scale_threshold";
5257
+ var PERFORMANCE_SLOW_QUERY_NOTICE_ID = "performance_slow_query";
5258
+ var NOTICE_CAP_LIMIT = 10;
5259
+ var NOTICE_CAP_WINDOW_MS = 7 * 24 * 60 * 60 * 1e3;
5260
+ var NOTICE_FLAG_TIMEOUT_MS = 500;
5261
+ var POSTHOG_FLAGS_URL = "https://us.i.posthog.com/flags?v=2";
5262
+ var DISPLAYED_VARIANT = "displayed";
5263
+ var HOLDOUT_VARIANT = "holdout";
5264
+ var LOG_LINE_NOTICE_TYPE = "log_line";
5265
+ var ERROR_NOTICE_TYPE = "error";
5266
+ var TEMPORAL_TIMESTAMP_PLAIN_ERROR = "The timestamp parameter is not supported by the OSS Memory SDK.";
5267
+ var TEMPORAL_REFERENCE_DATE_PLAIN_ERROR = "The referenceDate parameter is not supported by the OSS Memory SDK.";
5268
+ var DECAY_FEATURE_PLAIN_ERROR = "The decay parameter is not supported by the OSS Memory SDK.";
5269
+ var DECAY_USAGE_DELETE_THRESHOLD = 5;
5270
+ var SCALE_MEMORY_COUNT_THRESHOLD = 2e3;
5271
+ var SCALE_MEMORY_COUNT_CHECK_INTERVAL = 100;
5272
+ var SCALE_TOP_K_THRESHOLD = 50;
5273
+ var PERFORMANCE_SLOW_QUERY_THRESHOLD_MS = 2e3;
5274
+ var MAX_TEMPORAL_DETECTION_DEPTH = 32;
5275
+ var ISO_DATE_RE = /\b\d{4}-\d{2}-\d{2}(?:[T\s]\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)?\b/;
5276
+ var RELATIVE_TIME_RE = /\b(today|yesterday|tomorrow|last\s+(?:night|week|month|year)|this\s+(?:week|month|year)|next\s+(?:week|month|year)|(?:past|last)\s+\d+\s+(?:day|days|week|weeks|month|months|year|years)|(?:since|before|after|until)\s+(?:today|yesterday|tomorrow|\d{4}-\d{2}-\d{2}|last\s+(?:week|month|year)))\b/i;
5277
+ var RANGE_OPERATORS = /* @__PURE__ */ new Set(["gt", "gte", "lt", "lte"]);
5278
+ var firstRunConsumedInProcess = false;
5279
+ var firstRunClaimInProgress = false;
5280
+ var decayUsageSuccessfulDeleteCount = 0;
5281
+ var noticeCapacityReachedInProcess = /* @__PURE__ */ new Set();
5282
+ var scaleMemoryCountAddsSinceCheck = 0;
5283
+ var scaleMemoryCountCheckedInProcess = false;
5284
+ var scaleMemoryCountThresholdEvaluatedInProcess = false;
5285
+ function getMem0Dir() {
5286
+ return process.env.MEM0_DIR || path3.join(os2.homedir(), ".mem0");
5287
+ }
5288
+ function getMem0ConfigPath() {
5289
+ return path3.join(getMem0Dir(), "config.json");
5290
+ }
5291
+ function loadMem0Config() {
5292
+ try {
5293
+ const configPath = getMem0ConfigPath();
5294
+ if (!fs4.existsSync(configPath)) return {};
5295
+ const parsed = JSON.parse(fs4.readFileSync(configPath, "utf8"));
5296
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
5297
+ } catch (e) {
5298
+ return {};
5299
+ }
5300
+ }
5301
+ function writeMem0ConfigAtomic(config) {
5302
+ const configPath = getMem0ConfigPath();
5303
+ const dir = path3.dirname(configPath);
5304
+ const tempPath = path3.join(
5305
+ dir,
5306
+ `.config.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`
5307
+ );
5308
+ try {
5309
+ fs4.mkdirSync(dir, { recursive: true });
5310
+ fs4.writeFileSync(tempPath, JSON.stringify(config, null, 4));
5311
+ fs4.renameSync(tempPath, configPath);
5312
+ return true;
5313
+ } catch (e) {
5314
+ try {
5315
+ if (fs4.existsSync(tempPath)) fs4.unlinkSync(tempPath);
5316
+ } catch (e2) {
5317
+ }
5318
+ return false;
5319
+ }
5320
+ }
5321
+ function getNoticeState(config, noticeId) {
5322
+ const stateSection = config[NOTICE_STATE_SECTION] && typeof config[NOTICE_STATE_SECTION] === "object" && !Array.isArray(config[NOTICE_STATE_SECTION]) ? config[NOTICE_STATE_SECTION] : {};
5323
+ const noticeState = stateSection[noticeId];
5324
+ return noticeState && typeof noticeState === "object" && !Array.isArray(noticeState) ? noticeState : {};
5325
+ }
5326
+ function setNoticeState(config, noticeId, state) {
5327
+ const stateSection = config[NOTICE_STATE_SECTION] && typeof config[NOTICE_STATE_SECTION] === "object" && !Array.isArray(config[NOTICE_STATE_SECTION]) ? { ...config[NOTICE_STATE_SECTION] } : {};
5328
+ return {
5329
+ ...config,
5330
+ [NOTICE_STATE_SECTION]: {
5331
+ ...stateSection,
5332
+ [noticeId]: state
5333
+ }
5334
+ };
5335
+ }
5336
+ function parsePayload(payload) {
5337
+ try {
5338
+ if (typeof payload === "string") {
5339
+ const parsed = JSON.parse(payload);
5340
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
5341
+ }
5342
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : void 0;
5343
+ } catch (e) {
5344
+ return void 0;
5345
+ }
5346
+ }
5347
+ function getNoticeConfigFromPayload(payload, noticeId) {
5348
+ const parsedPayload = parsePayload(payload);
5349
+ const notices = parsedPayload == null ? void 0 : parsedPayload.notices;
5350
+ if (!notices || typeof notices !== "object" || Array.isArray(notices)) {
5351
+ return { found: false, payload: parsedPayload };
5352
+ }
5353
+ const noticeConfig = notices[noticeId];
5354
+ if (!noticeConfig || typeof noticeConfig !== "object" || Array.isArray(noticeConfig)) {
5355
+ return { found: false, payload: parsedPayload };
5356
+ }
5357
+ return {
5358
+ found: true,
5359
+ config: noticeConfig,
5360
+ payload: parsedPayload
5361
+ };
5362
+ }
5363
+ async function evaluateNoticeFlag(distinctId, options = {}) {
5364
+ var _a2, _b2, _c, _d;
5365
+ if (!isTelemetryEnabled()) return null;
5366
+ const timeoutMs = (_a2 = options.timeoutMs) != null ? _a2 : NOTICE_FLAG_TIMEOUT_MS;
5367
+ const fetchImpl = (_b2 = options.fetchImpl) != null ? _b2 : fetch;
5368
+ const controller = new AbortController();
5369
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
5370
+ try {
5371
+ const response = await fetchImpl(POSTHOG_FLAGS_URL, {
5372
+ method: "POST",
5373
+ headers: { "Content-Type": "application/json" },
5374
+ body: JSON.stringify({
5375
+ api_key: POSTHOG_API_KEY,
5376
+ distinct_id: distinctId
5377
+ }),
5378
+ signal: controller.signal
5379
+ });
5380
+ if (!response.ok) return null;
5381
+ const data = await response.json();
5382
+ const flag = (_c = data == null ? void 0 : data.flags) == null ? void 0 : _c[NOTICE_FLAG_KEY];
5383
+ if (!flag || flag.enabled === false) return null;
5384
+ const variant = typeof flag.variant === "string" ? flag.variant : null;
5385
+ if (!variant) return null;
5386
+ return {
5387
+ variant,
5388
+ payload: parsePayload((_d = flag.metadata) == null ? void 0 : _d.payload),
5389
+ flag
5390
+ };
5391
+ } catch (e) {
5392
+ return null;
5393
+ } finally {
5394
+ clearTimeout(timeout);
5395
+ }
5396
+ }
5397
+ function eventsInWindow(events, now, windowMs) {
5398
+ if (!Array.isArray(events)) return [];
5399
+ const cutoff = now.getTime() - windowMs;
5400
+ return events.filter((event) => {
5401
+ if (!event || typeof event !== "object" || Array.isArray(event)) {
5402
+ return false;
5403
+ }
5404
+ const evaluatedAt = event.evaluated_at;
5405
+ if (typeof evaluatedAt !== "string") return false;
5406
+ const timestamp = Date.parse(evaluatedAt);
5407
+ return Number.isFinite(timestamp) && timestamp >= cutoff;
5408
+ });
5409
+ }
5410
+ function hasNoticeCapRoom(state, options = {}) {
5411
+ var _a2, _b2, _c;
5412
+ const now = (_a2 = options.now) != null ? _a2 : /* @__PURE__ */ new Date();
5413
+ const limit = (_b2 = options.limit) != null ? _b2 : NOTICE_CAP_LIMIT;
5414
+ const windowMs = (_c = options.windowMs) != null ? _c : NOTICE_CAP_WINDOW_MS;
5415
+ return eventsInWindow(state.events, now, windowMs).length < limit;
5416
+ }
5417
+ function isNoticeCapacityReachedInProcess(noticeId) {
5418
+ return noticeCapacityReachedInProcess.has(noticeId);
5419
+ }
5420
+ function markNoticeCapacityReachedInProcess(noticeId) {
5421
+ noticeCapacityReachedInProcess.add(noticeId);
5422
+ }
5423
+ function hasNoticeCapRoomForNotice(noticeId, state, options = {}) {
5424
+ const hasRoom = hasNoticeCapRoom(state, options);
5425
+ if (!hasRoom) markNoticeCapacityReachedInProcess(noticeId);
5426
+ return hasRoom;
5427
+ }
5428
+ function appendNoticeCapEvent(state, event, options = {}) {
5429
+ var _a2, _b2, _c;
5430
+ const now = (_a2 = options.now) != null ? _a2 : /* @__PURE__ */ new Date();
5431
+ const limit = (_b2 = options.limit) != null ? _b2 : NOTICE_CAP_LIMIT;
5432
+ const windowMs = (_c = options.windowMs) != null ? _c : NOTICE_CAP_WINDOW_MS;
5433
+ const events = eventsInWindow(state.events, now, windowMs);
5434
+ if (events.length >= limit) return null;
5435
+ return {
5436
+ ...state,
5437
+ events: [
5438
+ ...events,
5439
+ {
5440
+ evaluated_at: now.toISOString(),
5441
+ ...event
5442
+ }
5443
+ ]
5444
+ };
5445
+ }
5446
+ function recordNoticeOpportunity(noticeId, event, options = {}) {
5447
+ if (!isTelemetryEnabled()) return false;
5448
+ if (isNoticeCapacityReachedInProcess(noticeId)) return false;
5449
+ const config = loadMem0Config();
5450
+ const state = getNoticeState(config, noticeId);
5451
+ const nextState = appendNoticeCapEvent(state, event, options);
5452
+ if (!nextState) {
5453
+ markNoticeCapacityReachedInProcess(noticeId);
5454
+ return false;
5455
+ }
5456
+ const written = writeMem0ConfigAtomic(
5457
+ setNoticeState(config, noticeId, nextState)
5458
+ );
5459
+ if (written && !hasNoticeCapRoom(nextState, options)) {
5460
+ markNoticeCapacityReachedInProcess(noticeId);
5461
+ }
5462
+ return written;
5463
+ }
5464
+ function isFirstRunConsumed(config) {
5465
+ return getNoticeState(config, FIRST_RUN_NOTICE_ID).consumed === true;
5466
+ }
5467
+ function markFirstRunConsumed(triggerFunction, variant) {
5468
+ const config = loadMem0Config();
5469
+ const state = getNoticeState(config, FIRST_RUN_NOTICE_ID);
5470
+ const nextState = {
5471
+ ...state,
5472
+ consumed: true,
5473
+ consumed_at: (/* @__PURE__ */ new Date()).toISOString(),
5474
+ trigger_function: triggerFunction,
5475
+ variant
5476
+ };
5477
+ return writeMem0ConfigAtomic(
5478
+ setNoticeState(config, FIRST_RUN_NOTICE_ID, nextState)
5479
+ );
5480
+ }
5481
+ function getDisplayDecision(noticeId, expectedNoticeType, variant, payload) {
5482
+ var _a2;
5483
+ const parsed = getNoticeConfigFromPayload(payload, noticeId);
5484
+ const copy = typeof ((_a2 = parsed.config) == null ? void 0 : _a2.copy) === "string" ? parsed.config.copy : void 0;
5485
+ if (!parsed.found || !parsed.config) {
5486
+ return {
5487
+ displayed: false,
5488
+ noticeConfigFound: false,
5489
+ bypassReason: "missing_notice_config"
5490
+ };
5491
+ }
5492
+ const noticeConfig = parsed.config;
5493
+ if (noticeConfig.enabled === false) {
5494
+ return {
5495
+ displayed: false,
5496
+ noticeConfigFound: true,
5497
+ copy,
5498
+ bypassReason: "payload_disabled",
5499
+ disabledReason: "payload_disabled"
5500
+ };
5501
+ }
5502
+ if (noticeConfig.notice_type !== expectedNoticeType) {
5503
+ return {
5504
+ displayed: false,
5505
+ noticeConfigFound: true,
5506
+ copy,
5507
+ bypassReason: "invalid_notice_type"
5508
+ };
5509
+ }
5510
+ if (!copy || copy.trim() === "") {
5511
+ return {
5512
+ displayed: false,
5513
+ noticeConfigFound: true,
5514
+ bypassReason: "missing_copy"
5515
+ };
5516
+ }
5517
+ if (variant !== DISPLAYED_VARIANT) {
5518
+ return {
5519
+ displayed: false,
5520
+ noticeConfigFound: true,
5521
+ copy,
5522
+ bypassReason: "holdout"
5523
+ };
5524
+ }
5525
+ return {
5526
+ displayed: true,
5527
+ noticeConfigFound: true,
5528
+ copy
5529
+ };
5530
+ }
5531
+ function renderScaleCopy(template, trigger) {
5532
+ var _a2, _b2, _c;
5533
+ if (typeof template !== "string" || template.trim() === "") return void 0;
5534
+ return template.replace(/\{top_k\}/g, String((_a2 = trigger.topK) != null ? _a2 : "")).replace(/\{topK\}/g, String((_b2 = trigger.topK) != null ? _b2 : "")).replace(/\{memory_count\}/g, String((_c = trigger.memoryCount) != null ? _c : ""));
5535
+ }
5536
+ function getScaleDisplayDecision(variant, payload, trigger) {
5537
+ var _a2;
5538
+ const parsed = getNoticeConfigFromPayload(payload, SCALE_THRESHOLD_NOTICE_ID);
5539
+ const copies = ((_a2 = parsed.config) == null ? void 0 : _a2.copies) && typeof parsed.config.copies === "object" && !Array.isArray(parsed.config.copies) ? parsed.config.copies : {};
5540
+ const copyKey = trigger.triggerSource === "memory_count" ? "memory_count" : "top_k";
5541
+ const copy = renderScaleCopy(copies[copyKey], trigger);
5542
+ if (!parsed.found || !parsed.config) {
5543
+ return {
5544
+ displayed: false,
5545
+ noticeConfigFound: false,
5546
+ bypassReason: "missing_notice_config"
5547
+ };
5548
+ }
5549
+ const noticeConfig = parsed.config;
5550
+ if (noticeConfig.enabled === false) {
5551
+ return {
5552
+ displayed: false,
5553
+ noticeConfigFound: true,
5554
+ copy,
5555
+ bypassReason: "payload_disabled",
5556
+ disabledReason: "payload_disabled"
5557
+ };
5558
+ }
5559
+ if (noticeConfig.notice_type !== LOG_LINE_NOTICE_TYPE) {
5560
+ return {
5561
+ displayed: false,
5562
+ noticeConfigFound: true,
5563
+ copy,
5564
+ bypassReason: "invalid_notice_type"
5565
+ };
5566
+ }
5567
+ if (!copy || copy.trim() === "") {
5568
+ return {
5569
+ displayed: false,
5570
+ noticeConfigFound: true,
5571
+ bypassReason: "missing_copy"
5572
+ };
5573
+ }
5574
+ if (variant !== DISPLAYED_VARIANT) {
5575
+ return {
5576
+ displayed: false,
5577
+ noticeConfigFound: true,
5578
+ copy,
5579
+ bypassReason: "holdout"
5580
+ };
5581
+ }
5582
+ return {
5583
+ displayed: true,
5584
+ noticeConfigFound: true,
5585
+ copy
5586
+ };
5587
+ }
5588
+ function getFeatureErrorDecision(noticeId, expectedNoticeType, variant, payload) {
5589
+ var _a2;
5590
+ const parsed = getNoticeConfigFromPayload(payload, noticeId);
5591
+ const copy = typeof ((_a2 = parsed.config) == null ? void 0 : _a2.copy) === "string" ? parsed.config.copy : void 0;
5592
+ if (!parsed.found || !parsed.config) {
5593
+ return {
5594
+ displayed: false,
5595
+ noticeConfigFound: false,
5596
+ bypassReason: "missing_notice_config"
5597
+ };
5598
+ }
5599
+ const noticeConfig = parsed.config;
5600
+ if (noticeConfig.enabled === false) {
5601
+ return {
5602
+ displayed: false,
5603
+ noticeConfigFound: true,
5604
+ copy,
5605
+ bypassReason: "payload_disabled",
5606
+ disabledReason: "payload_disabled"
5607
+ };
5608
+ }
5609
+ if (noticeConfig.notice_type !== expectedNoticeType) {
5610
+ return {
5611
+ displayed: false,
5612
+ noticeConfigFound: true,
5613
+ copy,
5614
+ bypassReason: "invalid_notice_type"
5615
+ };
5616
+ }
5617
+ if (!copy || copy.trim() === "") {
5618
+ return {
5619
+ displayed: false,
5620
+ noticeConfigFound: true,
5621
+ bypassReason: "missing_copy"
5622
+ };
5623
+ }
5624
+ if (variant !== DISPLAYED_VARIANT && variant !== HOLDOUT_VARIANT) {
5625
+ return {
5626
+ displayed: false,
5627
+ noticeConfigFound: true,
5628
+ copy,
5629
+ bypassReason: "not_displayed"
5630
+ };
5631
+ }
5632
+ return {
5633
+ displayed: true,
5634
+ noticeConfigFound: true,
5635
+ copy
5636
+ };
5637
+ }
5638
+ async function getDecayFeatureErrorMessage(instance) {
5639
+ if (!isTelemetryEnabled()) return DECAY_FEATURE_PLAIN_ERROR;
5640
+ try {
5641
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
5642
+ if (!flagEvaluation) return DECAY_FEATURE_PLAIN_ERROR;
5643
+ const decision = getFeatureErrorDecision(
5644
+ DECAY_FEATURE_NOTICE_ID,
5645
+ ERROR_NOTICE_TYPE,
5646
+ flagEvaluation.variant,
5647
+ flagEvaluation.payload
5648
+ );
5649
+ await emitNoticeDisplayed(instance, {
5650
+ notice_id: DECAY_FEATURE_NOTICE_ID,
5651
+ notice_type: ERROR_NOTICE_TYPE,
5652
+ flag_key: NOTICE_FLAG_KEY,
5653
+ variant: flagEvaluation.variant,
5654
+ displayed: decision.displayed,
5655
+ payload: decision.copy,
5656
+ bypass_reason: decision.bypassReason,
5657
+ disabled_reason: decision.disabledReason,
5658
+ notice_config_found: decision.noticeConfigFound,
5659
+ sync_type: "async",
5660
+ trigger_function: "update_project",
5661
+ trigger_parameter: "decay"
5662
+ });
5663
+ if (decision.displayed && decision.copy) {
5664
+ return decision.copy;
5665
+ }
5666
+ } catch (e) {
5667
+ }
5668
+ return DECAY_FEATURE_PLAIN_ERROR;
5669
+ }
5670
+ async function getTemporalFeatureErrorMessage(instance, trigger) {
5671
+ const plainError = trigger.triggerParameter === "timestamp" ? TEMPORAL_TIMESTAMP_PLAIN_ERROR : TEMPORAL_REFERENCE_DATE_PLAIN_ERROR;
5672
+ if (!isTelemetryEnabled()) return plainError;
5673
+ try {
5674
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
5675
+ if (!flagEvaluation) return plainError;
5676
+ const decision = getFeatureErrorDecision(
5677
+ TEMPORAL_FEATURE_NOTICE_ID,
5678
+ ERROR_NOTICE_TYPE,
5679
+ flagEvaluation.variant,
5680
+ flagEvaluation.payload
5681
+ );
5682
+ await emitNoticeDisplayed(instance, {
5683
+ notice_id: TEMPORAL_FEATURE_NOTICE_ID,
5684
+ notice_type: ERROR_NOTICE_TYPE,
5685
+ flag_key: NOTICE_FLAG_KEY,
5686
+ variant: flagEvaluation.variant,
5687
+ displayed: decision.displayed,
5688
+ payload: decision.copy,
5689
+ bypass_reason: decision.bypassReason,
5690
+ disabled_reason: decision.disabledReason,
5691
+ notice_config_found: decision.noticeConfigFound,
5692
+ sync_type: "async",
5693
+ trigger_function: trigger.triggerFunction,
5694
+ trigger_parameter: trigger.triggerParameter
5695
+ });
5696
+ if (decision.displayed && decision.copy) {
5697
+ return decision.copy;
5698
+ }
5699
+ } catch (e) {
5700
+ }
5701
+ return plainError;
5702
+ }
5703
+ function getDecayUsageDeleteCountAfterSuccess() {
5704
+ if (!isTelemetryEnabled()) return 0;
5705
+ decayUsageSuccessfulDeleteCount += 1;
5706
+ return decayUsageSuccessfulDeleteCount;
5707
+ }
5708
+ function isDecayUsageDeleteEligible(deleteCount) {
5709
+ return deleteCount >= DECAY_USAGE_DELETE_THRESHOLD;
5710
+ }
5711
+ function isRecord(value) {
5712
+ return value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date);
5713
+ }
5714
+ function isTemporalKey(key) {
5715
+ const keyText = String(key).toLowerCase();
5716
+ return [
5717
+ "date",
5718
+ "time",
5719
+ "timestamp",
5720
+ "datetime",
5721
+ "event_date",
5722
+ "reference_date",
5723
+ "referencedate",
5724
+ "created_at",
5725
+ "createdat",
5726
+ "updated_at",
5727
+ "updatedat",
5728
+ "started_at",
5729
+ "startedat",
5730
+ "ended_at",
5731
+ "endedat",
5732
+ "expires_at",
5733
+ "expiresat"
5734
+ ].includes(keyText) || keyText.endsWith("_date") || keyText.endsWith("_time") || keyText.endsWith("_at") || keyText.includes("timestamp");
5735
+ }
5736
+ function looksTemporalValue(value, allowEpoch) {
5737
+ if (value instanceof Date) return !Number.isNaN(value.getTime());
5738
+ if (typeof value === "string") {
5739
+ return ISO_DATE_RE.test(value) || RELATIVE_TIME_RE.test(value);
5740
+ }
5741
+ if (allowEpoch && typeof value === "number" && Number.isFinite(value)) {
5742
+ return value >= 946684800 && value <= 4102444800 || value >= 9466848e5 && value <= 41024448e5;
5743
+ }
5744
+ return false;
5745
+ }
5746
+ function detectTemporalUsageFromMetadata(metadata) {
5747
+ try {
5748
+ if (!isRecord(metadata)) return null;
5749
+ const visited = /* @__PURE__ */ new WeakSet();
5750
+ const stack = [{ value: metadata, depth: 0 }];
5751
+ while (stack.length > 0) {
5752
+ const current = stack.pop();
5753
+ if (current.depth > MAX_TEMPORAL_DETECTION_DEPTH) continue;
5754
+ if (Array.isArray(current.value)) {
5755
+ for (const child of current.value) {
5756
+ if (looksTemporalValue(child, false)) {
5757
+ return {
5758
+ triggerSource: "metadata",
5759
+ triggerReason: "date_like_metadata"
5760
+ };
5761
+ }
5762
+ stack.push({
5763
+ value: child,
5764
+ parentKey: current.parentKey,
5765
+ depth: current.depth + 1
5766
+ });
5767
+ }
5768
+ continue;
5769
+ }
5770
+ if (!isRecord(current.value)) continue;
5771
+ if (visited.has(current.value)) continue;
5772
+ visited.add(current.value);
5773
+ for (const [key, value] of Object.entries(current.value)) {
5774
+ const temporalKey = isTemporalKey(key);
5775
+ if (temporalKey && looksTemporalValue(value, true) || looksTemporalValue(value, false)) {
5776
+ return {
5777
+ triggerSource: "metadata",
5778
+ triggerReason: "date_like_metadata"
5779
+ };
5780
+ }
5781
+ if (isRecord(value) || Array.isArray(value)) {
5782
+ stack.push({ value, parentKey: key, depth: current.depth + 1 });
5783
+ }
5784
+ }
5785
+ }
5786
+ } catch (e) {
5787
+ }
5788
+ return null;
5789
+ }
5790
+ function hasTemporalFilter(filters) {
5791
+ try {
5792
+ if (!isRecord(filters)) return false;
5793
+ const visited = /* @__PURE__ */ new WeakSet();
5794
+ const stack = [
5795
+ { value: filters, depth: 0 }
5796
+ ];
5797
+ while (stack.length > 0) {
5798
+ const current = stack.pop();
5799
+ if (current.depth > MAX_TEMPORAL_DETECTION_DEPTH) continue;
5800
+ if (Array.isArray(current.value)) {
5801
+ for (const child of current.value) {
5802
+ stack.push({ value: child, depth: current.depth + 1 });
5803
+ }
5804
+ continue;
5805
+ }
5806
+ if (!isRecord(current.value)) continue;
5807
+ if (visited.has(current.value)) continue;
5808
+ visited.add(current.value);
5809
+ for (const [key, value] of Object.entries(current.value)) {
5810
+ if (["AND", "OR", "NOT", "$and", "$or", "$not"].includes(key)) {
5811
+ if (isRecord(value) || Array.isArray(value)) {
5812
+ stack.push({ value, depth: current.depth + 1 });
5813
+ }
5814
+ continue;
5815
+ }
5816
+ const temporalKey = isTemporalKey(key);
5817
+ if (isRecord(value)) {
5818
+ const rangeValues = Object.entries(value).filter(([operator]) => RANGE_OPERATORS.has(operator)).map(([, rangeValue]) => rangeValue);
5819
+ if (rangeValues.length > 0 && (temporalKey || rangeValues.some(
5820
+ (rangeValue) => looksTemporalValue(rangeValue, temporalKey)
5821
+ ))) {
5822
+ return true;
5823
+ }
5824
+ stack.push({ value, depth: current.depth + 1 });
5825
+ } else if (temporalKey && looksTemporalValue(value, true)) {
5826
+ return true;
5827
+ }
5828
+ }
5829
+ }
5830
+ } catch (e) {
5831
+ }
5832
+ return false;
5833
+ }
5834
+ function detectTemporalUsageFromSearch(query, filters) {
5835
+ try {
5836
+ if (typeof query === "string") {
5837
+ if (RELATIVE_TIME_RE.test(query)) {
5838
+ return { triggerSource: "query", triggerReason: "relative_phrase" };
5839
+ }
5840
+ if (ISO_DATE_RE.test(query)) {
5841
+ return { triggerSource: "query", triggerReason: "date_like_query" };
5842
+ }
5843
+ }
5844
+ if (hasTemporalFilter(filters)) {
5845
+ return { triggerSource: "filter", triggerReason: "date_range_filter" };
5846
+ }
5847
+ } catch (e) {
5848
+ }
5849
+ return null;
5850
+ }
5851
+ function coerceNonnegativeInteger(value) {
5852
+ if (typeof value === "boolean") return null;
5853
+ const parsed = Number(value);
5854
+ if (!Number.isFinite(parsed) || !Number.isInteger(parsed) || parsed < 0) {
5855
+ return null;
5856
+ }
5857
+ return parsed;
5858
+ }
5859
+ function countAddedMemories(addResult) {
5860
+ const results = isRecord(addResult) && Array.isArray(addResult.results) ? addResult.results : addResult;
5861
+ if (!Array.isArray(results)) return 0;
5862
+ return results.filter((item) => {
5863
+ if (!isRecord(item)) return false;
5864
+ const metadata = item.metadata;
5865
+ return isRecord(metadata) && metadata.event === "ADD";
5866
+ }).length;
5867
+ }
5868
+ function extractProviderCount(info) {
5869
+ if (!info) return null;
5870
+ if (typeof info === "number") return coerceNonnegativeInteger(info);
5871
+ if (isRecord(info)) {
5872
+ for (const key of [
5873
+ "count",
5874
+ "points_count",
5875
+ "vectors_count",
5876
+ "indexed_vectors_count"
5877
+ ]) {
5878
+ const value = coerceNonnegativeInteger(info[key]);
5879
+ if (value !== null) return value;
5880
+ }
5881
+ const result = extractProviderCount(info.result);
5882
+ if (result !== null) return result;
5883
+ }
5884
+ return null;
5885
+ }
5886
+ async function getProviderMemoryCount(memoryInstance) {
5887
+ try {
5888
+ const vectorStore = memoryInstance == null ? void 0 : memoryInstance.vectorStore;
5889
+ if (!vectorStore) return null;
5890
+ if (typeof vectorStore.count === "function") {
5891
+ const value = extractProviderCount(await vectorStore.count());
5892
+ if (value !== null) return value;
5893
+ }
5894
+ const collectionName = vectorStore.collectionName;
5895
+ const client = vectorStore.client;
5896
+ if (client && collectionName && typeof client.count === "function") {
5897
+ const value = extractProviderCount(
5898
+ await client.count(collectionName, { exact: true })
5899
+ );
5900
+ if (value !== null) return value;
5901
+ }
5902
+ if (client && collectionName && typeof client.getCollection === "function") {
5903
+ const value = extractProviderCount(
5904
+ await client.getCollection(collectionName)
5905
+ );
5906
+ if (value !== null) return value;
5907
+ }
5908
+ } catch (e) {
5909
+ }
5910
+ return null;
5911
+ }
5912
+ function markScaleMemoryCountThresholdEvaluated() {
5913
+ try {
5914
+ const config = loadMem0Config();
5915
+ const state = getNoticeState(config, SCALE_THRESHOLD_NOTICE_ID);
5916
+ if (state.memory_count_threshold_evaluated === true) {
5917
+ scaleMemoryCountThresholdEvaluatedInProcess = true;
5918
+ return false;
5919
+ }
5920
+ const nextState = {
5921
+ ...state,
5922
+ memory_count_threshold_evaluated: true
5923
+ };
5924
+ const written = writeMem0ConfigAtomic(
5925
+ setNoticeState(config, SCALE_THRESHOLD_NOTICE_ID, nextState)
5926
+ );
5927
+ if (written) scaleMemoryCountThresholdEvaluatedInProcess = true;
5928
+ return written;
5929
+ } catch (e) {
5930
+ return false;
5931
+ }
5932
+ }
5933
+ function detectScaleThresholdFromTopK(topK) {
5934
+ const topKValue = coerceNonnegativeInteger(topK);
5935
+ if (topKValue === null || topKValue < SCALE_TOP_K_THRESHOLD) return null;
5936
+ return {
5937
+ triggerSource: "top_k",
5938
+ triggerReason: "high_top_k",
5939
+ topK: topKValue,
5940
+ threshold: SCALE_TOP_K_THRESHOLD
5941
+ };
5942
+ }
5943
+ async function detectScaleThresholdFromAddResult(memoryInstance, addResult) {
5944
+ if (!isTelemetryEnabled()) return null;
5945
+ const addedCount = countAddedMemories(addResult);
5946
+ if (addedCount === 0) return null;
5947
+ try {
5948
+ if (scaleMemoryCountThresholdEvaluatedInProcess) return null;
5949
+ scaleMemoryCountAddsSinceCheck += addedCount;
5950
+ const shouldCheck = !scaleMemoryCountCheckedInProcess || scaleMemoryCountAddsSinceCheck >= SCALE_MEMORY_COUNT_CHECK_INTERVAL;
5951
+ if (!shouldCheck) return null;
5952
+ scaleMemoryCountCheckedInProcess = true;
5953
+ scaleMemoryCountAddsSinceCheck = 0;
5954
+ const config = loadMem0Config();
5955
+ const state = getNoticeState(config, SCALE_THRESHOLD_NOTICE_ID);
5956
+ if (state.memory_count_threshold_evaluated === true) {
5957
+ scaleMemoryCountThresholdEvaluatedInProcess = true;
5958
+ return null;
5959
+ }
5960
+ if (!hasNoticeCapRoom(state)) return null;
5961
+ } catch (e) {
5962
+ return null;
5963
+ }
5964
+ const providerCount = await getProviderMemoryCount(memoryInstance);
5965
+ if (providerCount === null || providerCount < SCALE_MEMORY_COUNT_THRESHOLD) {
5966
+ return null;
5967
+ }
5968
+ if (!markScaleMemoryCountThresholdEvaluated()) return null;
5969
+ return {
5970
+ triggerSource: "memory_count",
5971
+ triggerReason: "memory_count_threshold",
5972
+ memoryCount: providerCount,
5973
+ threshold: SCALE_MEMORY_COUNT_THRESHOLD
5974
+ };
5975
+ }
5976
+ function detectPerformanceSlowQuery(elapsedMs, topK, resultCount) {
5977
+ const elapsedMsValue = coerceNonnegativeInteger(
5978
+ Math.round(Number(elapsedMs))
5979
+ );
5980
+ const topKValue = coerceNonnegativeInteger(topK);
5981
+ const resultCountValue = coerceNonnegativeInteger(resultCount);
5982
+ if (elapsedMsValue === null || topKValue === null || resultCountValue === null || elapsedMsValue <= PERFORMANCE_SLOW_QUERY_THRESHOLD_MS) {
5983
+ return null;
5984
+ }
5985
+ return {
5986
+ elapsedMs: elapsedMsValue,
5987
+ thresholdMs: PERFORMANCE_SLOW_QUERY_THRESHOLD_MS,
5988
+ topK: topKValue,
5989
+ resultCount: resultCountValue
5990
+ };
5991
+ }
5992
+ async function displayScaleThresholdNotice(instance, trigger) {
5993
+ if (!isTelemetryEnabled()) return;
5994
+ if (isNoticeCapacityReachedInProcess(SCALE_THRESHOLD_NOTICE_ID)) return;
5995
+ try {
5996
+ const config = loadMem0Config();
5997
+ const state = getNoticeState(config, SCALE_THRESHOLD_NOTICE_ID);
5998
+ if (!hasNoticeCapRoomForNotice(SCALE_THRESHOLD_NOTICE_ID, state)) return;
5999
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
6000
+ if (!flagEvaluation) return;
6001
+ const decision = getScaleDisplayDecision(
6002
+ flagEvaluation.variant,
6003
+ flagEvaluation.payload,
6004
+ trigger
6005
+ );
6006
+ const opportunity = {
6007
+ variant: flagEvaluation.variant,
6008
+ sync_type: "async",
6009
+ trigger_function: trigger.triggerFunction,
6010
+ trigger_source: trigger.triggerSource,
6011
+ trigger_reason: trigger.triggerReason,
6012
+ ...trigger.topK !== void 0 && { top_k: trigger.topK },
6013
+ ...trigger.memoryCount !== void 0 && {
6014
+ memory_count: trigger.memoryCount
6015
+ },
6016
+ threshold: trigger.threshold
6017
+ };
6018
+ if (!recordNoticeOpportunity(SCALE_THRESHOLD_NOTICE_ID, opportunity)) {
6019
+ return;
6020
+ }
6021
+ await emitNoticeDisplayed(instance, {
6022
+ notice_id: SCALE_THRESHOLD_NOTICE_ID,
6023
+ notice_type: LOG_LINE_NOTICE_TYPE,
6024
+ flag_key: NOTICE_FLAG_KEY,
6025
+ variant: flagEvaluation.variant,
6026
+ displayed: decision.displayed,
6027
+ payload: decision.copy,
6028
+ bypass_reason: decision.bypassReason,
6029
+ disabled_reason: decision.disabledReason,
6030
+ notice_config_found: decision.noticeConfigFound,
6031
+ sync_type: "async",
6032
+ trigger_function: trigger.triggerFunction,
6033
+ trigger_source: trigger.triggerSource,
6034
+ trigger_reason: trigger.triggerReason,
6035
+ top_k: trigger.topK,
6036
+ memory_count: trigger.memoryCount,
6037
+ threshold: trigger.threshold
6038
+ });
6039
+ if (decision.displayed && decision.copy) {
6040
+ process.stderr.write(`${decision.copy}
6041
+ `);
6042
+ }
6043
+ } catch (e) {
6044
+ }
6045
+ }
6046
+ async function displayPerformanceSlowQueryNotice(instance, trigger) {
6047
+ if (!isTelemetryEnabled()) return;
6048
+ if (isNoticeCapacityReachedInProcess(PERFORMANCE_SLOW_QUERY_NOTICE_ID)) {
6049
+ return;
6050
+ }
6051
+ try {
6052
+ const config = loadMem0Config();
6053
+ const state = getNoticeState(config, PERFORMANCE_SLOW_QUERY_NOTICE_ID);
6054
+ if (!hasNoticeCapRoomForNotice(PERFORMANCE_SLOW_QUERY_NOTICE_ID, state)) {
6055
+ return;
6056
+ }
6057
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
6058
+ if (!flagEvaluation) return;
6059
+ const decision = getDisplayDecision(
6060
+ PERFORMANCE_SLOW_QUERY_NOTICE_ID,
6061
+ LOG_LINE_NOTICE_TYPE,
6062
+ flagEvaluation.variant,
6063
+ flagEvaluation.payload
6064
+ );
6065
+ const opportunity = {
6066
+ variant: flagEvaluation.variant,
6067
+ sync_type: "async",
6068
+ trigger_function: trigger.triggerFunction,
6069
+ trigger_reason: trigger.triggerReason
6070
+ };
6071
+ if (!recordNoticeOpportunity(PERFORMANCE_SLOW_QUERY_NOTICE_ID, opportunity)) {
6072
+ return;
6073
+ }
6074
+ await emitNoticeDisplayed(instance, {
6075
+ notice_id: PERFORMANCE_SLOW_QUERY_NOTICE_ID,
6076
+ notice_type: LOG_LINE_NOTICE_TYPE,
6077
+ flag_key: NOTICE_FLAG_KEY,
6078
+ variant: flagEvaluation.variant,
6079
+ displayed: decision.displayed,
6080
+ payload: decision.copy,
6081
+ bypass_reason: decision.bypassReason,
6082
+ disabled_reason: decision.disabledReason,
6083
+ notice_config_found: decision.noticeConfigFound,
6084
+ sync_type: "async",
6085
+ trigger_function: trigger.triggerFunction,
6086
+ trigger_reason: trigger.triggerReason,
6087
+ elapsed_ms: trigger.elapsedMs,
6088
+ threshold_ms: trigger.thresholdMs,
6089
+ top_k: trigger.topK,
6090
+ result_count: trigger.resultCount
6091
+ });
6092
+ if (decision.displayed && decision.copy) {
6093
+ process.stderr.write(`${decision.copy}
6094
+ `);
6095
+ }
6096
+ } catch (e) {
6097
+ }
6098
+ }
6099
+ async function displayTemporalUsageNotice(instance, trigger) {
6100
+ if (!isTelemetryEnabled()) return;
6101
+ if (isNoticeCapacityReachedInProcess(TEMPORAL_USAGE_NOTICE_ID)) return;
6102
+ try {
6103
+ const config = loadMem0Config();
6104
+ const state = getNoticeState(config, TEMPORAL_USAGE_NOTICE_ID);
6105
+ if (!hasNoticeCapRoomForNotice(TEMPORAL_USAGE_NOTICE_ID, state)) return;
6106
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
6107
+ if (!flagEvaluation) return;
6108
+ const decision = getDisplayDecision(
6109
+ TEMPORAL_USAGE_NOTICE_ID,
6110
+ LOG_LINE_NOTICE_TYPE,
6111
+ flagEvaluation.variant,
6112
+ flagEvaluation.payload
6113
+ );
6114
+ const opportunity = {
6115
+ variant: flagEvaluation.variant,
6116
+ sync_type: "async",
6117
+ trigger_function: trigger.triggerFunction,
6118
+ trigger_source: trigger.triggerSource,
6119
+ trigger_reason: trigger.triggerReason
6120
+ };
6121
+ if (!recordNoticeOpportunity(TEMPORAL_USAGE_NOTICE_ID, opportunity)) {
6122
+ return;
6123
+ }
6124
+ await emitNoticeDisplayed(instance, {
6125
+ notice_id: TEMPORAL_USAGE_NOTICE_ID,
6126
+ notice_type: LOG_LINE_NOTICE_TYPE,
6127
+ flag_key: NOTICE_FLAG_KEY,
6128
+ variant: flagEvaluation.variant,
6129
+ displayed: decision.displayed,
6130
+ payload: decision.copy,
6131
+ bypass_reason: decision.bypassReason,
6132
+ disabled_reason: decision.disabledReason,
6133
+ notice_config_found: decision.noticeConfigFound,
6134
+ sync_type: "async",
6135
+ trigger_function: trigger.triggerFunction,
6136
+ trigger_source: trigger.triggerSource,
6137
+ trigger_reason: trigger.triggerReason
6138
+ });
6139
+ if (decision.displayed && decision.copy) {
6140
+ process.stderr.write(`${decision.copy}
6141
+ `);
6142
+ }
6143
+ } catch (e) {
6144
+ }
6145
+ }
6146
+ async function displayDecayUsageNotice(instance, trigger) {
6147
+ if (!isTelemetryEnabled()) return;
6148
+ if (isNoticeCapacityReachedInProcess(DECAY_USAGE_NOTICE_ID)) return;
6149
+ try {
6150
+ const config = loadMem0Config();
6151
+ const state = getNoticeState(config, DECAY_USAGE_NOTICE_ID);
6152
+ if (!hasNoticeCapRoomForNotice(DECAY_USAGE_NOTICE_ID, state)) return;
6153
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
6154
+ if (!flagEvaluation) return;
6155
+ const decision = getDisplayDecision(
6156
+ DECAY_USAGE_NOTICE_ID,
6157
+ LOG_LINE_NOTICE_TYPE,
6158
+ flagEvaluation.variant,
6159
+ flagEvaluation.payload
6160
+ );
6161
+ const opportunity = {
6162
+ variant: flagEvaluation.variant,
6163
+ sync_type: "async",
6164
+ trigger_function: trigger.triggerFunction,
6165
+ trigger_source: trigger.triggerSource,
6166
+ trigger_reason: trigger.triggerReason,
6167
+ ...trigger.deleteCount !== void 0 && {
6168
+ delete_count: trigger.deleteCount
6169
+ },
6170
+ ...trigger.deletedCount !== void 0 && {
6171
+ deleted_count: trigger.deletedCount
6172
+ }
6173
+ };
6174
+ if (!recordNoticeOpportunity(DECAY_USAGE_NOTICE_ID, opportunity)) {
6175
+ return;
6176
+ }
6177
+ await emitNoticeDisplayed(instance, {
6178
+ notice_id: DECAY_USAGE_NOTICE_ID,
6179
+ notice_type: LOG_LINE_NOTICE_TYPE,
6180
+ flag_key: NOTICE_FLAG_KEY,
6181
+ variant: flagEvaluation.variant,
6182
+ displayed: decision.displayed,
6183
+ payload: decision.copy,
6184
+ bypass_reason: decision.bypassReason,
6185
+ disabled_reason: decision.disabledReason,
6186
+ notice_config_found: decision.noticeConfigFound,
6187
+ sync_type: "async",
6188
+ trigger_function: trigger.triggerFunction,
6189
+ trigger_source: trigger.triggerSource,
6190
+ trigger_reason: trigger.triggerReason,
6191
+ ...trigger.deleteCount !== void 0 && {
6192
+ delete_count: trigger.deleteCount
6193
+ },
6194
+ ...trigger.deletedCount !== void 0 && {
6195
+ deleted_count: trigger.deletedCount
6196
+ }
6197
+ });
6198
+ if (decision.displayed && decision.copy) {
6199
+ process.stderr.write(`${decision.copy}
6200
+ `);
6201
+ }
6202
+ } catch (e) {
6203
+ }
6204
+ }
6205
+ async function displayFirstRunNotice(instance, triggerFunction) {
6206
+ if (!isTelemetryEnabled()) return;
6207
+ if (firstRunConsumedInProcess || firstRunClaimInProgress) return;
6208
+ const config = loadMem0Config();
6209
+ if (isFirstRunConsumed(config)) {
6210
+ firstRunConsumedInProcess = true;
6211
+ return;
6212
+ }
6213
+ firstRunClaimInProgress = true;
6214
+ try {
6215
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
6216
+ if (!flagEvaluation) {
6217
+ firstRunClaimInProgress = false;
6218
+ return;
6219
+ }
6220
+ const decision = getDisplayDecision(
6221
+ FIRST_RUN_NOTICE_ID,
6222
+ LOG_LINE_NOTICE_TYPE,
6223
+ flagEvaluation.variant,
6224
+ flagEvaluation.payload
6225
+ );
6226
+ firstRunConsumedInProcess = true;
6227
+ markFirstRunConsumed(triggerFunction, flagEvaluation.variant);
6228
+ await emitNoticeDisplayed(instance, {
6229
+ notice_id: FIRST_RUN_NOTICE_ID,
6230
+ notice_type: LOG_LINE_NOTICE_TYPE,
6231
+ flag_key: NOTICE_FLAG_KEY,
6232
+ variant: flagEvaluation.variant,
6233
+ displayed: decision.displayed,
6234
+ payload: decision.copy,
6235
+ bypass_reason: decision.bypassReason,
6236
+ disabled_reason: decision.disabledReason,
6237
+ notice_config_found: decision.noticeConfigFound,
6238
+ sync_type: "async",
6239
+ trigger_function: triggerFunction
6240
+ });
6241
+ if (decision.displayed && decision.copy) {
6242
+ process.stderr.write(`${decision.copy}
6243
+ `);
6244
+ }
6245
+ } catch (e) {
6246
+ if (!firstRunConsumedInProcess) firstRunClaimInProgress = false;
6247
+ } finally {
6248
+ if (firstRunConsumedInProcess) firstRunClaimInProgress = false;
6249
+ }
6250
+ }
6251
+ async function emitNoticeDisplayed(instance, properties) {
6252
+ if (!isTelemetryEnabled()) return;
6253
+ try {
6254
+ await captureNoticeEvent(instance, properties);
6255
+ } catch (e) {
6256
+ }
6257
+ }
5216
6258
 
5217
6259
  // src/oss/src/utils/lemmatization.ts
5218
6260
  var STOP_WORDS = /* @__PURE__ */ new Set([
@@ -5910,7 +6952,7 @@ function extractCompoundsRegex(text) {
5910
6952
  return entities;
5911
6953
  }
5912
6954
  function extractEntities(text) {
5913
- var _a2, _b;
6955
+ var _a2, _b2;
5914
6956
  const raw = [];
5915
6957
  raw.push(...extractQuoted(text));
5916
6958
  raw.push(...extractProper(text));
@@ -5953,7 +6995,7 @@ function extractEntities(text) {
5953
6995
  for (const entity of cleaned) {
5954
6996
  const key = entity.text.toLowerCase();
5955
6997
  const existing = best.get(key);
5956
- if (!existing || ((_a2 = typePriority[entity.type]) != null ? _a2 : 99) < ((_b = typePriority[existing.type]) != null ? _b : 99)) {
6998
+ if (!existing || ((_a2 = typePriority[entity.type]) != null ? _a2 : 99) < ((_b2 = typePriority[existing.type]) != null ? _b2 : 99)) {
5957
6999
  best.set(key, entity);
5958
7000
  }
5959
7001
  }
@@ -5989,8 +7031,8 @@ function getBm25Params(query, lemmatized) {
5989
7031
  function normalizeBm25(rawScore, midpoint, steepness) {
5990
7032
  return 1 / (1 + Math.exp(-steepness * (rawScore - midpoint)));
5991
7033
  }
5992
- function scoreAndRank(semanticResults, bm25Scores, entityBoosts, threshold, topK) {
5993
- var _a2, _b, _c;
7034
+ function scoreAndRank(semanticResults, bm25Scores, entityBoosts, threshold, topK, explain = false) {
7035
+ var _a2, _b2, _c;
5994
7036
  const hasBm25 = Object.keys(bm25Scores).length > 0;
5995
7037
  const hasEntity = Object.keys(entityBoosts).length > 0;
5996
7038
  let maxPossible = 1;
@@ -6011,15 +7053,27 @@ function scoreAndRank(semanticResults, bm25Scores, entityBoosts, threshold, topK
6011
7053
  continue;
6012
7054
  }
6013
7055
  const memIdStr = String(memId);
6014
- const bm25Score = (_b = bm25Scores[memIdStr]) != null ? _b : 0;
7056
+ const bm25Score = (_b2 = bm25Scores[memIdStr]) != null ? _b2 : 0;
6015
7057
  const entityBoost = (_c = entityBoosts[memIdStr]) != null ? _c : 0;
6016
7058
  const rawCombined = semanticScore + bm25Score + entityBoost;
6017
7059
  const combined = Math.min(rawCombined / maxPossible, 1);
6018
- scored.push({
7060
+ const entry = {
6019
7061
  id: memIdStr,
6020
7062
  score: combined,
6021
7063
  payload: result.payload
6022
- });
7064
+ };
7065
+ if (explain) {
7066
+ entry.scoreDetails = {
7067
+ semanticScore,
7068
+ bm25Score,
7069
+ entityBoost,
7070
+ rawScore: rawCombined,
7071
+ maxPossibleScore: maxPossible,
7072
+ finalScore: combined,
7073
+ threshold
7074
+ };
7075
+ }
7076
+ scored.push(entry);
6023
7077
  }
6024
7078
  scored.sort((a, b) => b.score - a.score);
6025
7079
  return scored.slice(0, topK);
@@ -6027,18 +7081,18 @@ function scoreAndRank(semanticResults, bm25Scores, entityBoosts, threshold, topK
6027
7081
 
6028
7082
  // src/client/config.ts
6029
7083
  async function getNodeFs() {
6030
- var _a2, _b, _c, _d, _e;
7084
+ var _a2, _b2, _c, _d, _e;
6031
7085
  if (typeof process === "undefined" || !((_a2 = process.versions) == null ? void 0 : _a2.node)) return null;
6032
7086
  try {
6033
- const [fs4, path3, os2, crypto] = await Promise.all([
7087
+ const [fs5, path4, os3, crypto] = await Promise.all([
6034
7088
  import("fs"),
6035
7089
  import("path"),
6036
7090
  import("os"),
6037
7091
  import("crypto")
6038
7092
  ]);
6039
- const fsMod = (_b = fs4.default) != null ? _b : fs4;
6040
- const pathMod = (_c = path3.default) != null ? _c : path3;
6041
- const osMod = (_d = os2.default) != null ? _d : os2;
7093
+ const fsMod = (_b2 = fs5.default) != null ? _b2 : fs5;
7094
+ const pathMod = (_c = path4.default) != null ? _c : path4;
7095
+ const osMod = (_d = os3.default) != null ? _d : os3;
6042
7096
  const cryptoMod = (_e = crypto.default) != null ? _e : crypto;
6043
7097
  const dir = process.env.MEM0_DIR || pathMod.join(osMod.homedir(), ".mem0");
6044
7098
  return {
@@ -6418,6 +7472,52 @@ var Memory = class _Memory {
6418
7472
  console.error(`Failed to capture ${methodName} event:`, error);
6419
7473
  }
6420
7474
  }
7475
+ async _displayFirstRunNotice(triggerFunction) {
7476
+ try {
7477
+ await this._getTelemetryId();
7478
+ await displayFirstRunNotice(this, triggerFunction);
7479
+ } catch (e) {
7480
+ }
7481
+ }
7482
+ async _displayDecayUsageNotice(trigger) {
7483
+ try {
7484
+ await this._getTelemetryId();
7485
+ await displayDecayUsageNotice(this, trigger);
7486
+ } catch (e) {
7487
+ }
7488
+ }
7489
+ async _displayTemporalUsageNotice(trigger) {
7490
+ try {
7491
+ await this._getTelemetryId();
7492
+ await displayTemporalUsageNotice(this, trigger);
7493
+ } catch (e) {
7494
+ }
7495
+ }
7496
+ async _displayScaleThresholdNotice(trigger) {
7497
+ try {
7498
+ await this._getTelemetryId();
7499
+ await displayScaleThresholdNotice(this, trigger);
7500
+ } catch (e) {
7501
+ }
7502
+ }
7503
+ async _displayPerformanceSlowQueryNotice(trigger) {
7504
+ try {
7505
+ await this._getTelemetryId();
7506
+ await displayPerformanceSlowQueryNotice(this, trigger);
7507
+ } catch (e) {
7508
+ }
7509
+ }
7510
+ async _getNoticeTelemetryId() {
7511
+ try {
7512
+ if (!this.telemetryId || this.telemetryId === "anonymous" || this.telemetryId === "anonymous-supabase") {
7513
+ this.telemetryId = await getOrCreateMem0UserId() || "anonymous";
7514
+ }
7515
+ return this.telemetryId;
7516
+ } catch (e) {
7517
+ this.telemetryId = "anonymous";
7518
+ return this.telemetryId;
7519
+ }
7520
+ }
6421
7521
  static fromConfig(configDict) {
6422
7522
  try {
6423
7523
  const config = MemoryConfigSchema.parse(configDict);
@@ -6427,12 +7527,31 @@ var Memory = class _Memory {
6427
7527
  throw e;
6428
7528
  }
6429
7529
  }
7530
+ async updateProject(options = {}) {
7531
+ if ((options == null ? void 0 : options.decay) === true) {
7532
+ await this._getNoticeTelemetryId();
7533
+ throw new Error(await getDecayFeatureErrorMessage(this));
7534
+ }
7535
+ throw new Error("Project updates are not supported by the OSS Memory SDK.");
7536
+ }
6430
7537
  async add(messages, config) {
7538
+ if ((config == null ? void 0 : config.timestamp) !== void 0) {
7539
+ await this._getNoticeTelemetryId();
7540
+ throw new Error(
7541
+ await getTemporalFeatureErrorMessage(this, {
7542
+ triggerFunction: "add",
7543
+ triggerParameter: "timestamp"
7544
+ })
7545
+ );
7546
+ }
6431
7547
  if (messages === void 0 || messages === null) {
6432
7548
  throw new Error(
6433
7549
  "messages is required and cannot be undefined or null. Provide a string or array of messages."
6434
7550
  );
6435
7551
  }
7552
+ const temporalUsageNotice = detectTemporalUsageFromMetadata(
7553
+ config == null ? void 0 : config.metadata
7554
+ );
6436
7555
  await this._ensureInitialized();
6437
7556
  await this._captureEvent("add", {
6438
7557
  message_count: Array.isArray(messages) ? messages.length : 1,
@@ -6460,12 +7579,32 @@ var Memory = class _Memory {
6460
7579
  filters,
6461
7580
  infer
6462
7581
  );
7582
+ if (temporalUsageNotice) {
7583
+ await this._displayTemporalUsageNotice({
7584
+ triggerFunction: "add",
7585
+ triggerSource: temporalUsageNotice.triggerSource,
7586
+ triggerReason: temporalUsageNotice.triggerReason
7587
+ });
7588
+ } else {
7589
+ const scaleThresholdNotice = await detectScaleThresholdFromAddResult(
7590
+ this,
7591
+ vectorStoreResult
7592
+ );
7593
+ if (scaleThresholdNotice) {
7594
+ await this._displayScaleThresholdNotice({
7595
+ triggerFunction: "add",
7596
+ ...scaleThresholdNotice
7597
+ });
7598
+ } else {
7599
+ await this._displayFirstRunNotice("add");
7600
+ }
7601
+ }
6463
7602
  return {
6464
7603
  results: vectorStoreResult
6465
7604
  };
6466
7605
  }
6467
7606
  async addToVectorStore(messages, metadata, filters, infer) {
6468
- var _a2, _b, _c, _d, _e, _f, _g;
7607
+ var _a2, _b2, _c, _d, _e, _f, _g;
6469
7608
  if (!infer) {
6470
7609
  const returnedMemories = [];
6471
7610
  for (const message of messages) {
@@ -6507,7 +7646,7 @@ var Memory = class _Memory {
6507
7646
  uuidMapping[String(idx)] = mem.id;
6508
7647
  existingMemories.push({
6509
7648
  id: String(idx),
6510
- text: (_b = (_a2 = mem.payload) == null ? void 0 : _a2.data) != null ? _b : ""
7649
+ text: (_b2 = (_a2 = mem.payload) == null ? void 0 : _a2.data) != null ? _b2 : ""
6511
7650
  });
6512
7651
  }
6513
7652
  const isAgentScoped = !!filters.agent_id && !filters.user_id;
@@ -6819,7 +7958,10 @@ var Memory = class _Memory {
6819
7958
  async get(memoryId) {
6820
7959
  await this._ensureInitialized();
6821
7960
  const memory = await this.vectorStore.get(memoryId);
6822
- if (!memory) return null;
7961
+ if (!memory) {
7962
+ await this._displayFirstRunNotice("get");
7963
+ return null;
7964
+ }
6823
7965
  const filters = {
6824
7966
  ...memory.payload.user_id && { user_id: memory.payload.user_id },
6825
7967
  ...memory.payload.agent_id && { agent_id: memory.payload.agent_id },
@@ -6849,10 +7991,25 @@ var Memory = class _Memory {
6849
7991
  memoryItem.metadata[key] = value;
6850
7992
  }
6851
7993
  }
6852
- return { ...memoryItem, ...filters };
7994
+ const result = { ...memoryItem, ...filters };
7995
+ await this._displayFirstRunNotice("get");
7996
+ return result;
6853
7997
  }
6854
7998
  async search(query, config) {
6855
- var _a2, _b, _c, _d, _e;
7999
+ var _a2, _b2, _c, _d, _e;
8000
+ if ((config == null ? void 0 : config.referenceDate) !== void 0) {
8001
+ await this._getNoticeTelemetryId();
8002
+ throw new Error(
8003
+ await getTemporalFeatureErrorMessage(this, {
8004
+ triggerFunction: "search",
8005
+ triggerParameter: "referenceDate"
8006
+ })
8007
+ );
8008
+ }
8009
+ const temporalUsageNotice = detectTemporalUsageFromSearch(
8010
+ query,
8011
+ config == null ? void 0 : config.filters
8012
+ );
6856
8013
  rejectTopLevelEntityParams(config, "search");
6857
8014
  validateSearchParams(config.threshold, config.topK);
6858
8015
  const normalizedFilters = config.filters ? Object.fromEntries(
@@ -6867,7 +8024,7 @@ var Memory = class _Memory {
6867
8024
  }).filter(([, v]) => v !== void 0)
6868
8025
  ) : {};
6869
8026
  await this._ensureInitialized();
6870
- const { topK = 20, threshold = 0.1 } = config;
8027
+ const { topK = 20, threshold = 0.1, explain = false } = config;
6871
8028
  await this._captureEvent("search", {
6872
8029
  query_length: query.length,
6873
8030
  topK,
@@ -6891,6 +8048,7 @@ var Memory = class _Memory {
6891
8048
  "filters must contain at least one of: user_id, agent_id, run_id. Example: filters: { user_id: 'u1' }"
6892
8049
  );
6893
8050
  }
8051
+ const searchStartMs = Date.now();
6894
8052
  const queryLemmatized = lemmatizeForBm25(query);
6895
8053
  const queryEntities = extractEntities(query);
6896
8054
  const queryEmbedding = await this.embedder.embed(query);
@@ -6917,7 +8075,7 @@ var Memory = class _Memory {
6917
8075
  const [midpoint, steepness] = getBm25Params(query, queryLemmatized);
6918
8076
  for (const mem of keywordResults) {
6919
8077
  const memId = String(mem.id);
6920
- const rawScore = (_b = mem.score) != null ? _b : 0;
8078
+ const rawScore = (_b2 = mem.score) != null ? _b2 : 0;
6921
8079
  if (rawScore > 0) {
6922
8080
  bm25Scores[memId] = normalizeBm25(rawScore, midpoint, steepness);
6923
8081
  }
@@ -6937,15 +8095,32 @@ var Memory = class _Memory {
6937
8095
  }
6938
8096
  if (deduped.length > 0) {
6939
8097
  const entityStore = await this.getEntityStore();
6940
- for (const entity of deduped) {
6941
- try {
6942
- const entityEmbedding = await this.embedder.embed(entity.text);
6943
- const matches = await entityStore.search(
6944
- entityEmbedding,
6945
- 500,
6946
- effectiveFilters
6947
- );
6948
- for (const match of matches) {
8098
+ const entitySearchFilters = {};
8099
+ for (const k of ["user_id", "agent_id", "run_id"]) {
8100
+ if (effectiveFilters[k])
8101
+ entitySearchFilters[k] = effectiveFilters[k];
8102
+ }
8103
+ const entityTexts = deduped.map((e) => e.text);
8104
+ const embeddings = await this.embedder.embedBatch(entityTexts);
8105
+ if (embeddings.length !== entityTexts.length) {
8106
+ console.warn(
8107
+ `embedBatch returned ${embeddings.length} vectors for ${entityTexts.length} texts \u2014 skipping entity boost`
8108
+ );
8109
+ } else {
8110
+ const searchResults = await Promise.allSettled(
8111
+ deduped.map(
8112
+ (_, i) => entityStore.search(embeddings[i], 500, entitySearchFilters)
8113
+ )
8114
+ );
8115
+ for (const result2 of searchResults) {
8116
+ if (result2.status === "rejected") {
8117
+ console.warn(
8118
+ "Entity boost search failed for one entity:",
8119
+ result2.reason
8120
+ );
8121
+ continue;
8122
+ }
8123
+ for (const match of result2.value) {
6949
8124
  const similarity = (_c = match.score) != null ? _c : 0;
6950
8125
  if (similarity < 0.5) continue;
6951
8126
  const payload = match.payload || {};
@@ -6964,7 +8139,6 @@ var Memory = class _Memory {
6964
8139
  }
6965
8140
  }
6966
8141
  }
6967
- } catch (e) {
6968
8142
  }
6969
8143
  }
6970
8144
  }
@@ -6985,7 +8159,8 @@ var Memory = class _Memory {
6985
8159
  bm25Scores,
6986
8160
  entityBoosts,
6987
8161
  threshold != null ? threshold : 0.1,
6988
- topK
8162
+ topK,
8163
+ explain
6989
8164
  );
6990
8165
  const excludedKeys = /* @__PURE__ */ new Set([
6991
8166
  "user_id",
@@ -7013,25 +8188,72 @@ var Memory = class _Memory {
7013
8188
  metadata: Object.entries(payload).filter(([key]) => !excludedKeys.has(key)).reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {}),
7014
8189
  ...payload.user_id && { user_id: payload.user_id },
7015
8190
  ...payload.agent_id && { agent_id: payload.agent_id },
7016
- ...payload.run_id && { run_id: payload.run_id }
8191
+ ...payload.run_id && { run_id: payload.run_id },
8192
+ ...scored.scoreDetails && { score_details: scored.scoreDetails }
7017
8193
  };
7018
8194
  });
7019
- return {
8195
+ const result = {
7020
8196
  results
7021
8197
  };
8198
+ const searchElapsedMs = Date.now() - searchStartMs;
8199
+ if (temporalUsageNotice) {
8200
+ await this._displayTemporalUsageNotice({
8201
+ triggerFunction: "search",
8202
+ triggerSource: temporalUsageNotice.triggerSource,
8203
+ triggerReason: temporalUsageNotice.triggerReason
8204
+ });
8205
+ } else {
8206
+ const scaleThresholdNotice = detectScaleThresholdFromTopK(topK);
8207
+ if (scaleThresholdNotice) {
8208
+ await this._displayScaleThresholdNotice({
8209
+ triggerFunction: "search",
8210
+ ...scaleThresholdNotice
8211
+ });
8212
+ } else {
8213
+ const performanceSlowQueryNotice = detectPerformanceSlowQuery(
8214
+ searchElapsedMs,
8215
+ topK,
8216
+ results.length
8217
+ );
8218
+ if (performanceSlowQueryNotice) {
8219
+ await this._displayPerformanceSlowQueryNotice({
8220
+ triggerFunction: "search",
8221
+ triggerReason: "slow_query",
8222
+ ...performanceSlowQueryNotice
8223
+ });
8224
+ } else {
8225
+ await this._displayFirstRunNotice("search");
8226
+ }
8227
+ }
8228
+ }
8229
+ return result;
7022
8230
  }
7023
8231
  async update(memoryId, data) {
7024
8232
  await this._ensureInitialized();
7025
8233
  await this._captureEvent("update", { memory_id: memoryId });
7026
8234
  const embedding = await this.embedder.embed(data);
7027
8235
  await this.updateMemory(memoryId, data, { [data]: embedding });
7028
- return { message: "Memory updated successfully!" };
8236
+ const result = { message: "Memory updated successfully!" };
8237
+ await this._displayFirstRunNotice("update");
8238
+ return result;
7029
8239
  }
7030
8240
  async delete(memoryId) {
7031
8241
  await this._ensureInitialized();
7032
8242
  await this._captureEvent("delete", { memory_id: memoryId });
7033
8243
  await this.deleteMemory(memoryId);
7034
- return { message: "Memory deleted successfully!" };
8244
+ const result = { message: "Memory deleted successfully!" };
8245
+ const deleteCount = getDecayUsageDeleteCountAfterSuccess();
8246
+ if (isDecayUsageDeleteEligible(deleteCount)) {
8247
+ await this._displayDecayUsageNotice({
8248
+ triggerFunction: "delete",
8249
+ triggerSource: "delete_count",
8250
+ triggerReason: "repeated_deletes",
8251
+ deleteCount
8252
+ });
8253
+ } else {
8254
+ await this._displayFirstRunNotice("delete");
8255
+ }
8256
+ return result;
7035
8257
  }
7036
8258
  async deleteAll(config) {
7037
8259
  await this._ensureInitialized();
@@ -7054,11 +8276,24 @@ var Memory = class _Memory {
7054
8276
  for (const memory of memories) {
7055
8277
  await this.deleteMemory(memory.id);
7056
8278
  }
7057
- return { message: "Memories deleted successfully!" };
8279
+ const result = { message: "Memories deleted successfully!" };
8280
+ if (memories.length > 0) {
8281
+ await this._displayDecayUsageNotice({
8282
+ triggerFunction: "delete_all",
8283
+ triggerSource: "delete_all",
8284
+ triggerReason: "bulk_delete",
8285
+ deletedCount: memories.length
8286
+ });
8287
+ } else {
8288
+ await this._displayFirstRunNotice("delete_all");
8289
+ }
8290
+ return result;
7058
8291
  }
7059
8292
  async history(memoryId) {
7060
8293
  await this._ensureInitialized();
7061
- return this.db.getHistory(memoryId);
8294
+ const result = await this.db.getHistory(memoryId);
8295
+ await this._displayFirstRunNotice("history");
8296
+ return result;
7062
8297
  }
7063
8298
  async reset() {
7064
8299
  await this._ensureInitialized();
@@ -7099,9 +8334,10 @@ var Memory = class _Memory {
7099
8334
  console.error(this._initError);
7100
8335
  });
7101
8336
  await this._initPromise;
8337
+ await this._displayFirstRunNotice("reset");
7102
8338
  }
7103
8339
  async getAll(config) {
7104
- var _a2, _b, _c;
8340
+ var _a2, _b2, _c;
7105
8341
  rejectTopLevelEntityParams(config, "getAll");
7106
8342
  validateSearchParams(void 0, config.topK);
7107
8343
  await this._ensureInitialized();
@@ -7110,7 +8346,7 @@ var Memory = class _Memory {
7110
8346
  Object.entries({
7111
8347
  ...config.filters || {},
7112
8348
  user_id: validateAndTrimEntityId((_a2 = config.filters) == null ? void 0 : _a2.user_id, "user_id"),
7113
- agent_id: validateAndTrimEntityId((_b = config.filters) == null ? void 0 : _b.agent_id, "agent_id"),
8349
+ agent_id: validateAndTrimEntityId((_b2 = config.filters) == null ? void 0 : _b2.agent_id, "agent_id"),
7114
8350
  run_id: validateAndTrimEntityId((_c = config.filters) == null ? void 0 : _c.run_id, "run_id")
7115
8351
  }).filter(([, v]) => v !== void 0)
7116
8352
  );
@@ -7148,7 +8384,17 @@ var Memory = class _Memory {
7148
8384
  ...mem.payload.agent_id && { agent_id: mem.payload.agent_id },
7149
8385
  ...mem.payload.run_id && { run_id: mem.payload.run_id }
7150
8386
  }));
7151
- return { results };
8387
+ const result = { results };
8388
+ const scaleThresholdNotice = detectScaleThresholdFromTopK(topK);
8389
+ if (scaleThresholdNotice) {
8390
+ await this._displayScaleThresholdNotice({
8391
+ triggerFunction: "get_all",
8392
+ ...scaleThresholdNotice
8393
+ });
8394
+ } else {
8395
+ await this._displayFirstRunNotice("get_all");
8396
+ }
8397
+ return result;
7152
8398
  }
7153
8399
  async createMemory(data, existingEmbeddings, metadata) {
7154
8400
  const memoryId = (0, import_uuid3.v4)();