mem0ai 3.0.1 → 3.0.3

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.
@@ -40,7 +40,8 @@ var MemoryConfigSchema = z.object({
40
40
  model: z.union([z.string(), z.any()]).optional(),
41
41
  modelProperties: z.record(z.string(), z.any()).optional(),
42
42
  baseURL: z.string().optional(),
43
- url: z.string().optional()
43
+ url: z.string().optional(),
44
+ timeout: z.number().optional()
44
45
  })
45
46
  }),
46
47
  historyDbPath: z.string().optional(),
@@ -211,7 +212,8 @@ var OpenAILLM = class {
211
212
  constructor(config) {
212
213
  this.openai = new OpenAI3({
213
214
  apiKey: config.apiKey,
214
- baseURL: config.baseURL
215
+ baseURL: config.baseURL,
216
+ ...config.timeout != null && { timeout: config.timeout }
215
217
  });
216
218
  this.model = config.model || "gpt-5-mini";
217
219
  }
@@ -264,7 +266,11 @@ var OpenAILLM = class {
264
266
  import OpenAI4 from "openai";
265
267
  var OpenAIStructuredLLM = class {
266
268
  constructor(config) {
267
- this.openai = new OpenAI4({ apiKey: config.apiKey });
269
+ this.openai = new OpenAI4({
270
+ apiKey: config.apiKey,
271
+ baseURL: config.baseURL,
272
+ ...config.timeout != null && { timeout: config.timeout }
273
+ });
268
274
  this.model = config.model || "gpt-5-mini";
269
275
  }
270
276
  async generateResponse(messages, responseFormat, tools) {
@@ -830,9 +836,9 @@ var _MemoryVectorStore = class _MemoryVectorStore {
830
836
  if (row) {
831
837
  return row.user_id;
832
838
  }
833
- const randomUserId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
834
- this.db.prepare(`INSERT INTO memory_migrations (user_id) VALUES (?)`).run(randomUserId);
835
- return randomUserId;
839
+ const randomUserId2 = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
840
+ this.db.prepare(`INSERT INTO memory_migrations (user_id) VALUES (?)`).run(randomUserId2);
841
+ return randomUserId2;
836
842
  }
837
843
  async setUserId(userId) {
838
844
  this.db.prepare(`DELETE FROM memory_migrations`).run();
@@ -1119,17 +1125,17 @@ var Qdrant = class {
1119
1125
  if (result.points.length > 0) {
1120
1126
  return (_a2 = result.points[0].payload) == null ? void 0 : _a2.user_id;
1121
1127
  }
1122
- const randomUserId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
1128
+ const randomUserId2 = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
1123
1129
  await this.client.upsert("memory_migrations", {
1124
1130
  points: [
1125
1131
  {
1126
1132
  id: this.generateUUID(),
1127
1133
  vector: [0],
1128
- payload: { user_id: randomUserId }
1134
+ payload: { user_id: randomUserId2 }
1129
1135
  }
1130
1136
  ]
1131
1137
  });
1132
- return randomUserId;
1138
+ return randomUserId2;
1133
1139
  } catch (error) {
1134
1140
  console.error("Error getting user ID:", error);
1135
1141
  throw error;
@@ -1433,11 +1439,11 @@ var VectorizeDB = class {
1433
1439
  if (result.matches.length > 0) {
1434
1440
  return result.matches[0].metadata.userId;
1435
1441
  }
1436
- const randomUserId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
1442
+ const randomUserId2 = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
1437
1443
  const data = {
1438
1444
  id: this.generateUUID(),
1439
1445
  values: [0],
1440
- metadata: { userId: randomUserId }
1446
+ metadata: { userId: randomUserId2 }
1441
1447
  };
1442
1448
  await fetch(
1443
1449
  `https://api.cloudflare.com/client/v4/accounts/${this.accountId}/vectorize/v2/indexes/memory_migrations/upsert`,
@@ -1451,7 +1457,7 @@ var VectorizeDB = class {
1451
1457
  // ndjson format
1452
1458
  }
1453
1459
  );
1454
- return randomUserId;
1460
+ return randomUserId2;
1455
1461
  } catch (error) {
1456
1462
  console.error("Error getting user ID:", error);
1457
1463
  throw new Error(
@@ -2066,9 +2072,9 @@ var RedisDB = class {
2066
2072
  if (userId) {
2067
2073
  return userId;
2068
2074
  }
2069
- const randomUserId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
2070
- await this.client.set("memory_migrations:1", randomUserId);
2071
- return randomUserId;
2075
+ const randomUserId2 = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
2076
+ await this.client.set("memory_migrations:1", randomUserId2);
2077
+ return randomUserId2;
2072
2078
  } catch (error) {
2073
2079
  console.error("Error getting user ID:", error);
2074
2080
  throw error;
@@ -2444,18 +2450,18 @@ See the SQL migration instructions in the code comments.`
2444
2450
  try {
2445
2451
  const { data: tableExists } = await this.client.from("memory_migrations").select("user_id").limit(1);
2446
2452
  if (!tableExists || tableExists.length === 0) {
2447
- const randomUserId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
2448
- const { error: insertError } = await this.client.from("memory_migrations").insert({ user_id: randomUserId });
2453
+ const randomUserId2 = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
2454
+ const { error: insertError } = await this.client.from("memory_migrations").insert({ user_id: randomUserId2 });
2449
2455
  if (insertError) throw insertError;
2450
- return randomUserId;
2456
+ return randomUserId2;
2451
2457
  }
2452
2458
  const { data, error } = await this.client.from("memory_migrations").select("user_id").limit(1);
2453
2459
  if (error) throw error;
2454
2460
  if (!data || data.length === 0) {
2455
- const randomUserId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
2456
- const { error: insertError } = await this.client.from("memory_migrations").insert({ user_id: randomUserId });
2461
+ const randomUserId2 = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
2462
+ const { error: insertError } = await this.client.from("memory_migrations").insert({ user_id: randomUserId2 });
2457
2463
  if (insertError) throw insertError;
2458
- return randomUserId;
2464
+ return randomUserId2;
2459
2465
  }
2460
2466
  return data[0].user_id;
2461
2467
  } catch (error) {
@@ -3489,17 +3495,105 @@ function removeCodeBlocks(text) {
3489
3495
  return stripped.replace(/<think>[\s\S]*?<\/think>/g, "").trim();
3490
3496
  }
3491
3497
  function extractJson(text) {
3492
- const cleaned = removeCodeBlocks(text);
3498
+ let cleaned = text.replace(/<\|end_of_text\|>/g, "").replace(/<\|eot_id\|>/g, "").replace(/<\|im_end\|>/g, "").replace(/<\|im_start\|>/g, "").replace(/<\|endoftext\|>/g, "");
3499
+ cleaned = removeCodeBlocks(cleaned);
3493
3500
  const trimmed = cleaned.trim();
3501
+ if (!trimmed) return "";
3502
+ const braceIndices = [];
3503
+ for (let i = 0; i < trimmed.length; i++) {
3504
+ if (trimmed[i] === "{") braceIndices.push(i);
3505
+ }
3506
+ for (const start of braceIndices) {
3507
+ let depth = 0;
3508
+ let inString = false;
3509
+ let escapeNext = false;
3510
+ for (let i = start; i < trimmed.length; i++) {
3511
+ const char = trimmed[i];
3512
+ if (escapeNext) {
3513
+ escapeNext = false;
3514
+ continue;
3515
+ }
3516
+ if (char === "\\") {
3517
+ escapeNext = true;
3518
+ continue;
3519
+ }
3520
+ if (char === '"' && !escapeNext) {
3521
+ inString = !inString;
3522
+ continue;
3523
+ }
3524
+ if (inString) continue;
3525
+ if (char === "{") depth++;
3526
+ else if (char === "}") {
3527
+ depth--;
3528
+ if (depth === 0) {
3529
+ const candidate = trimmed.substring(start, i + 1);
3530
+ try {
3531
+ JSON.parse(candidate);
3532
+ return candidate;
3533
+ } catch (e) {
3534
+ break;
3535
+ }
3536
+ }
3537
+ }
3538
+ }
3539
+ }
3494
3540
  const firstBrace = trimmed.indexOf("{");
3495
3541
  const lastBrace = trimmed.lastIndexOf("}");
3496
3542
  if (firstBrace !== -1 && lastBrace > firstBrace) {
3497
- return trimmed.substring(firstBrace, lastBrace + 1);
3543
+ const candidate = trimmed.substring(firstBrace, lastBrace + 1);
3544
+ try {
3545
+ JSON.parse(candidate);
3546
+ return candidate;
3547
+ } catch (e) {
3548
+ }
3549
+ }
3550
+ const bracketIndices = [];
3551
+ for (let i = 0; i < trimmed.length; i++) {
3552
+ if (trimmed[i] === "[") bracketIndices.push(i);
3553
+ }
3554
+ for (const start of bracketIndices) {
3555
+ let depth = 0;
3556
+ let inString = false;
3557
+ let escapeNext = false;
3558
+ for (let i = start; i < trimmed.length; i++) {
3559
+ const char = trimmed[i];
3560
+ if (escapeNext) {
3561
+ escapeNext = false;
3562
+ continue;
3563
+ }
3564
+ if (char === "\\") {
3565
+ escapeNext = true;
3566
+ continue;
3567
+ }
3568
+ if (char === '"' && !escapeNext) {
3569
+ inString = !inString;
3570
+ continue;
3571
+ }
3572
+ if (inString) continue;
3573
+ if (char === "[") depth++;
3574
+ else if (char === "]") {
3575
+ depth--;
3576
+ if (depth === 0) {
3577
+ const candidate = trimmed.substring(start, i + 1);
3578
+ try {
3579
+ JSON.parse(candidate);
3580
+ return candidate;
3581
+ } catch (e) {
3582
+ break;
3583
+ }
3584
+ }
3585
+ }
3586
+ }
3498
3587
  }
3499
3588
  const firstBracket = trimmed.indexOf("[");
3500
3589
  const lastBracket = trimmed.lastIndexOf("]");
3501
3590
  if (firstBracket !== -1 && lastBracket > firstBracket) {
3502
- return trimmed.substring(firstBracket, lastBracket + 1);
3591
+ const candidate = trimmed.substring(firstBracket, lastBracket + 1);
3592
+ try {
3593
+ JSON.parse(candidate);
3594
+ return candidate;
3595
+ } catch (e) {
3596
+ }
3503
3597
  }
3504
3598
  return trimmed;
3505
3599
  }
@@ -4247,14 +4341,14 @@ var AzureAISearch = class {
4247
4341
  return userId;
4248
4342
  }
4249
4343
  }
4250
- const randomUserId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
4344
+ const randomUserId2 = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
4251
4345
  await this.searchClient.uploadDocuments([
4252
4346
  {
4253
4347
  id: this.generateUUID(),
4254
- user_id: randomUserId
4348
+ user_id: randomUserId2
4255
4349
  }
4256
4350
  ]);
4257
- return randomUserId;
4351
+ return randomUserId2;
4258
4352
  } catch (error) {
4259
4353
  console.error("Error getting user ID:", error);
4260
4354
  throw error;
@@ -4302,13 +4396,33 @@ var AzureAISearch = class {
4302
4396
 
4303
4397
  // src/oss/src/vector_stores/pgvector.ts
4304
4398
  import pkg from "pg";
4305
- var { Client } = pkg;
4399
+ var { Client, escapeIdentifier } = pkg;
4400
+ var SAFE_IDENTIFIER_RE = /^[a-zA-Z_][a-zA-Z0-9_]{0,127}$/;
4401
+ function validateIdentifier(name, label = "identifier") {
4402
+ if (!SAFE_IDENTIFIER_RE.test(name)) {
4403
+ throw new Error(
4404
+ `Invalid ${label} '${name}': only letters, digits, and underscores are allowed, must start with a letter or underscore, and be at most 128 characters.`
4405
+ );
4406
+ }
4407
+ return name;
4408
+ }
4409
+ function escapeFilterKey(key) {
4410
+ if (!SAFE_IDENTIFIER_RE.test(key)) {
4411
+ throw new Error(
4412
+ `Invalid filter key '${key}': only letters, digits, and underscores are allowed.`
4413
+ );
4414
+ }
4415
+ return key;
4416
+ }
4306
4417
  var PGVector = class {
4307
4418
  constructor(config) {
4308
- this.collectionName = config.collectionName || "memories";
4419
+ this.collectionName = validateIdentifier(
4420
+ config.collectionName || "memories",
4421
+ "collectionName"
4422
+ );
4309
4423
  this.useDiskann = config.diskann || false;
4310
4424
  this.useHnsw = config.hnsw || false;
4311
- this.dbName = config.dbname || "vector_store";
4425
+ this.dbName = validateIdentifier(config.dbname || "vector_store", "dbname");
4312
4426
  this.config = config;
4313
4427
  this.client = new Client({
4314
4428
  database: "postgres",
@@ -4320,6 +4434,9 @@ var PGVector = class {
4320
4434
  });
4321
4435
  this.initialize().catch(console.error);
4322
4436
  }
4437
+ col() {
4438
+ return escapeIdentifier(this.collectionName);
4439
+ }
4323
4440
  async initialize() {
4324
4441
  if (!this._initPromise) {
4325
4442
  this._initPromise = this._doInitialize();
@@ -4366,13 +4483,14 @@ var PGVector = class {
4366
4483
  return result.rows.length > 0;
4367
4484
  }
4368
4485
  async createDatabase(dbName) {
4369
- await this.client.query(`CREATE DATABASE ${dbName}`);
4486
+ await this.client.query(`CREATE DATABASE ${escapeIdentifier(dbName)}`);
4370
4487
  }
4371
4488
  async createCol(embeddingModelDims) {
4489
+ const dims = Math.floor(embeddingModelDims);
4372
4490
  await this.client.query(`
4373
- CREATE TABLE IF NOT EXISTS ${this.collectionName} (
4491
+ CREATE TABLE IF NOT EXISTS ${this.col()} (
4374
4492
  id UUID PRIMARY KEY,
4375
- vector vector(${embeddingModelDims}),
4493
+ vector vector(${dims}),
4376
4494
  payload JSONB
4377
4495
  );
4378
4496
  `);
@@ -4383,8 +4501,8 @@ var PGVector = class {
4383
4501
  );
4384
4502
  if (result.rows.length > 0) {
4385
4503
  await this.client.query(`
4386
- CREATE INDEX IF NOT EXISTS ${this.collectionName}_diskann_idx
4387
- ON ${this.collectionName}
4504
+ CREATE INDEX IF NOT EXISTS ${escapeIdentifier(this.collectionName + "_diskann_idx")}
4505
+ ON ${this.col()}
4388
4506
  USING diskann (vector);
4389
4507
  `);
4390
4508
  }
@@ -4394,8 +4512,8 @@ var PGVector = class {
4394
4512
  } else if (this.useHnsw) {
4395
4513
  try {
4396
4514
  await this.client.query(`
4397
- CREATE INDEX IF NOT EXISTS ${this.collectionName}_hnsw_idx
4398
- ON ${this.collectionName}
4515
+ CREATE INDEX IF NOT EXISTS ${escapeIdentifier(this.collectionName + "_hnsw_idx")}
4516
+ ON ${this.col()}
4399
4517
  USING hnsw (vector vector_cosine_ops);
4400
4518
  `);
4401
4519
  } catch (error) {
@@ -4407,11 +4525,10 @@ var PGVector = class {
4407
4525
  const values = vectors.map((vector, i) => ({
4408
4526
  id: ids[i],
4409
4527
  vector: `[${vector.join(",")}]`,
4410
- // Format vector as string with square brackets
4411
4528
  payload: payloads[i]
4412
4529
  }));
4413
4530
  const query = `
4414
- INSERT INTO ${this.collectionName} (id, vector, payload)
4531
+ INSERT INTO ${this.col()} (id, vector, payload)
4415
4532
  VALUES ($1, $2::vector, $3::jsonb)
4416
4533
  `;
4417
4534
  await Promise.all(
@@ -4427,7 +4544,8 @@ var PGVector = class {
4427
4544
  let filterIndex = 3;
4428
4545
  if (filters) {
4429
4546
  for (const [key, value] of Object.entries(filters)) {
4430
- filterConditions.push(`payload->>'${key}' = $${filterIndex}`);
4547
+ const safeKey = escapeFilterKey(key);
4548
+ filterConditions.push(`payload->>'${safeKey}' = $${filterIndex}`);
4431
4549
  filterValues.push(value);
4432
4550
  filterIndex++;
4433
4551
  }
@@ -4435,7 +4553,7 @@ var PGVector = class {
4435
4553
  const filterClause = filterConditions.length > 0 ? "AND " + filterConditions.join(" AND ") : "";
4436
4554
  const searchQuery = `
4437
4555
  SELECT id, ts_rank_cd(to_tsvector('simple', payload->>'textLemmatized'), plainto_tsquery('simple', $1)) AS score, payload
4438
- FROM ${this.collectionName}
4556
+ FROM ${this.col()}
4439
4557
  WHERE to_tsvector('simple', payload->>'textLemmatized') @@ plainto_tsquery('simple', $1)
4440
4558
  ${filterClause}
4441
4559
  ORDER BY score DESC
@@ -4459,7 +4577,8 @@ var PGVector = class {
4459
4577
  let filterIndex = 3;
4460
4578
  if (filters) {
4461
4579
  for (const [key, value] of Object.entries(filters)) {
4462
- filterConditions.push(`payload->>'${key}' = $${filterIndex}`);
4580
+ const safeKey = escapeFilterKey(key);
4581
+ filterConditions.push(`payload->>'${safeKey}' = $${filterIndex}`);
4463
4582
  filterValues.push(value);
4464
4583
  filterIndex++;
4465
4584
  }
@@ -4467,7 +4586,7 @@ var PGVector = class {
4467
4586
  const filterClause = filterConditions.length > 0 ? "WHERE " + filterConditions.join(" AND ") : "";
4468
4587
  const searchQuery = `
4469
4588
  SELECT id, vector <=> $1::vector AS distance, payload
4470
- FROM ${this.collectionName}
4589
+ FROM ${this.col()}
4471
4590
  ${filterClause}
4472
4591
  ORDER BY distance
4473
4592
  LIMIT $2
@@ -4476,12 +4595,12 @@ var PGVector = class {
4476
4595
  return result.rows.map((row) => ({
4477
4596
  id: row.id,
4478
4597
  payload: row.payload,
4479
- score: row.distance
4598
+ score: Math.max(0, Math.min(1, 1 - Number(row.distance)))
4480
4599
  }));
4481
4600
  }
4482
4601
  async get(vectorId) {
4483
4602
  const result = await this.client.query(
4484
- `SELECT id, payload FROM ${this.collectionName} WHERE id = $1`,
4603
+ `SELECT id, payload FROM ${this.col()} WHERE id = $1`,
4485
4604
  [vectorId]
4486
4605
  );
4487
4606
  if (result.rows.length === 0) return null;
@@ -4494,7 +4613,7 @@ var PGVector = class {
4494
4613
  const vectorStr = `[${vector.join(",")}]`;
4495
4614
  await this.client.query(
4496
4615
  `
4497
- UPDATE ${this.collectionName}
4616
+ UPDATE ${this.col()}
4498
4617
  SET vector = $1::vector, payload = $2::jsonb
4499
4618
  WHERE id = $3
4500
4619
  `,
@@ -4502,13 +4621,12 @@ var PGVector = class {
4502
4621
  );
4503
4622
  }
4504
4623
  async delete(vectorId) {
4505
- await this.client.query(
4506
- `DELETE FROM ${this.collectionName} WHERE id = $1`,
4507
- [vectorId]
4508
- );
4624
+ await this.client.query(`DELETE FROM ${this.col()} WHERE id = $1`, [
4625
+ vectorId
4626
+ ]);
4509
4627
  }
4510
4628
  async deleteCol() {
4511
- await this.client.query(`DROP TABLE IF EXISTS ${this.collectionName}`);
4629
+ await this.client.query(`DROP TABLE IF EXISTS ${this.col()}`);
4512
4630
  }
4513
4631
  async listCols() {
4514
4632
  const result = await this.client.query(`
@@ -4524,7 +4642,8 @@ var PGVector = class {
4524
4642
  let paramIndex = 1;
4525
4643
  if (filters) {
4526
4644
  for (const [key, value] of Object.entries(filters)) {
4527
- filterConditions.push(`payload->>'${key}' = $${paramIndex}`);
4645
+ const safeKey = escapeFilterKey(key);
4646
+ filterConditions.push(`payload->>'${safeKey}' = $${paramIndex}`);
4528
4647
  filterValues.push(value);
4529
4648
  paramIndex++;
4530
4649
  }
@@ -4532,13 +4651,13 @@ var PGVector = class {
4532
4651
  const filterClause = filterConditions.length > 0 ? "WHERE " + filterConditions.join(" AND ") : "";
4533
4652
  const listQuery = `
4534
4653
  SELECT id, payload
4535
- FROM ${this.collectionName}
4654
+ FROM ${this.col()}
4536
4655
  ${filterClause}
4537
4656
  LIMIT $${paramIndex}
4538
4657
  `;
4539
4658
  const countQuery = `
4540
4659
  SELECT COUNT(*)
4541
- FROM ${this.collectionName}
4660
+ FROM ${this.col()}
4542
4661
  ${filterClause}
4543
4662
  `;
4544
4663
  filterValues.push(topK);
@@ -4563,12 +4682,12 @@ var PGVector = class {
4563
4682
  if (result.rows.length > 0) {
4564
4683
  return result.rows[0].user_id;
4565
4684
  }
4566
- const randomUserId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
4685
+ const randomUserId2 = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
4567
4686
  await this.client.query(
4568
4687
  "INSERT INTO memory_migrations (user_id) VALUES ($1)",
4569
- [randomUserId]
4688
+ [randomUserId2]
4570
4689
  );
4571
- return randomUserId;
4690
+ return randomUserId2;
4572
4691
  }
4573
4692
  async setUserId(userId) {
4574
4693
  await this.client.query("DELETE FROM memory_migrations");
@@ -4869,7 +4988,7 @@ var parse_vision_messages = async (messages) => {
4869
4988
  };
4870
4989
 
4871
4990
  // src/oss/src/utils/telemetry.ts
4872
- var version = "3.0.1";
4991
+ var version = true ? "3.0.3" : "dev";
4873
4992
  var MEM0_TELEMETRY = true;
4874
4993
  var _a;
4875
4994
  try {
@@ -5771,6 +5890,69 @@ function scoreAndRank(semanticResults, bm25Scores, entityBoosts, threshold, topK
5771
5890
  return scored.slice(0, topK);
5772
5891
  }
5773
5892
 
5893
+ // src/client/config.ts
5894
+ async function getNodeFs() {
5895
+ var _a2, _b, _c, _d, _e;
5896
+ if (typeof process === "undefined" || !((_a2 = process.versions) == null ? void 0 : _a2.node)) return null;
5897
+ try {
5898
+ const [fs4, path3, os2, crypto] = await Promise.all([
5899
+ import("fs"),
5900
+ import("path"),
5901
+ import("os"),
5902
+ import("crypto")
5903
+ ]);
5904
+ const fsMod = (_b = fs4.default) != null ? _b : fs4;
5905
+ const pathMod = (_c = path3.default) != null ? _c : path3;
5906
+ const osMod = (_d = os2.default) != null ? _d : os2;
5907
+ const cryptoMod = (_e = crypto.default) != null ? _e : crypto;
5908
+ const dir = process.env.MEM0_DIR || pathMod.join(osMod.homedir(), ".mem0");
5909
+ return {
5910
+ fs: fsMod,
5911
+ path: pathMod,
5912
+ crypto: cryptoMod,
5913
+ configPath: pathMod.join(dir, "config.json")
5914
+ };
5915
+ } catch (e) {
5916
+ return null;
5917
+ }
5918
+ }
5919
+ function loadConfig(node) {
5920
+ try {
5921
+ if (!node.fs.existsSync(node.configPath)) return null;
5922
+ const parsed = JSON.parse(node.fs.readFileSync(node.configPath, "utf8"));
5923
+ return parsed && typeof parsed === "object" ? parsed : null;
5924
+ } catch (e) {
5925
+ return null;
5926
+ }
5927
+ }
5928
+ function writeConfig(node, config) {
5929
+ node.fs.mkdirSync(node.path.dirname(node.configPath), { recursive: true });
5930
+ node.fs.writeFileSync(node.configPath, JSON.stringify(config, null, 4));
5931
+ }
5932
+ function randomUserId(node) {
5933
+ if (typeof node.crypto.randomUUID === "function") {
5934
+ return node.crypto.randomUUID();
5935
+ }
5936
+ return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
5937
+ }
5938
+ async function getOrCreateMem0UserId() {
5939
+ var _a2;
5940
+ const node = await getNodeFs();
5941
+ if (!node) return null;
5942
+ try {
5943
+ const config = (_a2 = loadConfig(node)) != null ? _a2 : {};
5944
+ if (typeof config.user_id === "string" && config.user_id) {
5945
+ return config.user_id;
5946
+ }
5947
+ const userId = randomUserId(node);
5948
+ config.user_id = userId;
5949
+ writeConfig(node, config);
5950
+ return userId;
5951
+ } catch (e) {
5952
+ return null;
5953
+ }
5954
+ }
5955
+
5774
5956
  // src/oss/src/memory/index.ts
5775
5957
  var ENTITY_PARAMS = [
5776
5958
  "user_id",
@@ -6077,7 +6259,11 @@ var Memory = class _Memory {
6077
6259
  async _getTelemetryId() {
6078
6260
  try {
6079
6261
  if (!this.telemetryId || this.telemetryId === "anonymous" || this.telemetryId === "anonymous-supabase") {
6080
- this.telemetryId = await this.vectorStore.getUserId();
6262
+ this.telemetryId = await getOrCreateMem0UserId() || await this.vectorStore.getUserId();
6263
+ try {
6264
+ await this.vectorStore.setUserId(this.telemetryId);
6265
+ } catch (e) {
6266
+ }
6081
6267
  }
6082
6268
  return this.telemetryId;
6083
6269
  } catch (error) {