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.
@@ -41,7 +41,10 @@ var MemoryConfigSchema = z.object({
41
41
  modelProperties: z.record(z.string(), z.any()).optional(),
42
42
  baseURL: z.string().optional(),
43
43
  url: z.string().optional(),
44
- timeout: z.number().optional()
44
+ timeout: z.number().optional(),
45
+ temperature: z.number().optional(),
46
+ topP: z.number().optional(),
47
+ maxTokens: z.number().optional()
45
48
  })
46
49
  }),
47
50
  historyDbPath: z.string().optional(),
@@ -170,8 +173,8 @@ var DEFAULT_MODEL = "nomic-ai/nomic-embed-text-v1.5-GGUF/nomic-embed-text-v1.5.f
170
173
  var DEFAULT_LMSTUDIO_API_KEY = "lm-studio";
171
174
  var LMStudioEmbedder = class {
172
175
  constructor(config) {
173
- var _a2, _b;
174
- const baseURL = (_b = (_a2 = config.baseURL) != null ? _a2 : config.url) != null ? _b : DEFAULT_BASE_URL;
176
+ var _a2, _b2;
177
+ const baseURL = (_b2 = (_a2 = config.baseURL) != null ? _a2 : config.url) != null ? _b2 : DEFAULT_BASE_URL;
175
178
  const apiKey = config.apiKey || DEFAULT_LMSTUDIO_API_KEY;
176
179
  this.openai = new OpenAI2({ apiKey, baseURL: String(baseURL) });
177
180
  this.model = config.model || DEFAULT_MODEL;
@@ -331,25 +334,54 @@ var OpenAIStructuredLLM = class {
331
334
  import Anthropic from "@anthropic-ai/sdk";
332
335
  var AnthropicLLM = class {
333
336
  constructor(config) {
337
+ var _a2, _b2;
334
338
  const apiKey = config.apiKey || process.env.ANTHROPIC_API_KEY;
335
339
  if (!apiKey) {
336
340
  throw new Error("Anthropic API key is required");
337
341
  }
338
342
  this.client = new Anthropic({ apiKey });
339
- this.model = config.model || "claude-3-sonnet-20240229";
343
+ this.model = config.model || "claude-sonnet-4-6";
344
+ this.maxTokens = (_a2 = config.maxTokens) != null ? _a2 : 2e3;
345
+ this.temperature = (_b2 = config.temperature) != null ? _b2 : 0.1;
346
+ this.topP = config.topP;
340
347
  }
341
- async generateResponse(messages, responseFormat) {
348
+ async generateResponse(messages, responseFormat, tools) {
342
349
  const systemMessage = messages.find((msg) => msg.role === "system");
343
350
  const otherMessages = messages.filter((msg) => msg.role !== "system");
344
- const response = await this.client.messages.create({
351
+ const params = {
345
352
  model: this.model,
346
353
  messages: otherMessages.map((msg) => ({
347
354
  role: msg.role,
348
355
  content: typeof msg.content === "string" ? msg.content : msg.content.image_url.url
349
356
  })),
350
357
  system: typeof (systemMessage == null ? void 0 : systemMessage.content) === "string" ? systemMessage.content : void 0,
351
- max_tokens: 4096
352
- });
358
+ max_tokens: this.maxTokens
359
+ };
360
+ if (this.temperature !== void 0) {
361
+ params.temperature = this.temperature;
362
+ } else if (this.topP !== void 0) {
363
+ params.top_p = this.topP;
364
+ }
365
+ if (tools) {
366
+ params.tools = tools;
367
+ params.tool_choice = { type: "auto" };
368
+ }
369
+ const response = await this.client.messages.create(params);
370
+ if (tools) {
371
+ let content = "";
372
+ const toolCalls = [];
373
+ for (const block of response.content) {
374
+ if (block.type === "text") {
375
+ content = block.text;
376
+ } else if (block.type === "tool_use") {
377
+ toolCalls.push({
378
+ name: block.name,
379
+ arguments: JSON.stringify(block.input)
380
+ });
381
+ }
382
+ }
383
+ return { content, role: "assistant", toolCalls };
384
+ }
353
385
  const firstBlock = response.content[0];
354
386
  if (firstBlock.type === "text") {
355
387
  return firstBlock.text;
@@ -359,10 +391,10 @@ var AnthropicLLM = class {
359
391
  }
360
392
  async generateChat(messages) {
361
393
  const response = await this.generateResponse(messages);
362
- return {
363
- content: response,
364
- role: "assistant"
365
- };
394
+ if (typeof response === "string") {
395
+ return { content: response, role: "assistant" };
396
+ }
397
+ return response;
366
398
  }
367
399
  };
368
400
 
@@ -1165,7 +1197,7 @@ var Qdrant = class {
1165
1197
  }
1166
1198
  }
1167
1199
  async ensureCollection(name, size) {
1168
- var _a2, _b, _c;
1200
+ var _a2, _b2, _c;
1169
1201
  try {
1170
1202
  await this.client.createCollection(name, {
1171
1203
  vectors: {
@@ -1178,7 +1210,7 @@ var Qdrant = class {
1178
1210
  if (name === this.collectionName) {
1179
1211
  try {
1180
1212
  const collectionInfo = await this.client.getCollection(name);
1181
- const vectorConfig = (_b = (_a2 = collectionInfo.config) == null ? void 0 : _a2.params) == null ? void 0 : _b.vectors;
1213
+ const vectorConfig = (_b2 = (_a2 = collectionInfo.config) == null ? void 0 : _a2.params) == null ? void 0 : _b2.vectors;
1182
1214
  if (vectorConfig && vectorConfig.size !== size) {
1183
1215
  throw new Error(
1184
1216
  `Collection ${name} exists but has wrong vector size. Expected: ${size}, got: ${vectorConfig.size}`
@@ -1265,7 +1297,7 @@ var VectorizeDB = class {
1265
1297
  return null;
1266
1298
  }
1267
1299
  async search(query, topK = 5, filters) {
1268
- var _a2, _b;
1300
+ var _a2, _b2;
1269
1301
  try {
1270
1302
  const result = await ((_a2 = this.client) == null ? void 0 : _a2.vectorize.indexes.query(
1271
1303
  this.indexName,
@@ -1277,7 +1309,7 @@ var VectorizeDB = class {
1277
1309
  topK
1278
1310
  }
1279
1311
  ));
1280
- return ((_b = result == null ? void 0 : result.matches) == null ? void 0 : _b.map((match) => ({
1312
+ return ((_b2 = result == null ? void 0 : result.matches) == null ? void 0 : _b2.map((match) => ({
1281
1313
  id: match.id,
1282
1314
  payload: match.metadata,
1283
1315
  score: match.score
@@ -1372,7 +1404,7 @@ var VectorizeDB = class {
1372
1404
  }
1373
1405
  }
1374
1406
  async list(filters, topK = 20) {
1375
- var _a2, _b;
1407
+ var _a2, _b2;
1376
1408
  try {
1377
1409
  const result = await ((_a2 = this.client) == null ? void 0 : _a2.vectorize.indexes.query(
1378
1410
  this.indexName,
@@ -1385,7 +1417,7 @@ var VectorizeDB = class {
1385
1417
  returnMetadata: "all"
1386
1418
  }
1387
1419
  ));
1388
- const matches = ((_b = result == null ? void 0 : result.matches) == null ? void 0 : _b.map((match) => ({
1420
+ const matches = ((_b2 = result == null ? void 0 : result.matches) == null ? void 0 : _b2.map((match) => ({
1389
1421
  id: match.id,
1390
1422
  payload: match.metadata,
1391
1423
  score: match.score
@@ -1409,7 +1441,7 @@ var VectorizeDB = class {
1409
1441
  );
1410
1442
  }
1411
1443
  async getUserId() {
1412
- var _a2, _b, _c;
1444
+ var _a2, _b2, _c;
1413
1445
  try {
1414
1446
  let found = false;
1415
1447
  for await (const index of this.client.vectorize.indexes.list({
@@ -1429,7 +1461,7 @@ var VectorizeDB = class {
1429
1461
  }
1430
1462
  }));
1431
1463
  }
1432
- const result = await ((_b = this.client) == null ? void 0 : _b.vectorize.indexes.query(
1464
+ const result = await ((_b2 = this.client) == null ? void 0 : _b2.vectorize.indexes.query(
1433
1465
  "memory_migrations",
1434
1466
  {
1435
1467
  account_id: this.accountId,
@@ -1468,7 +1500,7 @@ var VectorizeDB = class {
1468
1500
  }
1469
1501
  }
1470
1502
  async setUserId(userId) {
1471
- var _a2, _b;
1503
+ var _a2, _b2;
1472
1504
  try {
1473
1505
  const result = await ((_a2 = this.client) == null ? void 0 : _a2.vectorize.indexes.query(
1474
1506
  "memory_migrations",
@@ -1491,7 +1523,7 @@ var VectorizeDB = class {
1491
1523
  method: "POST",
1492
1524
  headers: {
1493
1525
  "Content-Type": "application/x-ndjson",
1494
- Authorization: `Bearer ${(_b = this.client) == null ? void 0 : _b.apiToken}`
1526
+ Authorization: `Bearer ${(_b2 = this.client) == null ? void 0 : _b2.apiToken}`
1495
1527
  },
1496
1528
  body: JSON.stringify(data) + "\n"
1497
1529
  // ndjson format
@@ -1511,7 +1543,7 @@ var VectorizeDB = class {
1511
1543
  return this._initPromise;
1512
1544
  }
1513
1545
  async _doInitialize() {
1514
- var _a2, _b, _c, _d, _e;
1546
+ var _a2, _b2, _c, _d, _e;
1515
1547
  try {
1516
1548
  let indexFound = false;
1517
1549
  for await (const idx of this.client.vectorize.indexes.list({
@@ -1534,7 +1566,7 @@ var VectorizeDB = class {
1534
1566
  }));
1535
1567
  const properties2 = ["userId", "agentId", "runId"];
1536
1568
  for (const propertyName of properties2) {
1537
- await ((_b = this.client) == null ? void 0 : _b.vectorize.indexes.metadataIndex.create(
1569
+ await ((_b2 = this.client) == null ? void 0 : _b2.vectorize.indexes.metadataIndex.create(
1538
1570
  this.indexName,
1539
1571
  {
1540
1572
  account_id: this.accountId,
@@ -2587,7 +2619,7 @@ var SQLiteManager = class {
2587
2619
  }
2588
2620
  async batchAddHistory(records) {
2589
2621
  const txn = this.db.transaction(() => {
2590
- var _a2, _b, _c;
2622
+ var _a2, _b2, _c;
2591
2623
  for (const record of records) {
2592
2624
  this.stmtInsert.run(
2593
2625
  record.memoryId,
@@ -2595,7 +2627,7 @@ var SQLiteManager = class {
2595
2627
  record.newValue,
2596
2628
  record.action,
2597
2629
  (_a2 = record.createdAt) != null ? _a2 : null,
2598
- (_b = record.updatedAt) != null ? _b : null,
2630
+ (_b2 = record.updatedAt) != null ? _b2 : null,
2599
2631
  (_c = record.isDeleted) != null ? _c : 0
2600
2632
  );
2601
2633
  }
@@ -3447,12 +3479,12 @@ function truncateContent(text, limit = PAST_MESSAGE_TRUNCATION_LIMIT) {
3447
3479
  return text.slice(0, limit) + "...";
3448
3480
  }
3449
3481
  function formatConversationHistory(messages) {
3450
- var _a2, _b;
3482
+ var _a2, _b2;
3451
3483
  if (!messages || messages.length === 0) return "";
3452
3484
  let result = "";
3453
3485
  for (const msg of messages) {
3454
3486
  const role = (_a2 = msg.role) != null ? _a2 : "";
3455
- const content = (_b = msg.content) != null ? _b : "";
3487
+ const content = (_b2 = msg.content) != null ? _b2 : "";
3456
3488
  if (role && content) {
3457
3489
  result += `${role}: ${truncateContent(content)}
3458
3490
  `;
@@ -3464,10 +3496,10 @@ function serializeMemories(memories) {
3464
3496
  return JSON.stringify(memories != null ? memories : []);
3465
3497
  }
3466
3498
  function generateAdditiveExtractionPrompt(options) {
3467
- var _a2, _b, _c;
3499
+ var _a2, _b2, _c;
3468
3500
  const now = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
3469
3501
  const currentDate = (_a2 = options.currentDate) != null ? _a2 : now;
3470
- const observationDate = (_b = options.observationDate) != null ? _b : currentDate;
3502
+ const observationDate = (_b2 = options.observationDate) != null ? _b2 : currentDate;
3471
3503
  const sections = [];
3472
3504
  sections.push("## Summary\n");
3473
3505
  sections.push(
@@ -3638,14 +3670,14 @@ var LangchainLLM = class {
3638
3670
  this.modelName = this.llmInstance.modelId || this.llmInstance.model || "langchain-model";
3639
3671
  }
3640
3672
  async generateResponse(messages, response_format, tools) {
3641
- var _a2, _b, _c, _d, _e;
3673
+ var _a2, _b2, _c, _d, _e;
3642
3674
  const langchainMessages = convertToLangchainMessages(messages);
3643
3675
  let runnable = this.llmInstance;
3644
3676
  const invokeOptions = {};
3645
3677
  let isStructuredOutput = false;
3646
3678
  let selectedSchema = null;
3647
3679
  const systemPromptContent = ((_a2 = messages.find((m) => m.role === "system")) == null ? void 0 : _a2.content) || "";
3648
- const userPromptContent = ((_b = messages.find((m) => m.role === "user")) == null ? void 0 : _b.content) || "";
3680
+ const userPromptContent = ((_b2 = messages.find((m) => m.role === "user")) == null ? void 0 : _b2.content) || "";
3649
3681
  if (systemPromptContent.includes("Personal Information Organizer") && systemPromptContent.includes("extract relevant pieces of information")) {
3650
3682
  selectedSchema = FactRetrievalSchema;
3651
3683
  } else if (userPromptContent.includes("smart memory manager") && userPromptContent.includes("Compare newly retrieved facts")) {
@@ -3775,7 +3807,7 @@ var LangchainVectorStore = class {
3775
3807
  // Simple in-memory user ID
3776
3808
  constructor(config) {
3777
3809
  this.storeUserId = "anonymous-langchain-user";
3778
- var _a2, _b;
3810
+ var _a2, _b2;
3779
3811
  if (!config.client || typeof config.client !== "object") {
3780
3812
  throw new Error(
3781
3813
  "Langchain vector store provider requires an initialized Langchain VectorStore instance passed via the 'client' field."
@@ -3791,7 +3823,7 @@ var LangchainVectorStore = class {
3791
3823
  if (!this.dimension && ((_a2 = this.lcStore.embeddings) == null ? void 0 : _a2.embeddingDimension)) {
3792
3824
  this.dimension = this.lcStore.embeddings.embeddingDimension;
3793
3825
  }
3794
- if (!this.dimension && ((_b = this.lcStore.embedding) == null ? void 0 : _b.embeddingDimension)) {
3826
+ if (!this.dimension && ((_b2 = this.lcStore.embedding) == null ? void 0 : _b2.embeddingDimension)) {
3795
3827
  this.dimension = this.lcStore.embedding.embeddingDimension;
3796
3828
  }
3797
3829
  if (!this.dimension) {
@@ -4937,13 +4969,13 @@ var DEFAULT_MEMORY_CONFIG = {
4937
4969
  // src/oss/src/config/manager.ts
4938
4970
  var ConfigManager = class {
4939
4971
  static mergeConfig(userConfig = {}) {
4940
- var _a2, _b, _c, _d, _e, _f, _g;
4972
+ var _a2, _b2, _c, _d, _e, _f, _g;
4941
4973
  const mergedConfig = {
4942
4974
  version: userConfig.version || DEFAULT_MEMORY_CONFIG.version,
4943
4975
  embedder: {
4944
4976
  provider: ((_a2 = userConfig.embedder) == null ? void 0 : _a2.provider) || DEFAULT_MEMORY_CONFIG.embedder.provider,
4945
4977
  config: (() => {
4946
- var _a3, _b2, _c2, _d2;
4978
+ var _a3, _b3, _c2, _d2;
4947
4979
  const defaultConf = DEFAULT_MEMORY_CONFIG.embedder.config;
4948
4980
  const userConf = (_a3 = userConfig.embedder) == null ? void 0 : _a3.config;
4949
4981
  let finalModel = defaultConf.model;
@@ -4952,7 +4984,7 @@ var ConfigManager = class {
4952
4984
  } else if ((userConf == null ? void 0 : userConf.model) && typeof userConf.model === "string") {
4953
4985
  finalModel = userConf.model;
4954
4986
  }
4955
- 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;
4987
+ 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;
4956
4988
  const embeddingDims = (_d2 = userConf == null ? void 0 : userConf.embeddingDims) != null ? _d2 : userConf == null ? void 0 : userConf.embedding_dims;
4957
4989
  return {
4958
4990
  apiKey: (userConf == null ? void 0 : userConf.apiKey) !== void 0 ? userConf.apiKey : defaultConf.apiKey,
@@ -4965,12 +4997,12 @@ var ConfigManager = class {
4965
4997
  })()
4966
4998
  },
4967
4999
  vectorStore: {
4968
- provider: ((_b = userConfig.vectorStore) == null ? void 0 : _b.provider) || DEFAULT_MEMORY_CONFIG.vectorStore.provider,
5000
+ provider: ((_b2 = userConfig.vectorStore) == null ? void 0 : _b2.provider) || DEFAULT_MEMORY_CONFIG.vectorStore.provider,
4969
5001
  config: (() => {
4970
- var _a3, _b2, _c2;
5002
+ var _a3, _b3, _c2;
4971
5003
  const defaultConf = DEFAULT_MEMORY_CONFIG.vectorStore.config;
4972
5004
  const userConf = (_a3 = userConfig.vectorStore) == null ? void 0 : _a3.config;
4973
- const explicitDimension = (userConf == null ? void 0 : userConf.dimension) || ((_c2 = (_b2 = userConfig.embedder) == null ? void 0 : _b2.config) == null ? void 0 : _c2.embeddingDims) || void 0;
5005
+ const explicitDimension = (userConf == null ? void 0 : userConf.dimension) || ((_c2 = (_b3 = userConfig.embedder) == null ? void 0 : _b3.config) == null ? void 0 : _c2.embeddingDims) || void 0;
4974
5006
  if ((userConf == null ? void 0 : userConf.client) && typeof userConf.client === "object") {
4975
5007
  return {
4976
5008
  client: userConf.client,
@@ -4994,7 +5026,7 @@ var ConfigManager = class {
4994
5026
  llm: {
4995
5027
  provider: ((_c = userConfig.llm) == null ? void 0 : _c.provider) || DEFAULT_MEMORY_CONFIG.llm.provider,
4996
5028
  config: (() => {
4997
- var _a3, _b2, _c2, _d2;
5029
+ var _a3, _b3, _c2, _d2, _e2, _f2, _g2;
4998
5030
  const defaultConf = DEFAULT_MEMORY_CONFIG.llm.config;
4999
5031
  const userConf = (_a3 = userConfig.llm) == null ? void 0 : _a3.config;
5000
5032
  let finalModel = defaultConf.model;
@@ -5003,20 +5035,27 @@ var ConfigManager = class {
5003
5035
  } else if ((userConf == null ? void 0 : userConf.model) && typeof userConf.model === "string") {
5004
5036
  finalModel = userConf.model;
5005
5037
  }
5006
- 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;
5038
+ 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;
5039
+ const llmRaw = userConf;
5040
+ const temperature = (_e2 = userConf == null ? void 0 : userConf.temperature) != null ? _e2 : llmRaw == null ? void 0 : llmRaw.temperature;
5041
+ const topP = (_f2 = userConf == null ? void 0 : userConf.topP) != null ? _f2 : llmRaw == null ? void 0 : llmRaw.top_p;
5042
+ const maxTokens = (_g2 = userConf == null ? void 0 : userConf.maxTokens) != null ? _g2 : llmRaw == null ? void 0 : llmRaw.max_tokens;
5007
5043
  return {
5008
5044
  baseURL: llmBaseURL,
5009
5045
  url: userConf == null ? void 0 : userConf.url,
5010
5046
  apiKey: (userConf == null ? void 0 : userConf.apiKey) !== void 0 ? userConf.apiKey : defaultConf.apiKey,
5011
5047
  model: finalModel,
5012
- modelProperties: (userConf == null ? void 0 : userConf.modelProperties) !== void 0 ? userConf.modelProperties : defaultConf.modelProperties
5048
+ modelProperties: (userConf == null ? void 0 : userConf.modelProperties) !== void 0 ? userConf.modelProperties : defaultConf.modelProperties,
5049
+ temperature,
5050
+ topP,
5051
+ maxTokens
5013
5052
  };
5014
5053
  })()
5015
5054
  },
5016
5055
  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),
5017
5056
  customInstructions: userConfig.customInstructions,
5018
5057
  historyStore: (() => {
5019
- var _a3, _b2;
5058
+ var _a3, _b3;
5020
5059
  const defaultHistoryStore = DEFAULT_MEMORY_CONFIG.historyStore;
5021
5060
  const historyProvider = ((_a3 = userConfig.historyStore) == null ? void 0 : _a3.provider) || defaultHistoryStore.provider;
5022
5061
  const isSqlite = historyProvider.toLowerCase() === "sqlite";
@@ -5027,7 +5066,7 @@ var ConfigManager = class {
5027
5066
  config: {
5028
5067
  ...isSqlite ? defaultHistoryStore.config : {},
5029
5068
  ...isSqlite && userConfig.historyDbPath ? { historyDbPath: userConfig.historyDbPath } : {},
5030
- ...(_b2 = userConfig.historyStore) == null ? void 0 : _b2.config
5069
+ ...(_b3 = userConfig.historyStore) == null ? void 0 : _b3.config
5031
5070
  }
5032
5071
  };
5033
5072
  })(),
@@ -5075,15 +5114,16 @@ var parse_vision_messages = async (messages) => {
5075
5114
  };
5076
5115
 
5077
5116
  // src/oss/src/utils/telemetry.ts
5078
- var version = true ? "3.0.7" : "dev";
5117
+ var version = true ? "3.0.9" : "dev";
5079
5118
  var MEM0_TELEMETRY = true;
5080
- var _a;
5119
+ var _a, _b;
5081
5120
  try {
5082
- MEM0_TELEMETRY = ((_a = process == null ? void 0 : process.env) == null ? void 0 : _a.MEM0_TELEMETRY) === "false" ? false : true;
5121
+ MEM0_TELEMETRY = ((_b = (_a = process == null ? void 0 : process.env) == null ? void 0 : _a.MEM0_TELEMETRY) == null ? void 0 : _b.toLowerCase()) === "false" ? false : true;
5083
5122
  } catch (error) {
5084
5123
  }
5085
5124
  var POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX";
5086
5125
  var POSTHOG_HOST = "https://us.i.posthog.com/i/v0/e/";
5126
+ var NOTICE_EVENT_NAME = "mem0.notice_displayed";
5087
5127
  var DEFAULT_SAMPLE_RATE = 0.1;
5088
5128
  var MEM0_TELEMETRY_SAMPLE_RATE = (() => {
5089
5129
  var _a2;
@@ -5099,7 +5139,11 @@ var MEM0_TELEMETRY_SAMPLE_RATE = (() => {
5099
5139
  }
5100
5140
  return DEFAULT_SAMPLE_RATE;
5101
5141
  })();
5102
- var LIFECYCLE_EVENTS = /* @__PURE__ */ new Set(["init", "reset"]);
5142
+ var ALWAYS_SEND_EVENTS = /* @__PURE__ */ new Set([
5143
+ "init",
5144
+ "reset",
5145
+ "notice_displayed"
5146
+ ]);
5103
5147
  var UnifiedTelemetry = class {
5104
5148
  constructor(projectApiKey, host) {
5105
5149
  this.apiKey = projectApiKey;
@@ -5139,13 +5183,16 @@ var UnifiedTelemetry = class {
5139
5183
  }
5140
5184
  };
5141
5185
  var telemetry = new UnifiedTelemetry(POSTHOG_API_KEY, POSTHOG_HOST);
5186
+ function isTelemetryEnabled() {
5187
+ return MEM0_TELEMETRY;
5188
+ }
5142
5189
  async function captureClientEvent(eventName, instance, additionalData = {}) {
5143
5190
  if (!instance.telemetryId) {
5144
5191
  console.warn("No telemetry ID found for instance");
5145
5192
  return;
5146
5193
  }
5147
- const isLifecycle = LIFECYCLE_EVENTS.has(eventName);
5148
- if (!isLifecycle && Math.random() >= MEM0_TELEMETRY_SAMPLE_RATE) {
5194
+ const alwaysSend = ALWAYS_SEND_EVENTS.has(eventName);
5195
+ if (!alwaysSend && Math.random() >= MEM0_TELEMETRY_SAMPLE_RATE) {
5149
5196
  return;
5150
5197
  }
5151
5198
  const eventData = {
@@ -5157,7 +5204,7 @@ async function captureClientEvent(eventName, instance, additionalData = {}) {
5157
5204
  client_source: "nodejs",
5158
5205
  ...additionalData,
5159
5206
  // sample_rate set AFTER the spread so callers can never override it
5160
- sample_rate: isLifecycle ? 1 : MEM0_TELEMETRY_SAMPLE_RATE
5207
+ sample_rate: alwaysSend ? 1 : MEM0_TELEMETRY_SAMPLE_RATE
5161
5208
  };
5162
5209
  await telemetry.captureEvent(
5163
5210
  instance.telemetryId,
@@ -5165,6 +5212,1038 @@ async function captureClientEvent(eventName, instance, additionalData = {}) {
5165
5212
  eventData
5166
5213
  );
5167
5214
  }
5215
+ async function captureNoticeEvent(instance, properties = {}) {
5216
+ if (!instance.telemetryId) return;
5217
+ const eventData = {
5218
+ function: `${instance.constructor.name}`,
5219
+ method: "notice_displayed",
5220
+ api_host: instance.host,
5221
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5222
+ client_version: version,
5223
+ client_source: "nodejs",
5224
+ ...properties,
5225
+ sample_rate: 1
5226
+ };
5227
+ await telemetry.captureEvent(
5228
+ instance.telemetryId,
5229
+ NOTICE_EVENT_NAME,
5230
+ eventData
5231
+ );
5232
+ }
5233
+
5234
+ // src/oss/src/utils/notices.ts
5235
+ import * as fs4 from "fs";
5236
+ import * as os2 from "os";
5237
+ import * as path3 from "path";
5238
+ var NOTICE_FLAG_KEY = "mem0-oss-notices";
5239
+ var NOTICE_STATE_SECTION = "notice_state";
5240
+ var FIRST_RUN_NOTICE_ID = "first_run";
5241
+ var TEMPORAL_FEATURE_NOTICE_ID = "temporal_stub";
5242
+ var TEMPORAL_USAGE_NOTICE_ID = "temporal_usage";
5243
+ var DECAY_FEATURE_NOTICE_ID = "decay_stub";
5244
+ var DECAY_USAGE_NOTICE_ID = "decay_usage";
5245
+ var SCALE_THRESHOLD_NOTICE_ID = "scale_threshold";
5246
+ var PERFORMANCE_SLOW_QUERY_NOTICE_ID = "performance_slow_query";
5247
+ var NOTICE_CAP_LIMIT = 10;
5248
+ var NOTICE_CAP_WINDOW_MS = 7 * 24 * 60 * 60 * 1e3;
5249
+ var NOTICE_FLAG_TIMEOUT_MS = 500;
5250
+ var POSTHOG_FLAGS_URL = "https://us.i.posthog.com/flags?v=2";
5251
+ var DISPLAYED_VARIANT = "displayed";
5252
+ var HOLDOUT_VARIANT = "holdout";
5253
+ var LOG_LINE_NOTICE_TYPE = "log_line";
5254
+ var ERROR_NOTICE_TYPE = "error";
5255
+ var TEMPORAL_TIMESTAMP_PLAIN_ERROR = "The timestamp parameter is not supported by the OSS Memory SDK.";
5256
+ var TEMPORAL_REFERENCE_DATE_PLAIN_ERROR = "The referenceDate parameter is not supported by the OSS Memory SDK.";
5257
+ var DECAY_FEATURE_PLAIN_ERROR = "The decay parameter is not supported by the OSS Memory SDK.";
5258
+ var DECAY_USAGE_DELETE_THRESHOLD = 5;
5259
+ var SCALE_MEMORY_COUNT_THRESHOLD = 2e3;
5260
+ var SCALE_MEMORY_COUNT_CHECK_INTERVAL = 100;
5261
+ var SCALE_TOP_K_THRESHOLD = 50;
5262
+ var PERFORMANCE_SLOW_QUERY_THRESHOLD_MS = 2e3;
5263
+ var MAX_TEMPORAL_DETECTION_DEPTH = 32;
5264
+ 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/;
5265
+ 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;
5266
+ var RANGE_OPERATORS = /* @__PURE__ */ new Set(["gt", "gte", "lt", "lte"]);
5267
+ var firstRunConsumedInProcess = false;
5268
+ var firstRunClaimInProgress = false;
5269
+ var decayUsageSuccessfulDeleteCount = 0;
5270
+ var noticeCapacityReachedInProcess = /* @__PURE__ */ new Set();
5271
+ var scaleMemoryCountAddsSinceCheck = 0;
5272
+ var scaleMemoryCountCheckedInProcess = false;
5273
+ var scaleMemoryCountThresholdEvaluatedInProcess = false;
5274
+ function getMem0Dir() {
5275
+ return process.env.MEM0_DIR || path3.join(os2.homedir(), ".mem0");
5276
+ }
5277
+ function getMem0ConfigPath() {
5278
+ return path3.join(getMem0Dir(), "config.json");
5279
+ }
5280
+ function loadMem0Config() {
5281
+ try {
5282
+ const configPath = getMem0ConfigPath();
5283
+ if (!fs4.existsSync(configPath)) return {};
5284
+ const parsed = JSON.parse(fs4.readFileSync(configPath, "utf8"));
5285
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
5286
+ } catch (e) {
5287
+ return {};
5288
+ }
5289
+ }
5290
+ function writeMem0ConfigAtomic(config) {
5291
+ const configPath = getMem0ConfigPath();
5292
+ const dir = path3.dirname(configPath);
5293
+ const tempPath = path3.join(
5294
+ dir,
5295
+ `.config.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`
5296
+ );
5297
+ try {
5298
+ fs4.mkdirSync(dir, { recursive: true });
5299
+ fs4.writeFileSync(tempPath, JSON.stringify(config, null, 4));
5300
+ fs4.renameSync(tempPath, configPath);
5301
+ return true;
5302
+ } catch (e) {
5303
+ try {
5304
+ if (fs4.existsSync(tempPath)) fs4.unlinkSync(tempPath);
5305
+ } catch (e2) {
5306
+ }
5307
+ return false;
5308
+ }
5309
+ }
5310
+ function getNoticeState(config, noticeId) {
5311
+ const stateSection = config[NOTICE_STATE_SECTION] && typeof config[NOTICE_STATE_SECTION] === "object" && !Array.isArray(config[NOTICE_STATE_SECTION]) ? config[NOTICE_STATE_SECTION] : {};
5312
+ const noticeState = stateSection[noticeId];
5313
+ return noticeState && typeof noticeState === "object" && !Array.isArray(noticeState) ? noticeState : {};
5314
+ }
5315
+ function setNoticeState(config, noticeId, state) {
5316
+ const stateSection = config[NOTICE_STATE_SECTION] && typeof config[NOTICE_STATE_SECTION] === "object" && !Array.isArray(config[NOTICE_STATE_SECTION]) ? { ...config[NOTICE_STATE_SECTION] } : {};
5317
+ return {
5318
+ ...config,
5319
+ [NOTICE_STATE_SECTION]: {
5320
+ ...stateSection,
5321
+ [noticeId]: state
5322
+ }
5323
+ };
5324
+ }
5325
+ function parsePayload(payload) {
5326
+ try {
5327
+ if (typeof payload === "string") {
5328
+ const parsed = JSON.parse(payload);
5329
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
5330
+ }
5331
+ return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : void 0;
5332
+ } catch (e) {
5333
+ return void 0;
5334
+ }
5335
+ }
5336
+ function getNoticeConfigFromPayload(payload, noticeId) {
5337
+ const parsedPayload = parsePayload(payload);
5338
+ const notices = parsedPayload == null ? void 0 : parsedPayload.notices;
5339
+ if (!notices || typeof notices !== "object" || Array.isArray(notices)) {
5340
+ return { found: false, payload: parsedPayload };
5341
+ }
5342
+ const noticeConfig = notices[noticeId];
5343
+ if (!noticeConfig || typeof noticeConfig !== "object" || Array.isArray(noticeConfig)) {
5344
+ return { found: false, payload: parsedPayload };
5345
+ }
5346
+ return {
5347
+ found: true,
5348
+ config: noticeConfig,
5349
+ payload: parsedPayload
5350
+ };
5351
+ }
5352
+ async function evaluateNoticeFlag(distinctId, options = {}) {
5353
+ var _a2, _b2, _c, _d;
5354
+ if (!isTelemetryEnabled()) return null;
5355
+ const timeoutMs = (_a2 = options.timeoutMs) != null ? _a2 : NOTICE_FLAG_TIMEOUT_MS;
5356
+ const fetchImpl = (_b2 = options.fetchImpl) != null ? _b2 : fetch;
5357
+ const controller = new AbortController();
5358
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
5359
+ try {
5360
+ const response = await fetchImpl(POSTHOG_FLAGS_URL, {
5361
+ method: "POST",
5362
+ headers: { "Content-Type": "application/json" },
5363
+ body: JSON.stringify({
5364
+ api_key: POSTHOG_API_KEY,
5365
+ distinct_id: distinctId
5366
+ }),
5367
+ signal: controller.signal
5368
+ });
5369
+ if (!response.ok) return null;
5370
+ const data = await response.json();
5371
+ const flag = (_c = data == null ? void 0 : data.flags) == null ? void 0 : _c[NOTICE_FLAG_KEY];
5372
+ if (!flag || flag.enabled === false) return null;
5373
+ const variant = typeof flag.variant === "string" ? flag.variant : null;
5374
+ if (!variant) return null;
5375
+ return {
5376
+ variant,
5377
+ payload: parsePayload((_d = flag.metadata) == null ? void 0 : _d.payload),
5378
+ flag
5379
+ };
5380
+ } catch (e) {
5381
+ return null;
5382
+ } finally {
5383
+ clearTimeout(timeout);
5384
+ }
5385
+ }
5386
+ function eventsInWindow(events, now, windowMs) {
5387
+ if (!Array.isArray(events)) return [];
5388
+ const cutoff = now.getTime() - windowMs;
5389
+ return events.filter((event) => {
5390
+ if (!event || typeof event !== "object" || Array.isArray(event)) {
5391
+ return false;
5392
+ }
5393
+ const evaluatedAt = event.evaluated_at;
5394
+ if (typeof evaluatedAt !== "string") return false;
5395
+ const timestamp = Date.parse(evaluatedAt);
5396
+ return Number.isFinite(timestamp) && timestamp >= cutoff;
5397
+ });
5398
+ }
5399
+ function hasNoticeCapRoom(state, options = {}) {
5400
+ var _a2, _b2, _c;
5401
+ const now = (_a2 = options.now) != null ? _a2 : /* @__PURE__ */ new Date();
5402
+ const limit = (_b2 = options.limit) != null ? _b2 : NOTICE_CAP_LIMIT;
5403
+ const windowMs = (_c = options.windowMs) != null ? _c : NOTICE_CAP_WINDOW_MS;
5404
+ return eventsInWindow(state.events, now, windowMs).length < limit;
5405
+ }
5406
+ function isNoticeCapacityReachedInProcess(noticeId) {
5407
+ return noticeCapacityReachedInProcess.has(noticeId);
5408
+ }
5409
+ function markNoticeCapacityReachedInProcess(noticeId) {
5410
+ noticeCapacityReachedInProcess.add(noticeId);
5411
+ }
5412
+ function hasNoticeCapRoomForNotice(noticeId, state, options = {}) {
5413
+ const hasRoom = hasNoticeCapRoom(state, options);
5414
+ if (!hasRoom) markNoticeCapacityReachedInProcess(noticeId);
5415
+ return hasRoom;
5416
+ }
5417
+ function appendNoticeCapEvent(state, event, options = {}) {
5418
+ var _a2, _b2, _c;
5419
+ const now = (_a2 = options.now) != null ? _a2 : /* @__PURE__ */ new Date();
5420
+ const limit = (_b2 = options.limit) != null ? _b2 : NOTICE_CAP_LIMIT;
5421
+ const windowMs = (_c = options.windowMs) != null ? _c : NOTICE_CAP_WINDOW_MS;
5422
+ const events = eventsInWindow(state.events, now, windowMs);
5423
+ if (events.length >= limit) return null;
5424
+ return {
5425
+ ...state,
5426
+ events: [
5427
+ ...events,
5428
+ {
5429
+ evaluated_at: now.toISOString(),
5430
+ ...event
5431
+ }
5432
+ ]
5433
+ };
5434
+ }
5435
+ function recordNoticeOpportunity(noticeId, event, options = {}) {
5436
+ if (!isTelemetryEnabled()) return false;
5437
+ if (isNoticeCapacityReachedInProcess(noticeId)) return false;
5438
+ const config = loadMem0Config();
5439
+ const state = getNoticeState(config, noticeId);
5440
+ const nextState = appendNoticeCapEvent(state, event, options);
5441
+ if (!nextState) {
5442
+ markNoticeCapacityReachedInProcess(noticeId);
5443
+ return false;
5444
+ }
5445
+ const written = writeMem0ConfigAtomic(
5446
+ setNoticeState(config, noticeId, nextState)
5447
+ );
5448
+ if (written && !hasNoticeCapRoom(nextState, options)) {
5449
+ markNoticeCapacityReachedInProcess(noticeId);
5450
+ }
5451
+ return written;
5452
+ }
5453
+ function isFirstRunConsumed(config) {
5454
+ return getNoticeState(config, FIRST_RUN_NOTICE_ID).consumed === true;
5455
+ }
5456
+ function markFirstRunConsumed(triggerFunction, variant) {
5457
+ const config = loadMem0Config();
5458
+ const state = getNoticeState(config, FIRST_RUN_NOTICE_ID);
5459
+ const nextState = {
5460
+ ...state,
5461
+ consumed: true,
5462
+ consumed_at: (/* @__PURE__ */ new Date()).toISOString(),
5463
+ trigger_function: triggerFunction,
5464
+ variant
5465
+ };
5466
+ return writeMem0ConfigAtomic(
5467
+ setNoticeState(config, FIRST_RUN_NOTICE_ID, nextState)
5468
+ );
5469
+ }
5470
+ function getDisplayDecision(noticeId, expectedNoticeType, variant, payload) {
5471
+ var _a2;
5472
+ const parsed = getNoticeConfigFromPayload(payload, noticeId);
5473
+ const copy = typeof ((_a2 = parsed.config) == null ? void 0 : _a2.copy) === "string" ? parsed.config.copy : void 0;
5474
+ if (!parsed.found || !parsed.config) {
5475
+ return {
5476
+ displayed: false,
5477
+ noticeConfigFound: false,
5478
+ bypassReason: "missing_notice_config"
5479
+ };
5480
+ }
5481
+ const noticeConfig = parsed.config;
5482
+ if (noticeConfig.enabled === false) {
5483
+ return {
5484
+ displayed: false,
5485
+ noticeConfigFound: true,
5486
+ copy,
5487
+ bypassReason: "payload_disabled",
5488
+ disabledReason: "payload_disabled"
5489
+ };
5490
+ }
5491
+ if (noticeConfig.notice_type !== expectedNoticeType) {
5492
+ return {
5493
+ displayed: false,
5494
+ noticeConfigFound: true,
5495
+ copy,
5496
+ bypassReason: "invalid_notice_type"
5497
+ };
5498
+ }
5499
+ if (!copy || copy.trim() === "") {
5500
+ return {
5501
+ displayed: false,
5502
+ noticeConfigFound: true,
5503
+ bypassReason: "missing_copy"
5504
+ };
5505
+ }
5506
+ if (variant !== DISPLAYED_VARIANT) {
5507
+ return {
5508
+ displayed: false,
5509
+ noticeConfigFound: true,
5510
+ copy,
5511
+ bypassReason: "holdout"
5512
+ };
5513
+ }
5514
+ return {
5515
+ displayed: true,
5516
+ noticeConfigFound: true,
5517
+ copy
5518
+ };
5519
+ }
5520
+ function renderScaleCopy(template, trigger) {
5521
+ var _a2, _b2, _c;
5522
+ if (typeof template !== "string" || template.trim() === "") return void 0;
5523
+ 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 : ""));
5524
+ }
5525
+ function getScaleDisplayDecision(variant, payload, trigger) {
5526
+ var _a2;
5527
+ const parsed = getNoticeConfigFromPayload(payload, SCALE_THRESHOLD_NOTICE_ID);
5528
+ const copies = ((_a2 = parsed.config) == null ? void 0 : _a2.copies) && typeof parsed.config.copies === "object" && !Array.isArray(parsed.config.copies) ? parsed.config.copies : {};
5529
+ const copyKey = trigger.triggerSource === "memory_count" ? "memory_count" : "top_k";
5530
+ const copy = renderScaleCopy(copies[copyKey], trigger);
5531
+ if (!parsed.found || !parsed.config) {
5532
+ return {
5533
+ displayed: false,
5534
+ noticeConfigFound: false,
5535
+ bypassReason: "missing_notice_config"
5536
+ };
5537
+ }
5538
+ const noticeConfig = parsed.config;
5539
+ if (noticeConfig.enabled === false) {
5540
+ return {
5541
+ displayed: false,
5542
+ noticeConfigFound: true,
5543
+ copy,
5544
+ bypassReason: "payload_disabled",
5545
+ disabledReason: "payload_disabled"
5546
+ };
5547
+ }
5548
+ if (noticeConfig.notice_type !== LOG_LINE_NOTICE_TYPE) {
5549
+ return {
5550
+ displayed: false,
5551
+ noticeConfigFound: true,
5552
+ copy,
5553
+ bypassReason: "invalid_notice_type"
5554
+ };
5555
+ }
5556
+ if (!copy || copy.trim() === "") {
5557
+ return {
5558
+ displayed: false,
5559
+ noticeConfigFound: true,
5560
+ bypassReason: "missing_copy"
5561
+ };
5562
+ }
5563
+ if (variant !== DISPLAYED_VARIANT) {
5564
+ return {
5565
+ displayed: false,
5566
+ noticeConfigFound: true,
5567
+ copy,
5568
+ bypassReason: "holdout"
5569
+ };
5570
+ }
5571
+ return {
5572
+ displayed: true,
5573
+ noticeConfigFound: true,
5574
+ copy
5575
+ };
5576
+ }
5577
+ function getFeatureErrorDecision(noticeId, expectedNoticeType, variant, payload) {
5578
+ var _a2;
5579
+ const parsed = getNoticeConfigFromPayload(payload, noticeId);
5580
+ const copy = typeof ((_a2 = parsed.config) == null ? void 0 : _a2.copy) === "string" ? parsed.config.copy : void 0;
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 !== expectedNoticeType) {
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 && variant !== HOLDOUT_VARIANT) {
5614
+ return {
5615
+ displayed: false,
5616
+ noticeConfigFound: true,
5617
+ copy,
5618
+ bypassReason: "not_displayed"
5619
+ };
5620
+ }
5621
+ return {
5622
+ displayed: true,
5623
+ noticeConfigFound: true,
5624
+ copy
5625
+ };
5626
+ }
5627
+ async function getDecayFeatureErrorMessage(instance) {
5628
+ if (!isTelemetryEnabled()) return DECAY_FEATURE_PLAIN_ERROR;
5629
+ try {
5630
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
5631
+ if (!flagEvaluation) return DECAY_FEATURE_PLAIN_ERROR;
5632
+ const decision = getFeatureErrorDecision(
5633
+ DECAY_FEATURE_NOTICE_ID,
5634
+ ERROR_NOTICE_TYPE,
5635
+ flagEvaluation.variant,
5636
+ flagEvaluation.payload
5637
+ );
5638
+ await emitNoticeDisplayed(instance, {
5639
+ notice_id: DECAY_FEATURE_NOTICE_ID,
5640
+ notice_type: ERROR_NOTICE_TYPE,
5641
+ flag_key: NOTICE_FLAG_KEY,
5642
+ variant: flagEvaluation.variant,
5643
+ displayed: decision.displayed,
5644
+ payload: decision.copy,
5645
+ bypass_reason: decision.bypassReason,
5646
+ disabled_reason: decision.disabledReason,
5647
+ notice_config_found: decision.noticeConfigFound,
5648
+ sync_type: "async",
5649
+ trigger_function: "update_project",
5650
+ trigger_parameter: "decay"
5651
+ });
5652
+ if (decision.displayed && decision.copy) {
5653
+ return decision.copy;
5654
+ }
5655
+ } catch (e) {
5656
+ }
5657
+ return DECAY_FEATURE_PLAIN_ERROR;
5658
+ }
5659
+ async function getTemporalFeatureErrorMessage(instance, trigger) {
5660
+ const plainError = trigger.triggerParameter === "timestamp" ? TEMPORAL_TIMESTAMP_PLAIN_ERROR : TEMPORAL_REFERENCE_DATE_PLAIN_ERROR;
5661
+ if (!isTelemetryEnabled()) return plainError;
5662
+ try {
5663
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
5664
+ if (!flagEvaluation) return plainError;
5665
+ const decision = getFeatureErrorDecision(
5666
+ TEMPORAL_FEATURE_NOTICE_ID,
5667
+ ERROR_NOTICE_TYPE,
5668
+ flagEvaluation.variant,
5669
+ flagEvaluation.payload
5670
+ );
5671
+ await emitNoticeDisplayed(instance, {
5672
+ notice_id: TEMPORAL_FEATURE_NOTICE_ID,
5673
+ notice_type: ERROR_NOTICE_TYPE,
5674
+ flag_key: NOTICE_FLAG_KEY,
5675
+ variant: flagEvaluation.variant,
5676
+ displayed: decision.displayed,
5677
+ payload: decision.copy,
5678
+ bypass_reason: decision.bypassReason,
5679
+ disabled_reason: decision.disabledReason,
5680
+ notice_config_found: decision.noticeConfigFound,
5681
+ sync_type: "async",
5682
+ trigger_function: trigger.triggerFunction,
5683
+ trigger_parameter: trigger.triggerParameter
5684
+ });
5685
+ if (decision.displayed && decision.copy) {
5686
+ return decision.copy;
5687
+ }
5688
+ } catch (e) {
5689
+ }
5690
+ return plainError;
5691
+ }
5692
+ function getDecayUsageDeleteCountAfterSuccess() {
5693
+ if (!isTelemetryEnabled()) return 0;
5694
+ decayUsageSuccessfulDeleteCount += 1;
5695
+ return decayUsageSuccessfulDeleteCount;
5696
+ }
5697
+ function isDecayUsageDeleteEligible(deleteCount) {
5698
+ return deleteCount >= DECAY_USAGE_DELETE_THRESHOLD;
5699
+ }
5700
+ function isRecord(value) {
5701
+ return value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date);
5702
+ }
5703
+ function isTemporalKey(key) {
5704
+ const keyText = String(key).toLowerCase();
5705
+ return [
5706
+ "date",
5707
+ "time",
5708
+ "timestamp",
5709
+ "datetime",
5710
+ "event_date",
5711
+ "reference_date",
5712
+ "referencedate",
5713
+ "created_at",
5714
+ "createdat",
5715
+ "updated_at",
5716
+ "updatedat",
5717
+ "started_at",
5718
+ "startedat",
5719
+ "ended_at",
5720
+ "endedat",
5721
+ "expires_at",
5722
+ "expiresat"
5723
+ ].includes(keyText) || keyText.endsWith("_date") || keyText.endsWith("_time") || keyText.endsWith("_at") || keyText.includes("timestamp");
5724
+ }
5725
+ function looksTemporalValue(value, allowEpoch) {
5726
+ if (value instanceof Date) return !Number.isNaN(value.getTime());
5727
+ if (typeof value === "string") {
5728
+ return ISO_DATE_RE.test(value) || RELATIVE_TIME_RE.test(value);
5729
+ }
5730
+ if (allowEpoch && typeof value === "number" && Number.isFinite(value)) {
5731
+ return value >= 946684800 && value <= 4102444800 || value >= 9466848e5 && value <= 41024448e5;
5732
+ }
5733
+ return false;
5734
+ }
5735
+ function detectTemporalUsageFromMetadata(metadata) {
5736
+ try {
5737
+ if (!isRecord(metadata)) return null;
5738
+ const visited = /* @__PURE__ */ new WeakSet();
5739
+ const stack = [{ value: metadata, depth: 0 }];
5740
+ while (stack.length > 0) {
5741
+ const current = stack.pop();
5742
+ if (current.depth > MAX_TEMPORAL_DETECTION_DEPTH) continue;
5743
+ if (Array.isArray(current.value)) {
5744
+ for (const child of current.value) {
5745
+ if (looksTemporalValue(child, false)) {
5746
+ return {
5747
+ triggerSource: "metadata",
5748
+ triggerReason: "date_like_metadata"
5749
+ };
5750
+ }
5751
+ stack.push({
5752
+ value: child,
5753
+ parentKey: current.parentKey,
5754
+ depth: current.depth + 1
5755
+ });
5756
+ }
5757
+ continue;
5758
+ }
5759
+ if (!isRecord(current.value)) continue;
5760
+ if (visited.has(current.value)) continue;
5761
+ visited.add(current.value);
5762
+ for (const [key, value] of Object.entries(current.value)) {
5763
+ const temporalKey = isTemporalKey(key);
5764
+ if (temporalKey && looksTemporalValue(value, true) || looksTemporalValue(value, false)) {
5765
+ return {
5766
+ triggerSource: "metadata",
5767
+ triggerReason: "date_like_metadata"
5768
+ };
5769
+ }
5770
+ if (isRecord(value) || Array.isArray(value)) {
5771
+ stack.push({ value, parentKey: key, depth: current.depth + 1 });
5772
+ }
5773
+ }
5774
+ }
5775
+ } catch (e) {
5776
+ }
5777
+ return null;
5778
+ }
5779
+ function hasTemporalFilter(filters) {
5780
+ try {
5781
+ if (!isRecord(filters)) return false;
5782
+ const visited = /* @__PURE__ */ new WeakSet();
5783
+ const stack = [
5784
+ { value: filters, depth: 0 }
5785
+ ];
5786
+ while (stack.length > 0) {
5787
+ const current = stack.pop();
5788
+ if (current.depth > MAX_TEMPORAL_DETECTION_DEPTH) continue;
5789
+ if (Array.isArray(current.value)) {
5790
+ for (const child of current.value) {
5791
+ stack.push({ value: child, depth: current.depth + 1 });
5792
+ }
5793
+ continue;
5794
+ }
5795
+ if (!isRecord(current.value)) continue;
5796
+ if (visited.has(current.value)) continue;
5797
+ visited.add(current.value);
5798
+ for (const [key, value] of Object.entries(current.value)) {
5799
+ if (["AND", "OR", "NOT", "$and", "$or", "$not"].includes(key)) {
5800
+ if (isRecord(value) || Array.isArray(value)) {
5801
+ stack.push({ value, depth: current.depth + 1 });
5802
+ }
5803
+ continue;
5804
+ }
5805
+ const temporalKey = isTemporalKey(key);
5806
+ if (isRecord(value)) {
5807
+ const rangeValues = Object.entries(value).filter(([operator]) => RANGE_OPERATORS.has(operator)).map(([, rangeValue]) => rangeValue);
5808
+ if (rangeValues.length > 0 && (temporalKey || rangeValues.some(
5809
+ (rangeValue) => looksTemporalValue(rangeValue, temporalKey)
5810
+ ))) {
5811
+ return true;
5812
+ }
5813
+ stack.push({ value, depth: current.depth + 1 });
5814
+ } else if (temporalKey && looksTemporalValue(value, true)) {
5815
+ return true;
5816
+ }
5817
+ }
5818
+ }
5819
+ } catch (e) {
5820
+ }
5821
+ return false;
5822
+ }
5823
+ function detectTemporalUsageFromSearch(query, filters) {
5824
+ try {
5825
+ if (typeof query === "string") {
5826
+ if (RELATIVE_TIME_RE.test(query)) {
5827
+ return { triggerSource: "query", triggerReason: "relative_phrase" };
5828
+ }
5829
+ if (ISO_DATE_RE.test(query)) {
5830
+ return { triggerSource: "query", triggerReason: "date_like_query" };
5831
+ }
5832
+ }
5833
+ if (hasTemporalFilter(filters)) {
5834
+ return { triggerSource: "filter", triggerReason: "date_range_filter" };
5835
+ }
5836
+ } catch (e) {
5837
+ }
5838
+ return null;
5839
+ }
5840
+ function coerceNonnegativeInteger(value) {
5841
+ if (typeof value === "boolean") return null;
5842
+ const parsed = Number(value);
5843
+ if (!Number.isFinite(parsed) || !Number.isInteger(parsed) || parsed < 0) {
5844
+ return null;
5845
+ }
5846
+ return parsed;
5847
+ }
5848
+ function countAddedMemories(addResult) {
5849
+ const results = isRecord(addResult) && Array.isArray(addResult.results) ? addResult.results : addResult;
5850
+ if (!Array.isArray(results)) return 0;
5851
+ return results.filter((item) => {
5852
+ if (!isRecord(item)) return false;
5853
+ const metadata = item.metadata;
5854
+ return isRecord(metadata) && metadata.event === "ADD";
5855
+ }).length;
5856
+ }
5857
+ function extractProviderCount(info) {
5858
+ if (!info) return null;
5859
+ if (typeof info === "number") return coerceNonnegativeInteger(info);
5860
+ if (isRecord(info)) {
5861
+ for (const key of [
5862
+ "count",
5863
+ "points_count",
5864
+ "vectors_count",
5865
+ "indexed_vectors_count"
5866
+ ]) {
5867
+ const value = coerceNonnegativeInteger(info[key]);
5868
+ if (value !== null) return value;
5869
+ }
5870
+ const result = extractProviderCount(info.result);
5871
+ if (result !== null) return result;
5872
+ }
5873
+ return null;
5874
+ }
5875
+ async function getProviderMemoryCount(memoryInstance) {
5876
+ try {
5877
+ const vectorStore = memoryInstance == null ? void 0 : memoryInstance.vectorStore;
5878
+ if (!vectorStore) return null;
5879
+ if (typeof vectorStore.count === "function") {
5880
+ const value = extractProviderCount(await vectorStore.count());
5881
+ if (value !== null) return value;
5882
+ }
5883
+ const collectionName = vectorStore.collectionName;
5884
+ const client = vectorStore.client;
5885
+ if (client && collectionName && typeof client.count === "function") {
5886
+ const value = extractProviderCount(
5887
+ await client.count(collectionName, { exact: true })
5888
+ );
5889
+ if (value !== null) return value;
5890
+ }
5891
+ if (client && collectionName && typeof client.getCollection === "function") {
5892
+ const value = extractProviderCount(
5893
+ await client.getCollection(collectionName)
5894
+ );
5895
+ if (value !== null) return value;
5896
+ }
5897
+ } catch (e) {
5898
+ }
5899
+ return null;
5900
+ }
5901
+ function markScaleMemoryCountThresholdEvaluated() {
5902
+ try {
5903
+ const config = loadMem0Config();
5904
+ const state = getNoticeState(config, SCALE_THRESHOLD_NOTICE_ID);
5905
+ if (state.memory_count_threshold_evaluated === true) {
5906
+ scaleMemoryCountThresholdEvaluatedInProcess = true;
5907
+ return false;
5908
+ }
5909
+ const nextState = {
5910
+ ...state,
5911
+ memory_count_threshold_evaluated: true
5912
+ };
5913
+ const written = writeMem0ConfigAtomic(
5914
+ setNoticeState(config, SCALE_THRESHOLD_NOTICE_ID, nextState)
5915
+ );
5916
+ if (written) scaleMemoryCountThresholdEvaluatedInProcess = true;
5917
+ return written;
5918
+ } catch (e) {
5919
+ return false;
5920
+ }
5921
+ }
5922
+ function detectScaleThresholdFromTopK(topK) {
5923
+ const topKValue = coerceNonnegativeInteger(topK);
5924
+ if (topKValue === null || topKValue < SCALE_TOP_K_THRESHOLD) return null;
5925
+ return {
5926
+ triggerSource: "top_k",
5927
+ triggerReason: "high_top_k",
5928
+ topK: topKValue,
5929
+ threshold: SCALE_TOP_K_THRESHOLD
5930
+ };
5931
+ }
5932
+ async function detectScaleThresholdFromAddResult(memoryInstance, addResult) {
5933
+ if (!isTelemetryEnabled()) return null;
5934
+ const addedCount = countAddedMemories(addResult);
5935
+ if (addedCount === 0) return null;
5936
+ try {
5937
+ if (scaleMemoryCountThresholdEvaluatedInProcess) return null;
5938
+ scaleMemoryCountAddsSinceCheck += addedCount;
5939
+ const shouldCheck = !scaleMemoryCountCheckedInProcess || scaleMemoryCountAddsSinceCheck >= SCALE_MEMORY_COUNT_CHECK_INTERVAL;
5940
+ if (!shouldCheck) return null;
5941
+ scaleMemoryCountCheckedInProcess = true;
5942
+ scaleMemoryCountAddsSinceCheck = 0;
5943
+ const config = loadMem0Config();
5944
+ const state = getNoticeState(config, SCALE_THRESHOLD_NOTICE_ID);
5945
+ if (state.memory_count_threshold_evaluated === true) {
5946
+ scaleMemoryCountThresholdEvaluatedInProcess = true;
5947
+ return null;
5948
+ }
5949
+ if (!hasNoticeCapRoom(state)) return null;
5950
+ } catch (e) {
5951
+ return null;
5952
+ }
5953
+ const providerCount = await getProviderMemoryCount(memoryInstance);
5954
+ if (providerCount === null || providerCount < SCALE_MEMORY_COUNT_THRESHOLD) {
5955
+ return null;
5956
+ }
5957
+ if (!markScaleMemoryCountThresholdEvaluated()) return null;
5958
+ return {
5959
+ triggerSource: "memory_count",
5960
+ triggerReason: "memory_count_threshold",
5961
+ memoryCount: providerCount,
5962
+ threshold: SCALE_MEMORY_COUNT_THRESHOLD
5963
+ };
5964
+ }
5965
+ function detectPerformanceSlowQuery(elapsedMs, topK, resultCount) {
5966
+ const elapsedMsValue = coerceNonnegativeInteger(
5967
+ Math.round(Number(elapsedMs))
5968
+ );
5969
+ const topKValue = coerceNonnegativeInteger(topK);
5970
+ const resultCountValue = coerceNonnegativeInteger(resultCount);
5971
+ if (elapsedMsValue === null || topKValue === null || resultCountValue === null || elapsedMsValue <= PERFORMANCE_SLOW_QUERY_THRESHOLD_MS) {
5972
+ return null;
5973
+ }
5974
+ return {
5975
+ elapsedMs: elapsedMsValue,
5976
+ thresholdMs: PERFORMANCE_SLOW_QUERY_THRESHOLD_MS,
5977
+ topK: topKValue,
5978
+ resultCount: resultCountValue
5979
+ };
5980
+ }
5981
+ async function displayScaleThresholdNotice(instance, trigger) {
5982
+ if (!isTelemetryEnabled()) return;
5983
+ if (isNoticeCapacityReachedInProcess(SCALE_THRESHOLD_NOTICE_ID)) return;
5984
+ try {
5985
+ const config = loadMem0Config();
5986
+ const state = getNoticeState(config, SCALE_THRESHOLD_NOTICE_ID);
5987
+ if (!hasNoticeCapRoomForNotice(SCALE_THRESHOLD_NOTICE_ID, state)) return;
5988
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
5989
+ if (!flagEvaluation) return;
5990
+ const decision = getScaleDisplayDecision(
5991
+ flagEvaluation.variant,
5992
+ flagEvaluation.payload,
5993
+ trigger
5994
+ );
5995
+ const opportunity = {
5996
+ variant: flagEvaluation.variant,
5997
+ sync_type: "async",
5998
+ trigger_function: trigger.triggerFunction,
5999
+ trigger_source: trigger.triggerSource,
6000
+ trigger_reason: trigger.triggerReason,
6001
+ ...trigger.topK !== void 0 && { top_k: trigger.topK },
6002
+ ...trigger.memoryCount !== void 0 && {
6003
+ memory_count: trigger.memoryCount
6004
+ },
6005
+ threshold: trigger.threshold
6006
+ };
6007
+ if (!recordNoticeOpportunity(SCALE_THRESHOLD_NOTICE_ID, opportunity)) {
6008
+ return;
6009
+ }
6010
+ await emitNoticeDisplayed(instance, {
6011
+ notice_id: SCALE_THRESHOLD_NOTICE_ID,
6012
+ notice_type: LOG_LINE_NOTICE_TYPE,
6013
+ flag_key: NOTICE_FLAG_KEY,
6014
+ variant: flagEvaluation.variant,
6015
+ displayed: decision.displayed,
6016
+ payload: decision.copy,
6017
+ bypass_reason: decision.bypassReason,
6018
+ disabled_reason: decision.disabledReason,
6019
+ notice_config_found: decision.noticeConfigFound,
6020
+ sync_type: "async",
6021
+ trigger_function: trigger.triggerFunction,
6022
+ trigger_source: trigger.triggerSource,
6023
+ trigger_reason: trigger.triggerReason,
6024
+ top_k: trigger.topK,
6025
+ memory_count: trigger.memoryCount,
6026
+ threshold: trigger.threshold
6027
+ });
6028
+ if (decision.displayed && decision.copy) {
6029
+ process.stderr.write(`${decision.copy}
6030
+ `);
6031
+ }
6032
+ } catch (e) {
6033
+ }
6034
+ }
6035
+ async function displayPerformanceSlowQueryNotice(instance, trigger) {
6036
+ if (!isTelemetryEnabled()) return;
6037
+ if (isNoticeCapacityReachedInProcess(PERFORMANCE_SLOW_QUERY_NOTICE_ID)) {
6038
+ return;
6039
+ }
6040
+ try {
6041
+ const config = loadMem0Config();
6042
+ const state = getNoticeState(config, PERFORMANCE_SLOW_QUERY_NOTICE_ID);
6043
+ if (!hasNoticeCapRoomForNotice(PERFORMANCE_SLOW_QUERY_NOTICE_ID, state)) {
6044
+ return;
6045
+ }
6046
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
6047
+ if (!flagEvaluation) return;
6048
+ const decision = getDisplayDecision(
6049
+ PERFORMANCE_SLOW_QUERY_NOTICE_ID,
6050
+ LOG_LINE_NOTICE_TYPE,
6051
+ flagEvaluation.variant,
6052
+ flagEvaluation.payload
6053
+ );
6054
+ const opportunity = {
6055
+ variant: flagEvaluation.variant,
6056
+ sync_type: "async",
6057
+ trigger_function: trigger.triggerFunction,
6058
+ trigger_reason: trigger.triggerReason
6059
+ };
6060
+ if (!recordNoticeOpportunity(PERFORMANCE_SLOW_QUERY_NOTICE_ID, opportunity)) {
6061
+ return;
6062
+ }
6063
+ await emitNoticeDisplayed(instance, {
6064
+ notice_id: PERFORMANCE_SLOW_QUERY_NOTICE_ID,
6065
+ notice_type: LOG_LINE_NOTICE_TYPE,
6066
+ flag_key: NOTICE_FLAG_KEY,
6067
+ variant: flagEvaluation.variant,
6068
+ displayed: decision.displayed,
6069
+ payload: decision.copy,
6070
+ bypass_reason: decision.bypassReason,
6071
+ disabled_reason: decision.disabledReason,
6072
+ notice_config_found: decision.noticeConfigFound,
6073
+ sync_type: "async",
6074
+ trigger_function: trigger.triggerFunction,
6075
+ trigger_reason: trigger.triggerReason,
6076
+ elapsed_ms: trigger.elapsedMs,
6077
+ threshold_ms: trigger.thresholdMs,
6078
+ top_k: trigger.topK,
6079
+ result_count: trigger.resultCount
6080
+ });
6081
+ if (decision.displayed && decision.copy) {
6082
+ process.stderr.write(`${decision.copy}
6083
+ `);
6084
+ }
6085
+ } catch (e) {
6086
+ }
6087
+ }
6088
+ async function displayTemporalUsageNotice(instance, trigger) {
6089
+ if (!isTelemetryEnabled()) return;
6090
+ if (isNoticeCapacityReachedInProcess(TEMPORAL_USAGE_NOTICE_ID)) return;
6091
+ try {
6092
+ const config = loadMem0Config();
6093
+ const state = getNoticeState(config, TEMPORAL_USAGE_NOTICE_ID);
6094
+ if (!hasNoticeCapRoomForNotice(TEMPORAL_USAGE_NOTICE_ID, state)) return;
6095
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
6096
+ if (!flagEvaluation) return;
6097
+ const decision = getDisplayDecision(
6098
+ TEMPORAL_USAGE_NOTICE_ID,
6099
+ LOG_LINE_NOTICE_TYPE,
6100
+ flagEvaluation.variant,
6101
+ flagEvaluation.payload
6102
+ );
6103
+ const opportunity = {
6104
+ variant: flagEvaluation.variant,
6105
+ sync_type: "async",
6106
+ trigger_function: trigger.triggerFunction,
6107
+ trigger_source: trigger.triggerSource,
6108
+ trigger_reason: trigger.triggerReason
6109
+ };
6110
+ if (!recordNoticeOpportunity(TEMPORAL_USAGE_NOTICE_ID, opportunity)) {
6111
+ return;
6112
+ }
6113
+ await emitNoticeDisplayed(instance, {
6114
+ notice_id: TEMPORAL_USAGE_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_source: trigger.triggerSource,
6126
+ trigger_reason: trigger.triggerReason
6127
+ });
6128
+ if (decision.displayed && decision.copy) {
6129
+ process.stderr.write(`${decision.copy}
6130
+ `);
6131
+ }
6132
+ } catch (e) {
6133
+ }
6134
+ }
6135
+ async function displayDecayUsageNotice(instance, trigger) {
6136
+ if (!isTelemetryEnabled()) return;
6137
+ if (isNoticeCapacityReachedInProcess(DECAY_USAGE_NOTICE_ID)) return;
6138
+ try {
6139
+ const config = loadMem0Config();
6140
+ const state = getNoticeState(config, DECAY_USAGE_NOTICE_ID);
6141
+ if (!hasNoticeCapRoomForNotice(DECAY_USAGE_NOTICE_ID, state)) return;
6142
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
6143
+ if (!flagEvaluation) return;
6144
+ const decision = getDisplayDecision(
6145
+ DECAY_USAGE_NOTICE_ID,
6146
+ LOG_LINE_NOTICE_TYPE,
6147
+ flagEvaluation.variant,
6148
+ flagEvaluation.payload
6149
+ );
6150
+ const opportunity = {
6151
+ variant: flagEvaluation.variant,
6152
+ sync_type: "async",
6153
+ trigger_function: trigger.triggerFunction,
6154
+ trigger_source: trigger.triggerSource,
6155
+ trigger_reason: trigger.triggerReason,
6156
+ ...trigger.deleteCount !== void 0 && {
6157
+ delete_count: trigger.deleteCount
6158
+ },
6159
+ ...trigger.deletedCount !== void 0 && {
6160
+ deleted_count: trigger.deletedCount
6161
+ }
6162
+ };
6163
+ if (!recordNoticeOpportunity(DECAY_USAGE_NOTICE_ID, opportunity)) {
6164
+ return;
6165
+ }
6166
+ await emitNoticeDisplayed(instance, {
6167
+ notice_id: DECAY_USAGE_NOTICE_ID,
6168
+ notice_type: LOG_LINE_NOTICE_TYPE,
6169
+ flag_key: NOTICE_FLAG_KEY,
6170
+ variant: flagEvaluation.variant,
6171
+ displayed: decision.displayed,
6172
+ payload: decision.copy,
6173
+ bypass_reason: decision.bypassReason,
6174
+ disabled_reason: decision.disabledReason,
6175
+ notice_config_found: decision.noticeConfigFound,
6176
+ sync_type: "async",
6177
+ trigger_function: trigger.triggerFunction,
6178
+ trigger_source: trigger.triggerSource,
6179
+ trigger_reason: trigger.triggerReason,
6180
+ ...trigger.deleteCount !== void 0 && {
6181
+ delete_count: trigger.deleteCount
6182
+ },
6183
+ ...trigger.deletedCount !== void 0 && {
6184
+ deleted_count: trigger.deletedCount
6185
+ }
6186
+ });
6187
+ if (decision.displayed && decision.copy) {
6188
+ process.stderr.write(`${decision.copy}
6189
+ `);
6190
+ }
6191
+ } catch (e) {
6192
+ }
6193
+ }
6194
+ async function displayFirstRunNotice(instance, triggerFunction) {
6195
+ if (!isTelemetryEnabled()) return;
6196
+ if (firstRunConsumedInProcess || firstRunClaimInProgress) return;
6197
+ const config = loadMem0Config();
6198
+ if (isFirstRunConsumed(config)) {
6199
+ firstRunConsumedInProcess = true;
6200
+ return;
6201
+ }
6202
+ firstRunClaimInProgress = true;
6203
+ try {
6204
+ const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
6205
+ if (!flagEvaluation) {
6206
+ firstRunClaimInProgress = false;
6207
+ return;
6208
+ }
6209
+ const decision = getDisplayDecision(
6210
+ FIRST_RUN_NOTICE_ID,
6211
+ LOG_LINE_NOTICE_TYPE,
6212
+ flagEvaluation.variant,
6213
+ flagEvaluation.payload
6214
+ );
6215
+ firstRunConsumedInProcess = true;
6216
+ markFirstRunConsumed(triggerFunction, flagEvaluation.variant);
6217
+ await emitNoticeDisplayed(instance, {
6218
+ notice_id: FIRST_RUN_NOTICE_ID,
6219
+ notice_type: LOG_LINE_NOTICE_TYPE,
6220
+ flag_key: NOTICE_FLAG_KEY,
6221
+ variant: flagEvaluation.variant,
6222
+ displayed: decision.displayed,
6223
+ payload: decision.copy,
6224
+ bypass_reason: decision.bypassReason,
6225
+ disabled_reason: decision.disabledReason,
6226
+ notice_config_found: decision.noticeConfigFound,
6227
+ sync_type: "async",
6228
+ trigger_function: triggerFunction
6229
+ });
6230
+ if (decision.displayed && decision.copy) {
6231
+ process.stderr.write(`${decision.copy}
6232
+ `);
6233
+ }
6234
+ } catch (e) {
6235
+ if (!firstRunConsumedInProcess) firstRunClaimInProgress = false;
6236
+ } finally {
6237
+ if (firstRunConsumedInProcess) firstRunClaimInProgress = false;
6238
+ }
6239
+ }
6240
+ async function emitNoticeDisplayed(instance, properties) {
6241
+ if (!isTelemetryEnabled()) return;
6242
+ try {
6243
+ await captureNoticeEvent(instance, properties);
6244
+ } catch (e) {
6245
+ }
6246
+ }
5168
6247
 
5169
6248
  // src/oss/src/utils/lemmatization.ts
5170
6249
  var STOP_WORDS = /* @__PURE__ */ new Set([
@@ -5862,7 +6941,7 @@ function extractCompoundsRegex(text) {
5862
6941
  return entities;
5863
6942
  }
5864
6943
  function extractEntities(text) {
5865
- var _a2, _b;
6944
+ var _a2, _b2;
5866
6945
  const raw = [];
5867
6946
  raw.push(...extractQuoted(text));
5868
6947
  raw.push(...extractProper(text));
@@ -5905,7 +6984,7 @@ function extractEntities(text) {
5905
6984
  for (const entity of cleaned) {
5906
6985
  const key = entity.text.toLowerCase();
5907
6986
  const existing = best.get(key);
5908
- if (!existing || ((_a2 = typePriority[entity.type]) != null ? _a2 : 99) < ((_b = typePriority[existing.type]) != null ? _b : 99)) {
6987
+ if (!existing || ((_a2 = typePriority[entity.type]) != null ? _a2 : 99) < ((_b2 = typePriority[existing.type]) != null ? _b2 : 99)) {
5909
6988
  best.set(key, entity);
5910
6989
  }
5911
6990
  }
@@ -5942,7 +7021,7 @@ function normalizeBm25(rawScore, midpoint, steepness) {
5942
7021
  return 1 / (1 + Math.exp(-steepness * (rawScore - midpoint)));
5943
7022
  }
5944
7023
  function scoreAndRank(semanticResults, bm25Scores, entityBoosts, threshold, topK, explain = false) {
5945
- var _a2, _b, _c;
7024
+ var _a2, _b2, _c;
5946
7025
  const hasBm25 = Object.keys(bm25Scores).length > 0;
5947
7026
  const hasEntity = Object.keys(entityBoosts).length > 0;
5948
7027
  let maxPossible = 1;
@@ -5963,7 +7042,7 @@ function scoreAndRank(semanticResults, bm25Scores, entityBoosts, threshold, topK
5963
7042
  continue;
5964
7043
  }
5965
7044
  const memIdStr = String(memId);
5966
- const bm25Score = (_b = bm25Scores[memIdStr]) != null ? _b : 0;
7045
+ const bm25Score = (_b2 = bm25Scores[memIdStr]) != null ? _b2 : 0;
5967
7046
  const entityBoost = (_c = entityBoosts[memIdStr]) != null ? _c : 0;
5968
7047
  const rawCombined = semanticScore + bm25Score + entityBoost;
5969
7048
  const combined = Math.min(rawCombined / maxPossible, 1);
@@ -5991,18 +7070,18 @@ function scoreAndRank(semanticResults, bm25Scores, entityBoosts, threshold, topK
5991
7070
 
5992
7071
  // src/client/config.ts
5993
7072
  async function getNodeFs() {
5994
- var _a2, _b, _c, _d, _e;
7073
+ var _a2, _b2, _c, _d, _e;
5995
7074
  if (typeof process === "undefined" || !((_a2 = process.versions) == null ? void 0 : _a2.node)) return null;
5996
7075
  try {
5997
- const [fs4, path3, os2, crypto] = await Promise.all([
7076
+ const [fs5, path4, os3, crypto] = await Promise.all([
5998
7077
  import("fs"),
5999
7078
  import("path"),
6000
7079
  import("os"),
6001
7080
  import("crypto")
6002
7081
  ]);
6003
- const fsMod = (_b = fs4.default) != null ? _b : fs4;
6004
- const pathMod = (_c = path3.default) != null ? _c : path3;
6005
- const osMod = (_d = os2.default) != null ? _d : os2;
7082
+ const fsMod = (_b2 = fs5.default) != null ? _b2 : fs5;
7083
+ const pathMod = (_c = path4.default) != null ? _c : path4;
7084
+ const osMod = (_d = os3.default) != null ? _d : os3;
6006
7085
  const cryptoMod = (_e = crypto.default) != null ? _e : crypto;
6007
7086
  const dir = process.env.MEM0_DIR || pathMod.join(osMod.homedir(), ".mem0");
6008
7087
  return {
@@ -6382,6 +7461,52 @@ var Memory = class _Memory {
6382
7461
  console.error(`Failed to capture ${methodName} event:`, error);
6383
7462
  }
6384
7463
  }
7464
+ async _displayFirstRunNotice(triggerFunction) {
7465
+ try {
7466
+ await this._getTelemetryId();
7467
+ await displayFirstRunNotice(this, triggerFunction);
7468
+ } catch (e) {
7469
+ }
7470
+ }
7471
+ async _displayDecayUsageNotice(trigger) {
7472
+ try {
7473
+ await this._getTelemetryId();
7474
+ await displayDecayUsageNotice(this, trigger);
7475
+ } catch (e) {
7476
+ }
7477
+ }
7478
+ async _displayTemporalUsageNotice(trigger) {
7479
+ try {
7480
+ await this._getTelemetryId();
7481
+ await displayTemporalUsageNotice(this, trigger);
7482
+ } catch (e) {
7483
+ }
7484
+ }
7485
+ async _displayScaleThresholdNotice(trigger) {
7486
+ try {
7487
+ await this._getTelemetryId();
7488
+ await displayScaleThresholdNotice(this, trigger);
7489
+ } catch (e) {
7490
+ }
7491
+ }
7492
+ async _displayPerformanceSlowQueryNotice(trigger) {
7493
+ try {
7494
+ await this._getTelemetryId();
7495
+ await displayPerformanceSlowQueryNotice(this, trigger);
7496
+ } catch (e) {
7497
+ }
7498
+ }
7499
+ async _getNoticeTelemetryId() {
7500
+ try {
7501
+ if (!this.telemetryId || this.telemetryId === "anonymous" || this.telemetryId === "anonymous-supabase") {
7502
+ this.telemetryId = await getOrCreateMem0UserId() || "anonymous";
7503
+ }
7504
+ return this.telemetryId;
7505
+ } catch (e) {
7506
+ this.telemetryId = "anonymous";
7507
+ return this.telemetryId;
7508
+ }
7509
+ }
6385
7510
  static fromConfig(configDict) {
6386
7511
  try {
6387
7512
  const config = MemoryConfigSchema.parse(configDict);
@@ -6391,12 +7516,31 @@ var Memory = class _Memory {
6391
7516
  throw e;
6392
7517
  }
6393
7518
  }
7519
+ async updateProject(options = {}) {
7520
+ if ((options == null ? void 0 : options.decay) === true) {
7521
+ await this._getNoticeTelemetryId();
7522
+ throw new Error(await getDecayFeatureErrorMessage(this));
7523
+ }
7524
+ throw new Error("Project updates are not supported by the OSS Memory SDK.");
7525
+ }
6394
7526
  async add(messages, config) {
7527
+ if ((config == null ? void 0 : config.timestamp) !== void 0) {
7528
+ await this._getNoticeTelemetryId();
7529
+ throw new Error(
7530
+ await getTemporalFeatureErrorMessage(this, {
7531
+ triggerFunction: "add",
7532
+ triggerParameter: "timestamp"
7533
+ })
7534
+ );
7535
+ }
6395
7536
  if (messages === void 0 || messages === null) {
6396
7537
  throw new Error(
6397
7538
  "messages is required and cannot be undefined or null. Provide a string or array of messages."
6398
7539
  );
6399
7540
  }
7541
+ const temporalUsageNotice = detectTemporalUsageFromMetadata(
7542
+ config == null ? void 0 : config.metadata
7543
+ );
6400
7544
  await this._ensureInitialized();
6401
7545
  await this._captureEvent("add", {
6402
7546
  message_count: Array.isArray(messages) ? messages.length : 1,
@@ -6424,12 +7568,32 @@ var Memory = class _Memory {
6424
7568
  filters,
6425
7569
  infer
6426
7570
  );
7571
+ if (temporalUsageNotice) {
7572
+ await this._displayTemporalUsageNotice({
7573
+ triggerFunction: "add",
7574
+ triggerSource: temporalUsageNotice.triggerSource,
7575
+ triggerReason: temporalUsageNotice.triggerReason
7576
+ });
7577
+ } else {
7578
+ const scaleThresholdNotice = await detectScaleThresholdFromAddResult(
7579
+ this,
7580
+ vectorStoreResult
7581
+ );
7582
+ if (scaleThresholdNotice) {
7583
+ await this._displayScaleThresholdNotice({
7584
+ triggerFunction: "add",
7585
+ ...scaleThresholdNotice
7586
+ });
7587
+ } else {
7588
+ await this._displayFirstRunNotice("add");
7589
+ }
7590
+ }
6427
7591
  return {
6428
7592
  results: vectorStoreResult
6429
7593
  };
6430
7594
  }
6431
7595
  async addToVectorStore(messages, metadata, filters, infer) {
6432
- var _a2, _b, _c, _d, _e, _f, _g;
7596
+ var _a2, _b2, _c, _d, _e, _f, _g;
6433
7597
  if (!infer) {
6434
7598
  const returnedMemories = [];
6435
7599
  for (const message of messages) {
@@ -6471,7 +7635,7 @@ var Memory = class _Memory {
6471
7635
  uuidMapping[String(idx)] = mem.id;
6472
7636
  existingMemories.push({
6473
7637
  id: String(idx),
6474
- text: (_b = (_a2 = mem.payload) == null ? void 0 : _a2.data) != null ? _b : ""
7638
+ text: (_b2 = (_a2 = mem.payload) == null ? void 0 : _a2.data) != null ? _b2 : ""
6475
7639
  });
6476
7640
  }
6477
7641
  const isAgentScoped = !!filters.agent_id && !filters.user_id;
@@ -6783,7 +7947,10 @@ var Memory = class _Memory {
6783
7947
  async get(memoryId) {
6784
7948
  await this._ensureInitialized();
6785
7949
  const memory = await this.vectorStore.get(memoryId);
6786
- if (!memory) return null;
7950
+ if (!memory) {
7951
+ await this._displayFirstRunNotice("get");
7952
+ return null;
7953
+ }
6787
7954
  const filters = {
6788
7955
  ...memory.payload.user_id && { user_id: memory.payload.user_id },
6789
7956
  ...memory.payload.agent_id && { agent_id: memory.payload.agent_id },
@@ -6813,10 +7980,25 @@ var Memory = class _Memory {
6813
7980
  memoryItem.metadata[key] = value;
6814
7981
  }
6815
7982
  }
6816
- return { ...memoryItem, ...filters };
7983
+ const result = { ...memoryItem, ...filters };
7984
+ await this._displayFirstRunNotice("get");
7985
+ return result;
6817
7986
  }
6818
7987
  async search(query, config) {
6819
- var _a2, _b, _c, _d, _e;
7988
+ var _a2, _b2, _c, _d, _e;
7989
+ if ((config == null ? void 0 : config.referenceDate) !== void 0) {
7990
+ await this._getNoticeTelemetryId();
7991
+ throw new Error(
7992
+ await getTemporalFeatureErrorMessage(this, {
7993
+ triggerFunction: "search",
7994
+ triggerParameter: "referenceDate"
7995
+ })
7996
+ );
7997
+ }
7998
+ const temporalUsageNotice = detectTemporalUsageFromSearch(
7999
+ query,
8000
+ config == null ? void 0 : config.filters
8001
+ );
6820
8002
  rejectTopLevelEntityParams(config, "search");
6821
8003
  validateSearchParams(config.threshold, config.topK);
6822
8004
  const normalizedFilters = config.filters ? Object.fromEntries(
@@ -6855,6 +8037,7 @@ var Memory = class _Memory {
6855
8037
  "filters must contain at least one of: user_id, agent_id, run_id. Example: filters: { user_id: 'u1' }"
6856
8038
  );
6857
8039
  }
8040
+ const searchStartMs = Date.now();
6858
8041
  const queryLemmatized = lemmatizeForBm25(query);
6859
8042
  const queryEntities = extractEntities(query);
6860
8043
  const queryEmbedding = await this.embedder.embed(query);
@@ -6881,7 +8064,7 @@ var Memory = class _Memory {
6881
8064
  const [midpoint, steepness] = getBm25Params(query, queryLemmatized);
6882
8065
  for (const mem of keywordResults) {
6883
8066
  const memId = String(mem.id);
6884
- const rawScore = (_b = mem.score) != null ? _b : 0;
8067
+ const rawScore = (_b2 = mem.score) != null ? _b2 : 0;
6885
8068
  if (rawScore > 0) {
6886
8069
  bm25Scores[memId] = normalizeBm25(rawScore, midpoint, steepness);
6887
8070
  }
@@ -6918,15 +8101,15 @@ var Memory = class _Memory {
6918
8101
  (_, i) => entityStore.search(embeddings[i], 500, entitySearchFilters)
6919
8102
  )
6920
8103
  );
6921
- for (const result of searchResults) {
6922
- if (result.status === "rejected") {
8104
+ for (const result2 of searchResults) {
8105
+ if (result2.status === "rejected") {
6923
8106
  console.warn(
6924
8107
  "Entity boost search failed for one entity:",
6925
- result.reason
8108
+ result2.reason
6926
8109
  );
6927
8110
  continue;
6928
8111
  }
6929
- for (const match of result.value) {
8112
+ for (const match of result2.value) {
6930
8113
  const similarity = (_c = match.score) != null ? _c : 0;
6931
8114
  if (similarity < 0.5) continue;
6932
8115
  const payload = match.payload || {};
@@ -6998,22 +8181,68 @@ var Memory = class _Memory {
6998
8181
  ...scored.scoreDetails && { score_details: scored.scoreDetails }
6999
8182
  };
7000
8183
  });
7001
- return {
8184
+ const result = {
7002
8185
  results
7003
8186
  };
8187
+ const searchElapsedMs = Date.now() - searchStartMs;
8188
+ if (temporalUsageNotice) {
8189
+ await this._displayTemporalUsageNotice({
8190
+ triggerFunction: "search",
8191
+ triggerSource: temporalUsageNotice.triggerSource,
8192
+ triggerReason: temporalUsageNotice.triggerReason
8193
+ });
8194
+ } else {
8195
+ const scaleThresholdNotice = detectScaleThresholdFromTopK(topK);
8196
+ if (scaleThresholdNotice) {
8197
+ await this._displayScaleThresholdNotice({
8198
+ triggerFunction: "search",
8199
+ ...scaleThresholdNotice
8200
+ });
8201
+ } else {
8202
+ const performanceSlowQueryNotice = detectPerformanceSlowQuery(
8203
+ searchElapsedMs,
8204
+ topK,
8205
+ results.length
8206
+ );
8207
+ if (performanceSlowQueryNotice) {
8208
+ await this._displayPerformanceSlowQueryNotice({
8209
+ triggerFunction: "search",
8210
+ triggerReason: "slow_query",
8211
+ ...performanceSlowQueryNotice
8212
+ });
8213
+ } else {
8214
+ await this._displayFirstRunNotice("search");
8215
+ }
8216
+ }
8217
+ }
8218
+ return result;
7004
8219
  }
7005
8220
  async update(memoryId, data) {
7006
8221
  await this._ensureInitialized();
7007
8222
  await this._captureEvent("update", { memory_id: memoryId });
7008
8223
  const embedding = await this.embedder.embed(data);
7009
8224
  await this.updateMemory(memoryId, data, { [data]: embedding });
7010
- return { message: "Memory updated successfully!" };
8225
+ const result = { message: "Memory updated successfully!" };
8226
+ await this._displayFirstRunNotice("update");
8227
+ return result;
7011
8228
  }
7012
8229
  async delete(memoryId) {
7013
8230
  await this._ensureInitialized();
7014
8231
  await this._captureEvent("delete", { memory_id: memoryId });
7015
8232
  await this.deleteMemory(memoryId);
7016
- return { message: "Memory deleted successfully!" };
8233
+ const result = { message: "Memory deleted successfully!" };
8234
+ const deleteCount = getDecayUsageDeleteCountAfterSuccess();
8235
+ if (isDecayUsageDeleteEligible(deleteCount)) {
8236
+ await this._displayDecayUsageNotice({
8237
+ triggerFunction: "delete",
8238
+ triggerSource: "delete_count",
8239
+ triggerReason: "repeated_deletes",
8240
+ deleteCount
8241
+ });
8242
+ } else {
8243
+ await this._displayFirstRunNotice("delete");
8244
+ }
8245
+ return result;
7017
8246
  }
7018
8247
  async deleteAll(config) {
7019
8248
  await this._ensureInitialized();
@@ -7036,11 +8265,24 @@ var Memory = class _Memory {
7036
8265
  for (const memory of memories) {
7037
8266
  await this.deleteMemory(memory.id);
7038
8267
  }
7039
- return { message: "Memories deleted successfully!" };
8268
+ const result = { message: "Memories deleted successfully!" };
8269
+ if (memories.length > 0) {
8270
+ await this._displayDecayUsageNotice({
8271
+ triggerFunction: "delete_all",
8272
+ triggerSource: "delete_all",
8273
+ triggerReason: "bulk_delete",
8274
+ deletedCount: memories.length
8275
+ });
8276
+ } else {
8277
+ await this._displayFirstRunNotice("delete_all");
8278
+ }
8279
+ return result;
7040
8280
  }
7041
8281
  async history(memoryId) {
7042
8282
  await this._ensureInitialized();
7043
- return this.db.getHistory(memoryId);
8283
+ const result = await this.db.getHistory(memoryId);
8284
+ await this._displayFirstRunNotice("history");
8285
+ return result;
7044
8286
  }
7045
8287
  async reset() {
7046
8288
  await this._ensureInitialized();
@@ -7081,9 +8323,10 @@ var Memory = class _Memory {
7081
8323
  console.error(this._initError);
7082
8324
  });
7083
8325
  await this._initPromise;
8326
+ await this._displayFirstRunNotice("reset");
7084
8327
  }
7085
8328
  async getAll(config) {
7086
- var _a2, _b, _c;
8329
+ var _a2, _b2, _c;
7087
8330
  rejectTopLevelEntityParams(config, "getAll");
7088
8331
  validateSearchParams(void 0, config.topK);
7089
8332
  await this._ensureInitialized();
@@ -7092,7 +8335,7 @@ var Memory = class _Memory {
7092
8335
  Object.entries({
7093
8336
  ...config.filters || {},
7094
8337
  user_id: validateAndTrimEntityId((_a2 = config.filters) == null ? void 0 : _a2.user_id, "user_id"),
7095
- agent_id: validateAndTrimEntityId((_b = config.filters) == null ? void 0 : _b.agent_id, "agent_id"),
8338
+ agent_id: validateAndTrimEntityId((_b2 = config.filters) == null ? void 0 : _b2.agent_id, "agent_id"),
7096
8339
  run_id: validateAndTrimEntityId((_c = config.filters) == null ? void 0 : _c.run_id, "run_id")
7097
8340
  }).filter(([, v]) => v !== void 0)
7098
8341
  );
@@ -7130,7 +8373,17 @@ var Memory = class _Memory {
7130
8373
  ...mem.payload.agent_id && { agent_id: mem.payload.agent_id },
7131
8374
  ...mem.payload.run_id && { run_id: mem.payload.run_id }
7132
8375
  }));
7133
- return { results };
8376
+ const result = { results };
8377
+ const scaleThresholdNotice = detectScaleThresholdFromTopK(topK);
8378
+ if (scaleThresholdNotice) {
8379
+ await this._displayScaleThresholdNotice({
8380
+ triggerFunction: "get_all",
8381
+ ...scaleThresholdNotice
8382
+ });
8383
+ } else {
8384
+ await this._displayFirstRunNotice("get_all");
8385
+ }
8386
+ return result;
7134
8387
  }
7135
8388
  async createMemory(data, existingEmbeddings, metadata) {
7136
8389
  const memoryId = uuidv43();
@@ -7160,20 +8413,13 @@ var Memory = class _Memory {
7160
8413
  const prevValue = existingMemory.payload.data;
7161
8414
  const embedding = existingEmbeddings[data] || await this.embedder.embed(data);
7162
8415
  const newMetadata = {
8416
+ ...existingMemory.payload,
7163
8417
  ...metadata,
7164
8418
  data,
7165
8419
  hash: createHash("md5").update(data).digest("hex"),
8420
+ textLemmatized: lemmatizeForBm25(data),
7166
8421
  createdAt: existingMemory.payload.createdAt,
7167
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
7168
- ...existingMemory.payload.user_id && {
7169
- user_id: existingMemory.payload.user_id
7170
- },
7171
- ...existingMemory.payload.agent_id && {
7172
- agent_id: existingMemory.payload.agent_id
7173
- },
7174
- ...existingMemory.payload.run_id && {
7175
- run_id: existingMemory.payload.run_id
7176
- }
8422
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
7177
8423
  };
7178
8424
  await this.vectorStore.update(memoryId, embedding, newMetadata);
7179
8425
  await this.db.addHistory(