mem0ai 3.0.6 → 3.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/dist/oss/index.d.mts +15 -1
- package/dist/oss/index.d.ts +15 -1
- package/dist/oss/index.js +1328 -82
- package/dist/oss/index.js.map +1 -1
- package/dist/oss/index.mjs +1328 -82
- package/dist/oss/index.mjs.map +1 -1
- package/package.json +7 -2
package/dist/oss/index.mjs
CHANGED
|
@@ -68,6 +68,7 @@ var OpenAIEmbedder = class {
|
|
|
68
68
|
const response = await this.openai.embeddings.create({
|
|
69
69
|
model: this.model,
|
|
70
70
|
input: text,
|
|
71
|
+
encoding_format: "float",
|
|
71
72
|
...this.embeddingDims !== void 0 && {
|
|
72
73
|
dimensions: this.embeddingDims
|
|
73
74
|
}
|
|
@@ -82,6 +83,7 @@ var OpenAIEmbedder = class {
|
|
|
82
83
|
const response = await this.openai.embeddings.create({
|
|
83
84
|
model: this.model,
|
|
84
85
|
input: chunk,
|
|
86
|
+
encoding_format: "float",
|
|
85
87
|
...this.embeddingDims !== void 0 && {
|
|
86
88
|
dimensions: this.embeddingDims
|
|
87
89
|
}
|
|
@@ -168,8 +170,8 @@ var DEFAULT_MODEL = "nomic-ai/nomic-embed-text-v1.5-GGUF/nomic-embed-text-v1.5.f
|
|
|
168
170
|
var DEFAULT_LMSTUDIO_API_KEY = "lm-studio";
|
|
169
171
|
var LMStudioEmbedder = class {
|
|
170
172
|
constructor(config) {
|
|
171
|
-
var _a2,
|
|
172
|
-
const baseURL = (
|
|
173
|
+
var _a2, _b2;
|
|
174
|
+
const baseURL = (_b2 = (_a2 = config.baseURL) != null ? _a2 : config.url) != null ? _b2 : DEFAULT_BASE_URL;
|
|
173
175
|
const apiKey = config.apiKey || DEFAULT_LMSTUDIO_API_KEY;
|
|
174
176
|
this.openai = new OpenAI2({ apiKey, baseURL: String(baseURL) });
|
|
175
177
|
this.model = config.model || DEFAULT_MODEL;
|
|
@@ -198,7 +200,7 @@ var LMStudioEmbedder = class {
|
|
|
198
200
|
input: normalized,
|
|
199
201
|
encoding_format: "float"
|
|
200
202
|
});
|
|
201
|
-
return response.data.map((item) => item.embedding);
|
|
203
|
+
return response.data.sort((a, b) => a.index - b.index).map((item) => item.embedding);
|
|
202
204
|
} catch (err) {
|
|
203
205
|
const message = err instanceof Error ? err.message : String(err);
|
|
204
206
|
throw new Error(`LM Studio embedder failed: ${message}`);
|
|
@@ -1163,7 +1165,7 @@ var Qdrant = class {
|
|
|
1163
1165
|
}
|
|
1164
1166
|
}
|
|
1165
1167
|
async ensureCollection(name, size) {
|
|
1166
|
-
var _a2,
|
|
1168
|
+
var _a2, _b2, _c;
|
|
1167
1169
|
try {
|
|
1168
1170
|
await this.client.createCollection(name, {
|
|
1169
1171
|
vectors: {
|
|
@@ -1176,7 +1178,7 @@ var Qdrant = class {
|
|
|
1176
1178
|
if (name === this.collectionName) {
|
|
1177
1179
|
try {
|
|
1178
1180
|
const collectionInfo = await this.client.getCollection(name);
|
|
1179
|
-
const vectorConfig = (
|
|
1181
|
+
const vectorConfig = (_b2 = (_a2 = collectionInfo.config) == null ? void 0 : _a2.params) == null ? void 0 : _b2.vectors;
|
|
1180
1182
|
if (vectorConfig && vectorConfig.size !== size) {
|
|
1181
1183
|
throw new Error(
|
|
1182
1184
|
`Collection ${name} exists but has wrong vector size. Expected: ${size}, got: ${vectorConfig.size}`
|
|
@@ -1263,7 +1265,7 @@ var VectorizeDB = class {
|
|
|
1263
1265
|
return null;
|
|
1264
1266
|
}
|
|
1265
1267
|
async search(query, topK = 5, filters) {
|
|
1266
|
-
var _a2,
|
|
1268
|
+
var _a2, _b2;
|
|
1267
1269
|
try {
|
|
1268
1270
|
const result = await ((_a2 = this.client) == null ? void 0 : _a2.vectorize.indexes.query(
|
|
1269
1271
|
this.indexName,
|
|
@@ -1275,7 +1277,7 @@ var VectorizeDB = class {
|
|
|
1275
1277
|
topK
|
|
1276
1278
|
}
|
|
1277
1279
|
));
|
|
1278
|
-
return ((
|
|
1280
|
+
return ((_b2 = result == null ? void 0 : result.matches) == null ? void 0 : _b2.map((match) => ({
|
|
1279
1281
|
id: match.id,
|
|
1280
1282
|
payload: match.metadata,
|
|
1281
1283
|
score: match.score
|
|
@@ -1370,7 +1372,7 @@ var VectorizeDB = class {
|
|
|
1370
1372
|
}
|
|
1371
1373
|
}
|
|
1372
1374
|
async list(filters, topK = 20) {
|
|
1373
|
-
var _a2,
|
|
1375
|
+
var _a2, _b2;
|
|
1374
1376
|
try {
|
|
1375
1377
|
const result = await ((_a2 = this.client) == null ? void 0 : _a2.vectorize.indexes.query(
|
|
1376
1378
|
this.indexName,
|
|
@@ -1383,7 +1385,7 @@ var VectorizeDB = class {
|
|
|
1383
1385
|
returnMetadata: "all"
|
|
1384
1386
|
}
|
|
1385
1387
|
));
|
|
1386
|
-
const matches = ((
|
|
1388
|
+
const matches = ((_b2 = result == null ? void 0 : result.matches) == null ? void 0 : _b2.map((match) => ({
|
|
1387
1389
|
id: match.id,
|
|
1388
1390
|
payload: match.metadata,
|
|
1389
1391
|
score: match.score
|
|
@@ -1407,7 +1409,7 @@ var VectorizeDB = class {
|
|
|
1407
1409
|
);
|
|
1408
1410
|
}
|
|
1409
1411
|
async getUserId() {
|
|
1410
|
-
var _a2,
|
|
1412
|
+
var _a2, _b2, _c;
|
|
1411
1413
|
try {
|
|
1412
1414
|
let found = false;
|
|
1413
1415
|
for await (const index of this.client.vectorize.indexes.list({
|
|
@@ -1427,7 +1429,7 @@ var VectorizeDB = class {
|
|
|
1427
1429
|
}
|
|
1428
1430
|
}));
|
|
1429
1431
|
}
|
|
1430
|
-
const result = await ((
|
|
1432
|
+
const result = await ((_b2 = this.client) == null ? void 0 : _b2.vectorize.indexes.query(
|
|
1431
1433
|
"memory_migrations",
|
|
1432
1434
|
{
|
|
1433
1435
|
account_id: this.accountId,
|
|
@@ -1466,7 +1468,7 @@ var VectorizeDB = class {
|
|
|
1466
1468
|
}
|
|
1467
1469
|
}
|
|
1468
1470
|
async setUserId(userId) {
|
|
1469
|
-
var _a2,
|
|
1471
|
+
var _a2, _b2;
|
|
1470
1472
|
try {
|
|
1471
1473
|
const result = await ((_a2 = this.client) == null ? void 0 : _a2.vectorize.indexes.query(
|
|
1472
1474
|
"memory_migrations",
|
|
@@ -1489,7 +1491,7 @@ var VectorizeDB = class {
|
|
|
1489
1491
|
method: "POST",
|
|
1490
1492
|
headers: {
|
|
1491
1493
|
"Content-Type": "application/x-ndjson",
|
|
1492
|
-
Authorization: `Bearer ${(
|
|
1494
|
+
Authorization: `Bearer ${(_b2 = this.client) == null ? void 0 : _b2.apiToken}`
|
|
1493
1495
|
},
|
|
1494
1496
|
body: JSON.stringify(data) + "\n"
|
|
1495
1497
|
// ndjson format
|
|
@@ -1509,7 +1511,7 @@ var VectorizeDB = class {
|
|
|
1509
1511
|
return this._initPromise;
|
|
1510
1512
|
}
|
|
1511
1513
|
async _doInitialize() {
|
|
1512
|
-
var _a2,
|
|
1514
|
+
var _a2, _b2, _c, _d, _e;
|
|
1513
1515
|
try {
|
|
1514
1516
|
let indexFound = false;
|
|
1515
1517
|
for await (const idx of this.client.vectorize.indexes.list({
|
|
@@ -1532,7 +1534,7 @@ var VectorizeDB = class {
|
|
|
1532
1534
|
}));
|
|
1533
1535
|
const properties2 = ["userId", "agentId", "runId"];
|
|
1534
1536
|
for (const propertyName of properties2) {
|
|
1535
|
-
await ((
|
|
1537
|
+
await ((_b2 = this.client) == null ? void 0 : _b2.vectorize.indexes.metadataIndex.create(
|
|
1536
1538
|
this.indexName,
|
|
1537
1539
|
{
|
|
1538
1540
|
account_id: this.accountId,
|
|
@@ -1885,7 +1887,7 @@ var RedisDB = class {
|
|
|
1885
1887
|
return {
|
|
1886
1888
|
id: doc.value.memory_id,
|
|
1887
1889
|
payload: toCamelCase(resultPayload),
|
|
1888
|
-
score: (_a2 = Number(doc.value.__vector_score)) != null ? _a2 : 0
|
|
1890
|
+
score: Math.max(0, 1 - ((_a2 = Number(doc.value.__vector_score)) != null ? _a2 : 0))
|
|
1889
1891
|
};
|
|
1890
1892
|
});
|
|
1891
1893
|
} catch (error) {
|
|
@@ -2585,7 +2587,7 @@ var SQLiteManager = class {
|
|
|
2585
2587
|
}
|
|
2586
2588
|
async batchAddHistory(records) {
|
|
2587
2589
|
const txn = this.db.transaction(() => {
|
|
2588
|
-
var _a2,
|
|
2590
|
+
var _a2, _b2, _c;
|
|
2589
2591
|
for (const record of records) {
|
|
2590
2592
|
this.stmtInsert.run(
|
|
2591
2593
|
record.memoryId,
|
|
@@ -2593,7 +2595,7 @@ var SQLiteManager = class {
|
|
|
2593
2595
|
record.newValue,
|
|
2594
2596
|
record.action,
|
|
2595
2597
|
(_a2 = record.createdAt) != null ? _a2 : null,
|
|
2596
|
-
(
|
|
2598
|
+
(_b2 = record.updatedAt) != null ? _b2 : null,
|
|
2597
2599
|
(_c = record.isDeleted) != null ? _c : 0
|
|
2598
2600
|
);
|
|
2599
2601
|
}
|
|
@@ -3445,12 +3447,12 @@ function truncateContent(text, limit = PAST_MESSAGE_TRUNCATION_LIMIT) {
|
|
|
3445
3447
|
return text.slice(0, limit) + "...";
|
|
3446
3448
|
}
|
|
3447
3449
|
function formatConversationHistory(messages) {
|
|
3448
|
-
var _a2,
|
|
3450
|
+
var _a2, _b2;
|
|
3449
3451
|
if (!messages || messages.length === 0) return "";
|
|
3450
3452
|
let result = "";
|
|
3451
3453
|
for (const msg of messages) {
|
|
3452
3454
|
const role = (_a2 = msg.role) != null ? _a2 : "";
|
|
3453
|
-
const content = (
|
|
3455
|
+
const content = (_b2 = msg.content) != null ? _b2 : "";
|
|
3454
3456
|
if (role && content) {
|
|
3455
3457
|
result += `${role}: ${truncateContent(content)}
|
|
3456
3458
|
`;
|
|
@@ -3462,10 +3464,10 @@ function serializeMemories(memories) {
|
|
|
3462
3464
|
return JSON.stringify(memories != null ? memories : []);
|
|
3463
3465
|
}
|
|
3464
3466
|
function generateAdditiveExtractionPrompt(options) {
|
|
3465
|
-
var _a2,
|
|
3467
|
+
var _a2, _b2, _c;
|
|
3466
3468
|
const now = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
3467
3469
|
const currentDate = (_a2 = options.currentDate) != null ? _a2 : now;
|
|
3468
|
-
const observationDate = (
|
|
3470
|
+
const observationDate = (_b2 = options.observationDate) != null ? _b2 : currentDate;
|
|
3469
3471
|
const sections = [];
|
|
3470
3472
|
sections.push("## Summary\n");
|
|
3471
3473
|
sections.push(
|
|
@@ -3636,14 +3638,14 @@ var LangchainLLM = class {
|
|
|
3636
3638
|
this.modelName = this.llmInstance.modelId || this.llmInstance.model || "langchain-model";
|
|
3637
3639
|
}
|
|
3638
3640
|
async generateResponse(messages, response_format, tools) {
|
|
3639
|
-
var _a2,
|
|
3641
|
+
var _a2, _b2, _c, _d, _e;
|
|
3640
3642
|
const langchainMessages = convertToLangchainMessages(messages);
|
|
3641
3643
|
let runnable = this.llmInstance;
|
|
3642
3644
|
const invokeOptions = {};
|
|
3643
3645
|
let isStructuredOutput = false;
|
|
3644
3646
|
let selectedSchema = null;
|
|
3645
3647
|
const systemPromptContent = ((_a2 = messages.find((m) => m.role === "system")) == null ? void 0 : _a2.content) || "";
|
|
3646
|
-
const userPromptContent = ((
|
|
3648
|
+
const userPromptContent = ((_b2 = messages.find((m) => m.role === "user")) == null ? void 0 : _b2.content) || "";
|
|
3647
3649
|
if (systemPromptContent.includes("Personal Information Organizer") && systemPromptContent.includes("extract relevant pieces of information")) {
|
|
3648
3650
|
selectedSchema = FactRetrievalSchema;
|
|
3649
3651
|
} else if (userPromptContent.includes("smart memory manager") && userPromptContent.includes("Compare newly retrieved facts")) {
|
|
@@ -3773,7 +3775,7 @@ var LangchainVectorStore = class {
|
|
|
3773
3775
|
// Simple in-memory user ID
|
|
3774
3776
|
constructor(config) {
|
|
3775
3777
|
this.storeUserId = "anonymous-langchain-user";
|
|
3776
|
-
var _a2,
|
|
3778
|
+
var _a2, _b2;
|
|
3777
3779
|
if (!config.client || typeof config.client !== "object") {
|
|
3778
3780
|
throw new Error(
|
|
3779
3781
|
"Langchain vector store provider requires an initialized Langchain VectorStore instance passed via the 'client' field."
|
|
@@ -3789,7 +3791,7 @@ var LangchainVectorStore = class {
|
|
|
3789
3791
|
if (!this.dimension && ((_a2 = this.lcStore.embeddings) == null ? void 0 : _a2.embeddingDimension)) {
|
|
3790
3792
|
this.dimension = this.lcStore.embeddings.embeddingDimension;
|
|
3791
3793
|
}
|
|
3792
|
-
if (!this.dimension && ((
|
|
3794
|
+
if (!this.dimension && ((_b2 = this.lcStore.embedding) == null ? void 0 : _b2.embeddingDimension)) {
|
|
3793
3795
|
this.dimension = this.lcStore.embedding.embeddingDimension;
|
|
3794
3796
|
}
|
|
3795
3797
|
if (!this.dimension) {
|
|
@@ -4935,13 +4937,13 @@ var DEFAULT_MEMORY_CONFIG = {
|
|
|
4935
4937
|
// src/oss/src/config/manager.ts
|
|
4936
4938
|
var ConfigManager = class {
|
|
4937
4939
|
static mergeConfig(userConfig = {}) {
|
|
4938
|
-
var _a2,
|
|
4940
|
+
var _a2, _b2, _c, _d, _e, _f, _g;
|
|
4939
4941
|
const mergedConfig = {
|
|
4940
4942
|
version: userConfig.version || DEFAULT_MEMORY_CONFIG.version,
|
|
4941
4943
|
embedder: {
|
|
4942
4944
|
provider: ((_a2 = userConfig.embedder) == null ? void 0 : _a2.provider) || DEFAULT_MEMORY_CONFIG.embedder.provider,
|
|
4943
4945
|
config: (() => {
|
|
4944
|
-
var _a3,
|
|
4946
|
+
var _a3, _b3, _c2, _d2;
|
|
4945
4947
|
const defaultConf = DEFAULT_MEMORY_CONFIG.embedder.config;
|
|
4946
4948
|
const userConf = (_a3 = userConfig.embedder) == null ? void 0 : _a3.config;
|
|
4947
4949
|
let finalModel = defaultConf.model;
|
|
@@ -4950,7 +4952,7 @@ var ConfigManager = class {
|
|
|
4950
4952
|
} else if ((userConf == null ? void 0 : userConf.model) && typeof userConf.model === "string") {
|
|
4951
4953
|
finalModel = userConf.model;
|
|
4952
4954
|
}
|
|
4953
|
-
const baseURL = (_c2 = (
|
|
4955
|
+
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;
|
|
4954
4956
|
const embeddingDims = (_d2 = userConf == null ? void 0 : userConf.embeddingDims) != null ? _d2 : userConf == null ? void 0 : userConf.embedding_dims;
|
|
4955
4957
|
return {
|
|
4956
4958
|
apiKey: (userConf == null ? void 0 : userConf.apiKey) !== void 0 ? userConf.apiKey : defaultConf.apiKey,
|
|
@@ -4963,12 +4965,12 @@ var ConfigManager = class {
|
|
|
4963
4965
|
})()
|
|
4964
4966
|
},
|
|
4965
4967
|
vectorStore: {
|
|
4966
|
-
provider: ((
|
|
4968
|
+
provider: ((_b2 = userConfig.vectorStore) == null ? void 0 : _b2.provider) || DEFAULT_MEMORY_CONFIG.vectorStore.provider,
|
|
4967
4969
|
config: (() => {
|
|
4968
|
-
var _a3,
|
|
4970
|
+
var _a3, _b3, _c2;
|
|
4969
4971
|
const defaultConf = DEFAULT_MEMORY_CONFIG.vectorStore.config;
|
|
4970
4972
|
const userConf = (_a3 = userConfig.vectorStore) == null ? void 0 : _a3.config;
|
|
4971
|
-
const explicitDimension = (userConf == null ? void 0 : userConf.dimension) || ((_c2 = (
|
|
4973
|
+
const explicitDimension = (userConf == null ? void 0 : userConf.dimension) || ((_c2 = (_b3 = userConfig.embedder) == null ? void 0 : _b3.config) == null ? void 0 : _c2.embeddingDims) || void 0;
|
|
4972
4974
|
if ((userConf == null ? void 0 : userConf.client) && typeof userConf.client === "object") {
|
|
4973
4975
|
return {
|
|
4974
4976
|
client: userConf.client,
|
|
@@ -4992,7 +4994,7 @@ var ConfigManager = class {
|
|
|
4992
4994
|
llm: {
|
|
4993
4995
|
provider: ((_c = userConfig.llm) == null ? void 0 : _c.provider) || DEFAULT_MEMORY_CONFIG.llm.provider,
|
|
4994
4996
|
config: (() => {
|
|
4995
|
-
var _a3,
|
|
4997
|
+
var _a3, _b3, _c2, _d2;
|
|
4996
4998
|
const defaultConf = DEFAULT_MEMORY_CONFIG.llm.config;
|
|
4997
4999
|
const userConf = (_a3 = userConfig.llm) == null ? void 0 : _a3.config;
|
|
4998
5000
|
let finalModel = defaultConf.model;
|
|
@@ -5001,7 +5003,7 @@ var ConfigManager = class {
|
|
|
5001
5003
|
} else if ((userConf == null ? void 0 : userConf.model) && typeof userConf.model === "string") {
|
|
5002
5004
|
finalModel = userConf.model;
|
|
5003
5005
|
}
|
|
5004
|
-
const llmBaseURL = (_d2 = (_c2 = (
|
|
5006
|
+
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;
|
|
5005
5007
|
return {
|
|
5006
5008
|
baseURL: llmBaseURL,
|
|
5007
5009
|
url: userConf == null ? void 0 : userConf.url,
|
|
@@ -5014,7 +5016,7 @@ var ConfigManager = class {
|
|
|
5014
5016
|
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),
|
|
5015
5017
|
customInstructions: userConfig.customInstructions,
|
|
5016
5018
|
historyStore: (() => {
|
|
5017
|
-
var _a3,
|
|
5019
|
+
var _a3, _b3;
|
|
5018
5020
|
const defaultHistoryStore = DEFAULT_MEMORY_CONFIG.historyStore;
|
|
5019
5021
|
const historyProvider = ((_a3 = userConfig.historyStore) == null ? void 0 : _a3.provider) || defaultHistoryStore.provider;
|
|
5020
5022
|
const isSqlite = historyProvider.toLowerCase() === "sqlite";
|
|
@@ -5025,7 +5027,7 @@ var ConfigManager = class {
|
|
|
5025
5027
|
config: {
|
|
5026
5028
|
...isSqlite ? defaultHistoryStore.config : {},
|
|
5027
5029
|
...isSqlite && userConfig.historyDbPath ? { historyDbPath: userConfig.historyDbPath } : {},
|
|
5028
|
-
...(
|
|
5030
|
+
...(_b3 = userConfig.historyStore) == null ? void 0 : _b3.config
|
|
5029
5031
|
}
|
|
5030
5032
|
};
|
|
5031
5033
|
})(),
|
|
@@ -5073,15 +5075,16 @@ var parse_vision_messages = async (messages) => {
|
|
|
5073
5075
|
};
|
|
5074
5076
|
|
|
5075
5077
|
// src/oss/src/utils/telemetry.ts
|
|
5076
|
-
var version = true ? "3.0.
|
|
5078
|
+
var version = true ? "3.0.8" : "dev";
|
|
5077
5079
|
var MEM0_TELEMETRY = true;
|
|
5078
|
-
var _a;
|
|
5080
|
+
var _a, _b;
|
|
5079
5081
|
try {
|
|
5080
|
-
MEM0_TELEMETRY = ((_a = process == null ? void 0 : process.env) == null ? void 0 : _a.MEM0_TELEMETRY) === "false" ? false : true;
|
|
5082
|
+
MEM0_TELEMETRY = ((_b = (_a = process == null ? void 0 : process.env) == null ? void 0 : _a.MEM0_TELEMETRY) == null ? void 0 : _b.toLowerCase()) === "false" ? false : true;
|
|
5081
5083
|
} catch (error) {
|
|
5082
5084
|
}
|
|
5083
5085
|
var POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX";
|
|
5084
5086
|
var POSTHOG_HOST = "https://us.i.posthog.com/i/v0/e/";
|
|
5087
|
+
var NOTICE_EVENT_NAME = "mem0.notice_displayed";
|
|
5085
5088
|
var DEFAULT_SAMPLE_RATE = 0.1;
|
|
5086
5089
|
var MEM0_TELEMETRY_SAMPLE_RATE = (() => {
|
|
5087
5090
|
var _a2;
|
|
@@ -5097,7 +5100,11 @@ var MEM0_TELEMETRY_SAMPLE_RATE = (() => {
|
|
|
5097
5100
|
}
|
|
5098
5101
|
return DEFAULT_SAMPLE_RATE;
|
|
5099
5102
|
})();
|
|
5100
|
-
var
|
|
5103
|
+
var ALWAYS_SEND_EVENTS = /* @__PURE__ */ new Set([
|
|
5104
|
+
"init",
|
|
5105
|
+
"reset",
|
|
5106
|
+
"notice_displayed"
|
|
5107
|
+
]);
|
|
5101
5108
|
var UnifiedTelemetry = class {
|
|
5102
5109
|
constructor(projectApiKey, host) {
|
|
5103
5110
|
this.apiKey = projectApiKey;
|
|
@@ -5137,13 +5144,16 @@ var UnifiedTelemetry = class {
|
|
|
5137
5144
|
}
|
|
5138
5145
|
};
|
|
5139
5146
|
var telemetry = new UnifiedTelemetry(POSTHOG_API_KEY, POSTHOG_HOST);
|
|
5147
|
+
function isTelemetryEnabled() {
|
|
5148
|
+
return MEM0_TELEMETRY;
|
|
5149
|
+
}
|
|
5140
5150
|
async function captureClientEvent(eventName, instance, additionalData = {}) {
|
|
5141
5151
|
if (!instance.telemetryId) {
|
|
5142
5152
|
console.warn("No telemetry ID found for instance");
|
|
5143
5153
|
return;
|
|
5144
5154
|
}
|
|
5145
|
-
const
|
|
5146
|
-
if (!
|
|
5155
|
+
const alwaysSend = ALWAYS_SEND_EVENTS.has(eventName);
|
|
5156
|
+
if (!alwaysSend && Math.random() >= MEM0_TELEMETRY_SAMPLE_RATE) {
|
|
5147
5157
|
return;
|
|
5148
5158
|
}
|
|
5149
5159
|
const eventData = {
|
|
@@ -5155,7 +5165,7 @@ async function captureClientEvent(eventName, instance, additionalData = {}) {
|
|
|
5155
5165
|
client_source: "nodejs",
|
|
5156
5166
|
...additionalData,
|
|
5157
5167
|
// sample_rate set AFTER the spread so callers can never override it
|
|
5158
|
-
sample_rate:
|
|
5168
|
+
sample_rate: alwaysSend ? 1 : MEM0_TELEMETRY_SAMPLE_RATE
|
|
5159
5169
|
};
|
|
5160
5170
|
await telemetry.captureEvent(
|
|
5161
5171
|
instance.telemetryId,
|
|
@@ -5163,6 +5173,1038 @@ async function captureClientEvent(eventName, instance, additionalData = {}) {
|
|
|
5163
5173
|
eventData
|
|
5164
5174
|
);
|
|
5165
5175
|
}
|
|
5176
|
+
async function captureNoticeEvent(instance, properties = {}) {
|
|
5177
|
+
if (!instance.telemetryId) return;
|
|
5178
|
+
const eventData = {
|
|
5179
|
+
function: `${instance.constructor.name}`,
|
|
5180
|
+
method: "notice_displayed",
|
|
5181
|
+
api_host: instance.host,
|
|
5182
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5183
|
+
client_version: version,
|
|
5184
|
+
client_source: "nodejs",
|
|
5185
|
+
...properties,
|
|
5186
|
+
sample_rate: 1
|
|
5187
|
+
};
|
|
5188
|
+
await telemetry.captureEvent(
|
|
5189
|
+
instance.telemetryId,
|
|
5190
|
+
NOTICE_EVENT_NAME,
|
|
5191
|
+
eventData
|
|
5192
|
+
);
|
|
5193
|
+
}
|
|
5194
|
+
|
|
5195
|
+
// src/oss/src/utils/notices.ts
|
|
5196
|
+
import * as fs4 from "fs";
|
|
5197
|
+
import * as os2 from "os";
|
|
5198
|
+
import * as path3 from "path";
|
|
5199
|
+
var NOTICE_FLAG_KEY = "mem0-oss-notices";
|
|
5200
|
+
var NOTICE_STATE_SECTION = "notice_state";
|
|
5201
|
+
var FIRST_RUN_NOTICE_ID = "first_run";
|
|
5202
|
+
var TEMPORAL_FEATURE_NOTICE_ID = "temporal_stub";
|
|
5203
|
+
var TEMPORAL_USAGE_NOTICE_ID = "temporal_usage";
|
|
5204
|
+
var DECAY_FEATURE_NOTICE_ID = "decay_stub";
|
|
5205
|
+
var DECAY_USAGE_NOTICE_ID = "decay_usage";
|
|
5206
|
+
var SCALE_THRESHOLD_NOTICE_ID = "scale_threshold";
|
|
5207
|
+
var PERFORMANCE_SLOW_QUERY_NOTICE_ID = "performance_slow_query";
|
|
5208
|
+
var NOTICE_CAP_LIMIT = 10;
|
|
5209
|
+
var NOTICE_CAP_WINDOW_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
5210
|
+
var NOTICE_FLAG_TIMEOUT_MS = 500;
|
|
5211
|
+
var POSTHOG_FLAGS_URL = "https://us.i.posthog.com/flags?v=2";
|
|
5212
|
+
var DISPLAYED_VARIANT = "displayed";
|
|
5213
|
+
var HOLDOUT_VARIANT = "holdout";
|
|
5214
|
+
var LOG_LINE_NOTICE_TYPE = "log_line";
|
|
5215
|
+
var ERROR_NOTICE_TYPE = "error";
|
|
5216
|
+
var TEMPORAL_TIMESTAMP_PLAIN_ERROR = "The timestamp parameter is not supported by the OSS Memory SDK.";
|
|
5217
|
+
var TEMPORAL_REFERENCE_DATE_PLAIN_ERROR = "The referenceDate parameter is not supported by the OSS Memory SDK.";
|
|
5218
|
+
var DECAY_FEATURE_PLAIN_ERROR = "The decay parameter is not supported by the OSS Memory SDK.";
|
|
5219
|
+
var DECAY_USAGE_DELETE_THRESHOLD = 5;
|
|
5220
|
+
var SCALE_MEMORY_COUNT_THRESHOLD = 2e3;
|
|
5221
|
+
var SCALE_MEMORY_COUNT_CHECK_INTERVAL = 100;
|
|
5222
|
+
var SCALE_TOP_K_THRESHOLD = 50;
|
|
5223
|
+
var PERFORMANCE_SLOW_QUERY_THRESHOLD_MS = 2e3;
|
|
5224
|
+
var MAX_TEMPORAL_DETECTION_DEPTH = 32;
|
|
5225
|
+
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/;
|
|
5226
|
+
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;
|
|
5227
|
+
var RANGE_OPERATORS = /* @__PURE__ */ new Set(["gt", "gte", "lt", "lte"]);
|
|
5228
|
+
var firstRunConsumedInProcess = false;
|
|
5229
|
+
var firstRunClaimInProgress = false;
|
|
5230
|
+
var decayUsageSuccessfulDeleteCount = 0;
|
|
5231
|
+
var noticeCapacityReachedInProcess = /* @__PURE__ */ new Set();
|
|
5232
|
+
var scaleMemoryCountAddsSinceCheck = 0;
|
|
5233
|
+
var scaleMemoryCountCheckedInProcess = false;
|
|
5234
|
+
var scaleMemoryCountThresholdEvaluatedInProcess = false;
|
|
5235
|
+
function getMem0Dir() {
|
|
5236
|
+
return process.env.MEM0_DIR || path3.join(os2.homedir(), ".mem0");
|
|
5237
|
+
}
|
|
5238
|
+
function getMem0ConfigPath() {
|
|
5239
|
+
return path3.join(getMem0Dir(), "config.json");
|
|
5240
|
+
}
|
|
5241
|
+
function loadMem0Config() {
|
|
5242
|
+
try {
|
|
5243
|
+
const configPath = getMem0ConfigPath();
|
|
5244
|
+
if (!fs4.existsSync(configPath)) return {};
|
|
5245
|
+
const parsed = JSON.parse(fs4.readFileSync(configPath, "utf8"));
|
|
5246
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
5247
|
+
} catch (e) {
|
|
5248
|
+
return {};
|
|
5249
|
+
}
|
|
5250
|
+
}
|
|
5251
|
+
function writeMem0ConfigAtomic(config) {
|
|
5252
|
+
const configPath = getMem0ConfigPath();
|
|
5253
|
+
const dir = path3.dirname(configPath);
|
|
5254
|
+
const tempPath = path3.join(
|
|
5255
|
+
dir,
|
|
5256
|
+
`.config.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`
|
|
5257
|
+
);
|
|
5258
|
+
try {
|
|
5259
|
+
fs4.mkdirSync(dir, { recursive: true });
|
|
5260
|
+
fs4.writeFileSync(tempPath, JSON.stringify(config, null, 4));
|
|
5261
|
+
fs4.renameSync(tempPath, configPath);
|
|
5262
|
+
return true;
|
|
5263
|
+
} catch (e) {
|
|
5264
|
+
try {
|
|
5265
|
+
if (fs4.existsSync(tempPath)) fs4.unlinkSync(tempPath);
|
|
5266
|
+
} catch (e2) {
|
|
5267
|
+
}
|
|
5268
|
+
return false;
|
|
5269
|
+
}
|
|
5270
|
+
}
|
|
5271
|
+
function getNoticeState(config, noticeId) {
|
|
5272
|
+
const stateSection = config[NOTICE_STATE_SECTION] && typeof config[NOTICE_STATE_SECTION] === "object" && !Array.isArray(config[NOTICE_STATE_SECTION]) ? config[NOTICE_STATE_SECTION] : {};
|
|
5273
|
+
const noticeState = stateSection[noticeId];
|
|
5274
|
+
return noticeState && typeof noticeState === "object" && !Array.isArray(noticeState) ? noticeState : {};
|
|
5275
|
+
}
|
|
5276
|
+
function setNoticeState(config, noticeId, state) {
|
|
5277
|
+
const stateSection = config[NOTICE_STATE_SECTION] && typeof config[NOTICE_STATE_SECTION] === "object" && !Array.isArray(config[NOTICE_STATE_SECTION]) ? { ...config[NOTICE_STATE_SECTION] } : {};
|
|
5278
|
+
return {
|
|
5279
|
+
...config,
|
|
5280
|
+
[NOTICE_STATE_SECTION]: {
|
|
5281
|
+
...stateSection,
|
|
5282
|
+
[noticeId]: state
|
|
5283
|
+
}
|
|
5284
|
+
};
|
|
5285
|
+
}
|
|
5286
|
+
function parsePayload(payload) {
|
|
5287
|
+
try {
|
|
5288
|
+
if (typeof payload === "string") {
|
|
5289
|
+
const parsed = JSON.parse(payload);
|
|
5290
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
5291
|
+
}
|
|
5292
|
+
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : void 0;
|
|
5293
|
+
} catch (e) {
|
|
5294
|
+
return void 0;
|
|
5295
|
+
}
|
|
5296
|
+
}
|
|
5297
|
+
function getNoticeConfigFromPayload(payload, noticeId) {
|
|
5298
|
+
const parsedPayload = parsePayload(payload);
|
|
5299
|
+
const notices = parsedPayload == null ? void 0 : parsedPayload.notices;
|
|
5300
|
+
if (!notices || typeof notices !== "object" || Array.isArray(notices)) {
|
|
5301
|
+
return { found: false, payload: parsedPayload };
|
|
5302
|
+
}
|
|
5303
|
+
const noticeConfig = notices[noticeId];
|
|
5304
|
+
if (!noticeConfig || typeof noticeConfig !== "object" || Array.isArray(noticeConfig)) {
|
|
5305
|
+
return { found: false, payload: parsedPayload };
|
|
5306
|
+
}
|
|
5307
|
+
return {
|
|
5308
|
+
found: true,
|
|
5309
|
+
config: noticeConfig,
|
|
5310
|
+
payload: parsedPayload
|
|
5311
|
+
};
|
|
5312
|
+
}
|
|
5313
|
+
async function evaluateNoticeFlag(distinctId, options = {}) {
|
|
5314
|
+
var _a2, _b2, _c, _d;
|
|
5315
|
+
if (!isTelemetryEnabled()) return null;
|
|
5316
|
+
const timeoutMs = (_a2 = options.timeoutMs) != null ? _a2 : NOTICE_FLAG_TIMEOUT_MS;
|
|
5317
|
+
const fetchImpl = (_b2 = options.fetchImpl) != null ? _b2 : fetch;
|
|
5318
|
+
const controller = new AbortController();
|
|
5319
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
5320
|
+
try {
|
|
5321
|
+
const response = await fetchImpl(POSTHOG_FLAGS_URL, {
|
|
5322
|
+
method: "POST",
|
|
5323
|
+
headers: { "Content-Type": "application/json" },
|
|
5324
|
+
body: JSON.stringify({
|
|
5325
|
+
api_key: POSTHOG_API_KEY,
|
|
5326
|
+
distinct_id: distinctId
|
|
5327
|
+
}),
|
|
5328
|
+
signal: controller.signal
|
|
5329
|
+
});
|
|
5330
|
+
if (!response.ok) return null;
|
|
5331
|
+
const data = await response.json();
|
|
5332
|
+
const flag = (_c = data == null ? void 0 : data.flags) == null ? void 0 : _c[NOTICE_FLAG_KEY];
|
|
5333
|
+
if (!flag || flag.enabled === false) return null;
|
|
5334
|
+
const variant = typeof flag.variant === "string" ? flag.variant : null;
|
|
5335
|
+
if (!variant) return null;
|
|
5336
|
+
return {
|
|
5337
|
+
variant,
|
|
5338
|
+
payload: parsePayload((_d = flag.metadata) == null ? void 0 : _d.payload),
|
|
5339
|
+
flag
|
|
5340
|
+
};
|
|
5341
|
+
} catch (e) {
|
|
5342
|
+
return null;
|
|
5343
|
+
} finally {
|
|
5344
|
+
clearTimeout(timeout);
|
|
5345
|
+
}
|
|
5346
|
+
}
|
|
5347
|
+
function eventsInWindow(events, now, windowMs) {
|
|
5348
|
+
if (!Array.isArray(events)) return [];
|
|
5349
|
+
const cutoff = now.getTime() - windowMs;
|
|
5350
|
+
return events.filter((event) => {
|
|
5351
|
+
if (!event || typeof event !== "object" || Array.isArray(event)) {
|
|
5352
|
+
return false;
|
|
5353
|
+
}
|
|
5354
|
+
const evaluatedAt = event.evaluated_at;
|
|
5355
|
+
if (typeof evaluatedAt !== "string") return false;
|
|
5356
|
+
const timestamp = Date.parse(evaluatedAt);
|
|
5357
|
+
return Number.isFinite(timestamp) && timestamp >= cutoff;
|
|
5358
|
+
});
|
|
5359
|
+
}
|
|
5360
|
+
function hasNoticeCapRoom(state, options = {}) {
|
|
5361
|
+
var _a2, _b2, _c;
|
|
5362
|
+
const now = (_a2 = options.now) != null ? _a2 : /* @__PURE__ */ new Date();
|
|
5363
|
+
const limit = (_b2 = options.limit) != null ? _b2 : NOTICE_CAP_LIMIT;
|
|
5364
|
+
const windowMs = (_c = options.windowMs) != null ? _c : NOTICE_CAP_WINDOW_MS;
|
|
5365
|
+
return eventsInWindow(state.events, now, windowMs).length < limit;
|
|
5366
|
+
}
|
|
5367
|
+
function isNoticeCapacityReachedInProcess(noticeId) {
|
|
5368
|
+
return noticeCapacityReachedInProcess.has(noticeId);
|
|
5369
|
+
}
|
|
5370
|
+
function markNoticeCapacityReachedInProcess(noticeId) {
|
|
5371
|
+
noticeCapacityReachedInProcess.add(noticeId);
|
|
5372
|
+
}
|
|
5373
|
+
function hasNoticeCapRoomForNotice(noticeId, state, options = {}) {
|
|
5374
|
+
const hasRoom = hasNoticeCapRoom(state, options);
|
|
5375
|
+
if (!hasRoom) markNoticeCapacityReachedInProcess(noticeId);
|
|
5376
|
+
return hasRoom;
|
|
5377
|
+
}
|
|
5378
|
+
function appendNoticeCapEvent(state, event, options = {}) {
|
|
5379
|
+
var _a2, _b2, _c;
|
|
5380
|
+
const now = (_a2 = options.now) != null ? _a2 : /* @__PURE__ */ new Date();
|
|
5381
|
+
const limit = (_b2 = options.limit) != null ? _b2 : NOTICE_CAP_LIMIT;
|
|
5382
|
+
const windowMs = (_c = options.windowMs) != null ? _c : NOTICE_CAP_WINDOW_MS;
|
|
5383
|
+
const events = eventsInWindow(state.events, now, windowMs);
|
|
5384
|
+
if (events.length >= limit) return null;
|
|
5385
|
+
return {
|
|
5386
|
+
...state,
|
|
5387
|
+
events: [
|
|
5388
|
+
...events,
|
|
5389
|
+
{
|
|
5390
|
+
evaluated_at: now.toISOString(),
|
|
5391
|
+
...event
|
|
5392
|
+
}
|
|
5393
|
+
]
|
|
5394
|
+
};
|
|
5395
|
+
}
|
|
5396
|
+
function recordNoticeOpportunity(noticeId, event, options = {}) {
|
|
5397
|
+
if (!isTelemetryEnabled()) return false;
|
|
5398
|
+
if (isNoticeCapacityReachedInProcess(noticeId)) return false;
|
|
5399
|
+
const config = loadMem0Config();
|
|
5400
|
+
const state = getNoticeState(config, noticeId);
|
|
5401
|
+
const nextState = appendNoticeCapEvent(state, event, options);
|
|
5402
|
+
if (!nextState) {
|
|
5403
|
+
markNoticeCapacityReachedInProcess(noticeId);
|
|
5404
|
+
return false;
|
|
5405
|
+
}
|
|
5406
|
+
const written = writeMem0ConfigAtomic(
|
|
5407
|
+
setNoticeState(config, noticeId, nextState)
|
|
5408
|
+
);
|
|
5409
|
+
if (written && !hasNoticeCapRoom(nextState, options)) {
|
|
5410
|
+
markNoticeCapacityReachedInProcess(noticeId);
|
|
5411
|
+
}
|
|
5412
|
+
return written;
|
|
5413
|
+
}
|
|
5414
|
+
function isFirstRunConsumed(config) {
|
|
5415
|
+
return getNoticeState(config, FIRST_RUN_NOTICE_ID).consumed === true;
|
|
5416
|
+
}
|
|
5417
|
+
function markFirstRunConsumed(triggerFunction, variant) {
|
|
5418
|
+
const config = loadMem0Config();
|
|
5419
|
+
const state = getNoticeState(config, FIRST_RUN_NOTICE_ID);
|
|
5420
|
+
const nextState = {
|
|
5421
|
+
...state,
|
|
5422
|
+
consumed: true,
|
|
5423
|
+
consumed_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
5424
|
+
trigger_function: triggerFunction,
|
|
5425
|
+
variant
|
|
5426
|
+
};
|
|
5427
|
+
return writeMem0ConfigAtomic(
|
|
5428
|
+
setNoticeState(config, FIRST_RUN_NOTICE_ID, nextState)
|
|
5429
|
+
);
|
|
5430
|
+
}
|
|
5431
|
+
function getDisplayDecision(noticeId, expectedNoticeType, variant, payload) {
|
|
5432
|
+
var _a2;
|
|
5433
|
+
const parsed = getNoticeConfigFromPayload(payload, noticeId);
|
|
5434
|
+
const copy = typeof ((_a2 = parsed.config) == null ? void 0 : _a2.copy) === "string" ? parsed.config.copy : void 0;
|
|
5435
|
+
if (!parsed.found || !parsed.config) {
|
|
5436
|
+
return {
|
|
5437
|
+
displayed: false,
|
|
5438
|
+
noticeConfigFound: false,
|
|
5439
|
+
bypassReason: "missing_notice_config"
|
|
5440
|
+
};
|
|
5441
|
+
}
|
|
5442
|
+
const noticeConfig = parsed.config;
|
|
5443
|
+
if (noticeConfig.enabled === false) {
|
|
5444
|
+
return {
|
|
5445
|
+
displayed: false,
|
|
5446
|
+
noticeConfigFound: true,
|
|
5447
|
+
copy,
|
|
5448
|
+
bypassReason: "payload_disabled",
|
|
5449
|
+
disabledReason: "payload_disabled"
|
|
5450
|
+
};
|
|
5451
|
+
}
|
|
5452
|
+
if (noticeConfig.notice_type !== expectedNoticeType) {
|
|
5453
|
+
return {
|
|
5454
|
+
displayed: false,
|
|
5455
|
+
noticeConfigFound: true,
|
|
5456
|
+
copy,
|
|
5457
|
+
bypassReason: "invalid_notice_type"
|
|
5458
|
+
};
|
|
5459
|
+
}
|
|
5460
|
+
if (!copy || copy.trim() === "") {
|
|
5461
|
+
return {
|
|
5462
|
+
displayed: false,
|
|
5463
|
+
noticeConfigFound: true,
|
|
5464
|
+
bypassReason: "missing_copy"
|
|
5465
|
+
};
|
|
5466
|
+
}
|
|
5467
|
+
if (variant !== DISPLAYED_VARIANT) {
|
|
5468
|
+
return {
|
|
5469
|
+
displayed: false,
|
|
5470
|
+
noticeConfigFound: true,
|
|
5471
|
+
copy,
|
|
5472
|
+
bypassReason: "holdout"
|
|
5473
|
+
};
|
|
5474
|
+
}
|
|
5475
|
+
return {
|
|
5476
|
+
displayed: true,
|
|
5477
|
+
noticeConfigFound: true,
|
|
5478
|
+
copy
|
|
5479
|
+
};
|
|
5480
|
+
}
|
|
5481
|
+
function renderScaleCopy(template, trigger) {
|
|
5482
|
+
var _a2, _b2, _c;
|
|
5483
|
+
if (typeof template !== "string" || template.trim() === "") return void 0;
|
|
5484
|
+
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 : ""));
|
|
5485
|
+
}
|
|
5486
|
+
function getScaleDisplayDecision(variant, payload, trigger) {
|
|
5487
|
+
var _a2;
|
|
5488
|
+
const parsed = getNoticeConfigFromPayload(payload, SCALE_THRESHOLD_NOTICE_ID);
|
|
5489
|
+
const copies = ((_a2 = parsed.config) == null ? void 0 : _a2.copies) && typeof parsed.config.copies === "object" && !Array.isArray(parsed.config.copies) ? parsed.config.copies : {};
|
|
5490
|
+
const copyKey = trigger.triggerSource === "memory_count" ? "memory_count" : "top_k";
|
|
5491
|
+
const copy = renderScaleCopy(copies[copyKey], trigger);
|
|
5492
|
+
if (!parsed.found || !parsed.config) {
|
|
5493
|
+
return {
|
|
5494
|
+
displayed: false,
|
|
5495
|
+
noticeConfigFound: false,
|
|
5496
|
+
bypassReason: "missing_notice_config"
|
|
5497
|
+
};
|
|
5498
|
+
}
|
|
5499
|
+
const noticeConfig = parsed.config;
|
|
5500
|
+
if (noticeConfig.enabled === false) {
|
|
5501
|
+
return {
|
|
5502
|
+
displayed: false,
|
|
5503
|
+
noticeConfigFound: true,
|
|
5504
|
+
copy,
|
|
5505
|
+
bypassReason: "payload_disabled",
|
|
5506
|
+
disabledReason: "payload_disabled"
|
|
5507
|
+
};
|
|
5508
|
+
}
|
|
5509
|
+
if (noticeConfig.notice_type !== LOG_LINE_NOTICE_TYPE) {
|
|
5510
|
+
return {
|
|
5511
|
+
displayed: false,
|
|
5512
|
+
noticeConfigFound: true,
|
|
5513
|
+
copy,
|
|
5514
|
+
bypassReason: "invalid_notice_type"
|
|
5515
|
+
};
|
|
5516
|
+
}
|
|
5517
|
+
if (!copy || copy.trim() === "") {
|
|
5518
|
+
return {
|
|
5519
|
+
displayed: false,
|
|
5520
|
+
noticeConfigFound: true,
|
|
5521
|
+
bypassReason: "missing_copy"
|
|
5522
|
+
};
|
|
5523
|
+
}
|
|
5524
|
+
if (variant !== DISPLAYED_VARIANT) {
|
|
5525
|
+
return {
|
|
5526
|
+
displayed: false,
|
|
5527
|
+
noticeConfigFound: true,
|
|
5528
|
+
copy,
|
|
5529
|
+
bypassReason: "holdout"
|
|
5530
|
+
};
|
|
5531
|
+
}
|
|
5532
|
+
return {
|
|
5533
|
+
displayed: true,
|
|
5534
|
+
noticeConfigFound: true,
|
|
5535
|
+
copy
|
|
5536
|
+
};
|
|
5537
|
+
}
|
|
5538
|
+
function getFeatureErrorDecision(noticeId, expectedNoticeType, variant, payload) {
|
|
5539
|
+
var _a2;
|
|
5540
|
+
const parsed = getNoticeConfigFromPayload(payload, noticeId);
|
|
5541
|
+
const copy = typeof ((_a2 = parsed.config) == null ? void 0 : _a2.copy) === "string" ? parsed.config.copy : void 0;
|
|
5542
|
+
if (!parsed.found || !parsed.config) {
|
|
5543
|
+
return {
|
|
5544
|
+
displayed: false,
|
|
5545
|
+
noticeConfigFound: false,
|
|
5546
|
+
bypassReason: "missing_notice_config"
|
|
5547
|
+
};
|
|
5548
|
+
}
|
|
5549
|
+
const noticeConfig = parsed.config;
|
|
5550
|
+
if (noticeConfig.enabled === false) {
|
|
5551
|
+
return {
|
|
5552
|
+
displayed: false,
|
|
5553
|
+
noticeConfigFound: true,
|
|
5554
|
+
copy,
|
|
5555
|
+
bypassReason: "payload_disabled",
|
|
5556
|
+
disabledReason: "payload_disabled"
|
|
5557
|
+
};
|
|
5558
|
+
}
|
|
5559
|
+
if (noticeConfig.notice_type !== expectedNoticeType) {
|
|
5560
|
+
return {
|
|
5561
|
+
displayed: false,
|
|
5562
|
+
noticeConfigFound: true,
|
|
5563
|
+
copy,
|
|
5564
|
+
bypassReason: "invalid_notice_type"
|
|
5565
|
+
};
|
|
5566
|
+
}
|
|
5567
|
+
if (!copy || copy.trim() === "") {
|
|
5568
|
+
return {
|
|
5569
|
+
displayed: false,
|
|
5570
|
+
noticeConfigFound: true,
|
|
5571
|
+
bypassReason: "missing_copy"
|
|
5572
|
+
};
|
|
5573
|
+
}
|
|
5574
|
+
if (variant !== DISPLAYED_VARIANT && variant !== HOLDOUT_VARIANT) {
|
|
5575
|
+
return {
|
|
5576
|
+
displayed: false,
|
|
5577
|
+
noticeConfigFound: true,
|
|
5578
|
+
copy,
|
|
5579
|
+
bypassReason: "not_displayed"
|
|
5580
|
+
};
|
|
5581
|
+
}
|
|
5582
|
+
return {
|
|
5583
|
+
displayed: true,
|
|
5584
|
+
noticeConfigFound: true,
|
|
5585
|
+
copy
|
|
5586
|
+
};
|
|
5587
|
+
}
|
|
5588
|
+
async function getDecayFeatureErrorMessage(instance) {
|
|
5589
|
+
if (!isTelemetryEnabled()) return DECAY_FEATURE_PLAIN_ERROR;
|
|
5590
|
+
try {
|
|
5591
|
+
const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
|
|
5592
|
+
if (!flagEvaluation) return DECAY_FEATURE_PLAIN_ERROR;
|
|
5593
|
+
const decision = getFeatureErrorDecision(
|
|
5594
|
+
DECAY_FEATURE_NOTICE_ID,
|
|
5595
|
+
ERROR_NOTICE_TYPE,
|
|
5596
|
+
flagEvaluation.variant,
|
|
5597
|
+
flagEvaluation.payload
|
|
5598
|
+
);
|
|
5599
|
+
await emitNoticeDisplayed(instance, {
|
|
5600
|
+
notice_id: DECAY_FEATURE_NOTICE_ID,
|
|
5601
|
+
notice_type: ERROR_NOTICE_TYPE,
|
|
5602
|
+
flag_key: NOTICE_FLAG_KEY,
|
|
5603
|
+
variant: flagEvaluation.variant,
|
|
5604
|
+
displayed: decision.displayed,
|
|
5605
|
+
payload: decision.copy,
|
|
5606
|
+
bypass_reason: decision.bypassReason,
|
|
5607
|
+
disabled_reason: decision.disabledReason,
|
|
5608
|
+
notice_config_found: decision.noticeConfigFound,
|
|
5609
|
+
sync_type: "async",
|
|
5610
|
+
trigger_function: "update_project",
|
|
5611
|
+
trigger_parameter: "decay"
|
|
5612
|
+
});
|
|
5613
|
+
if (decision.displayed && decision.copy) {
|
|
5614
|
+
return decision.copy;
|
|
5615
|
+
}
|
|
5616
|
+
} catch (e) {
|
|
5617
|
+
}
|
|
5618
|
+
return DECAY_FEATURE_PLAIN_ERROR;
|
|
5619
|
+
}
|
|
5620
|
+
async function getTemporalFeatureErrorMessage(instance, trigger) {
|
|
5621
|
+
const plainError = trigger.triggerParameter === "timestamp" ? TEMPORAL_TIMESTAMP_PLAIN_ERROR : TEMPORAL_REFERENCE_DATE_PLAIN_ERROR;
|
|
5622
|
+
if (!isTelemetryEnabled()) return plainError;
|
|
5623
|
+
try {
|
|
5624
|
+
const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
|
|
5625
|
+
if (!flagEvaluation) return plainError;
|
|
5626
|
+
const decision = getFeatureErrorDecision(
|
|
5627
|
+
TEMPORAL_FEATURE_NOTICE_ID,
|
|
5628
|
+
ERROR_NOTICE_TYPE,
|
|
5629
|
+
flagEvaluation.variant,
|
|
5630
|
+
flagEvaluation.payload
|
|
5631
|
+
);
|
|
5632
|
+
await emitNoticeDisplayed(instance, {
|
|
5633
|
+
notice_id: TEMPORAL_FEATURE_NOTICE_ID,
|
|
5634
|
+
notice_type: ERROR_NOTICE_TYPE,
|
|
5635
|
+
flag_key: NOTICE_FLAG_KEY,
|
|
5636
|
+
variant: flagEvaluation.variant,
|
|
5637
|
+
displayed: decision.displayed,
|
|
5638
|
+
payload: decision.copy,
|
|
5639
|
+
bypass_reason: decision.bypassReason,
|
|
5640
|
+
disabled_reason: decision.disabledReason,
|
|
5641
|
+
notice_config_found: decision.noticeConfigFound,
|
|
5642
|
+
sync_type: "async",
|
|
5643
|
+
trigger_function: trigger.triggerFunction,
|
|
5644
|
+
trigger_parameter: trigger.triggerParameter
|
|
5645
|
+
});
|
|
5646
|
+
if (decision.displayed && decision.copy) {
|
|
5647
|
+
return decision.copy;
|
|
5648
|
+
}
|
|
5649
|
+
} catch (e) {
|
|
5650
|
+
}
|
|
5651
|
+
return plainError;
|
|
5652
|
+
}
|
|
5653
|
+
function getDecayUsageDeleteCountAfterSuccess() {
|
|
5654
|
+
if (!isTelemetryEnabled()) return 0;
|
|
5655
|
+
decayUsageSuccessfulDeleteCount += 1;
|
|
5656
|
+
return decayUsageSuccessfulDeleteCount;
|
|
5657
|
+
}
|
|
5658
|
+
function isDecayUsageDeleteEligible(deleteCount) {
|
|
5659
|
+
return deleteCount >= DECAY_USAGE_DELETE_THRESHOLD;
|
|
5660
|
+
}
|
|
5661
|
+
function isRecord(value) {
|
|
5662
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date);
|
|
5663
|
+
}
|
|
5664
|
+
function isTemporalKey(key) {
|
|
5665
|
+
const keyText = String(key).toLowerCase();
|
|
5666
|
+
return [
|
|
5667
|
+
"date",
|
|
5668
|
+
"time",
|
|
5669
|
+
"timestamp",
|
|
5670
|
+
"datetime",
|
|
5671
|
+
"event_date",
|
|
5672
|
+
"reference_date",
|
|
5673
|
+
"referencedate",
|
|
5674
|
+
"created_at",
|
|
5675
|
+
"createdat",
|
|
5676
|
+
"updated_at",
|
|
5677
|
+
"updatedat",
|
|
5678
|
+
"started_at",
|
|
5679
|
+
"startedat",
|
|
5680
|
+
"ended_at",
|
|
5681
|
+
"endedat",
|
|
5682
|
+
"expires_at",
|
|
5683
|
+
"expiresat"
|
|
5684
|
+
].includes(keyText) || keyText.endsWith("_date") || keyText.endsWith("_time") || keyText.endsWith("_at") || keyText.includes("timestamp");
|
|
5685
|
+
}
|
|
5686
|
+
function looksTemporalValue(value, allowEpoch) {
|
|
5687
|
+
if (value instanceof Date) return !Number.isNaN(value.getTime());
|
|
5688
|
+
if (typeof value === "string") {
|
|
5689
|
+
return ISO_DATE_RE.test(value) || RELATIVE_TIME_RE.test(value);
|
|
5690
|
+
}
|
|
5691
|
+
if (allowEpoch && typeof value === "number" && Number.isFinite(value)) {
|
|
5692
|
+
return value >= 946684800 && value <= 4102444800 || value >= 9466848e5 && value <= 41024448e5;
|
|
5693
|
+
}
|
|
5694
|
+
return false;
|
|
5695
|
+
}
|
|
5696
|
+
function detectTemporalUsageFromMetadata(metadata) {
|
|
5697
|
+
try {
|
|
5698
|
+
if (!isRecord(metadata)) return null;
|
|
5699
|
+
const visited = /* @__PURE__ */ new WeakSet();
|
|
5700
|
+
const stack = [{ value: metadata, depth: 0 }];
|
|
5701
|
+
while (stack.length > 0) {
|
|
5702
|
+
const current = stack.pop();
|
|
5703
|
+
if (current.depth > MAX_TEMPORAL_DETECTION_DEPTH) continue;
|
|
5704
|
+
if (Array.isArray(current.value)) {
|
|
5705
|
+
for (const child of current.value) {
|
|
5706
|
+
if (looksTemporalValue(child, false)) {
|
|
5707
|
+
return {
|
|
5708
|
+
triggerSource: "metadata",
|
|
5709
|
+
triggerReason: "date_like_metadata"
|
|
5710
|
+
};
|
|
5711
|
+
}
|
|
5712
|
+
stack.push({
|
|
5713
|
+
value: child,
|
|
5714
|
+
parentKey: current.parentKey,
|
|
5715
|
+
depth: current.depth + 1
|
|
5716
|
+
});
|
|
5717
|
+
}
|
|
5718
|
+
continue;
|
|
5719
|
+
}
|
|
5720
|
+
if (!isRecord(current.value)) continue;
|
|
5721
|
+
if (visited.has(current.value)) continue;
|
|
5722
|
+
visited.add(current.value);
|
|
5723
|
+
for (const [key, value] of Object.entries(current.value)) {
|
|
5724
|
+
const temporalKey = isTemporalKey(key);
|
|
5725
|
+
if (temporalKey && looksTemporalValue(value, true) || looksTemporalValue(value, false)) {
|
|
5726
|
+
return {
|
|
5727
|
+
triggerSource: "metadata",
|
|
5728
|
+
triggerReason: "date_like_metadata"
|
|
5729
|
+
};
|
|
5730
|
+
}
|
|
5731
|
+
if (isRecord(value) || Array.isArray(value)) {
|
|
5732
|
+
stack.push({ value, parentKey: key, depth: current.depth + 1 });
|
|
5733
|
+
}
|
|
5734
|
+
}
|
|
5735
|
+
}
|
|
5736
|
+
} catch (e) {
|
|
5737
|
+
}
|
|
5738
|
+
return null;
|
|
5739
|
+
}
|
|
5740
|
+
function hasTemporalFilter(filters) {
|
|
5741
|
+
try {
|
|
5742
|
+
if (!isRecord(filters)) return false;
|
|
5743
|
+
const visited = /* @__PURE__ */ new WeakSet();
|
|
5744
|
+
const stack = [
|
|
5745
|
+
{ value: filters, depth: 0 }
|
|
5746
|
+
];
|
|
5747
|
+
while (stack.length > 0) {
|
|
5748
|
+
const current = stack.pop();
|
|
5749
|
+
if (current.depth > MAX_TEMPORAL_DETECTION_DEPTH) continue;
|
|
5750
|
+
if (Array.isArray(current.value)) {
|
|
5751
|
+
for (const child of current.value) {
|
|
5752
|
+
stack.push({ value: child, depth: current.depth + 1 });
|
|
5753
|
+
}
|
|
5754
|
+
continue;
|
|
5755
|
+
}
|
|
5756
|
+
if (!isRecord(current.value)) continue;
|
|
5757
|
+
if (visited.has(current.value)) continue;
|
|
5758
|
+
visited.add(current.value);
|
|
5759
|
+
for (const [key, value] of Object.entries(current.value)) {
|
|
5760
|
+
if (["AND", "OR", "NOT", "$and", "$or", "$not"].includes(key)) {
|
|
5761
|
+
if (isRecord(value) || Array.isArray(value)) {
|
|
5762
|
+
stack.push({ value, depth: current.depth + 1 });
|
|
5763
|
+
}
|
|
5764
|
+
continue;
|
|
5765
|
+
}
|
|
5766
|
+
const temporalKey = isTemporalKey(key);
|
|
5767
|
+
if (isRecord(value)) {
|
|
5768
|
+
const rangeValues = Object.entries(value).filter(([operator]) => RANGE_OPERATORS.has(operator)).map(([, rangeValue]) => rangeValue);
|
|
5769
|
+
if (rangeValues.length > 0 && (temporalKey || rangeValues.some(
|
|
5770
|
+
(rangeValue) => looksTemporalValue(rangeValue, temporalKey)
|
|
5771
|
+
))) {
|
|
5772
|
+
return true;
|
|
5773
|
+
}
|
|
5774
|
+
stack.push({ value, depth: current.depth + 1 });
|
|
5775
|
+
} else if (temporalKey && looksTemporalValue(value, true)) {
|
|
5776
|
+
return true;
|
|
5777
|
+
}
|
|
5778
|
+
}
|
|
5779
|
+
}
|
|
5780
|
+
} catch (e) {
|
|
5781
|
+
}
|
|
5782
|
+
return false;
|
|
5783
|
+
}
|
|
5784
|
+
function detectTemporalUsageFromSearch(query, filters) {
|
|
5785
|
+
try {
|
|
5786
|
+
if (typeof query === "string") {
|
|
5787
|
+
if (RELATIVE_TIME_RE.test(query)) {
|
|
5788
|
+
return { triggerSource: "query", triggerReason: "relative_phrase" };
|
|
5789
|
+
}
|
|
5790
|
+
if (ISO_DATE_RE.test(query)) {
|
|
5791
|
+
return { triggerSource: "query", triggerReason: "date_like_query" };
|
|
5792
|
+
}
|
|
5793
|
+
}
|
|
5794
|
+
if (hasTemporalFilter(filters)) {
|
|
5795
|
+
return { triggerSource: "filter", triggerReason: "date_range_filter" };
|
|
5796
|
+
}
|
|
5797
|
+
} catch (e) {
|
|
5798
|
+
}
|
|
5799
|
+
return null;
|
|
5800
|
+
}
|
|
5801
|
+
function coerceNonnegativeInteger(value) {
|
|
5802
|
+
if (typeof value === "boolean") return null;
|
|
5803
|
+
const parsed = Number(value);
|
|
5804
|
+
if (!Number.isFinite(parsed) || !Number.isInteger(parsed) || parsed < 0) {
|
|
5805
|
+
return null;
|
|
5806
|
+
}
|
|
5807
|
+
return parsed;
|
|
5808
|
+
}
|
|
5809
|
+
function countAddedMemories(addResult) {
|
|
5810
|
+
const results = isRecord(addResult) && Array.isArray(addResult.results) ? addResult.results : addResult;
|
|
5811
|
+
if (!Array.isArray(results)) return 0;
|
|
5812
|
+
return results.filter((item) => {
|
|
5813
|
+
if (!isRecord(item)) return false;
|
|
5814
|
+
const metadata = item.metadata;
|
|
5815
|
+
return isRecord(metadata) && metadata.event === "ADD";
|
|
5816
|
+
}).length;
|
|
5817
|
+
}
|
|
5818
|
+
function extractProviderCount(info) {
|
|
5819
|
+
if (!info) return null;
|
|
5820
|
+
if (typeof info === "number") return coerceNonnegativeInteger(info);
|
|
5821
|
+
if (isRecord(info)) {
|
|
5822
|
+
for (const key of [
|
|
5823
|
+
"count",
|
|
5824
|
+
"points_count",
|
|
5825
|
+
"vectors_count",
|
|
5826
|
+
"indexed_vectors_count"
|
|
5827
|
+
]) {
|
|
5828
|
+
const value = coerceNonnegativeInteger(info[key]);
|
|
5829
|
+
if (value !== null) return value;
|
|
5830
|
+
}
|
|
5831
|
+
const result = extractProviderCount(info.result);
|
|
5832
|
+
if (result !== null) return result;
|
|
5833
|
+
}
|
|
5834
|
+
return null;
|
|
5835
|
+
}
|
|
5836
|
+
async function getProviderMemoryCount(memoryInstance) {
|
|
5837
|
+
try {
|
|
5838
|
+
const vectorStore = memoryInstance == null ? void 0 : memoryInstance.vectorStore;
|
|
5839
|
+
if (!vectorStore) return null;
|
|
5840
|
+
if (typeof vectorStore.count === "function") {
|
|
5841
|
+
const value = extractProviderCount(await vectorStore.count());
|
|
5842
|
+
if (value !== null) return value;
|
|
5843
|
+
}
|
|
5844
|
+
const collectionName = vectorStore.collectionName;
|
|
5845
|
+
const client = vectorStore.client;
|
|
5846
|
+
if (client && collectionName && typeof client.count === "function") {
|
|
5847
|
+
const value = extractProviderCount(
|
|
5848
|
+
await client.count(collectionName, { exact: true })
|
|
5849
|
+
);
|
|
5850
|
+
if (value !== null) return value;
|
|
5851
|
+
}
|
|
5852
|
+
if (client && collectionName && typeof client.getCollection === "function") {
|
|
5853
|
+
const value = extractProviderCount(
|
|
5854
|
+
await client.getCollection(collectionName)
|
|
5855
|
+
);
|
|
5856
|
+
if (value !== null) return value;
|
|
5857
|
+
}
|
|
5858
|
+
} catch (e) {
|
|
5859
|
+
}
|
|
5860
|
+
return null;
|
|
5861
|
+
}
|
|
5862
|
+
function markScaleMemoryCountThresholdEvaluated() {
|
|
5863
|
+
try {
|
|
5864
|
+
const config = loadMem0Config();
|
|
5865
|
+
const state = getNoticeState(config, SCALE_THRESHOLD_NOTICE_ID);
|
|
5866
|
+
if (state.memory_count_threshold_evaluated === true) {
|
|
5867
|
+
scaleMemoryCountThresholdEvaluatedInProcess = true;
|
|
5868
|
+
return false;
|
|
5869
|
+
}
|
|
5870
|
+
const nextState = {
|
|
5871
|
+
...state,
|
|
5872
|
+
memory_count_threshold_evaluated: true
|
|
5873
|
+
};
|
|
5874
|
+
const written = writeMem0ConfigAtomic(
|
|
5875
|
+
setNoticeState(config, SCALE_THRESHOLD_NOTICE_ID, nextState)
|
|
5876
|
+
);
|
|
5877
|
+
if (written) scaleMemoryCountThresholdEvaluatedInProcess = true;
|
|
5878
|
+
return written;
|
|
5879
|
+
} catch (e) {
|
|
5880
|
+
return false;
|
|
5881
|
+
}
|
|
5882
|
+
}
|
|
5883
|
+
function detectScaleThresholdFromTopK(topK) {
|
|
5884
|
+
const topKValue = coerceNonnegativeInteger(topK);
|
|
5885
|
+
if (topKValue === null || topKValue < SCALE_TOP_K_THRESHOLD) return null;
|
|
5886
|
+
return {
|
|
5887
|
+
triggerSource: "top_k",
|
|
5888
|
+
triggerReason: "high_top_k",
|
|
5889
|
+
topK: topKValue,
|
|
5890
|
+
threshold: SCALE_TOP_K_THRESHOLD
|
|
5891
|
+
};
|
|
5892
|
+
}
|
|
5893
|
+
async function detectScaleThresholdFromAddResult(memoryInstance, addResult) {
|
|
5894
|
+
if (!isTelemetryEnabled()) return null;
|
|
5895
|
+
const addedCount = countAddedMemories(addResult);
|
|
5896
|
+
if (addedCount === 0) return null;
|
|
5897
|
+
try {
|
|
5898
|
+
if (scaleMemoryCountThresholdEvaluatedInProcess) return null;
|
|
5899
|
+
scaleMemoryCountAddsSinceCheck += addedCount;
|
|
5900
|
+
const shouldCheck = !scaleMemoryCountCheckedInProcess || scaleMemoryCountAddsSinceCheck >= SCALE_MEMORY_COUNT_CHECK_INTERVAL;
|
|
5901
|
+
if (!shouldCheck) return null;
|
|
5902
|
+
scaleMemoryCountCheckedInProcess = true;
|
|
5903
|
+
scaleMemoryCountAddsSinceCheck = 0;
|
|
5904
|
+
const config = loadMem0Config();
|
|
5905
|
+
const state = getNoticeState(config, SCALE_THRESHOLD_NOTICE_ID);
|
|
5906
|
+
if (state.memory_count_threshold_evaluated === true) {
|
|
5907
|
+
scaleMemoryCountThresholdEvaluatedInProcess = true;
|
|
5908
|
+
return null;
|
|
5909
|
+
}
|
|
5910
|
+
if (!hasNoticeCapRoom(state)) return null;
|
|
5911
|
+
} catch (e) {
|
|
5912
|
+
return null;
|
|
5913
|
+
}
|
|
5914
|
+
const providerCount = await getProviderMemoryCount(memoryInstance);
|
|
5915
|
+
if (providerCount === null || providerCount < SCALE_MEMORY_COUNT_THRESHOLD) {
|
|
5916
|
+
return null;
|
|
5917
|
+
}
|
|
5918
|
+
if (!markScaleMemoryCountThresholdEvaluated()) return null;
|
|
5919
|
+
return {
|
|
5920
|
+
triggerSource: "memory_count",
|
|
5921
|
+
triggerReason: "memory_count_threshold",
|
|
5922
|
+
memoryCount: providerCount,
|
|
5923
|
+
threshold: SCALE_MEMORY_COUNT_THRESHOLD
|
|
5924
|
+
};
|
|
5925
|
+
}
|
|
5926
|
+
function detectPerformanceSlowQuery(elapsedMs, topK, resultCount) {
|
|
5927
|
+
const elapsedMsValue = coerceNonnegativeInteger(
|
|
5928
|
+
Math.round(Number(elapsedMs))
|
|
5929
|
+
);
|
|
5930
|
+
const topKValue = coerceNonnegativeInteger(topK);
|
|
5931
|
+
const resultCountValue = coerceNonnegativeInteger(resultCount);
|
|
5932
|
+
if (elapsedMsValue === null || topKValue === null || resultCountValue === null || elapsedMsValue <= PERFORMANCE_SLOW_QUERY_THRESHOLD_MS) {
|
|
5933
|
+
return null;
|
|
5934
|
+
}
|
|
5935
|
+
return {
|
|
5936
|
+
elapsedMs: elapsedMsValue,
|
|
5937
|
+
thresholdMs: PERFORMANCE_SLOW_QUERY_THRESHOLD_MS,
|
|
5938
|
+
topK: topKValue,
|
|
5939
|
+
resultCount: resultCountValue
|
|
5940
|
+
};
|
|
5941
|
+
}
|
|
5942
|
+
async function displayScaleThresholdNotice(instance, trigger) {
|
|
5943
|
+
if (!isTelemetryEnabled()) return;
|
|
5944
|
+
if (isNoticeCapacityReachedInProcess(SCALE_THRESHOLD_NOTICE_ID)) return;
|
|
5945
|
+
try {
|
|
5946
|
+
const config = loadMem0Config();
|
|
5947
|
+
const state = getNoticeState(config, SCALE_THRESHOLD_NOTICE_ID);
|
|
5948
|
+
if (!hasNoticeCapRoomForNotice(SCALE_THRESHOLD_NOTICE_ID, state)) return;
|
|
5949
|
+
const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
|
|
5950
|
+
if (!flagEvaluation) return;
|
|
5951
|
+
const decision = getScaleDisplayDecision(
|
|
5952
|
+
flagEvaluation.variant,
|
|
5953
|
+
flagEvaluation.payload,
|
|
5954
|
+
trigger
|
|
5955
|
+
);
|
|
5956
|
+
const opportunity = {
|
|
5957
|
+
variant: flagEvaluation.variant,
|
|
5958
|
+
sync_type: "async",
|
|
5959
|
+
trigger_function: trigger.triggerFunction,
|
|
5960
|
+
trigger_source: trigger.triggerSource,
|
|
5961
|
+
trigger_reason: trigger.triggerReason,
|
|
5962
|
+
...trigger.topK !== void 0 && { top_k: trigger.topK },
|
|
5963
|
+
...trigger.memoryCount !== void 0 && {
|
|
5964
|
+
memory_count: trigger.memoryCount
|
|
5965
|
+
},
|
|
5966
|
+
threshold: trigger.threshold
|
|
5967
|
+
};
|
|
5968
|
+
if (!recordNoticeOpportunity(SCALE_THRESHOLD_NOTICE_ID, opportunity)) {
|
|
5969
|
+
return;
|
|
5970
|
+
}
|
|
5971
|
+
await emitNoticeDisplayed(instance, {
|
|
5972
|
+
notice_id: SCALE_THRESHOLD_NOTICE_ID,
|
|
5973
|
+
notice_type: LOG_LINE_NOTICE_TYPE,
|
|
5974
|
+
flag_key: NOTICE_FLAG_KEY,
|
|
5975
|
+
variant: flagEvaluation.variant,
|
|
5976
|
+
displayed: decision.displayed,
|
|
5977
|
+
payload: decision.copy,
|
|
5978
|
+
bypass_reason: decision.bypassReason,
|
|
5979
|
+
disabled_reason: decision.disabledReason,
|
|
5980
|
+
notice_config_found: decision.noticeConfigFound,
|
|
5981
|
+
sync_type: "async",
|
|
5982
|
+
trigger_function: trigger.triggerFunction,
|
|
5983
|
+
trigger_source: trigger.triggerSource,
|
|
5984
|
+
trigger_reason: trigger.triggerReason,
|
|
5985
|
+
top_k: trigger.topK,
|
|
5986
|
+
memory_count: trigger.memoryCount,
|
|
5987
|
+
threshold: trigger.threshold
|
|
5988
|
+
});
|
|
5989
|
+
if (decision.displayed && decision.copy) {
|
|
5990
|
+
process.stderr.write(`${decision.copy}
|
|
5991
|
+
`);
|
|
5992
|
+
}
|
|
5993
|
+
} catch (e) {
|
|
5994
|
+
}
|
|
5995
|
+
}
|
|
5996
|
+
async function displayPerformanceSlowQueryNotice(instance, trigger) {
|
|
5997
|
+
if (!isTelemetryEnabled()) return;
|
|
5998
|
+
if (isNoticeCapacityReachedInProcess(PERFORMANCE_SLOW_QUERY_NOTICE_ID)) {
|
|
5999
|
+
return;
|
|
6000
|
+
}
|
|
6001
|
+
try {
|
|
6002
|
+
const config = loadMem0Config();
|
|
6003
|
+
const state = getNoticeState(config, PERFORMANCE_SLOW_QUERY_NOTICE_ID);
|
|
6004
|
+
if (!hasNoticeCapRoomForNotice(PERFORMANCE_SLOW_QUERY_NOTICE_ID, state)) {
|
|
6005
|
+
return;
|
|
6006
|
+
}
|
|
6007
|
+
const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
|
|
6008
|
+
if (!flagEvaluation) return;
|
|
6009
|
+
const decision = getDisplayDecision(
|
|
6010
|
+
PERFORMANCE_SLOW_QUERY_NOTICE_ID,
|
|
6011
|
+
LOG_LINE_NOTICE_TYPE,
|
|
6012
|
+
flagEvaluation.variant,
|
|
6013
|
+
flagEvaluation.payload
|
|
6014
|
+
);
|
|
6015
|
+
const opportunity = {
|
|
6016
|
+
variant: flagEvaluation.variant,
|
|
6017
|
+
sync_type: "async",
|
|
6018
|
+
trigger_function: trigger.triggerFunction,
|
|
6019
|
+
trigger_reason: trigger.triggerReason
|
|
6020
|
+
};
|
|
6021
|
+
if (!recordNoticeOpportunity(PERFORMANCE_SLOW_QUERY_NOTICE_ID, opportunity)) {
|
|
6022
|
+
return;
|
|
6023
|
+
}
|
|
6024
|
+
await emitNoticeDisplayed(instance, {
|
|
6025
|
+
notice_id: PERFORMANCE_SLOW_QUERY_NOTICE_ID,
|
|
6026
|
+
notice_type: LOG_LINE_NOTICE_TYPE,
|
|
6027
|
+
flag_key: NOTICE_FLAG_KEY,
|
|
6028
|
+
variant: flagEvaluation.variant,
|
|
6029
|
+
displayed: decision.displayed,
|
|
6030
|
+
payload: decision.copy,
|
|
6031
|
+
bypass_reason: decision.bypassReason,
|
|
6032
|
+
disabled_reason: decision.disabledReason,
|
|
6033
|
+
notice_config_found: decision.noticeConfigFound,
|
|
6034
|
+
sync_type: "async",
|
|
6035
|
+
trigger_function: trigger.triggerFunction,
|
|
6036
|
+
trigger_reason: trigger.triggerReason,
|
|
6037
|
+
elapsed_ms: trigger.elapsedMs,
|
|
6038
|
+
threshold_ms: trigger.thresholdMs,
|
|
6039
|
+
top_k: trigger.topK,
|
|
6040
|
+
result_count: trigger.resultCount
|
|
6041
|
+
});
|
|
6042
|
+
if (decision.displayed && decision.copy) {
|
|
6043
|
+
process.stderr.write(`${decision.copy}
|
|
6044
|
+
`);
|
|
6045
|
+
}
|
|
6046
|
+
} catch (e) {
|
|
6047
|
+
}
|
|
6048
|
+
}
|
|
6049
|
+
async function displayTemporalUsageNotice(instance, trigger) {
|
|
6050
|
+
if (!isTelemetryEnabled()) return;
|
|
6051
|
+
if (isNoticeCapacityReachedInProcess(TEMPORAL_USAGE_NOTICE_ID)) return;
|
|
6052
|
+
try {
|
|
6053
|
+
const config = loadMem0Config();
|
|
6054
|
+
const state = getNoticeState(config, TEMPORAL_USAGE_NOTICE_ID);
|
|
6055
|
+
if (!hasNoticeCapRoomForNotice(TEMPORAL_USAGE_NOTICE_ID, state)) return;
|
|
6056
|
+
const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
|
|
6057
|
+
if (!flagEvaluation) return;
|
|
6058
|
+
const decision = getDisplayDecision(
|
|
6059
|
+
TEMPORAL_USAGE_NOTICE_ID,
|
|
6060
|
+
LOG_LINE_NOTICE_TYPE,
|
|
6061
|
+
flagEvaluation.variant,
|
|
6062
|
+
flagEvaluation.payload
|
|
6063
|
+
);
|
|
6064
|
+
const opportunity = {
|
|
6065
|
+
variant: flagEvaluation.variant,
|
|
6066
|
+
sync_type: "async",
|
|
6067
|
+
trigger_function: trigger.triggerFunction,
|
|
6068
|
+
trigger_source: trigger.triggerSource,
|
|
6069
|
+
trigger_reason: trigger.triggerReason
|
|
6070
|
+
};
|
|
6071
|
+
if (!recordNoticeOpportunity(TEMPORAL_USAGE_NOTICE_ID, opportunity)) {
|
|
6072
|
+
return;
|
|
6073
|
+
}
|
|
6074
|
+
await emitNoticeDisplayed(instance, {
|
|
6075
|
+
notice_id: TEMPORAL_USAGE_NOTICE_ID,
|
|
6076
|
+
notice_type: LOG_LINE_NOTICE_TYPE,
|
|
6077
|
+
flag_key: NOTICE_FLAG_KEY,
|
|
6078
|
+
variant: flagEvaluation.variant,
|
|
6079
|
+
displayed: decision.displayed,
|
|
6080
|
+
payload: decision.copy,
|
|
6081
|
+
bypass_reason: decision.bypassReason,
|
|
6082
|
+
disabled_reason: decision.disabledReason,
|
|
6083
|
+
notice_config_found: decision.noticeConfigFound,
|
|
6084
|
+
sync_type: "async",
|
|
6085
|
+
trigger_function: trigger.triggerFunction,
|
|
6086
|
+
trigger_source: trigger.triggerSource,
|
|
6087
|
+
trigger_reason: trigger.triggerReason
|
|
6088
|
+
});
|
|
6089
|
+
if (decision.displayed && decision.copy) {
|
|
6090
|
+
process.stderr.write(`${decision.copy}
|
|
6091
|
+
`);
|
|
6092
|
+
}
|
|
6093
|
+
} catch (e) {
|
|
6094
|
+
}
|
|
6095
|
+
}
|
|
6096
|
+
async function displayDecayUsageNotice(instance, trigger) {
|
|
6097
|
+
if (!isTelemetryEnabled()) return;
|
|
6098
|
+
if (isNoticeCapacityReachedInProcess(DECAY_USAGE_NOTICE_ID)) return;
|
|
6099
|
+
try {
|
|
6100
|
+
const config = loadMem0Config();
|
|
6101
|
+
const state = getNoticeState(config, DECAY_USAGE_NOTICE_ID);
|
|
6102
|
+
if (!hasNoticeCapRoomForNotice(DECAY_USAGE_NOTICE_ID, state)) return;
|
|
6103
|
+
const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
|
|
6104
|
+
if (!flagEvaluation) return;
|
|
6105
|
+
const decision = getDisplayDecision(
|
|
6106
|
+
DECAY_USAGE_NOTICE_ID,
|
|
6107
|
+
LOG_LINE_NOTICE_TYPE,
|
|
6108
|
+
flagEvaluation.variant,
|
|
6109
|
+
flagEvaluation.payload
|
|
6110
|
+
);
|
|
6111
|
+
const opportunity = {
|
|
6112
|
+
variant: flagEvaluation.variant,
|
|
6113
|
+
sync_type: "async",
|
|
6114
|
+
trigger_function: trigger.triggerFunction,
|
|
6115
|
+
trigger_source: trigger.triggerSource,
|
|
6116
|
+
trigger_reason: trigger.triggerReason,
|
|
6117
|
+
...trigger.deleteCount !== void 0 && {
|
|
6118
|
+
delete_count: trigger.deleteCount
|
|
6119
|
+
},
|
|
6120
|
+
...trigger.deletedCount !== void 0 && {
|
|
6121
|
+
deleted_count: trigger.deletedCount
|
|
6122
|
+
}
|
|
6123
|
+
};
|
|
6124
|
+
if (!recordNoticeOpportunity(DECAY_USAGE_NOTICE_ID, opportunity)) {
|
|
6125
|
+
return;
|
|
6126
|
+
}
|
|
6127
|
+
await emitNoticeDisplayed(instance, {
|
|
6128
|
+
notice_id: DECAY_USAGE_NOTICE_ID,
|
|
6129
|
+
notice_type: LOG_LINE_NOTICE_TYPE,
|
|
6130
|
+
flag_key: NOTICE_FLAG_KEY,
|
|
6131
|
+
variant: flagEvaluation.variant,
|
|
6132
|
+
displayed: decision.displayed,
|
|
6133
|
+
payload: decision.copy,
|
|
6134
|
+
bypass_reason: decision.bypassReason,
|
|
6135
|
+
disabled_reason: decision.disabledReason,
|
|
6136
|
+
notice_config_found: decision.noticeConfigFound,
|
|
6137
|
+
sync_type: "async",
|
|
6138
|
+
trigger_function: trigger.triggerFunction,
|
|
6139
|
+
trigger_source: trigger.triggerSource,
|
|
6140
|
+
trigger_reason: trigger.triggerReason,
|
|
6141
|
+
...trigger.deleteCount !== void 0 && {
|
|
6142
|
+
delete_count: trigger.deleteCount
|
|
6143
|
+
},
|
|
6144
|
+
...trigger.deletedCount !== void 0 && {
|
|
6145
|
+
deleted_count: trigger.deletedCount
|
|
6146
|
+
}
|
|
6147
|
+
});
|
|
6148
|
+
if (decision.displayed && decision.copy) {
|
|
6149
|
+
process.stderr.write(`${decision.copy}
|
|
6150
|
+
`);
|
|
6151
|
+
}
|
|
6152
|
+
} catch (e) {
|
|
6153
|
+
}
|
|
6154
|
+
}
|
|
6155
|
+
async function displayFirstRunNotice(instance, triggerFunction) {
|
|
6156
|
+
if (!isTelemetryEnabled()) return;
|
|
6157
|
+
if (firstRunConsumedInProcess || firstRunClaimInProgress) return;
|
|
6158
|
+
const config = loadMem0Config();
|
|
6159
|
+
if (isFirstRunConsumed(config)) {
|
|
6160
|
+
firstRunConsumedInProcess = true;
|
|
6161
|
+
return;
|
|
6162
|
+
}
|
|
6163
|
+
firstRunClaimInProgress = true;
|
|
6164
|
+
try {
|
|
6165
|
+
const flagEvaluation = await evaluateNoticeFlag(instance.telemetryId);
|
|
6166
|
+
if (!flagEvaluation) {
|
|
6167
|
+
firstRunClaimInProgress = false;
|
|
6168
|
+
return;
|
|
6169
|
+
}
|
|
6170
|
+
const decision = getDisplayDecision(
|
|
6171
|
+
FIRST_RUN_NOTICE_ID,
|
|
6172
|
+
LOG_LINE_NOTICE_TYPE,
|
|
6173
|
+
flagEvaluation.variant,
|
|
6174
|
+
flagEvaluation.payload
|
|
6175
|
+
);
|
|
6176
|
+
firstRunConsumedInProcess = true;
|
|
6177
|
+
markFirstRunConsumed(triggerFunction, flagEvaluation.variant);
|
|
6178
|
+
await emitNoticeDisplayed(instance, {
|
|
6179
|
+
notice_id: FIRST_RUN_NOTICE_ID,
|
|
6180
|
+
notice_type: LOG_LINE_NOTICE_TYPE,
|
|
6181
|
+
flag_key: NOTICE_FLAG_KEY,
|
|
6182
|
+
variant: flagEvaluation.variant,
|
|
6183
|
+
displayed: decision.displayed,
|
|
6184
|
+
payload: decision.copy,
|
|
6185
|
+
bypass_reason: decision.bypassReason,
|
|
6186
|
+
disabled_reason: decision.disabledReason,
|
|
6187
|
+
notice_config_found: decision.noticeConfigFound,
|
|
6188
|
+
sync_type: "async",
|
|
6189
|
+
trigger_function: triggerFunction
|
|
6190
|
+
});
|
|
6191
|
+
if (decision.displayed && decision.copy) {
|
|
6192
|
+
process.stderr.write(`${decision.copy}
|
|
6193
|
+
`);
|
|
6194
|
+
}
|
|
6195
|
+
} catch (e) {
|
|
6196
|
+
if (!firstRunConsumedInProcess) firstRunClaimInProgress = false;
|
|
6197
|
+
} finally {
|
|
6198
|
+
if (firstRunConsumedInProcess) firstRunClaimInProgress = false;
|
|
6199
|
+
}
|
|
6200
|
+
}
|
|
6201
|
+
async function emitNoticeDisplayed(instance, properties) {
|
|
6202
|
+
if (!isTelemetryEnabled()) return;
|
|
6203
|
+
try {
|
|
6204
|
+
await captureNoticeEvent(instance, properties);
|
|
6205
|
+
} catch (e) {
|
|
6206
|
+
}
|
|
6207
|
+
}
|
|
5166
6208
|
|
|
5167
6209
|
// src/oss/src/utils/lemmatization.ts
|
|
5168
6210
|
var STOP_WORDS = /* @__PURE__ */ new Set([
|
|
@@ -5860,7 +6902,7 @@ function extractCompoundsRegex(text) {
|
|
|
5860
6902
|
return entities;
|
|
5861
6903
|
}
|
|
5862
6904
|
function extractEntities(text) {
|
|
5863
|
-
var _a2,
|
|
6905
|
+
var _a2, _b2;
|
|
5864
6906
|
const raw = [];
|
|
5865
6907
|
raw.push(...extractQuoted(text));
|
|
5866
6908
|
raw.push(...extractProper(text));
|
|
@@ -5903,7 +6945,7 @@ function extractEntities(text) {
|
|
|
5903
6945
|
for (const entity of cleaned) {
|
|
5904
6946
|
const key = entity.text.toLowerCase();
|
|
5905
6947
|
const existing = best.get(key);
|
|
5906
|
-
if (!existing || ((_a2 = typePriority[entity.type]) != null ? _a2 : 99) < ((
|
|
6948
|
+
if (!existing || ((_a2 = typePriority[entity.type]) != null ? _a2 : 99) < ((_b2 = typePriority[existing.type]) != null ? _b2 : 99)) {
|
|
5907
6949
|
best.set(key, entity);
|
|
5908
6950
|
}
|
|
5909
6951
|
}
|
|
@@ -5939,8 +6981,8 @@ function getBm25Params(query, lemmatized) {
|
|
|
5939
6981
|
function normalizeBm25(rawScore, midpoint, steepness) {
|
|
5940
6982
|
return 1 / (1 + Math.exp(-steepness * (rawScore - midpoint)));
|
|
5941
6983
|
}
|
|
5942
|
-
function scoreAndRank(semanticResults, bm25Scores, entityBoosts, threshold, topK) {
|
|
5943
|
-
var _a2,
|
|
6984
|
+
function scoreAndRank(semanticResults, bm25Scores, entityBoosts, threshold, topK, explain = false) {
|
|
6985
|
+
var _a2, _b2, _c;
|
|
5944
6986
|
const hasBm25 = Object.keys(bm25Scores).length > 0;
|
|
5945
6987
|
const hasEntity = Object.keys(entityBoosts).length > 0;
|
|
5946
6988
|
let maxPossible = 1;
|
|
@@ -5961,15 +7003,27 @@ function scoreAndRank(semanticResults, bm25Scores, entityBoosts, threshold, topK
|
|
|
5961
7003
|
continue;
|
|
5962
7004
|
}
|
|
5963
7005
|
const memIdStr = String(memId);
|
|
5964
|
-
const bm25Score = (
|
|
7006
|
+
const bm25Score = (_b2 = bm25Scores[memIdStr]) != null ? _b2 : 0;
|
|
5965
7007
|
const entityBoost = (_c = entityBoosts[memIdStr]) != null ? _c : 0;
|
|
5966
7008
|
const rawCombined = semanticScore + bm25Score + entityBoost;
|
|
5967
7009
|
const combined = Math.min(rawCombined / maxPossible, 1);
|
|
5968
|
-
|
|
7010
|
+
const entry = {
|
|
5969
7011
|
id: memIdStr,
|
|
5970
7012
|
score: combined,
|
|
5971
7013
|
payload: result.payload
|
|
5972
|
-
}
|
|
7014
|
+
};
|
|
7015
|
+
if (explain) {
|
|
7016
|
+
entry.scoreDetails = {
|
|
7017
|
+
semanticScore,
|
|
7018
|
+
bm25Score,
|
|
7019
|
+
entityBoost,
|
|
7020
|
+
rawScore: rawCombined,
|
|
7021
|
+
maxPossibleScore: maxPossible,
|
|
7022
|
+
finalScore: combined,
|
|
7023
|
+
threshold
|
|
7024
|
+
};
|
|
7025
|
+
}
|
|
7026
|
+
scored.push(entry);
|
|
5973
7027
|
}
|
|
5974
7028
|
scored.sort((a, b) => b.score - a.score);
|
|
5975
7029
|
return scored.slice(0, topK);
|
|
@@ -5977,18 +7031,18 @@ function scoreAndRank(semanticResults, bm25Scores, entityBoosts, threshold, topK
|
|
|
5977
7031
|
|
|
5978
7032
|
// src/client/config.ts
|
|
5979
7033
|
async function getNodeFs() {
|
|
5980
|
-
var _a2,
|
|
7034
|
+
var _a2, _b2, _c, _d, _e;
|
|
5981
7035
|
if (typeof process === "undefined" || !((_a2 = process.versions) == null ? void 0 : _a2.node)) return null;
|
|
5982
7036
|
try {
|
|
5983
|
-
const [
|
|
7037
|
+
const [fs5, path4, os3, crypto] = await Promise.all([
|
|
5984
7038
|
import("fs"),
|
|
5985
7039
|
import("path"),
|
|
5986
7040
|
import("os"),
|
|
5987
7041
|
import("crypto")
|
|
5988
7042
|
]);
|
|
5989
|
-
const fsMod = (
|
|
5990
|
-
const pathMod = (_c =
|
|
5991
|
-
const osMod = (_d =
|
|
7043
|
+
const fsMod = (_b2 = fs5.default) != null ? _b2 : fs5;
|
|
7044
|
+
const pathMod = (_c = path4.default) != null ? _c : path4;
|
|
7045
|
+
const osMod = (_d = os3.default) != null ? _d : os3;
|
|
5992
7046
|
const cryptoMod = (_e = crypto.default) != null ? _e : crypto;
|
|
5993
7047
|
const dir = process.env.MEM0_DIR || pathMod.join(osMod.homedir(), ".mem0");
|
|
5994
7048
|
return {
|
|
@@ -6368,6 +7422,52 @@ var Memory = class _Memory {
|
|
|
6368
7422
|
console.error(`Failed to capture ${methodName} event:`, error);
|
|
6369
7423
|
}
|
|
6370
7424
|
}
|
|
7425
|
+
async _displayFirstRunNotice(triggerFunction) {
|
|
7426
|
+
try {
|
|
7427
|
+
await this._getTelemetryId();
|
|
7428
|
+
await displayFirstRunNotice(this, triggerFunction);
|
|
7429
|
+
} catch (e) {
|
|
7430
|
+
}
|
|
7431
|
+
}
|
|
7432
|
+
async _displayDecayUsageNotice(trigger) {
|
|
7433
|
+
try {
|
|
7434
|
+
await this._getTelemetryId();
|
|
7435
|
+
await displayDecayUsageNotice(this, trigger);
|
|
7436
|
+
} catch (e) {
|
|
7437
|
+
}
|
|
7438
|
+
}
|
|
7439
|
+
async _displayTemporalUsageNotice(trigger) {
|
|
7440
|
+
try {
|
|
7441
|
+
await this._getTelemetryId();
|
|
7442
|
+
await displayTemporalUsageNotice(this, trigger);
|
|
7443
|
+
} catch (e) {
|
|
7444
|
+
}
|
|
7445
|
+
}
|
|
7446
|
+
async _displayScaleThresholdNotice(trigger) {
|
|
7447
|
+
try {
|
|
7448
|
+
await this._getTelemetryId();
|
|
7449
|
+
await displayScaleThresholdNotice(this, trigger);
|
|
7450
|
+
} catch (e) {
|
|
7451
|
+
}
|
|
7452
|
+
}
|
|
7453
|
+
async _displayPerformanceSlowQueryNotice(trigger) {
|
|
7454
|
+
try {
|
|
7455
|
+
await this._getTelemetryId();
|
|
7456
|
+
await displayPerformanceSlowQueryNotice(this, trigger);
|
|
7457
|
+
} catch (e) {
|
|
7458
|
+
}
|
|
7459
|
+
}
|
|
7460
|
+
async _getNoticeTelemetryId() {
|
|
7461
|
+
try {
|
|
7462
|
+
if (!this.telemetryId || this.telemetryId === "anonymous" || this.telemetryId === "anonymous-supabase") {
|
|
7463
|
+
this.telemetryId = await getOrCreateMem0UserId() || "anonymous";
|
|
7464
|
+
}
|
|
7465
|
+
return this.telemetryId;
|
|
7466
|
+
} catch (e) {
|
|
7467
|
+
this.telemetryId = "anonymous";
|
|
7468
|
+
return this.telemetryId;
|
|
7469
|
+
}
|
|
7470
|
+
}
|
|
6371
7471
|
static fromConfig(configDict) {
|
|
6372
7472
|
try {
|
|
6373
7473
|
const config = MemoryConfigSchema.parse(configDict);
|
|
@@ -6377,12 +7477,31 @@ var Memory = class _Memory {
|
|
|
6377
7477
|
throw e;
|
|
6378
7478
|
}
|
|
6379
7479
|
}
|
|
7480
|
+
async updateProject(options = {}) {
|
|
7481
|
+
if ((options == null ? void 0 : options.decay) === true) {
|
|
7482
|
+
await this._getNoticeTelemetryId();
|
|
7483
|
+
throw new Error(await getDecayFeatureErrorMessage(this));
|
|
7484
|
+
}
|
|
7485
|
+
throw new Error("Project updates are not supported by the OSS Memory SDK.");
|
|
7486
|
+
}
|
|
6380
7487
|
async add(messages, config) {
|
|
7488
|
+
if ((config == null ? void 0 : config.timestamp) !== void 0) {
|
|
7489
|
+
await this._getNoticeTelemetryId();
|
|
7490
|
+
throw new Error(
|
|
7491
|
+
await getTemporalFeatureErrorMessage(this, {
|
|
7492
|
+
triggerFunction: "add",
|
|
7493
|
+
triggerParameter: "timestamp"
|
|
7494
|
+
})
|
|
7495
|
+
);
|
|
7496
|
+
}
|
|
6381
7497
|
if (messages === void 0 || messages === null) {
|
|
6382
7498
|
throw new Error(
|
|
6383
7499
|
"messages is required and cannot be undefined or null. Provide a string or array of messages."
|
|
6384
7500
|
);
|
|
6385
7501
|
}
|
|
7502
|
+
const temporalUsageNotice = detectTemporalUsageFromMetadata(
|
|
7503
|
+
config == null ? void 0 : config.metadata
|
|
7504
|
+
);
|
|
6386
7505
|
await this._ensureInitialized();
|
|
6387
7506
|
await this._captureEvent("add", {
|
|
6388
7507
|
message_count: Array.isArray(messages) ? messages.length : 1,
|
|
@@ -6410,12 +7529,32 @@ var Memory = class _Memory {
|
|
|
6410
7529
|
filters,
|
|
6411
7530
|
infer
|
|
6412
7531
|
);
|
|
7532
|
+
if (temporalUsageNotice) {
|
|
7533
|
+
await this._displayTemporalUsageNotice({
|
|
7534
|
+
triggerFunction: "add",
|
|
7535
|
+
triggerSource: temporalUsageNotice.triggerSource,
|
|
7536
|
+
triggerReason: temporalUsageNotice.triggerReason
|
|
7537
|
+
});
|
|
7538
|
+
} else {
|
|
7539
|
+
const scaleThresholdNotice = await detectScaleThresholdFromAddResult(
|
|
7540
|
+
this,
|
|
7541
|
+
vectorStoreResult
|
|
7542
|
+
);
|
|
7543
|
+
if (scaleThresholdNotice) {
|
|
7544
|
+
await this._displayScaleThresholdNotice({
|
|
7545
|
+
triggerFunction: "add",
|
|
7546
|
+
...scaleThresholdNotice
|
|
7547
|
+
});
|
|
7548
|
+
} else {
|
|
7549
|
+
await this._displayFirstRunNotice("add");
|
|
7550
|
+
}
|
|
7551
|
+
}
|
|
6413
7552
|
return {
|
|
6414
7553
|
results: vectorStoreResult
|
|
6415
7554
|
};
|
|
6416
7555
|
}
|
|
6417
7556
|
async addToVectorStore(messages, metadata, filters, infer) {
|
|
6418
|
-
var _a2,
|
|
7557
|
+
var _a2, _b2, _c, _d, _e, _f, _g;
|
|
6419
7558
|
if (!infer) {
|
|
6420
7559
|
const returnedMemories = [];
|
|
6421
7560
|
for (const message of messages) {
|
|
@@ -6457,7 +7596,7 @@ var Memory = class _Memory {
|
|
|
6457
7596
|
uuidMapping[String(idx)] = mem.id;
|
|
6458
7597
|
existingMemories.push({
|
|
6459
7598
|
id: String(idx),
|
|
6460
|
-
text: (
|
|
7599
|
+
text: (_b2 = (_a2 = mem.payload) == null ? void 0 : _a2.data) != null ? _b2 : ""
|
|
6461
7600
|
});
|
|
6462
7601
|
}
|
|
6463
7602
|
const isAgentScoped = !!filters.agent_id && !filters.user_id;
|
|
@@ -6769,7 +7908,10 @@ var Memory = class _Memory {
|
|
|
6769
7908
|
async get(memoryId) {
|
|
6770
7909
|
await this._ensureInitialized();
|
|
6771
7910
|
const memory = await this.vectorStore.get(memoryId);
|
|
6772
|
-
if (!memory)
|
|
7911
|
+
if (!memory) {
|
|
7912
|
+
await this._displayFirstRunNotice("get");
|
|
7913
|
+
return null;
|
|
7914
|
+
}
|
|
6773
7915
|
const filters = {
|
|
6774
7916
|
...memory.payload.user_id && { user_id: memory.payload.user_id },
|
|
6775
7917
|
...memory.payload.agent_id && { agent_id: memory.payload.agent_id },
|
|
@@ -6799,10 +7941,25 @@ var Memory = class _Memory {
|
|
|
6799
7941
|
memoryItem.metadata[key] = value;
|
|
6800
7942
|
}
|
|
6801
7943
|
}
|
|
6802
|
-
|
|
7944
|
+
const result = { ...memoryItem, ...filters };
|
|
7945
|
+
await this._displayFirstRunNotice("get");
|
|
7946
|
+
return result;
|
|
6803
7947
|
}
|
|
6804
7948
|
async search(query, config) {
|
|
6805
|
-
var _a2,
|
|
7949
|
+
var _a2, _b2, _c, _d, _e;
|
|
7950
|
+
if ((config == null ? void 0 : config.referenceDate) !== void 0) {
|
|
7951
|
+
await this._getNoticeTelemetryId();
|
|
7952
|
+
throw new Error(
|
|
7953
|
+
await getTemporalFeatureErrorMessage(this, {
|
|
7954
|
+
triggerFunction: "search",
|
|
7955
|
+
triggerParameter: "referenceDate"
|
|
7956
|
+
})
|
|
7957
|
+
);
|
|
7958
|
+
}
|
|
7959
|
+
const temporalUsageNotice = detectTemporalUsageFromSearch(
|
|
7960
|
+
query,
|
|
7961
|
+
config == null ? void 0 : config.filters
|
|
7962
|
+
);
|
|
6806
7963
|
rejectTopLevelEntityParams(config, "search");
|
|
6807
7964
|
validateSearchParams(config.threshold, config.topK);
|
|
6808
7965
|
const normalizedFilters = config.filters ? Object.fromEntries(
|
|
@@ -6817,7 +7974,7 @@ var Memory = class _Memory {
|
|
|
6817
7974
|
}).filter(([, v]) => v !== void 0)
|
|
6818
7975
|
) : {};
|
|
6819
7976
|
await this._ensureInitialized();
|
|
6820
|
-
const { topK = 20, threshold = 0.1 } = config;
|
|
7977
|
+
const { topK = 20, threshold = 0.1, explain = false } = config;
|
|
6821
7978
|
await this._captureEvent("search", {
|
|
6822
7979
|
query_length: query.length,
|
|
6823
7980
|
topK,
|
|
@@ -6841,6 +7998,7 @@ var Memory = class _Memory {
|
|
|
6841
7998
|
"filters must contain at least one of: user_id, agent_id, run_id. Example: filters: { user_id: 'u1' }"
|
|
6842
7999
|
);
|
|
6843
8000
|
}
|
|
8001
|
+
const searchStartMs = Date.now();
|
|
6844
8002
|
const queryLemmatized = lemmatizeForBm25(query);
|
|
6845
8003
|
const queryEntities = extractEntities(query);
|
|
6846
8004
|
const queryEmbedding = await this.embedder.embed(query);
|
|
@@ -6867,7 +8025,7 @@ var Memory = class _Memory {
|
|
|
6867
8025
|
const [midpoint, steepness] = getBm25Params(query, queryLemmatized);
|
|
6868
8026
|
for (const mem of keywordResults) {
|
|
6869
8027
|
const memId = String(mem.id);
|
|
6870
|
-
const rawScore = (
|
|
8028
|
+
const rawScore = (_b2 = mem.score) != null ? _b2 : 0;
|
|
6871
8029
|
if (rawScore > 0) {
|
|
6872
8030
|
bm25Scores[memId] = normalizeBm25(rawScore, midpoint, steepness);
|
|
6873
8031
|
}
|
|
@@ -6887,15 +8045,32 @@ var Memory = class _Memory {
|
|
|
6887
8045
|
}
|
|
6888
8046
|
if (deduped.length > 0) {
|
|
6889
8047
|
const entityStore = await this.getEntityStore();
|
|
6890
|
-
|
|
6891
|
-
|
|
6892
|
-
|
|
6893
|
-
|
|
6894
|
-
|
|
6895
|
-
|
|
6896
|
-
|
|
6897
|
-
|
|
6898
|
-
|
|
8048
|
+
const entitySearchFilters = {};
|
|
8049
|
+
for (const k of ["user_id", "agent_id", "run_id"]) {
|
|
8050
|
+
if (effectiveFilters[k])
|
|
8051
|
+
entitySearchFilters[k] = effectiveFilters[k];
|
|
8052
|
+
}
|
|
8053
|
+
const entityTexts = deduped.map((e) => e.text);
|
|
8054
|
+
const embeddings = await this.embedder.embedBatch(entityTexts);
|
|
8055
|
+
if (embeddings.length !== entityTexts.length) {
|
|
8056
|
+
console.warn(
|
|
8057
|
+
`embedBatch returned ${embeddings.length} vectors for ${entityTexts.length} texts \u2014 skipping entity boost`
|
|
8058
|
+
);
|
|
8059
|
+
} else {
|
|
8060
|
+
const searchResults = await Promise.allSettled(
|
|
8061
|
+
deduped.map(
|
|
8062
|
+
(_, i) => entityStore.search(embeddings[i], 500, entitySearchFilters)
|
|
8063
|
+
)
|
|
8064
|
+
);
|
|
8065
|
+
for (const result2 of searchResults) {
|
|
8066
|
+
if (result2.status === "rejected") {
|
|
8067
|
+
console.warn(
|
|
8068
|
+
"Entity boost search failed for one entity:",
|
|
8069
|
+
result2.reason
|
|
8070
|
+
);
|
|
8071
|
+
continue;
|
|
8072
|
+
}
|
|
8073
|
+
for (const match of result2.value) {
|
|
6899
8074
|
const similarity = (_c = match.score) != null ? _c : 0;
|
|
6900
8075
|
if (similarity < 0.5) continue;
|
|
6901
8076
|
const payload = match.payload || {};
|
|
@@ -6914,7 +8089,6 @@ var Memory = class _Memory {
|
|
|
6914
8089
|
}
|
|
6915
8090
|
}
|
|
6916
8091
|
}
|
|
6917
|
-
} catch (e) {
|
|
6918
8092
|
}
|
|
6919
8093
|
}
|
|
6920
8094
|
}
|
|
@@ -6935,7 +8109,8 @@ var Memory = class _Memory {
|
|
|
6935
8109
|
bm25Scores,
|
|
6936
8110
|
entityBoosts,
|
|
6937
8111
|
threshold != null ? threshold : 0.1,
|
|
6938
|
-
topK
|
|
8112
|
+
topK,
|
|
8113
|
+
explain
|
|
6939
8114
|
);
|
|
6940
8115
|
const excludedKeys = /* @__PURE__ */ new Set([
|
|
6941
8116
|
"user_id",
|
|
@@ -6963,25 +8138,72 @@ var Memory = class _Memory {
|
|
|
6963
8138
|
metadata: Object.entries(payload).filter(([key]) => !excludedKeys.has(key)).reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {}),
|
|
6964
8139
|
...payload.user_id && { user_id: payload.user_id },
|
|
6965
8140
|
...payload.agent_id && { agent_id: payload.agent_id },
|
|
6966
|
-
...payload.run_id && { run_id: payload.run_id }
|
|
8141
|
+
...payload.run_id && { run_id: payload.run_id },
|
|
8142
|
+
...scored.scoreDetails && { score_details: scored.scoreDetails }
|
|
6967
8143
|
};
|
|
6968
8144
|
});
|
|
6969
|
-
|
|
8145
|
+
const result = {
|
|
6970
8146
|
results
|
|
6971
8147
|
};
|
|
8148
|
+
const searchElapsedMs = Date.now() - searchStartMs;
|
|
8149
|
+
if (temporalUsageNotice) {
|
|
8150
|
+
await this._displayTemporalUsageNotice({
|
|
8151
|
+
triggerFunction: "search",
|
|
8152
|
+
triggerSource: temporalUsageNotice.triggerSource,
|
|
8153
|
+
triggerReason: temporalUsageNotice.triggerReason
|
|
8154
|
+
});
|
|
8155
|
+
} else {
|
|
8156
|
+
const scaleThresholdNotice = detectScaleThresholdFromTopK(topK);
|
|
8157
|
+
if (scaleThresholdNotice) {
|
|
8158
|
+
await this._displayScaleThresholdNotice({
|
|
8159
|
+
triggerFunction: "search",
|
|
8160
|
+
...scaleThresholdNotice
|
|
8161
|
+
});
|
|
8162
|
+
} else {
|
|
8163
|
+
const performanceSlowQueryNotice = detectPerformanceSlowQuery(
|
|
8164
|
+
searchElapsedMs,
|
|
8165
|
+
topK,
|
|
8166
|
+
results.length
|
|
8167
|
+
);
|
|
8168
|
+
if (performanceSlowQueryNotice) {
|
|
8169
|
+
await this._displayPerformanceSlowQueryNotice({
|
|
8170
|
+
triggerFunction: "search",
|
|
8171
|
+
triggerReason: "slow_query",
|
|
8172
|
+
...performanceSlowQueryNotice
|
|
8173
|
+
});
|
|
8174
|
+
} else {
|
|
8175
|
+
await this._displayFirstRunNotice("search");
|
|
8176
|
+
}
|
|
8177
|
+
}
|
|
8178
|
+
}
|
|
8179
|
+
return result;
|
|
6972
8180
|
}
|
|
6973
8181
|
async update(memoryId, data) {
|
|
6974
8182
|
await this._ensureInitialized();
|
|
6975
8183
|
await this._captureEvent("update", { memory_id: memoryId });
|
|
6976
8184
|
const embedding = await this.embedder.embed(data);
|
|
6977
8185
|
await this.updateMemory(memoryId, data, { [data]: embedding });
|
|
6978
|
-
|
|
8186
|
+
const result = { message: "Memory updated successfully!" };
|
|
8187
|
+
await this._displayFirstRunNotice("update");
|
|
8188
|
+
return result;
|
|
6979
8189
|
}
|
|
6980
8190
|
async delete(memoryId) {
|
|
6981
8191
|
await this._ensureInitialized();
|
|
6982
8192
|
await this._captureEvent("delete", { memory_id: memoryId });
|
|
6983
8193
|
await this.deleteMemory(memoryId);
|
|
6984
|
-
|
|
8194
|
+
const result = { message: "Memory deleted successfully!" };
|
|
8195
|
+
const deleteCount = getDecayUsageDeleteCountAfterSuccess();
|
|
8196
|
+
if (isDecayUsageDeleteEligible(deleteCount)) {
|
|
8197
|
+
await this._displayDecayUsageNotice({
|
|
8198
|
+
triggerFunction: "delete",
|
|
8199
|
+
triggerSource: "delete_count",
|
|
8200
|
+
triggerReason: "repeated_deletes",
|
|
8201
|
+
deleteCount
|
|
8202
|
+
});
|
|
8203
|
+
} else {
|
|
8204
|
+
await this._displayFirstRunNotice("delete");
|
|
8205
|
+
}
|
|
8206
|
+
return result;
|
|
6985
8207
|
}
|
|
6986
8208
|
async deleteAll(config) {
|
|
6987
8209
|
await this._ensureInitialized();
|
|
@@ -7004,11 +8226,24 @@ var Memory = class _Memory {
|
|
|
7004
8226
|
for (const memory of memories) {
|
|
7005
8227
|
await this.deleteMemory(memory.id);
|
|
7006
8228
|
}
|
|
7007
|
-
|
|
8229
|
+
const result = { message: "Memories deleted successfully!" };
|
|
8230
|
+
if (memories.length > 0) {
|
|
8231
|
+
await this._displayDecayUsageNotice({
|
|
8232
|
+
triggerFunction: "delete_all",
|
|
8233
|
+
triggerSource: "delete_all",
|
|
8234
|
+
triggerReason: "bulk_delete",
|
|
8235
|
+
deletedCount: memories.length
|
|
8236
|
+
});
|
|
8237
|
+
} else {
|
|
8238
|
+
await this._displayFirstRunNotice("delete_all");
|
|
8239
|
+
}
|
|
8240
|
+
return result;
|
|
7008
8241
|
}
|
|
7009
8242
|
async history(memoryId) {
|
|
7010
8243
|
await this._ensureInitialized();
|
|
7011
|
-
|
|
8244
|
+
const result = await this.db.getHistory(memoryId);
|
|
8245
|
+
await this._displayFirstRunNotice("history");
|
|
8246
|
+
return result;
|
|
7012
8247
|
}
|
|
7013
8248
|
async reset() {
|
|
7014
8249
|
await this._ensureInitialized();
|
|
@@ -7049,9 +8284,10 @@ var Memory = class _Memory {
|
|
|
7049
8284
|
console.error(this._initError);
|
|
7050
8285
|
});
|
|
7051
8286
|
await this._initPromise;
|
|
8287
|
+
await this._displayFirstRunNotice("reset");
|
|
7052
8288
|
}
|
|
7053
8289
|
async getAll(config) {
|
|
7054
|
-
var _a2,
|
|
8290
|
+
var _a2, _b2, _c;
|
|
7055
8291
|
rejectTopLevelEntityParams(config, "getAll");
|
|
7056
8292
|
validateSearchParams(void 0, config.topK);
|
|
7057
8293
|
await this._ensureInitialized();
|
|
@@ -7060,7 +8296,7 @@ var Memory = class _Memory {
|
|
|
7060
8296
|
Object.entries({
|
|
7061
8297
|
...config.filters || {},
|
|
7062
8298
|
user_id: validateAndTrimEntityId((_a2 = config.filters) == null ? void 0 : _a2.user_id, "user_id"),
|
|
7063
|
-
agent_id: validateAndTrimEntityId((
|
|
8299
|
+
agent_id: validateAndTrimEntityId((_b2 = config.filters) == null ? void 0 : _b2.agent_id, "agent_id"),
|
|
7064
8300
|
run_id: validateAndTrimEntityId((_c = config.filters) == null ? void 0 : _c.run_id, "run_id")
|
|
7065
8301
|
}).filter(([, v]) => v !== void 0)
|
|
7066
8302
|
);
|
|
@@ -7098,7 +8334,17 @@ var Memory = class _Memory {
|
|
|
7098
8334
|
...mem.payload.agent_id && { agent_id: mem.payload.agent_id },
|
|
7099
8335
|
...mem.payload.run_id && { run_id: mem.payload.run_id }
|
|
7100
8336
|
}));
|
|
7101
|
-
|
|
8337
|
+
const result = { results };
|
|
8338
|
+
const scaleThresholdNotice = detectScaleThresholdFromTopK(topK);
|
|
8339
|
+
if (scaleThresholdNotice) {
|
|
8340
|
+
await this._displayScaleThresholdNotice({
|
|
8341
|
+
triggerFunction: "get_all",
|
|
8342
|
+
...scaleThresholdNotice
|
|
8343
|
+
});
|
|
8344
|
+
} else {
|
|
8345
|
+
await this._displayFirstRunNotice("get_all");
|
|
8346
|
+
}
|
|
8347
|
+
return result;
|
|
7102
8348
|
}
|
|
7103
8349
|
async createMemory(data, existingEmbeddings, metadata) {
|
|
7104
8350
|
const memoryId = uuidv43();
|