mem0ai 3.0.2 → 3.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/oss/index.js CHANGED
@@ -58,7 +58,8 @@ __export(index_exports, {
58
58
  RedisDB: () => RedisDB,
59
59
  SupabaseDB: () => SupabaseDB,
60
60
  VectorStoreFactory: () => VectorStoreFactory,
61
- VectorizeDB: () => VectorizeDB
61
+ VectorizeDB: () => VectorizeDB,
62
+ buildFilterConditions: () => buildFilterConditions
62
63
  });
63
64
  module.exports = __toCommonJS(index_exports);
64
65
 
@@ -893,9 +894,9 @@ var _MemoryVectorStore = class _MemoryVectorStore {
893
894
  if (row) {
894
895
  return row.user_id;
895
896
  }
896
- const randomUserId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
897
- this.db.prepare(`INSERT INTO memory_migrations (user_id) VALUES (?)`).run(randomUserId);
898
- return randomUserId;
897
+ const randomUserId2 = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
898
+ this.db.prepare(`INSERT INTO memory_migrations (user_id) VALUES (?)`).run(randomUserId2);
899
+ return randomUserId2;
899
900
  }
900
901
  async setUserId(userId) {
901
902
  this.db.prepare(`DELETE FROM memory_migrations`).run();
@@ -1182,17 +1183,17 @@ var Qdrant = class {
1182
1183
  if (result.points.length > 0) {
1183
1184
  return (_a2 = result.points[0].payload) == null ? void 0 : _a2.user_id;
1184
1185
  }
1185
- const randomUserId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
1186
+ const randomUserId2 = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
1186
1187
  await this.client.upsert("memory_migrations", {
1187
1188
  points: [
1188
1189
  {
1189
1190
  id: this.generateUUID(),
1190
1191
  vector: [0],
1191
- payload: { user_id: randomUserId }
1192
+ payload: { user_id: randomUserId2 }
1192
1193
  }
1193
1194
  ]
1194
1195
  });
1195
- return randomUserId;
1196
+ return randomUserId2;
1196
1197
  } catch (error) {
1197
1198
  console.error("Error getting user ID:", error);
1198
1199
  throw error;
@@ -1496,11 +1497,11 @@ var VectorizeDB = class {
1496
1497
  if (result.matches.length > 0) {
1497
1498
  return result.matches[0].metadata.userId;
1498
1499
  }
1499
- const randomUserId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
1500
+ const randomUserId2 = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
1500
1501
  const data = {
1501
1502
  id: this.generateUUID(),
1502
1503
  values: [0],
1503
- metadata: { userId: randomUserId }
1504
+ metadata: { userId: randomUserId2 }
1504
1505
  };
1505
1506
  await fetch(
1506
1507
  `https://api.cloudflare.com/client/v4/accounts/${this.accountId}/vectorize/v2/indexes/memory_migrations/upsert`,
@@ -1514,7 +1515,7 @@ var VectorizeDB = class {
1514
1515
  // ndjson format
1515
1516
  }
1516
1517
  );
1517
- return randomUserId;
1518
+ return randomUserId2;
1518
1519
  } catch (error) {
1519
1520
  console.error("Error getting user ID:", error);
1520
1521
  throw new Error(
@@ -2129,9 +2130,9 @@ var RedisDB = class {
2129
2130
  if (userId) {
2130
2131
  return userId;
2131
2132
  }
2132
- const randomUserId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
2133
- await this.client.set("memory_migrations:1", randomUserId);
2134
- return randomUserId;
2133
+ const randomUserId2 = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
2134
+ await this.client.set("memory_migrations:1", randomUserId2);
2135
+ return randomUserId2;
2135
2136
  } catch (error) {
2136
2137
  console.error("Error getting user ID:", error);
2137
2138
  throw error;
@@ -2507,18 +2508,18 @@ See the SQL migration instructions in the code comments.`
2507
2508
  try {
2508
2509
  const { data: tableExists } = await this.client.from("memory_migrations").select("user_id").limit(1);
2509
2510
  if (!tableExists || tableExists.length === 0) {
2510
- const randomUserId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
2511
- const { error: insertError } = await this.client.from("memory_migrations").insert({ user_id: randomUserId });
2511
+ const randomUserId2 = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
2512
+ const { error: insertError } = await this.client.from("memory_migrations").insert({ user_id: randomUserId2 });
2512
2513
  if (insertError) throw insertError;
2513
- return randomUserId;
2514
+ return randomUserId2;
2514
2515
  }
2515
2516
  const { data, error } = await this.client.from("memory_migrations").select("user_id").limit(1);
2516
2517
  if (error) throw error;
2517
2518
  if (!data || data.length === 0) {
2518
- const randomUserId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
2519
- const { error: insertError } = await this.client.from("memory_migrations").insert({ user_id: randomUserId });
2519
+ const randomUserId2 = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
2520
+ const { error: insertError } = await this.client.from("memory_migrations").insert({ user_id: randomUserId2 });
2520
2521
  if (insertError) throw insertError;
2521
- return randomUserId;
2522
+ return randomUserId2;
2522
2523
  }
2523
2524
  return data[0].user_id;
2524
2525
  } catch (error) {
@@ -4390,14 +4391,14 @@ var AzureAISearch = class {
4390
4391
  return userId;
4391
4392
  }
4392
4393
  }
4393
- const randomUserId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
4394
+ const randomUserId2 = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
4394
4395
  await this.searchClient.uploadDocuments([
4395
4396
  {
4396
4397
  id: this.generateUUID(),
4397
- user_id: randomUserId
4398
+ user_id: randomUserId2
4398
4399
  }
4399
4400
  ]);
4400
- return randomUserId;
4401
+ return randomUserId2;
4401
4402
  } catch (error) {
4402
4403
  console.error("Error getting user ID:", error);
4403
4404
  throw error;
@@ -4445,13 +4446,135 @@ var AzureAISearch = class {
4445
4446
 
4446
4447
  // src/oss/src/vector_stores/pgvector.ts
4447
4448
  var import_pg = __toESM(require("pg"));
4448
- var { Client } = import_pg.default;
4449
+ var { Client, escapeIdentifier } = import_pg.default;
4450
+ var SAFE_IDENTIFIER_RE = /^[a-zA-Z_][a-zA-Z0-9_]{0,127}$/;
4451
+ function validateIdentifier(name, label = "identifier") {
4452
+ if (!SAFE_IDENTIFIER_RE.test(name)) {
4453
+ throw new Error(
4454
+ `Invalid ${label} '${name}': only letters, digits, and underscores are allowed, must start with a letter or underscore, and be at most 128 characters.`
4455
+ );
4456
+ }
4457
+ return name;
4458
+ }
4459
+ function escapeFilterKey(key) {
4460
+ if (!SAFE_IDENTIFIER_RE.test(key)) {
4461
+ throw new Error(
4462
+ `Invalid filter key '${key}': only letters, digits, and underscores are allowed.`
4463
+ );
4464
+ }
4465
+ return key;
4466
+ }
4467
+ var OPERATOR_SQL_MAP = {
4468
+ eq: { template: "payload->>'%KEY%' = $%IDX%", numeric: false },
4469
+ ne: { template: "payload->>'%KEY%' != $%IDX%", numeric: false },
4470
+ gt: { template: "(payload->>'%KEY%')::numeric > $%IDX%", numeric: true },
4471
+ gte: { template: "(payload->>'%KEY%')::numeric >= $%IDX%", numeric: true },
4472
+ lt: { template: "(payload->>'%KEY%')::numeric < $%IDX%", numeric: true },
4473
+ lte: { template: "(payload->>'%KEY%')::numeric <= $%IDX%", numeric: true },
4474
+ in: { template: "payload->>'%KEY%' = ANY($%IDX%::text[])", numeric: false },
4475
+ nin: {
4476
+ template: "NOT (payload->>'%KEY%' = ANY($%IDX%::text[]))",
4477
+ numeric: false
4478
+ },
4479
+ contains: {
4480
+ template: "payload->>'%KEY%' LIKE $%IDX% ESCAPE '\\'",
4481
+ numeric: false
4482
+ },
4483
+ icontains: {
4484
+ template: "payload->>'%KEY%' ILIKE $%IDX% ESCAPE '\\'",
4485
+ numeric: false
4486
+ }
4487
+ };
4488
+ function buildFilterConditions(filters, startIndex) {
4489
+ const conditions = [];
4490
+ const values = [];
4491
+ let paramIndex = startIndex;
4492
+ if (!filters) {
4493
+ return { conditions, values, paramIndex };
4494
+ }
4495
+ for (const [key, value] of Object.entries(filters)) {
4496
+ if (key === "$or") {
4497
+ const orGroups = [];
4498
+ for (const orFilter of value) {
4499
+ const sub = buildFilterConditions(orFilter, paramIndex);
4500
+ if (sub.conditions.length > 0) {
4501
+ orGroups.push("(" + sub.conditions.join(" AND ") + ")");
4502
+ values.push(...sub.values);
4503
+ paramIndex = sub.paramIndex;
4504
+ }
4505
+ }
4506
+ if (orGroups.length > 0) {
4507
+ conditions.push("(" + orGroups.join(" OR ") + ")");
4508
+ }
4509
+ continue;
4510
+ }
4511
+ if (key === "$not") {
4512
+ const notGroups = [];
4513
+ for (const notFilter of value) {
4514
+ const sub = buildFilterConditions(notFilter, paramIndex);
4515
+ if (sub.conditions.length > 0) {
4516
+ notGroups.push("(" + sub.conditions.join(" AND ") + ")");
4517
+ values.push(...sub.values);
4518
+ paramIndex = sub.paramIndex;
4519
+ }
4520
+ }
4521
+ if (notGroups.length > 0) {
4522
+ conditions.push("NOT (" + notGroups.join(" OR ") + ")");
4523
+ }
4524
+ continue;
4525
+ }
4526
+ const safeKey = escapeFilterKey(key);
4527
+ if (value === "*") {
4528
+ conditions.push(`payload ? $${paramIndex}`);
4529
+ values.push(key);
4530
+ paramIndex++;
4531
+ continue;
4532
+ }
4533
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
4534
+ for (const [op, opValue] of Object.entries(value)) {
4535
+ const mapping = OPERATOR_SQL_MAP[op];
4536
+ if (!mapping) {
4537
+ throw new Error(`Unsupported filter operator: ${op}`);
4538
+ }
4539
+ const clause = mapping.template.replace("%KEY%", safeKey).replace("%IDX%", String(paramIndex));
4540
+ conditions.push(clause);
4541
+ if (op === "in" || op === "nin") {
4542
+ values.push(opValue.map(String));
4543
+ } else if (op === "contains" || op === "icontains") {
4544
+ const escaped = String(opValue).replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
4545
+ values.push(`%${escaped}%`);
4546
+ } else if (mapping.numeric) {
4547
+ values.push(Number(opValue));
4548
+ } else {
4549
+ values.push(String(opValue));
4550
+ }
4551
+ paramIndex++;
4552
+ }
4553
+ } else if (Array.isArray(value)) {
4554
+ conditions.push(`payload->>'${safeKey}' = ANY($${paramIndex}::text[])`);
4555
+ values.push(value.map(String));
4556
+ paramIndex++;
4557
+ } else {
4558
+ conditions.push(`payload->>'${safeKey}' = $${paramIndex}`);
4559
+ if (typeof value === "boolean") {
4560
+ values.push(JSON.stringify(value));
4561
+ } else {
4562
+ values.push(String(value));
4563
+ }
4564
+ paramIndex++;
4565
+ }
4566
+ }
4567
+ return { conditions, values, paramIndex };
4568
+ }
4449
4569
  var PGVector = class {
4450
4570
  constructor(config) {
4451
- this.collectionName = config.collectionName || "memories";
4571
+ this.collectionName = validateIdentifier(
4572
+ config.collectionName || "memories",
4573
+ "collectionName"
4574
+ );
4452
4575
  this.useDiskann = config.diskann || false;
4453
4576
  this.useHnsw = config.hnsw || false;
4454
- this.dbName = config.dbname || "vector_store";
4577
+ this.dbName = validateIdentifier(config.dbname || "vector_store", "dbname");
4455
4578
  this.config = config;
4456
4579
  this.client = new Client({
4457
4580
  database: "postgres",
@@ -4463,6 +4586,9 @@ var PGVector = class {
4463
4586
  });
4464
4587
  this.initialize().catch(console.error);
4465
4588
  }
4589
+ col() {
4590
+ return escapeIdentifier(this.collectionName);
4591
+ }
4466
4592
  async initialize() {
4467
4593
  if (!this._initPromise) {
4468
4594
  this._initPromise = this._doInitialize();
@@ -4509,13 +4635,14 @@ var PGVector = class {
4509
4635
  return result.rows.length > 0;
4510
4636
  }
4511
4637
  async createDatabase(dbName) {
4512
- await this.client.query(`CREATE DATABASE ${dbName}`);
4638
+ await this.client.query(`CREATE DATABASE ${escapeIdentifier(dbName)}`);
4513
4639
  }
4514
4640
  async createCol(embeddingModelDims) {
4641
+ const dims = Math.floor(embeddingModelDims);
4515
4642
  await this.client.query(`
4516
- CREATE TABLE IF NOT EXISTS ${this.collectionName} (
4643
+ CREATE TABLE IF NOT EXISTS ${this.col()} (
4517
4644
  id UUID PRIMARY KEY,
4518
- vector vector(${embeddingModelDims}),
4645
+ vector vector(${dims}),
4519
4646
  payload JSONB
4520
4647
  );
4521
4648
  `);
@@ -4526,8 +4653,8 @@ var PGVector = class {
4526
4653
  );
4527
4654
  if (result.rows.length > 0) {
4528
4655
  await this.client.query(`
4529
- CREATE INDEX IF NOT EXISTS ${this.collectionName}_diskann_idx
4530
- ON ${this.collectionName}
4656
+ CREATE INDEX IF NOT EXISTS ${escapeIdentifier(this.collectionName + "_diskann_idx")}
4657
+ ON ${this.col()}
4531
4658
  USING diskann (vector);
4532
4659
  `);
4533
4660
  }
@@ -4537,8 +4664,8 @@ var PGVector = class {
4537
4664
  } else if (this.useHnsw) {
4538
4665
  try {
4539
4666
  await this.client.query(`
4540
- CREATE INDEX IF NOT EXISTS ${this.collectionName}_hnsw_idx
4541
- ON ${this.collectionName}
4667
+ CREATE INDEX IF NOT EXISTS ${escapeIdentifier(this.collectionName + "_hnsw_idx")}
4668
+ ON ${this.col()}
4542
4669
  USING hnsw (vector vector_cosine_ops);
4543
4670
  `);
4544
4671
  } catch (error) {
@@ -4550,11 +4677,10 @@ var PGVector = class {
4550
4677
  const values = vectors.map((vector, i) => ({
4551
4678
  id: ids[i],
4552
4679
  vector: `[${vector.join(",")}]`,
4553
- // Format vector as string with square brackets
4554
4680
  payload: payloads[i]
4555
4681
  }));
4556
4682
  const query = `
4557
- INSERT INTO ${this.collectionName} (id, vector, payload)
4683
+ INSERT INTO ${this.col()} (id, vector, payload)
4558
4684
  VALUES ($1, $2::vector, $3::jsonb)
4559
4685
  `;
4560
4686
  await Promise.all(
@@ -4565,20 +4691,16 @@ var PGVector = class {
4565
4691
  }
4566
4692
  async keywordSearch(query, topK = 5, filters) {
4567
4693
  try {
4568
- const filterConditions = [];
4569
- const filterValues = [query, topK];
4570
- let filterIndex = 3;
4571
- if (filters) {
4572
- for (const [key, value] of Object.entries(filters)) {
4573
- filterConditions.push(`payload->>'${key}' = $${filterIndex}`);
4574
- filterValues.push(value);
4575
- filterIndex++;
4576
- }
4577
- }
4578
- const filterClause = filterConditions.length > 0 ? "AND " + filterConditions.join(" AND ") : "";
4694
+ const {
4695
+ conditions,
4696
+ values,
4697
+ paramIndex: _
4698
+ } = buildFilterConditions(filters, 3);
4699
+ const filterValues = [query, topK, ...values];
4700
+ const filterClause = conditions.length > 0 ? "AND " + conditions.join(" AND ") : "";
4579
4701
  const searchQuery = `
4580
4702
  SELECT id, ts_rank_cd(to_tsvector('simple', payload->>'textLemmatized'), plainto_tsquery('simple', $1)) AS score, payload
4581
- FROM ${this.collectionName}
4703
+ FROM ${this.col()}
4582
4704
  WHERE to_tsvector('simple', payload->>'textLemmatized') @@ plainto_tsquery('simple', $1)
4583
4705
  ${filterClause}
4584
4706
  ORDER BY score DESC
@@ -4596,21 +4718,17 @@ var PGVector = class {
4596
4718
  }
4597
4719
  }
4598
4720
  async search(query, topK = 5, filters) {
4599
- const filterConditions = [];
4600
4721
  const queryVector = `[${query.join(",")}]`;
4601
- const filterValues = [queryVector, topK];
4602
- let filterIndex = 3;
4603
- if (filters) {
4604
- for (const [key, value] of Object.entries(filters)) {
4605
- filterConditions.push(`payload->>'${key}' = $${filterIndex}`);
4606
- filterValues.push(value);
4607
- filterIndex++;
4608
- }
4609
- }
4610
- const filterClause = filterConditions.length > 0 ? "WHERE " + filterConditions.join(" AND ") : "";
4722
+ const {
4723
+ conditions,
4724
+ values,
4725
+ paramIndex: _
4726
+ } = buildFilterConditions(filters, 3);
4727
+ const filterValues = [queryVector, topK, ...values];
4728
+ const filterClause = conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
4611
4729
  const searchQuery = `
4612
4730
  SELECT id, vector <=> $1::vector AS distance, payload
4613
- FROM ${this.collectionName}
4731
+ FROM ${this.col()}
4614
4732
  ${filterClause}
4615
4733
  ORDER BY distance
4616
4734
  LIMIT $2
@@ -4619,12 +4737,12 @@ var PGVector = class {
4619
4737
  return result.rows.map((row) => ({
4620
4738
  id: row.id,
4621
4739
  payload: row.payload,
4622
- score: row.distance
4740
+ score: Math.max(0, Math.min(1, 1 - Number(row.distance)))
4623
4741
  }));
4624
4742
  }
4625
4743
  async get(vectorId) {
4626
4744
  const result = await this.client.query(
4627
- `SELECT id, payload FROM ${this.collectionName} WHERE id = $1`,
4745
+ `SELECT id, payload FROM ${this.col()} WHERE id = $1`,
4628
4746
  [vectorId]
4629
4747
  );
4630
4748
  if (result.rows.length === 0) return null;
@@ -4637,7 +4755,7 @@ var PGVector = class {
4637
4755
  const vectorStr = `[${vector.join(",")}]`;
4638
4756
  await this.client.query(
4639
4757
  `
4640
- UPDATE ${this.collectionName}
4758
+ UPDATE ${this.col()}
4641
4759
  SET vector = $1::vector, payload = $2::jsonb
4642
4760
  WHERE id = $3
4643
4761
  `,
@@ -4645,13 +4763,12 @@ var PGVector = class {
4645
4763
  );
4646
4764
  }
4647
4765
  async delete(vectorId) {
4648
- await this.client.query(
4649
- `DELETE FROM ${this.collectionName} WHERE id = $1`,
4650
- [vectorId]
4651
- );
4766
+ await this.client.query(`DELETE FROM ${this.col()} WHERE id = $1`, [
4767
+ vectorId
4768
+ ]);
4652
4769
  }
4653
4770
  async deleteCol() {
4654
- await this.client.query(`DROP TABLE IF EXISTS ${this.collectionName}`);
4771
+ await this.client.query(`DROP TABLE IF EXISTS ${this.col()}`);
4655
4772
  }
4656
4773
  async listCols() {
4657
4774
  const result = await this.client.query(`
@@ -4662,33 +4779,27 @@ var PGVector = class {
4662
4779
  return result.rows.map((row) => row.table_name);
4663
4780
  }
4664
4781
  async list(filters, topK = 100) {
4665
- const filterConditions = [];
4666
- const filterValues = [];
4667
- let paramIndex = 1;
4668
- if (filters) {
4669
- for (const [key, value] of Object.entries(filters)) {
4670
- filterConditions.push(`payload->>'${key}' = $${paramIndex}`);
4671
- filterValues.push(value);
4672
- paramIndex++;
4673
- }
4674
- }
4675
- const filterClause = filterConditions.length > 0 ? "WHERE " + filterConditions.join(" AND ") : "";
4782
+ const {
4783
+ conditions,
4784
+ values: filterValues,
4785
+ paramIndex
4786
+ } = buildFilterConditions(filters, 1);
4787
+ const filterClause = conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";
4676
4788
  const listQuery = `
4677
4789
  SELECT id, payload
4678
- FROM ${this.collectionName}
4790
+ FROM ${this.col()}
4679
4791
  ${filterClause}
4680
4792
  LIMIT $${paramIndex}
4681
4793
  `;
4682
4794
  const countQuery = `
4683
4795
  SELECT COUNT(*)
4684
- FROM ${this.collectionName}
4796
+ FROM ${this.col()}
4685
4797
  ${filterClause}
4686
4798
  `;
4687
- filterValues.push(topK);
4799
+ const listValues = [...filterValues, topK];
4688
4800
  const [listResult, countResult] = await Promise.all([
4689
- this.client.query(listQuery, filterValues),
4690
- this.client.query(countQuery, filterValues.slice(0, -1))
4691
- // Remove limit parameter for count query
4801
+ this.client.query(listQuery, listValues),
4802
+ this.client.query(countQuery, filterValues)
4692
4803
  ]);
4693
4804
  const results = listResult.rows.map((row) => ({
4694
4805
  id: row.id,
@@ -4706,12 +4817,12 @@ var PGVector = class {
4706
4817
  if (result.rows.length > 0) {
4707
4818
  return result.rows[0].user_id;
4708
4819
  }
4709
- const randomUserId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
4820
+ const randomUserId2 = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
4710
4821
  await this.client.query(
4711
4822
  "INSERT INTO memory_migrations (user_id) VALUES ($1)",
4712
- [randomUserId]
4823
+ [randomUserId2]
4713
4824
  );
4714
- return randomUserId;
4825
+ return randomUserId2;
4715
4826
  }
4716
4827
  async setUserId(userId) {
4717
4828
  await this.client.query("DELETE FROM memory_migrations");
@@ -5012,7 +5123,7 @@ var parse_vision_messages = async (messages) => {
5012
5123
  };
5013
5124
 
5014
5125
  // src/oss/src/utils/telemetry.ts
5015
- var version = true ? "3.0.2" : "dev";
5126
+ var version = true ? "3.0.4" : "dev";
5016
5127
  var MEM0_TELEMETRY = true;
5017
5128
  var _a;
5018
5129
  try {
@@ -5914,6 +6025,69 @@ function scoreAndRank(semanticResults, bm25Scores, entityBoosts, threshold, topK
5914
6025
  return scored.slice(0, topK);
5915
6026
  }
5916
6027
 
6028
+ // src/client/config.ts
6029
+ async function getNodeFs() {
6030
+ var _a2, _b, _c, _d, _e;
6031
+ if (typeof process === "undefined" || !((_a2 = process.versions) == null ? void 0 : _a2.node)) return null;
6032
+ try {
6033
+ const [fs4, path3, os2, crypto] = await Promise.all([
6034
+ import("fs"),
6035
+ import("path"),
6036
+ import("os"),
6037
+ import("crypto")
6038
+ ]);
6039
+ const fsMod = (_b = fs4.default) != null ? _b : fs4;
6040
+ const pathMod = (_c = path3.default) != null ? _c : path3;
6041
+ const osMod = (_d = os2.default) != null ? _d : os2;
6042
+ const cryptoMod = (_e = crypto.default) != null ? _e : crypto;
6043
+ const dir = process.env.MEM0_DIR || pathMod.join(osMod.homedir(), ".mem0");
6044
+ return {
6045
+ fs: fsMod,
6046
+ path: pathMod,
6047
+ crypto: cryptoMod,
6048
+ configPath: pathMod.join(dir, "config.json")
6049
+ };
6050
+ } catch (e) {
6051
+ return null;
6052
+ }
6053
+ }
6054
+ function loadConfig(node) {
6055
+ try {
6056
+ if (!node.fs.existsSync(node.configPath)) return null;
6057
+ const parsed = JSON.parse(node.fs.readFileSync(node.configPath, "utf8"));
6058
+ return parsed && typeof parsed === "object" ? parsed : null;
6059
+ } catch (e) {
6060
+ return null;
6061
+ }
6062
+ }
6063
+ function writeConfig(node, config) {
6064
+ node.fs.mkdirSync(node.path.dirname(node.configPath), { recursive: true });
6065
+ node.fs.writeFileSync(node.configPath, JSON.stringify(config, null, 4));
6066
+ }
6067
+ function randomUserId(node) {
6068
+ if (typeof node.crypto.randomUUID === "function") {
6069
+ return node.crypto.randomUUID();
6070
+ }
6071
+ return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
6072
+ }
6073
+ async function getOrCreateMem0UserId() {
6074
+ var _a2;
6075
+ const node = await getNodeFs();
6076
+ if (!node) return null;
6077
+ try {
6078
+ const config = (_a2 = loadConfig(node)) != null ? _a2 : {};
6079
+ if (typeof config.user_id === "string" && config.user_id) {
6080
+ return config.user_id;
6081
+ }
6082
+ const userId = randomUserId(node);
6083
+ config.user_id = userId;
6084
+ writeConfig(node, config);
6085
+ return userId;
6086
+ } catch (e) {
6087
+ return null;
6088
+ }
6089
+ }
6090
+
5917
6091
  // src/oss/src/memory/index.ts
5918
6092
  var ENTITY_PARAMS = [
5919
6093
  "user_id",
@@ -6220,7 +6394,11 @@ var Memory = class _Memory {
6220
6394
  async _getTelemetryId() {
6221
6395
  try {
6222
6396
  if (!this.telemetryId || this.telemetryId === "anonymous" || this.telemetryId === "anonymous-supabase") {
6223
- this.telemetryId = await this.vectorStore.getUserId();
6397
+ this.telemetryId = await getOrCreateMem0UserId() || await this.vectorStore.getUserId();
6398
+ try {
6399
+ await this.vectorStore.setUserId(this.telemetryId);
6400
+ } catch (e) {
6401
+ }
6224
6402
  }
6225
6403
  return this.telemetryId;
6226
6404
  } catch (error) {
@@ -7214,6 +7392,7 @@ var Memory = class _Memory {
7214
7392
  RedisDB,
7215
7393
  SupabaseDB,
7216
7394
  VectorStoreFactory,
7217
- VectorizeDB
7395
+ VectorizeDB,
7396
+ buildFilterConditions
7218
7397
  });
7219
7398
  //# sourceMappingURL=index.js.map