mem0ai 3.0.7 → 3.0.9

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
@@ -99,7 +99,10 @@ var MemoryConfigSchema = import_zod.z.object({
99
99
  modelProperties: import_zod.z.record(import_zod.z.string(), import_zod.z.any()).optional(),
100
100
  baseURL: import_zod.z.string().optional(),
101
101
  url: import_zod.z.string().optional(),
102
- timeout: import_zod.z.number().optional()
102
+ timeout: import_zod.z.number().optional(),
103
+ temperature: import_zod.z.number().optional(),
104
+ topP: import_zod.z.number().optional(),
105
+ maxTokens: import_zod.z.number().optional()
103
106
  })
104
107
  }),
105
108
  historyDbPath: import_zod.z.string().optional(),
@@ -228,8 +231,8 @@ var DEFAULT_MODEL = "nomic-ai/nomic-embed-text-v1.5-GGUF/nomic-embed-text-v1.5.f
228
231
  var DEFAULT_LMSTUDIO_API_KEY = "lm-studio";
229
232
  var LMStudioEmbedder = class {
230
233
  constructor(config) {
231
- var _a2, _b;
232
- const baseURL = (_b = (_a2 = config.baseURL) != null ? _a2 : config.url) != null ? _b : DEFAULT_BASE_URL;
234
+ var _a2, _b2;
235
+ const baseURL = (_b2 = (_a2 = config.baseURL) != null ? _a2 : config.url) != null ? _b2 : DEFAULT_BASE_URL;
233
236
  const apiKey = config.apiKey || DEFAULT_LMSTUDIO_API_KEY;
234
237
  this.openai = new import_openai2.default({ apiKey, baseURL: String(baseURL) });
235
238
  this.model = config.model || DEFAULT_MODEL;
@@ -389,25 +392,54 @@ var OpenAIStructuredLLM = class {
389
392
  var import_sdk = __toESM(require("@anthropic-ai/sdk"));
390
393
  var AnthropicLLM = class {
391
394
  constructor(config) {
395
+ var _a2, _b2;
392
396
  const apiKey = config.apiKey || process.env.ANTHROPIC_API_KEY;
393
397
  if (!apiKey) {
394
398
  throw new Error("Anthropic API key is required");
395
399
  }
396
400
  this.client = new import_sdk.default({ apiKey });
397
- this.model = config.model || "claude-3-sonnet-20240229";
401
+ this.model = config.model || "claude-sonnet-4-6";
402
+ this.maxTokens = (_a2 = config.maxTokens) != null ? _a2 : 2e3;
403
+ this.temperature = (_b2 = config.temperature) != null ? _b2 : 0.1;
404
+ this.topP = config.topP;
398
405
  }
399
- async generateResponse(messages, responseFormat) {
406
+ async generateResponse(messages, responseFormat, tools) {
400
407
  const systemMessage = messages.find((msg) => msg.role === "system");
401
408
  const otherMessages = messages.filter((msg) => msg.role !== "system");
402
- const response = await this.client.messages.create({
409
+ const params = {
403
410
  model: this.model,
404
411
  messages: otherMessages.map((msg) => ({
405
412
  role: msg.role,
406
413
  content: typeof msg.content === "string" ? msg.content : msg.content.image_url.url
407
414
  })),
408
415
  system: typeof (systemMessage == null ? void 0 : systemMessage.content) === "string" ? systemMessage.content : void 0,
409
- max_tokens: 4096
410
- });
416
+ max_tokens: this.maxTokens
417
+ };
418
+ if (this.temperature !== void 0) {
419
+ params.temperature = this.temperature;
420
+ } else if (this.topP !== void 0) {
421
+ params.top_p = this.topP;
422
+ }
423
+ if (tools) {
424
+ params.tools = tools;
425
+ params.tool_choice = { type: "auto" };
426
+ }
427
+ const response = await this.client.messages.create(params);
428
+ if (tools) {
429
+ let content = "";
430
+ const toolCalls = [];
431
+ for (const block of response.content) {
432
+ if (block.type === "text") {
433
+ content = block.text;
434
+ } else if (block.type === "tool_use") {
435
+ toolCalls.push({
436
+ name: block.name,
437
+ arguments: JSON.stringify(block.input)
438
+ });
439
+ }
440
+ }
441
+ return { content, role: "assistant", toolCalls };
442
+ }
411
443
  const firstBlock = response.content[0];
412
444
  if (firstBlock.type === "text") {
413
445
  return firstBlock.text;
@@ -417,10 +449,10 @@ var AnthropicLLM = class {
417
449
  }
418
450
  async generateChat(messages) {
419
451
  const response = await this.generateResponse(messages);
420
- return {
421
- content: response,
422
- role: "assistant"
423
- };
452
+ if (typeof response === "string") {
453
+ return { content: response, role: "assistant" };
454
+ }
455
+ return response;
424
456
  }
425
457
  };
426
458
 
@@ -1223,7 +1255,7 @@ var Qdrant = class {
1223
1255
  }
1224
1256
  }
1225
1257
  async ensureCollection(name, size) {
1226
- var _a2, _b, _c;
1258
+ var _a2, _b2, _c;
1227
1259
  try {
1228
1260
  await this.client.createCollection(name, {
1229
1261
  vectors: {
@@ -1236,7 +1268,7 @@ var Qdrant = class {
1236
1268
  if (name === this.collectionName) {
1237
1269
  try {
1238
1270
  const collectionInfo = await this.client.getCollection(name);
1239
- const vectorConfig = (_b = (_a2 = collectionInfo.config) == null ? void 0 : _a2.params) == null ? void 0 : _b.vectors;
1271
+ const vectorConfig = (_b2 = (_a2 = collectionInfo.config) == null ? void 0 : _a2.params) == null ? void 0 : _b2.vectors;
1240
1272
  if (vectorConfig && vectorConfig.size !== size) {
1241
1273
  throw new Error(
1242
1274
  `Collection ${name} exists but has wrong vector size. Expected: ${size}, got: ${vectorConfig.size}`
@@ -1323,7 +1355,7 @@ var VectorizeDB = class {
1323
1355
  return null;
1324
1356
  }
1325
1357
  async search(query, topK = 5, filters) {
1326
- var _a2, _b;
1358
+ var _a2, _b2;
1327
1359
  try {
1328
1360
  const result = await ((_a2 = this.client) == null ? void 0 : _a2.vectorize.indexes.query(
1329
1361
  this.indexName,
@@ -1335,7 +1367,7 @@ var VectorizeDB = class {
1335
1367
  topK
1336
1368
  }
1337
1369
  ));
1338
- return ((_b = result == null ? void 0 : result.matches) == null ? void 0 : _b.map((match) => ({
1370
+ return ((_b2 = result == null ? void 0 : result.matches) == null ? void 0 : _b2.map((match) => ({
1339
1371
  id: match.id,
1340
1372
  payload: match.metadata,
1341
1373
  score: match.score
@@ -1430,7 +1462,7 @@ var VectorizeDB = class {
1430
1462
  }
1431
1463
  }
1432
1464
  async list(filters, topK = 20) {
1433
- var _a2, _b;
1465
+ var _a2, _b2;
1434
1466
  try {
1435
1467
  const result = await ((_a2 = this.client) == null ? void 0 : _a2.vectorize.indexes.query(
1436
1468
  this.indexName,
@@ -1443,7 +1475,7 @@ var VectorizeDB = class {
1443
1475
  returnMetadata: "all"
1444
1476
  }
1445
1477
  ));
1446
- const matches = ((_b = result == null ? void 0 : result.matches) == null ? void 0 : _b.map((match) => ({
1478
+ const matches = ((_b2 = result == null ? void 0 : result.matches) == null ? void 0 : _b2.map((match) => ({
1447
1479
  id: match.id,
1448
1480
  payload: match.metadata,
1449
1481
  score: match.score
@@ -1467,7 +1499,7 @@ var VectorizeDB = class {
1467
1499
  );
1468
1500
  }
1469
1501
  async getUserId() {
1470
- var _a2, _b, _c;
1502
+ var _a2, _b2, _c;
1471
1503
  try {
1472
1504
  let found = false;
1473
1505
  for await (const index of this.client.vectorize.indexes.list({
@@ -1487,7 +1519,7 @@ var VectorizeDB = class {
1487
1519
  }
1488
1520
  }));
1489
1521
  }
1490
- const result = await ((_b = this.client) == null ? void 0 : _b.vectorize.indexes.query(
1522
+ const result = await ((_b2 = this.client) == null ? void 0 : _b2.vectorize.indexes.query(
1491
1523
  "memory_migrations",
1492
1524
  {
1493
1525
  account_id: this.accountId,
@@ -1526,7 +1558,7 @@ var VectorizeDB = class {
1526
1558
  }
1527
1559
  }
1528
1560
  async setUserId(userId) {
1529
- var _a2, _b;
1561
+ var _a2, _b2;
1530
1562
  try {
1531
1563
  const result = await ((_a2 = this.client) == null ? void 0 : _a2.vectorize.indexes.query(
1532
1564
  "memory_migrations",
@@ -1549,7 +1581,7 @@ var VectorizeDB = class {
1549
1581
  method: "POST",
1550
1582
  headers: {
1551
1583
  "Content-Type": "application/x-ndjson",
1552
- Authorization: `Bearer ${(_b = this.client) == null ? void 0 : _b.apiToken}`
1584
+ Authorization: `Bearer ${(_b2 = this.client) == null ? void 0 : _b2.apiToken}`
1553
1585
  },
1554
1586
  body: JSON.stringify(data) + "\n"
1555
1587
  // ndjson format
@@ -1569,7 +1601,7 @@ var VectorizeDB = class {
1569
1601
  return this._initPromise;
1570
1602
  }
1571
1603
  async _doInitialize() {
1572
- var _a2, _b, _c, _d, _e;
1604
+ var _a2, _b2, _c, _d, _e;
1573
1605
  try {
1574
1606
  let indexFound = false;
1575
1607
  for await (const idx of this.client.vectorize.indexes.list({
@@ -1592,7 +1624,7 @@ var VectorizeDB = class {
1592
1624
  }));
1593
1625
  const properties2 = ["userId", "agentId", "runId"];
1594
1626
  for (const propertyName of properties2) {
1595
- await ((_b = this.client) == null ? void 0 : _b.vectorize.indexes.metadataIndex.create(
1627
+ await ((_b2 = this.client) == null ? void 0 : _b2.vectorize.indexes.metadataIndex.create(
1596
1628
  this.indexName,
1597
1629
  {
1598
1630
  account_id: this.accountId,
@@ -2645,7 +2677,7 @@ var SQLiteManager = class {
2645
2677
  }
2646
2678
  async batchAddHistory(records) {
2647
2679
  const txn = this.db.transaction(() => {
2648
- var _a2, _b, _c;
2680
+ var _a2, _b2, _c;
2649
2681
  for (const record of records) {
2650
2682
  this.stmtInsert.run(
2651
2683
  record.memoryId,
@@ -2653,7 +2685,7 @@ var SQLiteManager = class {
2653
2685
  record.newValue,
2654
2686
  record.action,
2655
2687
  (_a2 = record.createdAt) != null ? _a2 : null,
2656
- (_b = record.updatedAt) != null ? _b : null,
2688
+ (_b2 = record.updatedAt) != null ? _b2 : null,
2657
2689
  (_c = record.isDeleted) != null ? _c : 0
2658
2690
  );
2659
2691
  }
@@ -3501,12 +3533,12 @@ function truncateContent(text, limit = PAST_MESSAGE_TRUNCATION_LIMIT) {
3501
3533
  return text.slice(0, limit) + "...";
3502
3534
  }
3503
3535
  function formatConversationHistory(messages) {
3504
- var _a2, _b;
3536
+ var _a2, _b2;
3505
3537
  if (!messages || messages.length === 0) return "";
3506
3538
  let result = "";
3507
3539
  for (const msg of messages) {
3508
3540
  const role = (_a2 = msg.role) != null ? _a2 : "";
3509
- const content = (_b = msg.content) != null ? _b : "";
3541
+ const content = (_b2 = msg.content) != null ? _b2 : "";
3510
3542
  if (role && content) {
3511
3543
  result += `${role}: ${truncateContent(content)}
3512
3544
  `;
@@ -3518,10 +3550,10 @@ function serializeMemories(memories) {
3518
3550
  return JSON.stringify(memories != null ? memories : []);
3519
3551
  }
3520
3552
  function generateAdditiveExtractionPrompt(options) {
3521
- var _a2, _b, _c;
3553
+ var _a2, _b2, _c;
3522
3554
  const now = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
3523
3555
  const currentDate = (_a2 = options.currentDate) != null ? _a2 : now;
3524
- const observationDate = (_b = options.observationDate) != null ? _b : currentDate;
3556
+ const observationDate = (_b2 = options.observationDate) != null ? _b2 : currentDate;
3525
3557
  const sections = [];
3526
3558
  sections.push("## Summary\n");
3527
3559
  sections.push(
@@ -3692,14 +3724,14 @@ var LangchainLLM = class {
3692
3724
  this.modelName = this.llmInstance.modelId || this.llmInstance.model || "langchain-model";
3693
3725
  }
3694
3726
  async generateResponse(messages, response_format, tools) {
3695
- var _a2, _b, _c, _d, _e;
3727
+ var _a2, _b2, _c, _d, _e;
3696
3728
  const langchainMessages = convertToLangchainMessages(messages);
3697
3729
  let runnable = this.llmInstance;
3698
3730
  const invokeOptions = {};
3699
3731
  let isStructuredOutput = false;
3700
3732
  let selectedSchema = null;
3701
3733
  const systemPromptContent = ((_a2 = messages.find((m) => m.role === "system")) == null ? void 0 : _a2.content) || "";
3702
- const userPromptContent = ((_b = messages.find((m) => m.role === "user")) == null ? void 0 : _b.content) || "";
3734
+ const userPromptContent = ((_b2 = messages.find((m) => m.role === "user")) == null ? void 0 : _b2.content) || "";
3703
3735
  if (systemPromptContent.includes("Personal Information Organizer") && systemPromptContent.includes("extract relevant pieces of information")) {
3704
3736
  selectedSchema = FactRetrievalSchema;
3705
3737
  } else if (userPromptContent.includes("smart memory manager") && userPromptContent.includes("Compare newly retrieved facts")) {
@@ -3829,7 +3861,7 @@ var LangchainVectorStore = class {
3829
3861
  // Simple in-memory user ID
3830
3862
  constructor(config) {
3831
3863
  this.storeUserId = "anonymous-langchain-user";
3832
- var _a2, _b;
3864
+ var _a2, _b2;
3833
3865
  if (!config.client || typeof config.client !== "object") {
3834
3866
  throw new Error(
3835
3867
  "Langchain vector store provider requires an initialized Langchain VectorStore instance passed via the 'client' field."
@@ -3845,7 +3877,7 @@ var LangchainVectorStore = class {
3845
3877
  if (!this.dimension && ((_a2 = this.lcStore.embeddings) == null ? void 0 : _a2.embeddingDimension)) {
3846
3878
  this.dimension = this.lcStore.embeddings.embeddingDimension;
3847
3879
  }
3848
- if (!this.dimension && ((_b = this.lcStore.embedding) == null ? void 0 : _b.embeddingDimension)) {
3880
+ if (!this.dimension && ((_b2 = this.lcStore.embedding) == null ? void 0 : _b2.embeddingDimension)) {
3849
3881
  this.dimension = this.lcStore.embedding.embeddingDimension;
3850
3882
  }
3851
3883
  if (!this.dimension) {
@@ -4987,13 +5019,13 @@ var DEFAULT_MEMORY_CONFIG = {
4987
5019
  // src/oss/src/config/manager.ts
4988
5020
  var ConfigManager = class {
4989
5021
  static mergeConfig(userConfig = {}) {
4990
- var _a2, _b, _c, _d, _e, _f, _g;
5022
+ var _a2, _b2, _c, _d, _e, _f, _g;
4991
5023
  const mergedConfig = {
4992
5024
  version: userConfig.version || DEFAULT_MEMORY_CONFIG.version,
4993
5025
  embedder: {
4994
5026
  provider: ((_a2 = userConfig.embedder) == null ? void 0 : _a2.provider) || DEFAULT_MEMORY_CONFIG.embedder.provider,
4995
5027
  config: (() => {
4996
- var _a3, _b2, _c2, _d2;
5028
+ var _a3, _b3, _c2, _d2;
4997
5029
  const defaultConf = DEFAULT_MEMORY_CONFIG.embedder.config;
4998
5030
  const userConf = (_a3 = userConfig.embedder) == null ? void 0 : _a3.config;
4999
5031
  let finalModel = defaultConf.model;
@@ -5002,7 +5034,7 @@ var ConfigManager = class {
5002
5034
  } else if ((userConf == null ? void 0 : userConf.model) && typeof userConf.model === "string") {
5003
5035
  finalModel = userConf.model;
5004
5036
  }
5005
- 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;
5037
+ 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;
5006
5038
  const embeddingDims = (_d2 = userConf == null ? void 0 : userConf.embeddingDims) != null ? _d2 : userConf == null ? void 0 : userConf.embedding_dims;
5007
5039
  return {
5008
5040
  apiKey: (userConf == null ? void 0 : userConf.apiKey) !== void 0 ? userConf.apiKey : defaultConf.apiKey,
@@ -5015,12 +5047,12 @@ var ConfigManager = class {
5015
5047
  })()
5016
5048
  },
5017
5049
  vectorStore: {
5018
- provider: ((_b = userConfig.vectorStore) == null ? void 0 : _b.provider) || DEFAULT_MEMORY_CONFIG.vectorStore.provider,
5050
+ provider: ((_b2 = userConfig.vectorStore) == null ? void 0 : _b2.provider) || DEFAULT_MEMORY_CONFIG.vectorStore.provider,
5019
5051
  config: (() => {
5020
- var _a3, _b2, _c2;
5052
+ var _a3, _b3, _c2;
5021
5053
  const defaultConf = DEFAULT_MEMORY_CONFIG.vectorStore.config;
5022
5054
  const userConf = (_a3 = userConfig.vectorStore) == null ? void 0 : _a3.config;
5023
- const explicitDimension = (userConf == null ? void 0 : userConf.dimension) || ((_c2 = (_b2 = userConfig.embedder) == null ? void 0 : _b2.config) == null ? void 0 : _c2.embeddingDims) || void 0;
5055
+ const explicitDimension = (userConf == null ? void 0 : userConf.dimension) || ((_c2 = (_b3 = userConfig.embedder) == null ? void 0 : _b3.config) == null ? void 0 : _c2.embeddingDims) || void 0;
5024
5056
  if ((userConf == null ? void 0 : userConf.client) && typeof userConf.client === "object") {
5025
5057
  return {
5026
5058
  client: userConf.client,
@@ -5044,7 +5076,7 @@ var ConfigManager = class {
5044
5076
  llm: {
5045
5077
  provider: ((_c = userConfig.llm) == null ? void 0 : _c.provider) || DEFAULT_MEMORY_CONFIG.llm.provider,
5046
5078
  config: (() => {
5047
- var _a3, _b2, _c2, _d2;
5079
+ var _a3, _b3, _c2, _d2, _e2, _f2, _g2;
5048
5080
  const defaultConf = DEFAULT_MEMORY_CONFIG.llm.config;
5049
5081
  const userConf = (_a3 = userConfig.llm) == null ? void 0 : _a3.config;
5050
5082
  let finalModel = defaultConf.model;
@@ -5053,20 +5085,27 @@ var ConfigManager = class {
5053
5085
  } else if ((userConf == null ? void 0 : userConf.model) && typeof userConf.model === "string") {
5054
5086
  finalModel = userConf.model;
5055
5087
  }
5056
- 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;
5088
+ 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;
5089
+ const llmRaw = userConf;
5090
+ const temperature = (_e2 = userConf == null ? void 0 : userConf.temperature) != null ? _e2 : llmRaw == null ? void 0 : llmRaw.temperature;
5091
+ const topP = (_f2 = userConf == null ? void 0 : userConf.topP) != null ? _f2 : llmRaw == null ? void 0 : llmRaw.top_p;
5092
+ const maxTokens = (_g2 = userConf == null ? void 0 : userConf.maxTokens) != null ? _g2 : llmRaw == null ? void 0 : llmRaw.max_tokens;
5057
5093
  return {
5058
5094
  baseURL: llmBaseURL,
5059
5095
  url: userConf == null ? void 0 : userConf.url,
5060
5096
  apiKey: (userConf == null ? void 0 : userConf.apiKey) !== void 0 ? userConf.apiKey : defaultConf.apiKey,
5061
5097
  model: finalModel,
5062
- modelProperties: (userConf == null ? void 0 : userConf.modelProperties) !== void 0 ? userConf.modelProperties : defaultConf.modelProperties
5098
+ modelProperties: (userConf == null ? void 0 : userConf.modelProperties) !== void 0 ? userConf.modelProperties : defaultConf.modelProperties,
5099
+ temperature,
5100
+ topP,
5101
+ maxTokens
5063
5102
  };
5064
5103
  })()
5065
5104
  },
5066
5105
  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),
5067
5106
  customInstructions: userConfig.customInstructions,
5068
5107
  historyStore: (() => {
5069
- var _a3, _b2;
5108
+ var _a3, _b3;
5070
5109
  const defaultHistoryStore = DEFAULT_MEMORY_CONFIG.historyStore;
5071
5110
  const historyProvider = ((_a3 = userConfig.historyStore) == null ? void 0 : _a3.provider) || defaultHistoryStore.provider;
5072
5111
  const isSqlite = historyProvider.toLowerCase() === "sqlite";
@@ -5077,7 +5116,7 @@ var ConfigManager = class {
5077
5116
  config: {
5078
5117
  ...isSqlite ? defaultHistoryStore.config : {},
5079
5118
  ...isSqlite && userConfig.historyDbPath ? { historyDbPath: userConfig.historyDbPath } : {},
5080
- ...(_b2 = userConfig.historyStore) == null ? void 0 : _b2.config
5119
+ ...(_b3 = userConfig.historyStore) == null ? void 0 : _b3.config
5081
5120
  }
5082
5121
  };
5083
5122
  })(),
@@ -5125,15 +5164,16 @@ var parse_vision_messages = async (messages) => {
5125
5164
  };
5126
5165
 
5127
5166
  // src/oss/src/utils/telemetry.ts
5128
- var version = true ? "3.0.7" : "dev";
5167
+ var version = true ? "3.0.9" : "dev";
5129
5168
  var MEM0_TELEMETRY = true;
5130
- var _a;
5169
+ var _a, _b;
5131
5170
  try {
5132
- MEM0_TELEMETRY = ((_a = process == null ? void 0 : process.env) == null ? void 0 : _a.MEM0_TELEMETRY) === "false" ? false : true;
5171
+ MEM0_TELEMETRY = ((_b = (_a = process == null ? void 0 : process.env) == null ? void 0 : _a.MEM0_TELEMETRY) == null ? void 0 : _b.toLowerCase()) === "false" ? false : true;
5133
5172
  } catch (error) {
5134
5173
  }
5135
5174
  var POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX";
5136
5175
  var POSTHOG_HOST = "https://us.i.posthog.com/i/v0/e/";
5176
+ var NOTICE_EVENT_NAME = "mem0.notice_displayed";
5137
5177
  var DEFAULT_SAMPLE_RATE = 0.1;
5138
5178
  var MEM0_TELEMETRY_SAMPLE_RATE = (() => {
5139
5179
  var _a2;
@@ -5149,7 +5189,11 @@ var MEM0_TELEMETRY_SAMPLE_RATE = (() => {
5149
5189
  }
5150
5190
  return DEFAULT_SAMPLE_RATE;
5151
5191
  })();
5152
- var LIFECYCLE_EVENTS = /* @__PURE__ */ new Set(["init", "reset"]);
5192
+ var ALWAYS_SEND_EVENTS = /* @__PURE__ */ new Set([
5193
+ "init",
5194
+ "reset",
5195
+ "notice_displayed"
5196
+ ]);
5153
5197
  var UnifiedTelemetry = class {
5154
5198
  constructor(projectApiKey, host) {
5155
5199
  this.apiKey = projectApiKey;
@@ -5189,13 +5233,16 @@ var UnifiedTelemetry = class {
5189
5233
  }
5190
5234
  };
5191
5235
  var telemetry = new UnifiedTelemetry(POSTHOG_API_KEY, POSTHOG_HOST);
5236
+ function isTelemetryEnabled() {
5237
+ return MEM0_TELEMETRY;
5238
+ }
5192
5239
  async function captureClientEvent(eventName, instance, additionalData = {}) {
5193
5240
  if (!instance.telemetryId) {
5194
5241
  console.warn("No telemetry ID found for instance");
5195
5242
  return;
5196
5243
  }
5197
- const isLifecycle = LIFECYCLE_EVENTS.has(eventName);
5198
- if (!isLifecycle && Math.random() >= MEM0_TELEMETRY_SAMPLE_RATE) {
5244
+ const alwaysSend = ALWAYS_SEND_EVENTS.has(eventName);
5245
+ if (!alwaysSend && Math.random() >= MEM0_TELEMETRY_SAMPLE_RATE) {
5199
5246
  return;
5200
5247
  }
5201
5248
  const eventData = {
@@ -5207,7 +5254,7 @@ async function captureClientEvent(eventName, instance, additionalData = {}) {
5207
5254
  client_source: "nodejs",
5208
5255
  ...additionalData,
5209
5256
  // sample_rate set AFTER the spread so callers can never override it
5210
- sample_rate: isLifecycle ? 1 : MEM0_TELEMETRY_SAMPLE_RATE
5257
+ sample_rate: alwaysSend ? 1 : MEM0_TELEMETRY_SAMPLE_RATE
5211
5258
  };
5212
5259
  await telemetry.captureEvent(
5213
5260
  instance.telemetryId,
@@ -5215,6 +5262,1038 @@ async function captureClientEvent(eventName, instance, additionalData = {}) {
5215
5262
  eventData
5216
5263
  );
5217
5264
  }
5265
+ async function captureNoticeEvent(instance, properties = {}) {
5266
+ if (!instance.telemetryId) return;
5267
+ const eventData = {
5268
+ function: `${instance.constructor.name}`,
5269
+ method: "notice_displayed",
5270
+ api_host: instance.host,
5271
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5272
+ client_version: version,
5273
+ client_source: "nodejs",
5274
+ ...properties,
5275
+ sample_rate: 1
5276
+ };
5277
+ await telemetry.captureEvent(
5278
+ instance.telemetryId,
5279
+ NOTICE_EVENT_NAME,
5280
+ eventData
5281
+ );
5282
+ }
5283
+
5284
+ // src/oss/src/utils/notices.ts
5285
+ var fs4 = __toESM(require("fs"));
5286
+ var os2 = __toESM(require("os"));
5287
+ var path3 = __toESM(require("path"));
5288
+ var NOTICE_FLAG_KEY = "mem0-oss-notices";
5289
+ var NOTICE_STATE_SECTION = "notice_state";
5290
+ var FIRST_RUN_NOTICE_ID = "first_run";
5291
+ var TEMPORAL_FEATURE_NOTICE_ID = "temporal_stub";
5292
+ var TEMPORAL_USAGE_NOTICE_ID = "temporal_usage";
5293
+ var DECAY_FEATURE_NOTICE_ID = "decay_stub";
5294
+ var DECAY_USAGE_NOTICE_ID = "decay_usage";
5295
+ var SCALE_THRESHOLD_NOTICE_ID = "scale_threshold";
5296
+ var PERFORMANCE_SLOW_QUERY_NOTICE_ID = "performance_slow_query";
5297
+ var NOTICE_CAP_LIMIT = 10;
5298
+ var NOTICE_CAP_WINDOW_MS = 7 * 24 * 60 * 60 * 1e3;
5299
+ var NOTICE_FLAG_TIMEOUT_MS = 500;
5300
+ var POSTHOG_FLAGS_URL = "https://us.i.posthog.com/flags?v=2";
5301
+ var DISPLAYED_VARIANT = "displayed";
5302
+ var HOLDOUT_VARIANT = "holdout";
5303
+ var LOG_LINE_NOTICE_TYPE = "log_line";
5304
+ var ERROR_NOTICE_TYPE = "error";
5305
+ var TEMPORAL_TIMESTAMP_PLAIN_ERROR = "The timestamp parameter is not supported by the OSS Memory SDK.";
5306
+ var TEMPORAL_REFERENCE_DATE_PLAIN_ERROR = "The referenceDate parameter is not supported by the OSS Memory SDK.";
5307
+ var DECAY_FEATURE_PLAIN_ERROR = "The decay parameter is not supported by the OSS Memory SDK.";
5308
+ var DECAY_USAGE_DELETE_THRESHOLD = 5;
5309
+ var SCALE_MEMORY_COUNT_THRESHOLD = 2e3;
5310
+ var SCALE_MEMORY_COUNT_CHECK_INTERVAL = 100;
5311
+ var SCALE_TOP_K_THRESHOLD = 50;
5312
+ var PERFORMANCE_SLOW_QUERY_THRESHOLD_MS = 2e3;
5313
+ var MAX_TEMPORAL_DETECTION_DEPTH = 32;
5314
+ 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/;
5315
+ 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;
5316
+ var RANGE_OPERATORS = /* @__PURE__ */ new Set(["gt", "gte", "lt", "lte"]);
5317
+ var firstRunConsumedInProcess = false;
5318
+ var firstRunClaimInProgress = false;
5319
+ var decayUsageSuccessfulDeleteCount = 0;
5320
+ var noticeCapacityReachedInProcess = /* @__PURE__ */ new Set();
5321
+ var scaleMemoryCountAddsSinceCheck = 0;
5322
+ var scaleMemoryCountCheckedInProcess = false;
5323
+ var scaleMemoryCountThresholdEvaluatedInProcess = false;
5324
+ function getMem0Dir() {
5325
+ return process.env.MEM0_DIR || path3.join(os2.homedir(), ".mem0");
5326
+ }
5327
+ function getMem0ConfigPath() {
5328
+ return path3.join(getMem0Dir(), "config.json");
5329
+ }
5330
+ function loadMem0Config() {
5331
+ try {
5332
+ const configPath = getMem0ConfigPath();
5333
+ if (!fs4.existsSync(configPath)) return {};
5334
+ const parsed = JSON.parse(fs4.readFileSync(configPath, "utf8"));
5335
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
5336
+ } catch (e) {
5337
+ return {};
5338
+ }
5339
+ }
5340
+ function writeMem0ConfigAtomic(config) {
5341
+ const configPath = getMem0ConfigPath();
5342
+ const dir = path3.dirname(configPath);
5343
+ const tempPath = path3.join(
5344
+ dir,
5345
+ `.config.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`
5346
+ );
5347
+ try {
5348
+ fs4.mkdirSync(dir, { recursive: true });
5349
+ fs4.writeFileSync(tempPath, JSON.stringify(config, null, 4));
5350
+ fs4.renameSync(tempPath, configPath);
5351
+ return true;
5352
+ } catch (e) {
5353
+ try {
5354
+ if (fs4.existsSync(tempPath)) fs4.unlinkSync(tempPath);
5355
+ } catch (e2) {
5356
+ }
5357
+ return false;
5358
+ }
5359
+ }
5360
+ function getNoticeState(config, noticeId) {
5361
+ const stateSection = config[NOTICE_STATE_SECTION] && typeof config[NOTICE_STATE_SECTION] === "object" && !Array.isArray(config[NOTICE_STATE_SECTION]) ? config[NOTICE_STATE_SECTION] : {};
5362
+ const noticeState = stateSection[noticeId];
5363
+ return noticeState && typeof noticeState === "object" && !Array.isArray(noticeState) ? noticeState : {};
5364
+ }
5365
+ function setNoticeState(config, noticeId, state) {
5366
+ const stateSection = config[NOTICE_STATE_SECTION] && typeof config[NOTICE_STATE_SECTION] === "object" && !Array.isArray(config[NOTICE_STATE_SECTION]) ? { ...config[NOTICE_STATE_SECTION] } : {};
5367
+ return {
5368
+ ...config,
5369
+ [NOTICE_STATE_SECTION]: {
5370
+ ...stateSection,
5371
+ [noticeId]: state
5372
+ }
5373
+ };
5374
+ }
5375
+ function parsePayload(payload) {
5376
+ try {
5377
+ if (typeof payload === "string") {
5378
+ const parsed = JSON.parse(payload);
5379
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
5380
+ }
5381
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : void 0;
5382
+ } catch (e) {
5383
+ return void 0;
5384
+ }
5385
+ }
5386
+ function getNoticeConfigFromPayload(payload, noticeId) {
5387
+ const parsedPayload = parsePayload(payload);
5388
+ const notices = parsedPayload == null ? void 0 : parsedPayload.notices;
5389
+ if (!notices || typeof notices !== "object" || Array.isArray(notices)) {
5390
+ return { found: false, payload: parsedPayload };
5391
+ }
5392
+ const noticeConfig = notices[noticeId];
5393
+ if (!noticeConfig || typeof noticeConfig !== "object" || Array.isArray(noticeConfig)) {
5394
+ return { found: false, payload: parsedPayload };
5395
+ }
5396
+ return {
5397
+ found: true,
5398
+ config: noticeConfig,
5399
+ payload: parsedPayload
5400
+ };
5401
+ }
5402
+ async function evaluateNoticeFlag(distinctId, options = {}) {
5403
+ var _a2, _b2, _c, _d;
5404
+ if (!isTelemetryEnabled()) return null;
5405
+ const timeoutMs = (_a2 = options.timeoutMs) != null ? _a2 : NOTICE_FLAG_TIMEOUT_MS;
5406
+ const fetchImpl = (_b2 = options.fetchImpl) != null ? _b2 : fetch;
5407
+ const controller = new AbortController();
5408
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
5409
+ try {
5410
+ const response = await fetchImpl(POSTHOG_FLAGS_URL, {
5411
+ method: "POST",
5412
+ headers: { "Content-Type": "application/json" },
5413
+ body: JSON.stringify({
5414
+ api_key: POSTHOG_API_KEY,
5415
+ distinct_id: distinctId
5416
+ }),
5417
+ signal: controller.signal
5418
+ });
5419
+ if (!response.ok) return null;
5420
+ const data = await response.json();
5421
+ const flag = (_c = data == null ? void 0 : data.flags) == null ? void 0 : _c[NOTICE_FLAG_KEY];
5422
+ if (!flag || flag.enabled === false) return null;
5423
+ const variant = typeof flag.variant === "string" ? flag.variant : null;
5424
+ if (!variant) return null;
5425
+ return {
5426
+ variant,
5427
+ payload: parsePayload((_d = flag.metadata) == null ? void 0 : _d.payload),
5428
+ flag
5429
+ };
5430
+ } catch (e) {
5431
+ return null;
5432
+ } finally {
5433
+ clearTimeout(timeout);
5434
+ }
5435
+ }
5436
+ function eventsInWindow(events, now, windowMs) {
5437
+ if (!Array.isArray(events)) return [];
5438
+ const cutoff = now.getTime() - windowMs;
5439
+ return events.filter((event) => {
5440
+ if (!event || typeof event !== "object" || Array.isArray(event)) {
5441
+ return false;
5442
+ }
5443
+ const evaluatedAt = event.evaluated_at;
5444
+ if (typeof evaluatedAt !== "string") return false;
5445
+ const timestamp = Date.parse(evaluatedAt);
5446
+ return Number.isFinite(timestamp) && timestamp >= cutoff;
5447
+ });
5448
+ }
5449
+ function hasNoticeCapRoom(state, options = {}) {
5450
+ var _a2, _b2, _c;
5451
+ const now = (_a2 = options.now) != null ? _a2 : /* @__PURE__ */ new Date();
5452
+ const limit = (_b2 = options.limit) != null ? _b2 : NOTICE_CAP_LIMIT;
5453
+ const windowMs = (_c = options.windowMs) != null ? _c : NOTICE_CAP_WINDOW_MS;
5454
+ return eventsInWindow(state.events, now, windowMs).length < limit;
5455
+ }
5456
+ function isNoticeCapacityReachedInProcess(noticeId) {
5457
+ return noticeCapacityReachedInProcess.has(noticeId);
5458
+ }
5459
+ function markNoticeCapacityReachedInProcess(noticeId) {
5460
+ noticeCapacityReachedInProcess.add(noticeId);
5461
+ }
5462
+ function hasNoticeCapRoomForNotice(noticeId, state, options = {}) {
5463
+ const hasRoom = hasNoticeCapRoom(state, options);
5464
+ if (!hasRoom) markNoticeCapacityReachedInProcess(noticeId);
5465
+ return hasRoom;
5466
+ }
5467
+ function appendNoticeCapEvent(state, event, options = {}) {
5468
+ var _a2, _b2, _c;
5469
+ const now = (_a2 = options.now) != null ? _a2 : /* @__PURE__ */ new Date();
5470
+ const limit = (_b2 = options.limit) != null ? _b2 : NOTICE_CAP_LIMIT;
5471
+ const windowMs = (_c = options.windowMs) != null ? _c : NOTICE_CAP_WINDOW_MS;
5472
+ const events = eventsInWindow(state.events, now, windowMs);
5473
+ if (events.length >= limit) return null;
5474
+ return {
5475
+ ...state,
5476
+ events: [
5477
+ ...events,
5478
+ {
5479
+ evaluated_at: now.toISOString(),
5480
+ ...event
5481
+ }
5482
+ ]
5483
+ };
5484
+ }
5485
+ function recordNoticeOpportunity(noticeId, event, options = {}) {
5486
+ if (!isTelemetryEnabled()) return false;
5487
+ if (isNoticeCapacityReachedInProcess(noticeId)) return false;
5488
+ const config = loadMem0Config();
5489
+ const state = getNoticeState(config, noticeId);
5490
+ const nextState = appendNoticeCapEvent(state, event, options);
5491
+ if (!nextState) {
5492
+ markNoticeCapacityReachedInProcess(noticeId);
5493
+ return false;
5494
+ }
5495
+ const written = writeMem0ConfigAtomic(
5496
+ setNoticeState(config, noticeId, nextState)
5497
+ );
5498
+ if (written && !hasNoticeCapRoom(nextState, options)) {
5499
+ markNoticeCapacityReachedInProcess(noticeId);
5500
+ }
5501
+ return written;
5502
+ }
5503
+ function isFirstRunConsumed(config) {
5504
+ return getNoticeState(config, FIRST_RUN_NOTICE_ID).consumed === true;
5505
+ }
5506
+ function markFirstRunConsumed(triggerFunction, variant) {
5507
+ const config = loadMem0Config();
5508
+ const state = getNoticeState(config, FIRST_RUN_NOTICE_ID);
5509
+ const nextState = {
5510
+ ...state,
5511
+ consumed: true,
5512
+ consumed_at: (/* @__PURE__ */ new Date()).toISOString(),
5513
+ trigger_function: triggerFunction,
5514
+ variant
5515
+ };
5516
+ return writeMem0ConfigAtomic(
5517
+ setNoticeState(config, FIRST_RUN_NOTICE_ID, nextState)
5518
+ );
5519
+ }
5520
+ function getDisplayDecision(noticeId, expectedNoticeType, variant, payload) {
5521
+ var _a2;
5522
+ const parsed = getNoticeConfigFromPayload(payload, noticeId);
5523
+ const copy = typeof ((_a2 = parsed.config) == null ? void 0 : _a2.copy) === "string" ? parsed.config.copy : void 0;
5524
+ if (!parsed.found || !parsed.config) {
5525
+ return {
5526
+ displayed: false,
5527
+ noticeConfigFound: false,
5528
+ bypassReason: "missing_notice_config"
5529
+ };
5530
+ }
5531
+ const noticeConfig = parsed.config;
5532
+ if (noticeConfig.enabled === false) {
5533
+ return {
5534
+ displayed: false,
5535
+ noticeConfigFound: true,
5536
+ copy,
5537
+ bypassReason: "payload_disabled",
5538
+ disabledReason: "payload_disabled"
5539
+ };
5540
+ }
5541
+ if (noticeConfig.notice_type !== expectedNoticeType) {
5542
+ return {
5543
+ displayed: false,
5544
+ noticeConfigFound: true,
5545
+ copy,
5546
+ bypassReason: "invalid_notice_type"
5547
+ };
5548
+ }
5549
+ if (!copy || copy.trim() === "") {
5550
+ return {
5551
+ displayed: false,
5552
+ noticeConfigFound: true,
5553
+ bypassReason: "missing_copy"
5554
+ };
5555
+ }
5556
+ if (variant !== DISPLAYED_VARIANT) {
5557
+ return {
5558
+ displayed: false,
5559
+ noticeConfigFound: true,
5560
+ copy,
5561
+ bypassReason: "holdout"
5562
+ };
5563
+ }
5564
+ return {
5565
+ displayed: true,
5566
+ noticeConfigFound: true,
5567
+ copy
5568
+ };
5569
+ }
5570
+ function renderScaleCopy(template, trigger) {
5571
+ var _a2, _b2, _c;
5572
+ if (typeof template !== "string" || template.trim() === "") return void 0;
5573
+ 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 : ""));
5574
+ }
5575
+ function getScaleDisplayDecision(variant, payload, trigger) {
5576
+ var _a2;
5577
+ const parsed = getNoticeConfigFromPayload(payload, SCALE_THRESHOLD_NOTICE_ID);
5578
+ const copies = ((_a2 = parsed.config) == null ? void 0 : _a2.copies) && typeof parsed.config.copies === "object" && !Array.isArray(parsed.config.copies) ? parsed.config.copies : {};
5579
+ const copyKey = trigger.triggerSource === "memory_count" ? "memory_count" : "top_k";
5580
+ const copy = renderScaleCopy(copies[copyKey], trigger);
5581
+ if (!parsed.found || !parsed.config) {
5582
+ return {
5583
+ displayed: false,
5584
+ noticeConfigFound: false,
5585
+ bypassReason: "missing_notice_config"
5586
+ };
5587
+ }
5588
+ const noticeConfig = parsed.config;
5589
+ if (noticeConfig.enabled === false) {
5590
+ return {
5591
+ displayed: false,
5592
+ noticeConfigFound: true,
5593
+ copy,
5594
+ bypassReason: "payload_disabled",
5595
+ disabledReason: "payload_disabled"
5596
+ };
5597
+ }
5598
+ if (noticeConfig.notice_type !== LOG_LINE_NOTICE_TYPE) {
5599
+ return {
5600
+ displayed: false,
5601
+ noticeConfigFound: true,
5602
+ copy,
5603
+ bypassReason: "invalid_notice_type"
5604
+ };
5605
+ }
5606
+ if (!copy || copy.trim() === "") {
5607
+ return {
5608
+ displayed: false,
5609
+ noticeConfigFound: true,
5610
+ bypassReason: "missing_copy"
5611
+ };
5612
+ }
5613
+ if (variant !== DISPLAYED_VARIANT) {
5614
+ return {
5615
+ displayed: false,
5616
+ noticeConfigFound: true,
5617
+ copy,
5618
+ bypassReason: "holdout"
5619
+ };
5620
+ }
5621
+ return {
5622
+ displayed: true,
5623
+ noticeConfigFound: true,
5624
+ copy
5625
+ };
5626
+ }
5627
+ function getFeatureErrorDecision(noticeId, expectedNoticeType, variant, payload) {
5628
+ var _a2;
5629
+ const parsed = getNoticeConfigFromPayload(payload, noticeId);
5630
+ const copy = typeof ((_a2 = parsed.config) == null ? void 0 : _a2.copy) === "string" ? parsed.config.copy : void 0;
5631
+ if (!parsed.found || !parsed.config) {
5632
+ return {
5633
+ displayed: false,
5634
+ noticeConfigFound: false,
5635
+ bypassReason: "missing_notice_config"
5636
+ };
5637
+ }
5638
+ const noticeConfig = parsed.config;
5639
+ if (noticeConfig.enabled === false) {
5640
+ return {
5641
+ displayed: false,
5642
+ noticeConfigFound: true,
5643
+ copy,
5644
+ bypassReason: "payload_disabled",
5645
+ disabledReason: "payload_disabled"
5646
+ };
5647
+ }
5648
+ if (noticeConfig.notice_type !== expectedNoticeType) {
5649
+ return {
5650
+ displayed: false,
5651
+ noticeConfigFound: true,
5652
+ copy,
5653
+ bypassReason: "invalid_notice_type"
5654
+ };
5655
+ }
5656
+ if (!copy || copy.trim() === "") {
5657
+ return {
5658
+ displayed: false,
5659
+ noticeConfigFound: true,
5660
+ bypassReason: "missing_copy"
5661
+ };
5662
+ }
5663
+ if (variant !== DISPLAYED_VARIANT && variant !== HOLDOUT_VARIANT) {
5664
+ return {
5665
+ displayed: false,
5666
+ noticeConfigFound: true,
5667
+ copy,
5668
+ bypassReason: "not_displayed"
5669
+ };
5670
+ }
5671
+ return {
5672
+ displayed: true,
5673
+ noticeConfigFound: true,
5674
+ copy
5675
+ };
5676
+ }
5677
+ async function getDecayFeatureErrorMessage(instance) {
5678
+ if (!isTelemetryEnabled()) return DECAY_FEATURE_PLAIN_ERROR;
5679
+ try {
5680
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
5681
+ if (!flagEvaluation) return DECAY_FEATURE_PLAIN_ERROR;
5682
+ const decision = getFeatureErrorDecision(
5683
+ DECAY_FEATURE_NOTICE_ID,
5684
+ ERROR_NOTICE_TYPE,
5685
+ flagEvaluation.variant,
5686
+ flagEvaluation.payload
5687
+ );
5688
+ await emitNoticeDisplayed(instance, {
5689
+ notice_id: DECAY_FEATURE_NOTICE_ID,
5690
+ notice_type: ERROR_NOTICE_TYPE,
5691
+ flag_key: NOTICE_FLAG_KEY,
5692
+ variant: flagEvaluation.variant,
5693
+ displayed: decision.displayed,
5694
+ payload: decision.copy,
5695
+ bypass_reason: decision.bypassReason,
5696
+ disabled_reason: decision.disabledReason,
5697
+ notice_config_found: decision.noticeConfigFound,
5698
+ sync_type: "async",
5699
+ trigger_function: "update_project",
5700
+ trigger_parameter: "decay"
5701
+ });
5702
+ if (decision.displayed && decision.copy) {
5703
+ return decision.copy;
5704
+ }
5705
+ } catch (e) {
5706
+ }
5707
+ return DECAY_FEATURE_PLAIN_ERROR;
5708
+ }
5709
+ async function getTemporalFeatureErrorMessage(instance, trigger) {
5710
+ const plainError = trigger.triggerParameter === "timestamp" ? TEMPORAL_TIMESTAMP_PLAIN_ERROR : TEMPORAL_REFERENCE_DATE_PLAIN_ERROR;
5711
+ if (!isTelemetryEnabled()) return plainError;
5712
+ try {
5713
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
5714
+ if (!flagEvaluation) return plainError;
5715
+ const decision = getFeatureErrorDecision(
5716
+ TEMPORAL_FEATURE_NOTICE_ID,
5717
+ ERROR_NOTICE_TYPE,
5718
+ flagEvaluation.variant,
5719
+ flagEvaluation.payload
5720
+ );
5721
+ await emitNoticeDisplayed(instance, {
5722
+ notice_id: TEMPORAL_FEATURE_NOTICE_ID,
5723
+ notice_type: ERROR_NOTICE_TYPE,
5724
+ flag_key: NOTICE_FLAG_KEY,
5725
+ variant: flagEvaluation.variant,
5726
+ displayed: decision.displayed,
5727
+ payload: decision.copy,
5728
+ bypass_reason: decision.bypassReason,
5729
+ disabled_reason: decision.disabledReason,
5730
+ notice_config_found: decision.noticeConfigFound,
5731
+ sync_type: "async",
5732
+ trigger_function: trigger.triggerFunction,
5733
+ trigger_parameter: trigger.triggerParameter
5734
+ });
5735
+ if (decision.displayed && decision.copy) {
5736
+ return decision.copy;
5737
+ }
5738
+ } catch (e) {
5739
+ }
5740
+ return plainError;
5741
+ }
5742
+ function getDecayUsageDeleteCountAfterSuccess() {
5743
+ if (!isTelemetryEnabled()) return 0;
5744
+ decayUsageSuccessfulDeleteCount += 1;
5745
+ return decayUsageSuccessfulDeleteCount;
5746
+ }
5747
+ function isDecayUsageDeleteEligible(deleteCount) {
5748
+ return deleteCount >= DECAY_USAGE_DELETE_THRESHOLD;
5749
+ }
5750
+ function isRecord(value) {
5751
+ return value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date);
5752
+ }
5753
+ function isTemporalKey(key) {
5754
+ const keyText = String(key).toLowerCase();
5755
+ return [
5756
+ "date",
5757
+ "time",
5758
+ "timestamp",
5759
+ "datetime",
5760
+ "event_date",
5761
+ "reference_date",
5762
+ "referencedate",
5763
+ "created_at",
5764
+ "createdat",
5765
+ "updated_at",
5766
+ "updatedat",
5767
+ "started_at",
5768
+ "startedat",
5769
+ "ended_at",
5770
+ "endedat",
5771
+ "expires_at",
5772
+ "expiresat"
5773
+ ].includes(keyText) || keyText.endsWith("_date") || keyText.endsWith("_time") || keyText.endsWith("_at") || keyText.includes("timestamp");
5774
+ }
5775
+ function looksTemporalValue(value, allowEpoch) {
5776
+ if (value instanceof Date) return !Number.isNaN(value.getTime());
5777
+ if (typeof value === "string") {
5778
+ return ISO_DATE_RE.test(value) || RELATIVE_TIME_RE.test(value);
5779
+ }
5780
+ if (allowEpoch && typeof value === "number" && Number.isFinite(value)) {
5781
+ return value >= 946684800 && value <= 4102444800 || value >= 9466848e5 && value <= 41024448e5;
5782
+ }
5783
+ return false;
5784
+ }
5785
+ function detectTemporalUsageFromMetadata(metadata) {
5786
+ try {
5787
+ if (!isRecord(metadata)) return null;
5788
+ const visited = /* @__PURE__ */ new WeakSet();
5789
+ const stack = [{ value: metadata, depth: 0 }];
5790
+ while (stack.length > 0) {
5791
+ const current = stack.pop();
5792
+ if (current.depth > MAX_TEMPORAL_DETECTION_DEPTH) continue;
5793
+ if (Array.isArray(current.value)) {
5794
+ for (const child of current.value) {
5795
+ if (looksTemporalValue(child, false)) {
5796
+ return {
5797
+ triggerSource: "metadata",
5798
+ triggerReason: "date_like_metadata"
5799
+ };
5800
+ }
5801
+ stack.push({
5802
+ value: child,
5803
+ parentKey: current.parentKey,
5804
+ depth: current.depth + 1
5805
+ });
5806
+ }
5807
+ continue;
5808
+ }
5809
+ if (!isRecord(current.value)) continue;
5810
+ if (visited.has(current.value)) continue;
5811
+ visited.add(current.value);
5812
+ for (const [key, value] of Object.entries(current.value)) {
5813
+ const temporalKey = isTemporalKey(key);
5814
+ if (temporalKey && looksTemporalValue(value, true) || looksTemporalValue(value, false)) {
5815
+ return {
5816
+ triggerSource: "metadata",
5817
+ triggerReason: "date_like_metadata"
5818
+ };
5819
+ }
5820
+ if (isRecord(value) || Array.isArray(value)) {
5821
+ stack.push({ value, parentKey: key, depth: current.depth + 1 });
5822
+ }
5823
+ }
5824
+ }
5825
+ } catch (e) {
5826
+ }
5827
+ return null;
5828
+ }
5829
+ function hasTemporalFilter(filters) {
5830
+ try {
5831
+ if (!isRecord(filters)) return false;
5832
+ const visited = /* @__PURE__ */ new WeakSet();
5833
+ const stack = [
5834
+ { value: filters, depth: 0 }
5835
+ ];
5836
+ while (stack.length > 0) {
5837
+ const current = stack.pop();
5838
+ if (current.depth > MAX_TEMPORAL_DETECTION_DEPTH) continue;
5839
+ if (Array.isArray(current.value)) {
5840
+ for (const child of current.value) {
5841
+ stack.push({ value: child, depth: current.depth + 1 });
5842
+ }
5843
+ continue;
5844
+ }
5845
+ if (!isRecord(current.value)) continue;
5846
+ if (visited.has(current.value)) continue;
5847
+ visited.add(current.value);
5848
+ for (const [key, value] of Object.entries(current.value)) {
5849
+ if (["AND", "OR", "NOT", "$and", "$or", "$not"].includes(key)) {
5850
+ if (isRecord(value) || Array.isArray(value)) {
5851
+ stack.push({ value, depth: current.depth + 1 });
5852
+ }
5853
+ continue;
5854
+ }
5855
+ const temporalKey = isTemporalKey(key);
5856
+ if (isRecord(value)) {
5857
+ const rangeValues = Object.entries(value).filter(([operator]) => RANGE_OPERATORS.has(operator)).map(([, rangeValue]) => rangeValue);
5858
+ if (rangeValues.length > 0 && (temporalKey || rangeValues.some(
5859
+ (rangeValue) => looksTemporalValue(rangeValue, temporalKey)
5860
+ ))) {
5861
+ return true;
5862
+ }
5863
+ stack.push({ value, depth: current.depth + 1 });
5864
+ } else if (temporalKey && looksTemporalValue(value, true)) {
5865
+ return true;
5866
+ }
5867
+ }
5868
+ }
5869
+ } catch (e) {
5870
+ }
5871
+ return false;
5872
+ }
5873
+ function detectTemporalUsageFromSearch(query, filters) {
5874
+ try {
5875
+ if (typeof query === "string") {
5876
+ if (RELATIVE_TIME_RE.test(query)) {
5877
+ return { triggerSource: "query", triggerReason: "relative_phrase" };
5878
+ }
5879
+ if (ISO_DATE_RE.test(query)) {
5880
+ return { triggerSource: "query", triggerReason: "date_like_query" };
5881
+ }
5882
+ }
5883
+ if (hasTemporalFilter(filters)) {
5884
+ return { triggerSource: "filter", triggerReason: "date_range_filter" };
5885
+ }
5886
+ } catch (e) {
5887
+ }
5888
+ return null;
5889
+ }
5890
+ function coerceNonnegativeInteger(value) {
5891
+ if (typeof value === "boolean") return null;
5892
+ const parsed = Number(value);
5893
+ if (!Number.isFinite(parsed) || !Number.isInteger(parsed) || parsed < 0) {
5894
+ return null;
5895
+ }
5896
+ return parsed;
5897
+ }
5898
+ function countAddedMemories(addResult) {
5899
+ const results = isRecord(addResult) && Array.isArray(addResult.results) ? addResult.results : addResult;
5900
+ if (!Array.isArray(results)) return 0;
5901
+ return results.filter((item) => {
5902
+ if (!isRecord(item)) return false;
5903
+ const metadata = item.metadata;
5904
+ return isRecord(metadata) && metadata.event === "ADD";
5905
+ }).length;
5906
+ }
5907
+ function extractProviderCount(info) {
5908
+ if (!info) return null;
5909
+ if (typeof info === "number") return coerceNonnegativeInteger(info);
5910
+ if (isRecord(info)) {
5911
+ for (const key of [
5912
+ "count",
5913
+ "points_count",
5914
+ "vectors_count",
5915
+ "indexed_vectors_count"
5916
+ ]) {
5917
+ const value = coerceNonnegativeInteger(info[key]);
5918
+ if (value !== null) return value;
5919
+ }
5920
+ const result = extractProviderCount(info.result);
5921
+ if (result !== null) return result;
5922
+ }
5923
+ return null;
5924
+ }
5925
+ async function getProviderMemoryCount(memoryInstance) {
5926
+ try {
5927
+ const vectorStore = memoryInstance == null ? void 0 : memoryInstance.vectorStore;
5928
+ if (!vectorStore) return null;
5929
+ if (typeof vectorStore.count === "function") {
5930
+ const value = extractProviderCount(await vectorStore.count());
5931
+ if (value !== null) return value;
5932
+ }
5933
+ const collectionName = vectorStore.collectionName;
5934
+ const client = vectorStore.client;
5935
+ if (client && collectionName && typeof client.count === "function") {
5936
+ const value = extractProviderCount(
5937
+ await client.count(collectionName, { exact: true })
5938
+ );
5939
+ if (value !== null) return value;
5940
+ }
5941
+ if (client && collectionName && typeof client.getCollection === "function") {
5942
+ const value = extractProviderCount(
5943
+ await client.getCollection(collectionName)
5944
+ );
5945
+ if (value !== null) return value;
5946
+ }
5947
+ } catch (e) {
5948
+ }
5949
+ return null;
5950
+ }
5951
+ function markScaleMemoryCountThresholdEvaluated() {
5952
+ try {
5953
+ const config = loadMem0Config();
5954
+ const state = getNoticeState(config, SCALE_THRESHOLD_NOTICE_ID);
5955
+ if (state.memory_count_threshold_evaluated === true) {
5956
+ scaleMemoryCountThresholdEvaluatedInProcess = true;
5957
+ return false;
5958
+ }
5959
+ const nextState = {
5960
+ ...state,
5961
+ memory_count_threshold_evaluated: true
5962
+ };
5963
+ const written = writeMem0ConfigAtomic(
5964
+ setNoticeState(config, SCALE_THRESHOLD_NOTICE_ID, nextState)
5965
+ );
5966
+ if (written) scaleMemoryCountThresholdEvaluatedInProcess = true;
5967
+ return written;
5968
+ } catch (e) {
5969
+ return false;
5970
+ }
5971
+ }
5972
+ function detectScaleThresholdFromTopK(topK) {
5973
+ const topKValue = coerceNonnegativeInteger(topK);
5974
+ if (topKValue === null || topKValue < SCALE_TOP_K_THRESHOLD) return null;
5975
+ return {
5976
+ triggerSource: "top_k",
5977
+ triggerReason: "high_top_k",
5978
+ topK: topKValue,
5979
+ threshold: SCALE_TOP_K_THRESHOLD
5980
+ };
5981
+ }
5982
+ async function detectScaleThresholdFromAddResult(memoryInstance, addResult) {
5983
+ if (!isTelemetryEnabled()) return null;
5984
+ const addedCount = countAddedMemories(addResult);
5985
+ if (addedCount === 0) return null;
5986
+ try {
5987
+ if (scaleMemoryCountThresholdEvaluatedInProcess) return null;
5988
+ scaleMemoryCountAddsSinceCheck += addedCount;
5989
+ const shouldCheck = !scaleMemoryCountCheckedInProcess || scaleMemoryCountAddsSinceCheck >= SCALE_MEMORY_COUNT_CHECK_INTERVAL;
5990
+ if (!shouldCheck) return null;
5991
+ scaleMemoryCountCheckedInProcess = true;
5992
+ scaleMemoryCountAddsSinceCheck = 0;
5993
+ const config = loadMem0Config();
5994
+ const state = getNoticeState(config, SCALE_THRESHOLD_NOTICE_ID);
5995
+ if (state.memory_count_threshold_evaluated === true) {
5996
+ scaleMemoryCountThresholdEvaluatedInProcess = true;
5997
+ return null;
5998
+ }
5999
+ if (!hasNoticeCapRoom(state)) return null;
6000
+ } catch (e) {
6001
+ return null;
6002
+ }
6003
+ const providerCount = await getProviderMemoryCount(memoryInstance);
6004
+ if (providerCount === null || providerCount < SCALE_MEMORY_COUNT_THRESHOLD) {
6005
+ return null;
6006
+ }
6007
+ if (!markScaleMemoryCountThresholdEvaluated()) return null;
6008
+ return {
6009
+ triggerSource: "memory_count",
6010
+ triggerReason: "memory_count_threshold",
6011
+ memoryCount: providerCount,
6012
+ threshold: SCALE_MEMORY_COUNT_THRESHOLD
6013
+ };
6014
+ }
6015
+ function detectPerformanceSlowQuery(elapsedMs, topK, resultCount) {
6016
+ const elapsedMsValue = coerceNonnegativeInteger(
6017
+ Math.round(Number(elapsedMs))
6018
+ );
6019
+ const topKValue = coerceNonnegativeInteger(topK);
6020
+ const resultCountValue = coerceNonnegativeInteger(resultCount);
6021
+ if (elapsedMsValue === null || topKValue === null || resultCountValue === null || elapsedMsValue <= PERFORMANCE_SLOW_QUERY_THRESHOLD_MS) {
6022
+ return null;
6023
+ }
6024
+ return {
6025
+ elapsedMs: elapsedMsValue,
6026
+ thresholdMs: PERFORMANCE_SLOW_QUERY_THRESHOLD_MS,
6027
+ topK: topKValue,
6028
+ resultCount: resultCountValue
6029
+ };
6030
+ }
6031
+ async function displayScaleThresholdNotice(instance, trigger) {
6032
+ if (!isTelemetryEnabled()) return;
6033
+ if (isNoticeCapacityReachedInProcess(SCALE_THRESHOLD_NOTICE_ID)) return;
6034
+ try {
6035
+ const config = loadMem0Config();
6036
+ const state = getNoticeState(config, SCALE_THRESHOLD_NOTICE_ID);
6037
+ if (!hasNoticeCapRoomForNotice(SCALE_THRESHOLD_NOTICE_ID, state)) return;
6038
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
6039
+ if (!flagEvaluation) return;
6040
+ const decision = getScaleDisplayDecision(
6041
+ flagEvaluation.variant,
6042
+ flagEvaluation.payload,
6043
+ trigger
6044
+ );
6045
+ const opportunity = {
6046
+ variant: flagEvaluation.variant,
6047
+ sync_type: "async",
6048
+ trigger_function: trigger.triggerFunction,
6049
+ trigger_source: trigger.triggerSource,
6050
+ trigger_reason: trigger.triggerReason,
6051
+ ...trigger.topK !== void 0 && { top_k: trigger.topK },
6052
+ ...trigger.memoryCount !== void 0 && {
6053
+ memory_count: trigger.memoryCount
6054
+ },
6055
+ threshold: trigger.threshold
6056
+ };
6057
+ if (!recordNoticeOpportunity(SCALE_THRESHOLD_NOTICE_ID, opportunity)) {
6058
+ return;
6059
+ }
6060
+ await emitNoticeDisplayed(instance, {
6061
+ notice_id: SCALE_THRESHOLD_NOTICE_ID,
6062
+ notice_type: LOG_LINE_NOTICE_TYPE,
6063
+ flag_key: NOTICE_FLAG_KEY,
6064
+ variant: flagEvaluation.variant,
6065
+ displayed: decision.displayed,
6066
+ payload: decision.copy,
6067
+ bypass_reason: decision.bypassReason,
6068
+ disabled_reason: decision.disabledReason,
6069
+ notice_config_found: decision.noticeConfigFound,
6070
+ sync_type: "async",
6071
+ trigger_function: trigger.triggerFunction,
6072
+ trigger_source: trigger.triggerSource,
6073
+ trigger_reason: trigger.triggerReason,
6074
+ top_k: trigger.topK,
6075
+ memory_count: trigger.memoryCount,
6076
+ threshold: trigger.threshold
6077
+ });
6078
+ if (decision.displayed && decision.copy) {
6079
+ process.stderr.write(`${decision.copy}
6080
+ `);
6081
+ }
6082
+ } catch (e) {
6083
+ }
6084
+ }
6085
+ async function displayPerformanceSlowQueryNotice(instance, trigger) {
6086
+ if (!isTelemetryEnabled()) return;
6087
+ if (isNoticeCapacityReachedInProcess(PERFORMANCE_SLOW_QUERY_NOTICE_ID)) {
6088
+ return;
6089
+ }
6090
+ try {
6091
+ const config = loadMem0Config();
6092
+ const state = getNoticeState(config, PERFORMANCE_SLOW_QUERY_NOTICE_ID);
6093
+ if (!hasNoticeCapRoomForNotice(PERFORMANCE_SLOW_QUERY_NOTICE_ID, state)) {
6094
+ return;
6095
+ }
6096
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
6097
+ if (!flagEvaluation) return;
6098
+ const decision = getDisplayDecision(
6099
+ PERFORMANCE_SLOW_QUERY_NOTICE_ID,
6100
+ LOG_LINE_NOTICE_TYPE,
6101
+ flagEvaluation.variant,
6102
+ flagEvaluation.payload
6103
+ );
6104
+ const opportunity = {
6105
+ variant: flagEvaluation.variant,
6106
+ sync_type: "async",
6107
+ trigger_function: trigger.triggerFunction,
6108
+ trigger_reason: trigger.triggerReason
6109
+ };
6110
+ if (!recordNoticeOpportunity(PERFORMANCE_SLOW_QUERY_NOTICE_ID, opportunity)) {
6111
+ return;
6112
+ }
6113
+ await emitNoticeDisplayed(instance, {
6114
+ notice_id: PERFORMANCE_SLOW_QUERY_NOTICE_ID,
6115
+ notice_type: LOG_LINE_NOTICE_TYPE,
6116
+ flag_key: NOTICE_FLAG_KEY,
6117
+ variant: flagEvaluation.variant,
6118
+ displayed: decision.displayed,
6119
+ payload: decision.copy,
6120
+ bypass_reason: decision.bypassReason,
6121
+ disabled_reason: decision.disabledReason,
6122
+ notice_config_found: decision.noticeConfigFound,
6123
+ sync_type: "async",
6124
+ trigger_function: trigger.triggerFunction,
6125
+ trigger_reason: trigger.triggerReason,
6126
+ elapsed_ms: trigger.elapsedMs,
6127
+ threshold_ms: trigger.thresholdMs,
6128
+ top_k: trigger.topK,
6129
+ result_count: trigger.resultCount
6130
+ });
6131
+ if (decision.displayed && decision.copy) {
6132
+ process.stderr.write(`${decision.copy}
6133
+ `);
6134
+ }
6135
+ } catch (e) {
6136
+ }
6137
+ }
6138
+ async function displayTemporalUsageNotice(instance, trigger) {
6139
+ if (!isTelemetryEnabled()) return;
6140
+ if (isNoticeCapacityReachedInProcess(TEMPORAL_USAGE_NOTICE_ID)) return;
6141
+ try {
6142
+ const config = loadMem0Config();
6143
+ const state = getNoticeState(config, TEMPORAL_USAGE_NOTICE_ID);
6144
+ if (!hasNoticeCapRoomForNotice(TEMPORAL_USAGE_NOTICE_ID, state)) return;
6145
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
6146
+ if (!flagEvaluation) return;
6147
+ const decision = getDisplayDecision(
6148
+ TEMPORAL_USAGE_NOTICE_ID,
6149
+ LOG_LINE_NOTICE_TYPE,
6150
+ flagEvaluation.variant,
6151
+ flagEvaluation.payload
6152
+ );
6153
+ const opportunity = {
6154
+ variant: flagEvaluation.variant,
6155
+ sync_type: "async",
6156
+ trigger_function: trigger.triggerFunction,
6157
+ trigger_source: trigger.triggerSource,
6158
+ trigger_reason: trigger.triggerReason
6159
+ };
6160
+ if (!recordNoticeOpportunity(TEMPORAL_USAGE_NOTICE_ID, opportunity)) {
6161
+ return;
6162
+ }
6163
+ await emitNoticeDisplayed(instance, {
6164
+ notice_id: TEMPORAL_USAGE_NOTICE_ID,
6165
+ notice_type: LOG_LINE_NOTICE_TYPE,
6166
+ flag_key: NOTICE_FLAG_KEY,
6167
+ variant: flagEvaluation.variant,
6168
+ displayed: decision.displayed,
6169
+ payload: decision.copy,
6170
+ bypass_reason: decision.bypassReason,
6171
+ disabled_reason: decision.disabledReason,
6172
+ notice_config_found: decision.noticeConfigFound,
6173
+ sync_type: "async",
6174
+ trigger_function: trigger.triggerFunction,
6175
+ trigger_source: trigger.triggerSource,
6176
+ trigger_reason: trigger.triggerReason
6177
+ });
6178
+ if (decision.displayed && decision.copy) {
6179
+ process.stderr.write(`${decision.copy}
6180
+ `);
6181
+ }
6182
+ } catch (e) {
6183
+ }
6184
+ }
6185
+ async function displayDecayUsageNotice(instance, trigger) {
6186
+ if (!isTelemetryEnabled()) return;
6187
+ if (isNoticeCapacityReachedInProcess(DECAY_USAGE_NOTICE_ID)) return;
6188
+ try {
6189
+ const config = loadMem0Config();
6190
+ const state = getNoticeState(config, DECAY_USAGE_NOTICE_ID);
6191
+ if (!hasNoticeCapRoomForNotice(DECAY_USAGE_NOTICE_ID, state)) return;
6192
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
6193
+ if (!flagEvaluation) return;
6194
+ const decision = getDisplayDecision(
6195
+ DECAY_USAGE_NOTICE_ID,
6196
+ LOG_LINE_NOTICE_TYPE,
6197
+ flagEvaluation.variant,
6198
+ flagEvaluation.payload
6199
+ );
6200
+ const opportunity = {
6201
+ variant: flagEvaluation.variant,
6202
+ sync_type: "async",
6203
+ trigger_function: trigger.triggerFunction,
6204
+ trigger_source: trigger.triggerSource,
6205
+ trigger_reason: trigger.triggerReason,
6206
+ ...trigger.deleteCount !== void 0 && {
6207
+ delete_count: trigger.deleteCount
6208
+ },
6209
+ ...trigger.deletedCount !== void 0 && {
6210
+ deleted_count: trigger.deletedCount
6211
+ }
6212
+ };
6213
+ if (!recordNoticeOpportunity(DECAY_USAGE_NOTICE_ID, opportunity)) {
6214
+ return;
6215
+ }
6216
+ await emitNoticeDisplayed(instance, {
6217
+ notice_id: DECAY_USAGE_NOTICE_ID,
6218
+ notice_type: LOG_LINE_NOTICE_TYPE,
6219
+ flag_key: NOTICE_FLAG_KEY,
6220
+ variant: flagEvaluation.variant,
6221
+ displayed: decision.displayed,
6222
+ payload: decision.copy,
6223
+ bypass_reason: decision.bypassReason,
6224
+ disabled_reason: decision.disabledReason,
6225
+ notice_config_found: decision.noticeConfigFound,
6226
+ sync_type: "async",
6227
+ trigger_function: trigger.triggerFunction,
6228
+ trigger_source: trigger.triggerSource,
6229
+ trigger_reason: trigger.triggerReason,
6230
+ ...trigger.deleteCount !== void 0 && {
6231
+ delete_count: trigger.deleteCount
6232
+ },
6233
+ ...trigger.deletedCount !== void 0 && {
6234
+ deleted_count: trigger.deletedCount
6235
+ }
6236
+ });
6237
+ if (decision.displayed && decision.copy) {
6238
+ process.stderr.write(`${decision.copy}
6239
+ `);
6240
+ }
6241
+ } catch (e) {
6242
+ }
6243
+ }
6244
+ async function displayFirstRunNotice(instance, triggerFunction) {
6245
+ if (!isTelemetryEnabled()) return;
6246
+ if (firstRunConsumedInProcess || firstRunClaimInProgress) return;
6247
+ const config = loadMem0Config();
6248
+ if (isFirstRunConsumed(config)) {
6249
+ firstRunConsumedInProcess = true;
6250
+ return;
6251
+ }
6252
+ firstRunClaimInProgress = true;
6253
+ try {
6254
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
6255
+ if (!flagEvaluation) {
6256
+ firstRunClaimInProgress = false;
6257
+ return;
6258
+ }
6259
+ const decision = getDisplayDecision(
6260
+ FIRST_RUN_NOTICE_ID,
6261
+ LOG_LINE_NOTICE_TYPE,
6262
+ flagEvaluation.variant,
6263
+ flagEvaluation.payload
6264
+ );
6265
+ firstRunConsumedInProcess = true;
6266
+ markFirstRunConsumed(triggerFunction, flagEvaluation.variant);
6267
+ await emitNoticeDisplayed(instance, {
6268
+ notice_id: FIRST_RUN_NOTICE_ID,
6269
+ notice_type: LOG_LINE_NOTICE_TYPE,
6270
+ flag_key: NOTICE_FLAG_KEY,
6271
+ variant: flagEvaluation.variant,
6272
+ displayed: decision.displayed,
6273
+ payload: decision.copy,
6274
+ bypass_reason: decision.bypassReason,
6275
+ disabled_reason: decision.disabledReason,
6276
+ notice_config_found: decision.noticeConfigFound,
6277
+ sync_type: "async",
6278
+ trigger_function: triggerFunction
6279
+ });
6280
+ if (decision.displayed && decision.copy) {
6281
+ process.stderr.write(`${decision.copy}
6282
+ `);
6283
+ }
6284
+ } catch (e) {
6285
+ if (!firstRunConsumedInProcess) firstRunClaimInProgress = false;
6286
+ } finally {
6287
+ if (firstRunConsumedInProcess) firstRunClaimInProgress = false;
6288
+ }
6289
+ }
6290
+ async function emitNoticeDisplayed(instance, properties) {
6291
+ if (!isTelemetryEnabled()) return;
6292
+ try {
6293
+ await captureNoticeEvent(instance, properties);
6294
+ } catch (e) {
6295
+ }
6296
+ }
5218
6297
 
5219
6298
  // src/oss/src/utils/lemmatization.ts
5220
6299
  var STOP_WORDS = /* @__PURE__ */ new Set([
@@ -5912,7 +6991,7 @@ function extractCompoundsRegex(text) {
5912
6991
  return entities;
5913
6992
  }
5914
6993
  function extractEntities(text) {
5915
- var _a2, _b;
6994
+ var _a2, _b2;
5916
6995
  const raw = [];
5917
6996
  raw.push(...extractQuoted(text));
5918
6997
  raw.push(...extractProper(text));
@@ -5955,7 +7034,7 @@ function extractEntities(text) {
5955
7034
  for (const entity of cleaned) {
5956
7035
  const key = entity.text.toLowerCase();
5957
7036
  const existing = best.get(key);
5958
- if (!existing || ((_a2 = typePriority[entity.type]) != null ? _a2 : 99) < ((_b = typePriority[existing.type]) != null ? _b : 99)) {
7037
+ if (!existing || ((_a2 = typePriority[entity.type]) != null ? _a2 : 99) < ((_b2 = typePriority[existing.type]) != null ? _b2 : 99)) {
5959
7038
  best.set(key, entity);
5960
7039
  }
5961
7040
  }
@@ -5992,7 +7071,7 @@ function normalizeBm25(rawScore, midpoint, steepness) {
5992
7071
  return 1 / (1 + Math.exp(-steepness * (rawScore - midpoint)));
5993
7072
  }
5994
7073
  function scoreAndRank(semanticResults, bm25Scores, entityBoosts, threshold, topK, explain = false) {
5995
- var _a2, _b, _c;
7074
+ var _a2, _b2, _c;
5996
7075
  const hasBm25 = Object.keys(bm25Scores).length > 0;
5997
7076
  const hasEntity = Object.keys(entityBoosts).length > 0;
5998
7077
  let maxPossible = 1;
@@ -6013,7 +7092,7 @@ function scoreAndRank(semanticResults, bm25Scores, entityBoosts, threshold, topK
6013
7092
  continue;
6014
7093
  }
6015
7094
  const memIdStr = String(memId);
6016
- const bm25Score = (_b = bm25Scores[memIdStr]) != null ? _b : 0;
7095
+ const bm25Score = (_b2 = bm25Scores[memIdStr]) != null ? _b2 : 0;
6017
7096
  const entityBoost = (_c = entityBoosts[memIdStr]) != null ? _c : 0;
6018
7097
  const rawCombined = semanticScore + bm25Score + entityBoost;
6019
7098
  const combined = Math.min(rawCombined / maxPossible, 1);
@@ -6041,18 +7120,18 @@ function scoreAndRank(semanticResults, bm25Scores, entityBoosts, threshold, topK
6041
7120
 
6042
7121
  // src/client/config.ts
6043
7122
  async function getNodeFs() {
6044
- var _a2, _b, _c, _d, _e;
7123
+ var _a2, _b2, _c, _d, _e;
6045
7124
  if (typeof process === "undefined" || !((_a2 = process.versions) == null ? void 0 : _a2.node)) return null;
6046
7125
  try {
6047
- const [fs4, path3, os2, crypto] = await Promise.all([
7126
+ const [fs5, path4, os3, crypto] = await Promise.all([
6048
7127
  import("fs"),
6049
7128
  import("path"),
6050
7129
  import("os"),
6051
7130
  import("crypto")
6052
7131
  ]);
6053
- const fsMod = (_b = fs4.default) != null ? _b : fs4;
6054
- const pathMod = (_c = path3.default) != null ? _c : path3;
6055
- const osMod = (_d = os2.default) != null ? _d : os2;
7132
+ const fsMod = (_b2 = fs5.default) != null ? _b2 : fs5;
7133
+ const pathMod = (_c = path4.default) != null ? _c : path4;
7134
+ const osMod = (_d = os3.default) != null ? _d : os3;
6056
7135
  const cryptoMod = (_e = crypto.default) != null ? _e : crypto;
6057
7136
  const dir = process.env.MEM0_DIR || pathMod.join(osMod.homedir(), ".mem0");
6058
7137
  return {
@@ -6432,6 +7511,52 @@ var Memory = class _Memory {
6432
7511
  console.error(`Failed to capture ${methodName} event:`, error);
6433
7512
  }
6434
7513
  }
7514
+ async _displayFirstRunNotice(triggerFunction) {
7515
+ try {
7516
+ await this._getTelemetryId();
7517
+ await displayFirstRunNotice(this, triggerFunction);
7518
+ } catch (e) {
7519
+ }
7520
+ }
7521
+ async _displayDecayUsageNotice(trigger) {
7522
+ try {
7523
+ await this._getTelemetryId();
7524
+ await displayDecayUsageNotice(this, trigger);
7525
+ } catch (e) {
7526
+ }
7527
+ }
7528
+ async _displayTemporalUsageNotice(trigger) {
7529
+ try {
7530
+ await this._getTelemetryId();
7531
+ await displayTemporalUsageNotice(this, trigger);
7532
+ } catch (e) {
7533
+ }
7534
+ }
7535
+ async _displayScaleThresholdNotice(trigger) {
7536
+ try {
7537
+ await this._getTelemetryId();
7538
+ await displayScaleThresholdNotice(this, trigger);
7539
+ } catch (e) {
7540
+ }
7541
+ }
7542
+ async _displayPerformanceSlowQueryNotice(trigger) {
7543
+ try {
7544
+ await this._getTelemetryId();
7545
+ await displayPerformanceSlowQueryNotice(this, trigger);
7546
+ } catch (e) {
7547
+ }
7548
+ }
7549
+ async _getNoticeTelemetryId() {
7550
+ try {
7551
+ if (!this.telemetryId || this.telemetryId === "anonymous" || this.telemetryId === "anonymous-supabase") {
7552
+ this.telemetryId = await getOrCreateMem0UserId() || "anonymous";
7553
+ }
7554
+ return this.telemetryId;
7555
+ } catch (e) {
7556
+ this.telemetryId = "anonymous";
7557
+ return this.telemetryId;
7558
+ }
7559
+ }
6435
7560
  static fromConfig(configDict) {
6436
7561
  try {
6437
7562
  const config = MemoryConfigSchema.parse(configDict);
@@ -6441,12 +7566,31 @@ var Memory = class _Memory {
6441
7566
  throw e;
6442
7567
  }
6443
7568
  }
7569
+ async updateProject(options = {}) {
7570
+ if ((options == null ? void 0 : options.decay) === true) {
7571
+ await this._getNoticeTelemetryId();
7572
+ throw new Error(await getDecayFeatureErrorMessage(this));
7573
+ }
7574
+ throw new Error("Project updates are not supported by the OSS Memory SDK.");
7575
+ }
6444
7576
  async add(messages, config) {
7577
+ if ((config == null ? void 0 : config.timestamp) !== void 0) {
7578
+ await this._getNoticeTelemetryId();
7579
+ throw new Error(
7580
+ await getTemporalFeatureErrorMessage(this, {
7581
+ triggerFunction: "add",
7582
+ triggerParameter: "timestamp"
7583
+ })
7584
+ );
7585
+ }
6445
7586
  if (messages === void 0 || messages === null) {
6446
7587
  throw new Error(
6447
7588
  "messages is required and cannot be undefined or null. Provide a string or array of messages."
6448
7589
  );
6449
7590
  }
7591
+ const temporalUsageNotice = detectTemporalUsageFromMetadata(
7592
+ config == null ? void 0 : config.metadata
7593
+ );
6450
7594
  await this._ensureInitialized();
6451
7595
  await this._captureEvent("add", {
6452
7596
  message_count: Array.isArray(messages) ? messages.length : 1,
@@ -6474,12 +7618,32 @@ var Memory = class _Memory {
6474
7618
  filters,
6475
7619
  infer
6476
7620
  );
7621
+ if (temporalUsageNotice) {
7622
+ await this._displayTemporalUsageNotice({
7623
+ triggerFunction: "add",
7624
+ triggerSource: temporalUsageNotice.triggerSource,
7625
+ triggerReason: temporalUsageNotice.triggerReason
7626
+ });
7627
+ } else {
7628
+ const scaleThresholdNotice = await detectScaleThresholdFromAddResult(
7629
+ this,
7630
+ vectorStoreResult
7631
+ );
7632
+ if (scaleThresholdNotice) {
7633
+ await this._displayScaleThresholdNotice({
7634
+ triggerFunction: "add",
7635
+ ...scaleThresholdNotice
7636
+ });
7637
+ } else {
7638
+ await this._displayFirstRunNotice("add");
7639
+ }
7640
+ }
6477
7641
  return {
6478
7642
  results: vectorStoreResult
6479
7643
  };
6480
7644
  }
6481
7645
  async addToVectorStore(messages, metadata, filters, infer) {
6482
- var _a2, _b, _c, _d, _e, _f, _g;
7646
+ var _a2, _b2, _c, _d, _e, _f, _g;
6483
7647
  if (!infer) {
6484
7648
  const returnedMemories = [];
6485
7649
  for (const message of messages) {
@@ -6521,7 +7685,7 @@ var Memory = class _Memory {
6521
7685
  uuidMapping[String(idx)] = mem.id;
6522
7686
  existingMemories.push({
6523
7687
  id: String(idx),
6524
- text: (_b = (_a2 = mem.payload) == null ? void 0 : _a2.data) != null ? _b : ""
7688
+ text: (_b2 = (_a2 = mem.payload) == null ? void 0 : _a2.data) != null ? _b2 : ""
6525
7689
  });
6526
7690
  }
6527
7691
  const isAgentScoped = !!filters.agent_id && !filters.user_id;
@@ -6833,7 +7997,10 @@ var Memory = class _Memory {
6833
7997
  async get(memoryId) {
6834
7998
  await this._ensureInitialized();
6835
7999
  const memory = await this.vectorStore.get(memoryId);
6836
- if (!memory) return null;
8000
+ if (!memory) {
8001
+ await this._displayFirstRunNotice("get");
8002
+ return null;
8003
+ }
6837
8004
  const filters = {
6838
8005
  ...memory.payload.user_id && { user_id: memory.payload.user_id },
6839
8006
  ...memory.payload.agent_id && { agent_id: memory.payload.agent_id },
@@ -6863,10 +8030,25 @@ var Memory = class _Memory {
6863
8030
  memoryItem.metadata[key] = value;
6864
8031
  }
6865
8032
  }
6866
- return { ...memoryItem, ...filters };
8033
+ const result = { ...memoryItem, ...filters };
8034
+ await this._displayFirstRunNotice("get");
8035
+ return result;
6867
8036
  }
6868
8037
  async search(query, config) {
6869
- var _a2, _b, _c, _d, _e;
8038
+ var _a2, _b2, _c, _d, _e;
8039
+ if ((config == null ? void 0 : config.referenceDate) !== void 0) {
8040
+ await this._getNoticeTelemetryId();
8041
+ throw new Error(
8042
+ await getTemporalFeatureErrorMessage(this, {
8043
+ triggerFunction: "search",
8044
+ triggerParameter: "referenceDate"
8045
+ })
8046
+ );
8047
+ }
8048
+ const temporalUsageNotice = detectTemporalUsageFromSearch(
8049
+ query,
8050
+ config == null ? void 0 : config.filters
8051
+ );
6870
8052
  rejectTopLevelEntityParams(config, "search");
6871
8053
  validateSearchParams(config.threshold, config.topK);
6872
8054
  const normalizedFilters = config.filters ? Object.fromEntries(
@@ -6905,6 +8087,7 @@ var Memory = class _Memory {
6905
8087
  "filters must contain at least one of: user_id, agent_id, run_id. Example: filters: { user_id: 'u1' }"
6906
8088
  );
6907
8089
  }
8090
+ const searchStartMs = Date.now();
6908
8091
  const queryLemmatized = lemmatizeForBm25(query);
6909
8092
  const queryEntities = extractEntities(query);
6910
8093
  const queryEmbedding = await this.embedder.embed(query);
@@ -6931,7 +8114,7 @@ var Memory = class _Memory {
6931
8114
  const [midpoint, steepness] = getBm25Params(query, queryLemmatized);
6932
8115
  for (const mem of keywordResults) {
6933
8116
  const memId = String(mem.id);
6934
- const rawScore = (_b = mem.score) != null ? _b : 0;
8117
+ const rawScore = (_b2 = mem.score) != null ? _b2 : 0;
6935
8118
  if (rawScore > 0) {
6936
8119
  bm25Scores[memId] = normalizeBm25(rawScore, midpoint, steepness);
6937
8120
  }
@@ -6968,15 +8151,15 @@ var Memory = class _Memory {
6968
8151
  (_, i) => entityStore.search(embeddings[i], 500, entitySearchFilters)
6969
8152
  )
6970
8153
  );
6971
- for (const result of searchResults) {
6972
- if (result.status === "rejected") {
8154
+ for (const result2 of searchResults) {
8155
+ if (result2.status === "rejected") {
6973
8156
  console.warn(
6974
8157
  "Entity boost search failed for one entity:",
6975
- result.reason
8158
+ result2.reason
6976
8159
  );
6977
8160
  continue;
6978
8161
  }
6979
- for (const match of result.value) {
8162
+ for (const match of result2.value) {
6980
8163
  const similarity = (_c = match.score) != null ? _c : 0;
6981
8164
  if (similarity < 0.5) continue;
6982
8165
  const payload = match.payload || {};
@@ -7048,22 +8231,68 @@ var Memory = class _Memory {
7048
8231
  ...scored.scoreDetails && { score_details: scored.scoreDetails }
7049
8232
  };
7050
8233
  });
7051
- return {
8234
+ const result = {
7052
8235
  results
7053
8236
  };
8237
+ const searchElapsedMs = Date.now() - searchStartMs;
8238
+ if (temporalUsageNotice) {
8239
+ await this._displayTemporalUsageNotice({
8240
+ triggerFunction: "search",
8241
+ triggerSource: temporalUsageNotice.triggerSource,
8242
+ triggerReason: temporalUsageNotice.triggerReason
8243
+ });
8244
+ } else {
8245
+ const scaleThresholdNotice = detectScaleThresholdFromTopK(topK);
8246
+ if (scaleThresholdNotice) {
8247
+ await this._displayScaleThresholdNotice({
8248
+ triggerFunction: "search",
8249
+ ...scaleThresholdNotice
8250
+ });
8251
+ } else {
8252
+ const performanceSlowQueryNotice = detectPerformanceSlowQuery(
8253
+ searchElapsedMs,
8254
+ topK,
8255
+ results.length
8256
+ );
8257
+ if (performanceSlowQueryNotice) {
8258
+ await this._displayPerformanceSlowQueryNotice({
8259
+ triggerFunction: "search",
8260
+ triggerReason: "slow_query",
8261
+ ...performanceSlowQueryNotice
8262
+ });
8263
+ } else {
8264
+ await this._displayFirstRunNotice("search");
8265
+ }
8266
+ }
8267
+ }
8268
+ return result;
7054
8269
  }
7055
8270
  async update(memoryId, data) {
7056
8271
  await this._ensureInitialized();
7057
8272
  await this._captureEvent("update", { memory_id: memoryId });
7058
8273
  const embedding = await this.embedder.embed(data);
7059
8274
  await this.updateMemory(memoryId, data, { [data]: embedding });
7060
- return { message: "Memory updated successfully!" };
8275
+ const result = { message: "Memory updated successfully!" };
8276
+ await this._displayFirstRunNotice("update");
8277
+ return result;
7061
8278
  }
7062
8279
  async delete(memoryId) {
7063
8280
  await this._ensureInitialized();
7064
8281
  await this._captureEvent("delete", { memory_id: memoryId });
7065
8282
  await this.deleteMemory(memoryId);
7066
- return { message: "Memory deleted successfully!" };
8283
+ const result = { message: "Memory deleted successfully!" };
8284
+ const deleteCount = getDecayUsageDeleteCountAfterSuccess();
8285
+ if (isDecayUsageDeleteEligible(deleteCount)) {
8286
+ await this._displayDecayUsageNotice({
8287
+ triggerFunction: "delete",
8288
+ triggerSource: "delete_count",
8289
+ triggerReason: "repeated_deletes",
8290
+ deleteCount
8291
+ });
8292
+ } else {
8293
+ await this._displayFirstRunNotice("delete");
8294
+ }
8295
+ return result;
7067
8296
  }
7068
8297
  async deleteAll(config) {
7069
8298
  await this._ensureInitialized();
@@ -7086,11 +8315,24 @@ var Memory = class _Memory {
7086
8315
  for (const memory of memories) {
7087
8316
  await this.deleteMemory(memory.id);
7088
8317
  }
7089
- return { message: "Memories deleted successfully!" };
8318
+ const result = { message: "Memories deleted successfully!" };
8319
+ if (memories.length > 0) {
8320
+ await this._displayDecayUsageNotice({
8321
+ triggerFunction: "delete_all",
8322
+ triggerSource: "delete_all",
8323
+ triggerReason: "bulk_delete",
8324
+ deletedCount: memories.length
8325
+ });
8326
+ } else {
8327
+ await this._displayFirstRunNotice("delete_all");
8328
+ }
8329
+ return result;
7090
8330
  }
7091
8331
  async history(memoryId) {
7092
8332
  await this._ensureInitialized();
7093
- return this.db.getHistory(memoryId);
8333
+ const result = await this.db.getHistory(memoryId);
8334
+ await this._displayFirstRunNotice("history");
8335
+ return result;
7094
8336
  }
7095
8337
  async reset() {
7096
8338
  await this._ensureInitialized();
@@ -7131,9 +8373,10 @@ var Memory = class _Memory {
7131
8373
  console.error(this._initError);
7132
8374
  });
7133
8375
  await this._initPromise;
8376
+ await this._displayFirstRunNotice("reset");
7134
8377
  }
7135
8378
  async getAll(config) {
7136
- var _a2, _b, _c;
8379
+ var _a2, _b2, _c;
7137
8380
  rejectTopLevelEntityParams(config, "getAll");
7138
8381
  validateSearchParams(void 0, config.topK);
7139
8382
  await this._ensureInitialized();
@@ -7142,7 +8385,7 @@ var Memory = class _Memory {
7142
8385
  Object.entries({
7143
8386
  ...config.filters || {},
7144
8387
  user_id: validateAndTrimEntityId((_a2 = config.filters) == null ? void 0 : _a2.user_id, "user_id"),
7145
- agent_id: validateAndTrimEntityId((_b = config.filters) == null ? void 0 : _b.agent_id, "agent_id"),
8388
+ agent_id: validateAndTrimEntityId((_b2 = config.filters) == null ? void 0 : _b2.agent_id, "agent_id"),
7146
8389
  run_id: validateAndTrimEntityId((_c = config.filters) == null ? void 0 : _c.run_id, "run_id")
7147
8390
  }).filter(([, v]) => v !== void 0)
7148
8391
  );
@@ -7180,7 +8423,17 @@ var Memory = class _Memory {
7180
8423
  ...mem.payload.agent_id && { agent_id: mem.payload.agent_id },
7181
8424
  ...mem.payload.run_id && { run_id: mem.payload.run_id }
7182
8425
  }));
7183
- return { results };
8426
+ const result = { results };
8427
+ const scaleThresholdNotice = detectScaleThresholdFromTopK(topK);
8428
+ if (scaleThresholdNotice) {
8429
+ await this._displayScaleThresholdNotice({
8430
+ triggerFunction: "get_all",
8431
+ ...scaleThresholdNotice
8432
+ });
8433
+ } else {
8434
+ await this._displayFirstRunNotice("get_all");
8435
+ }
8436
+ return result;
7184
8437
  }
7185
8438
  async createMemory(data, existingEmbeddings, metadata) {
7186
8439
  const memoryId = (0, import_uuid3.v4)();
@@ -7210,20 +8463,13 @@ var Memory = class _Memory {
7210
8463
  const prevValue = existingMemory.payload.data;
7211
8464
  const embedding = existingEmbeddings[data] || await this.embedder.embed(data);
7212
8465
  const newMetadata = {
8466
+ ...existingMemory.payload,
7213
8467
  ...metadata,
7214
8468
  data,
7215
8469
  hash: (0, import_crypto2.createHash)("md5").update(data).digest("hex"),
8470
+ textLemmatized: lemmatizeForBm25(data),
7216
8471
  createdAt: existingMemory.payload.createdAt,
7217
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
7218
- ...existingMemory.payload.user_id && {
7219
- user_id: existingMemory.payload.user_id
7220
- },
7221
- ...existingMemory.payload.agent_id && {
7222
- agent_id: existingMemory.payload.agent_id
7223
- },
7224
- ...existingMemory.payload.run_id && {
7225
- run_id: existingMemory.payload.run_id
7226
- }
8472
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
7227
8473
  };
7228
8474
  await this.vectorStore.update(memoryId, embedding, newMetadata);
7229
8475
  await this.db.addHistory(