@mastra/mongodb 0.11.1-alpha.0 → 0.11.1-alpha.2

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.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ var error = require('@mastra/core/error');
3
4
  var vector = require('@mastra/core/vector');
4
5
  var mongodb = require('mongodb');
5
6
  var uuid = require('uuid');
@@ -118,28 +119,68 @@ var MongoDBVector = class extends vector.MastraVector {
118
119
  }
119
120
  // Public methods
120
121
  async connect() {
121
- await this.client.connect();
122
+ try {
123
+ await this.client.connect();
124
+ } catch (error$1) {
125
+ throw new error.MastraError(
126
+ {
127
+ id: "STORAGE_MONGODB_VECTOR_CONNECT_FAILED",
128
+ domain: error.ErrorDomain.STORAGE,
129
+ category: error.ErrorCategory.THIRD_PARTY
130
+ },
131
+ error$1
132
+ );
133
+ }
122
134
  }
123
135
  async disconnect() {
124
- await this.client.close();
136
+ try {
137
+ await this.client.close();
138
+ } catch (error$1) {
139
+ throw new error.MastraError(
140
+ {
141
+ id: "STORAGE_MONGODB_VECTOR_DISCONNECT_FAILED",
142
+ domain: error.ErrorDomain.STORAGE,
143
+ category: error.ErrorCategory.THIRD_PARTY
144
+ },
145
+ error$1
146
+ );
147
+ }
125
148
  }
126
149
  async createIndex({ indexName, dimension, metric = "cosine" }) {
127
- if (!Number.isInteger(dimension) || dimension <= 0) {
128
- throw new Error("Dimension must be a positive integer");
129
- }
130
- const mongoMetric = this.mongoMetricMap[metric];
131
- if (!mongoMetric) {
132
- throw new Error(`Invalid metric: "${metric}". Must be one of: cosine, euclidean, dotproduct`);
133
- }
134
- const collectionExists = await this.db.listCollections({ name: indexName }).hasNext();
135
- if (!collectionExists) {
136
- await this.db.createCollection(indexName);
150
+ let mongoMetric;
151
+ try {
152
+ if (!Number.isInteger(dimension) || dimension <= 0) {
153
+ throw new Error("Dimension must be a positive integer");
154
+ }
155
+ mongoMetric = this.mongoMetricMap[metric];
156
+ if (!mongoMetric) {
157
+ throw new Error(`Invalid metric: "${metric}". Must be one of: cosine, euclidean, dotproduct`);
158
+ }
159
+ } catch (error$1) {
160
+ throw new error.MastraError(
161
+ {
162
+ id: "STORAGE_MONGODB_VECTOR_CREATE_INDEX_INVALID_ARGS",
163
+ domain: error.ErrorDomain.STORAGE,
164
+ category: error.ErrorCategory.USER,
165
+ details: {
166
+ indexName,
167
+ dimension,
168
+ metric
169
+ }
170
+ },
171
+ error$1
172
+ );
137
173
  }
138
- const collection = await this.getCollection(indexName);
139
- const indexNameInternal = `${indexName}_vector_index`;
140
- const embeddingField = this.embeddingFieldName;
141
- const numDimensions = dimension;
174
+ let collection;
142
175
  try {
176
+ const collectionExists = await this.db.listCollections({ name: indexName }).hasNext();
177
+ if (!collectionExists) {
178
+ await this.db.createCollection(indexName);
179
+ }
180
+ collection = await this.getCollection(indexName);
181
+ const indexNameInternal = `${indexName}_vector_index`;
182
+ const embeddingField = this.embeddingFieldName;
183
+ const numDimensions = dimension;
143
184
  await collection.createSearchIndex({
144
185
  definition: {
145
186
  fields: [
@@ -154,12 +195,33 @@ var MongoDBVector = class extends vector.MastraVector {
154
195
  name: indexNameInternal,
155
196
  type: "vectorSearch"
156
197
  });
157
- } catch (error) {
158
- if (error.codeName !== "IndexAlreadyExists") {
159
- throw error;
198
+ } catch (error$1) {
199
+ if (error$1.codeName !== "IndexAlreadyExists") {
200
+ throw new error.MastraError(
201
+ {
202
+ id: "STORAGE_MONGODB_VECTOR_CREATE_INDEX_FAILED",
203
+ domain: error.ErrorDomain.STORAGE,
204
+ category: error.ErrorCategory.THIRD_PARTY
205
+ },
206
+ error$1
207
+ );
160
208
  }
161
209
  }
162
- await collection.updateOne({ _id: "__index_metadata__" }, { $set: { dimension, metric } }, { upsert: true });
210
+ try {
211
+ await collection?.updateOne({ _id: "__index_metadata__" }, { $set: { dimension, metric } }, { upsert: true });
212
+ } catch (error$1) {
213
+ throw new error.MastraError(
214
+ {
215
+ id: "STORAGE_MONGODB_VECTOR_CREATE_INDEX_FAILED_STORE_METADATA",
216
+ domain: error.ErrorDomain.STORAGE,
217
+ category: error.ErrorCategory.THIRD_PARTY,
218
+ details: {
219
+ indexName
220
+ }
221
+ },
222
+ error$1
223
+ );
224
+ }
163
225
  }
164
226
  /**
165
227
  * Waits for the index to be ready.
@@ -189,40 +251,54 @@ var MongoDBVector = class extends vector.MastraVector {
189
251
  throw new Error(`Index "${indexNameInternal}" did not become ready within timeout`);
190
252
  }
191
253
  async upsert({ indexName, vectors, metadata, ids, documents }) {
192
- const collection = await this.getCollection(indexName);
193
- this.collectionForValidation = collection;
194
- const stats = await this.describeIndex({ indexName });
195
- await this.validateVectorDimensions(vectors, stats.dimension);
196
- const generatedIds = ids || vectors.map(() => uuid.v4());
197
- const operations = vectors.map((vector, idx) => {
198
- const id = generatedIds[idx];
199
- const meta = metadata?.[idx] || {};
200
- const doc = documents?.[idx];
201
- const normalizedMeta = Object.keys(meta).reduce(
202
- (acc, key) => {
203
- acc[key] = meta[key] instanceof Date ? meta[key].toISOString() : meta[key];
204
- return acc;
254
+ try {
255
+ const collection = await this.getCollection(indexName);
256
+ this.collectionForValidation = collection;
257
+ const stats = await this.describeIndex({ indexName });
258
+ await this.validateVectorDimensions(vectors, stats.dimension);
259
+ const generatedIds = ids || vectors.map(() => uuid.v4());
260
+ const operations = vectors.map((vector, idx) => {
261
+ const id = generatedIds[idx];
262
+ const meta = metadata?.[idx] || {};
263
+ const doc = documents?.[idx];
264
+ const normalizedMeta = Object.keys(meta).reduce(
265
+ (acc, key) => {
266
+ acc[key] = meta[key] instanceof Date ? meta[key].toISOString() : meta[key];
267
+ return acc;
268
+ },
269
+ {}
270
+ );
271
+ const updateDoc = {
272
+ [this.embeddingFieldName]: vector,
273
+ [this.metadataFieldName]: normalizedMeta
274
+ };
275
+ if (doc !== void 0) {
276
+ updateDoc[this.documentFieldName] = doc;
277
+ }
278
+ return {
279
+ updateOne: {
280
+ filter: { _id: id },
281
+ // '_id' is a string as per MongoDBDocument interface
282
+ update: { $set: updateDoc },
283
+ upsert: true
284
+ }
285
+ };
286
+ });
287
+ await collection.bulkWrite(operations);
288
+ return generatedIds;
289
+ } catch (error$1) {
290
+ throw new error.MastraError(
291
+ {
292
+ id: "STORAGE_MONGODB_VECTOR_UPSERT_FAILED",
293
+ domain: error.ErrorDomain.STORAGE,
294
+ category: error.ErrorCategory.THIRD_PARTY,
295
+ details: {
296
+ indexName
297
+ }
205
298
  },
206
- {}
299
+ error$1
207
300
  );
208
- const updateDoc = {
209
- [this.embeddingFieldName]: vector,
210
- [this.metadataFieldName]: normalizedMeta
211
- };
212
- if (doc !== void 0) {
213
- updateDoc[this.documentFieldName] = doc;
214
- }
215
- return {
216
- updateOne: {
217
- filter: { _id: id },
218
- // '_id' is a string as per MongoDBDocument interface
219
- update: { $set: updateDoc },
220
- upsert: true
221
- }
222
- };
223
- });
224
- await collection.bulkWrite(operations);
225
- return generatedIds;
301
+ }
226
302
  }
227
303
  async query({
228
304
  indexName,
@@ -232,44 +308,44 @@ var MongoDBVector = class extends vector.MastraVector {
232
308
  includeVector = false,
233
309
  documentFilter
234
310
  }) {
235
- const collection = await this.getCollection(indexName, true);
236
- const indexNameInternal = `${indexName}_vector_index`;
237
- const mongoFilter = this.transformFilter(filter);
238
- const documentMongoFilter = documentFilter ? { [this.documentFieldName]: documentFilter } : {};
239
- let combinedFilter = {};
240
- if (Object.keys(mongoFilter).length > 0 && Object.keys(documentMongoFilter).length > 0) {
241
- combinedFilter = { $and: [mongoFilter, documentMongoFilter] };
242
- } else if (Object.keys(mongoFilter).length > 0) {
243
- combinedFilter = mongoFilter;
244
- } else if (Object.keys(documentMongoFilter).length > 0) {
245
- combinedFilter = documentMongoFilter;
246
- }
247
- const pipeline = [
248
- {
249
- $vectorSearch: {
250
- index: indexNameInternal,
251
- queryVector,
252
- path: this.embeddingFieldName,
253
- numCandidates: 100,
254
- limit: topK
255
- }
256
- },
257
- // Apply the filter using $match stage
258
- ...Object.keys(combinedFilter).length > 0 ? [{ $match: combinedFilter }] : [],
259
- {
260
- $set: { score: { $meta: "vectorSearchScore" } }
261
- },
262
- {
263
- $project: {
264
- _id: 1,
265
- score: 1,
266
- metadata: `$${this.metadataFieldName}`,
267
- document: `$${this.documentFieldName}`,
268
- ...includeVector && { vector: `$${this.embeddingFieldName}` }
269
- }
270
- }
271
- ];
272
311
  try {
312
+ const collection = await this.getCollection(indexName, true);
313
+ const indexNameInternal = `${indexName}_vector_index`;
314
+ const mongoFilter = this.transformFilter(filter);
315
+ const documentMongoFilter = documentFilter ? { [this.documentFieldName]: documentFilter } : {};
316
+ let combinedFilter = {};
317
+ if (Object.keys(mongoFilter).length > 0 && Object.keys(documentMongoFilter).length > 0) {
318
+ combinedFilter = { $and: [mongoFilter, documentMongoFilter] };
319
+ } else if (Object.keys(mongoFilter).length > 0) {
320
+ combinedFilter = mongoFilter;
321
+ } else if (Object.keys(documentMongoFilter).length > 0) {
322
+ combinedFilter = documentMongoFilter;
323
+ }
324
+ const pipeline = [
325
+ {
326
+ $vectorSearch: {
327
+ index: indexNameInternal,
328
+ queryVector,
329
+ path: this.embeddingFieldName,
330
+ numCandidates: 100,
331
+ limit: topK
332
+ }
333
+ },
334
+ // Apply the filter using $match stage
335
+ ...Object.keys(combinedFilter).length > 0 ? [{ $match: combinedFilter }] : [],
336
+ {
337
+ $set: { score: { $meta: "vectorSearchScore" } }
338
+ },
339
+ {
340
+ $project: {
341
+ _id: 1,
342
+ score: 1,
343
+ metadata: `$${this.metadataFieldName}`,
344
+ document: `$${this.documentFieldName}`,
345
+ ...includeVector && { vector: `$${this.embeddingFieldName}` }
346
+ }
347
+ }
348
+ ];
273
349
  const results = await collection.aggregate(pipeline).toArray();
274
350
  return results.map((result) => ({
275
351
  id: result._id,
@@ -278,14 +354,34 @@ var MongoDBVector = class extends vector.MastraVector {
278
354
  vector: includeVector ? result.vector : void 0,
279
355
  document: result.document
280
356
  }));
281
- } catch (error) {
282
- console.error("Error during vector search:", error);
283
- throw error;
357
+ } catch (error$1) {
358
+ throw new error.MastraError(
359
+ {
360
+ id: "STORAGE_MONGODB_VECTOR_QUERY_FAILED",
361
+ domain: error.ErrorDomain.STORAGE,
362
+ category: error.ErrorCategory.THIRD_PARTY,
363
+ details: {
364
+ indexName
365
+ }
366
+ },
367
+ error$1
368
+ );
284
369
  }
285
370
  }
286
371
  async listIndexes() {
287
- const collections = await this.db.listCollections().toArray();
288
- return collections.map((col) => col.name);
372
+ try {
373
+ const collections = await this.db.listCollections().toArray();
374
+ return collections.map((col) => col.name);
375
+ } catch (error$1) {
376
+ throw new error.MastraError(
377
+ {
378
+ id: "STORAGE_MONGODB_VECTOR_LIST_INDEXES_FAILED",
379
+ domain: error.ErrorDomain.STORAGE,
380
+ category: error.ErrorCategory.THIRD_PARTY
381
+ },
382
+ error$1
383
+ );
384
+ }
289
385
  }
290
386
  /**
291
387
  * Retrieves statistics about a vector index.
@@ -294,24 +390,52 @@ var MongoDBVector = class extends vector.MastraVector {
294
390
  * @returns A promise that resolves to the index statistics including dimension, count and metric
295
391
  */
296
392
  async describeIndex({ indexName }) {
297
- const collection = await this.getCollection(indexName, true);
298
- const count = await collection.countDocuments({ _id: { $ne: "__index_metadata__" } });
299
- const metadataDoc = await collection.findOne({ _id: "__index_metadata__" });
300
- const dimension = metadataDoc?.dimension || 0;
301
- const metric = metadataDoc?.metric || "cosine";
302
- return {
303
- dimension,
304
- count,
305
- metric
306
- };
393
+ try {
394
+ const collection = await this.getCollection(indexName, true);
395
+ const count = await collection.countDocuments({ _id: { $ne: "__index_metadata__" } });
396
+ const metadataDoc = await collection.findOne({ _id: "__index_metadata__" });
397
+ const dimension = metadataDoc?.dimension || 0;
398
+ const metric = metadataDoc?.metric || "cosine";
399
+ return {
400
+ dimension,
401
+ count,
402
+ metric
403
+ };
404
+ } catch (error$1) {
405
+ throw new error.MastraError(
406
+ {
407
+ id: "STORAGE_MONGODB_VECTOR_DESCRIBE_INDEX_FAILED",
408
+ domain: error.ErrorDomain.STORAGE,
409
+ category: error.ErrorCategory.THIRD_PARTY,
410
+ details: {
411
+ indexName
412
+ }
413
+ },
414
+ error$1
415
+ );
416
+ }
307
417
  }
308
418
  async deleteIndex({ indexName }) {
309
419
  const collection = await this.getCollection(indexName, false);
310
- if (collection) {
311
- await collection.drop();
312
- this.collections.delete(indexName);
313
- } else {
314
- throw new Error(`Index (Collection) "${indexName}" does not exist`);
420
+ try {
421
+ if (collection) {
422
+ await collection.drop();
423
+ this.collections.delete(indexName);
424
+ } else {
425
+ throw new Error(`Index (Collection) "${indexName}" does not exist`);
426
+ }
427
+ } catch (error$1) {
428
+ throw new error.MastraError(
429
+ {
430
+ id: "STORAGE_MONGODB_VECTOR_DELETE_INDEX_FAILED",
431
+ domain: error.ErrorDomain.STORAGE,
432
+ category: error.ErrorCategory.THIRD_PARTY,
433
+ details: {
434
+ indexName
435
+ }
436
+ },
437
+ error$1
438
+ );
315
439
  }
316
440
  }
317
441
  /**
@@ -347,8 +471,19 @@ var MongoDBVector = class extends vector.MastraVector {
347
471
  updateDoc[this.metadataFieldName] = normalizedMeta;
348
472
  }
349
473
  await collection.findOneAndUpdate({ _id: id }, { $set: updateDoc });
350
- } catch (error) {
351
- throw new Error(`Failed to update vector by id: ${id} for index name: ${indexName}: ${error.message}`);
474
+ } catch (error$1) {
475
+ throw new error.MastraError(
476
+ {
477
+ id: "STORAGE_MONGODB_VECTOR_UPDATE_VECTOR_FAILED",
478
+ domain: error.ErrorDomain.STORAGE,
479
+ category: error.ErrorCategory.THIRD_PARTY,
480
+ details: {
481
+ indexName,
482
+ id
483
+ }
484
+ },
485
+ error$1
486
+ );
352
487
  }
353
488
  }
354
489
  /**
@@ -362,8 +497,19 @@ var MongoDBVector = class extends vector.MastraVector {
362
497
  try {
363
498
  const collection = await this.getCollection(indexName, true);
364
499
  await collection.deleteOne({ _id: id });
365
- } catch (error) {
366
- throw new Error(`Failed to delete vector by id: ${id} for index name: ${indexName}: ${error.message}`);
500
+ } catch (error$1) {
501
+ throw new error.MastraError(
502
+ {
503
+ id: "STORAGE_MONGODB_VECTOR_DELETE_VECTOR_FAILED",
504
+ domain: error.ErrorDomain.STORAGE,
505
+ category: error.ErrorCategory.THIRD_PARTY,
506
+ details: {
507
+ indexName,
508
+ id
509
+ }
510
+ },
511
+ error$1
512
+ );
367
513
  }
368
514
  }
369
515
  // Private methods
@@ -419,14 +565,26 @@ var MongoDBStore = class extends storage.MastraStorage {
419
565
  constructor(config) {
420
566
  super({ name: "MongoDBStore" });
421
567
  this.#isConnected = false;
422
- if (!config.url?.trim().length) {
423
- throw new Error(
424
- "MongoDBStore: url must be provided and cannot be empty. Passing an empty string may cause fallback to local MongoDB defaults."
425
- );
426
- }
427
- if (!config.dbName?.trim().length) {
428
- throw new Error(
429
- "MongoDBStore: dbName must be provided and cannot be empty. Passing an empty string may cause fallback to local MongoDB defaults."
568
+ try {
569
+ if (!config.url?.trim().length) {
570
+ throw new Error(
571
+ "MongoDBStore: url must be provided and cannot be empty. Passing an empty string may cause fallback to local MongoDB defaults."
572
+ );
573
+ }
574
+ if (!config.dbName?.trim().length) {
575
+ throw new Error(
576
+ "MongoDBStore: dbName must be provided and cannot be empty. Passing an empty string may cause fallback to local MongoDB defaults."
577
+ );
578
+ }
579
+ } catch (error$1) {
580
+ throw new error.MastraError(
581
+ {
582
+ id: "STORAGE_MONGODB_STORE_CONSTRUCTOR_FAILED",
583
+ domain: error.ErrorDomain.STORAGE,
584
+ category: error.ErrorCategory.USER,
585
+ details: { url: config.url, dbName: config.dbName }
586
+ },
587
+ error$1
430
588
  );
431
589
  }
432
590
  this.#dbName = config.dbName;
@@ -459,9 +617,19 @@ var MongoDBStore = class extends storage.MastraStorage {
459
617
  try {
460
618
  const collection = await this.getCollection(tableName);
461
619
  await collection.deleteMany({});
462
- } catch (error) {
463
- if (error instanceof Error) {
464
- this.logger.error(error.message);
620
+ } catch (error$1) {
621
+ if (error$1 instanceof Error) {
622
+ const matstraError = new error.MastraError(
623
+ {
624
+ id: "STORAGE_MONGODB_STORE_CLEAR_TABLE_FAILED",
625
+ domain: error.ErrorDomain.STORAGE,
626
+ category: error.ErrorCategory.THIRD_PARTY,
627
+ details: { tableName }
628
+ },
629
+ error$1
630
+ );
631
+ this.logger.error(matstraError.message);
632
+ this.logger?.trackException(matstraError);
465
633
  }
466
634
  }
467
635
  }
@@ -469,9 +637,20 @@ var MongoDBStore = class extends storage.MastraStorage {
469
637
  try {
470
638
  const collection = await this.getCollection(tableName);
471
639
  await collection.insertOne(record);
472
- } catch (error) {
473
- this.logger.error(`Error upserting into table ${tableName}: ${error}`);
474
- throw error;
640
+ } catch (error$1) {
641
+ if (error$1 instanceof Error) {
642
+ const matstraError = new error.MastraError(
643
+ {
644
+ id: "STORAGE_MONGODB_STORE_INSERT_FAILED",
645
+ domain: error.ErrorDomain.STORAGE,
646
+ category: error.ErrorCategory.THIRD_PARTY,
647
+ details: { tableName }
648
+ },
649
+ error$1
650
+ );
651
+ this.logger.error(matstraError.message);
652
+ this.logger?.trackException(matstraError);
653
+ }
475
654
  }
476
655
  }
477
656
  async batchInsert({ tableName, records }) {
@@ -481,9 +660,16 @@ var MongoDBStore = class extends storage.MastraStorage {
481
660
  try {
482
661
  const collection = await this.getCollection(tableName);
483
662
  await collection.insertMany(records);
484
- } catch (error) {
485
- this.logger.error(`Error upserting into table ${tableName}: ${error}`);
486
- throw error;
663
+ } catch (error$1) {
664
+ throw new error.MastraError(
665
+ {
666
+ id: "STORAGE_MONGODB_STORE_BATCH_INSERT_FAILED",
667
+ domain: error.ErrorDomain.STORAGE,
668
+ category: error.ErrorCategory.THIRD_PARTY,
669
+ details: { tableName }
670
+ },
671
+ error$1
672
+ );
487
673
  }
488
674
  }
489
675
  async load({ tableName, keys }) {
@@ -491,9 +677,16 @@ var MongoDBStore = class extends storage.MastraStorage {
491
677
  try {
492
678
  const collection = await this.getCollection(tableName);
493
679
  return await collection.find(keys).toArray();
494
- } catch (error) {
495
- this.logger.error(`Error loading ${tableName} with keys ${JSON.stringify(keys)}: ${error}`);
496
- throw error;
680
+ } catch (error$1) {
681
+ throw new error.MastraError(
682
+ {
683
+ id: "STORAGE_MONGODB_STORE_LOAD_FAILED",
684
+ domain: error.ErrorDomain.STORAGE,
685
+ category: error.ErrorCategory.THIRD_PARTY,
686
+ details: { tableName }
687
+ },
688
+ error$1
689
+ );
497
690
  }
498
691
  }
499
692
  async getThreadById({ threadId }) {
@@ -507,9 +700,16 @@ var MongoDBStore = class extends storage.MastraStorage {
507
700
  ...result,
508
701
  metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
509
702
  };
510
- } catch (error) {
511
- this.logger.error(`Error loading thread with ID ${threadId}: ${error}`);
512
- throw error;
703
+ } catch (error$1) {
704
+ throw new error.MastraError(
705
+ {
706
+ id: "STORAGE_MONGODB_STORE_GET_THREAD_BY_ID_FAILED",
707
+ domain: error.ErrorDomain.STORAGE,
708
+ category: error.ErrorCategory.THIRD_PARTY,
709
+ details: { threadId }
710
+ },
711
+ error$1
712
+ );
513
713
  }
514
714
  }
515
715
  async getThreadsByResourceId({ resourceId }) {
@@ -523,9 +723,16 @@ var MongoDBStore = class extends storage.MastraStorage {
523
723
  ...result,
524
724
  metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
525
725
  }));
526
- } catch (error) {
527
- this.logger.error(`Error loading threads by resourceId ${resourceId}: ${error}`);
528
- throw error;
726
+ } catch (error$1) {
727
+ throw new error.MastraError(
728
+ {
729
+ id: "STORAGE_MONGODB_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
730
+ domain: error.ErrorDomain.STORAGE,
731
+ category: error.ErrorCategory.THIRD_PARTY,
732
+ details: { resourceId }
733
+ },
734
+ error$1
735
+ );
529
736
  }
530
737
  }
531
738
  async saveThread({ thread }) {
@@ -542,9 +749,16 @@ var MongoDBStore = class extends storage.MastraStorage {
542
749
  { upsert: true }
543
750
  );
544
751
  return thread;
545
- } catch (error) {
546
- this.logger.error(`Error saving thread ${thread.id}: ${error}`);
547
- throw error;
752
+ } catch (error$1) {
753
+ throw new error.MastraError(
754
+ {
755
+ id: "STORAGE_MONGODB_STORE_SAVE_THREAD_FAILED",
756
+ domain: error.ErrorDomain.STORAGE,
757
+ category: error.ErrorCategory.THIRD_PARTY,
758
+ details: { threadId: thread.id }
759
+ },
760
+ error$1
761
+ );
548
762
  }
549
763
  }
550
764
  async updateThread({
@@ -554,7 +768,13 @@ var MongoDBStore = class extends storage.MastraStorage {
554
768
  }) {
555
769
  const thread = await this.getThreadById({ threadId: id });
556
770
  if (!thread) {
557
- throw new Error(`Thread ${id} not found`);
771
+ throw new error.MastraError({
772
+ id: "STORAGE_MONGODB_STORE_UPDATE_THREAD_NOT_FOUND",
773
+ domain: error.ErrorDomain.STORAGE,
774
+ category: error.ErrorCategory.THIRD_PARTY,
775
+ details: { threadId: id },
776
+ text: `Thread ${id} not found`
777
+ });
558
778
  }
559
779
  const updatedThread = {
560
780
  ...thread,
@@ -575,9 +795,16 @@ var MongoDBStore = class extends storage.MastraStorage {
575
795
  }
576
796
  }
577
797
  );
578
- } catch (error) {
579
- this.logger.error(`Error updating thread ${id}:) ${error}`);
580
- throw error;
798
+ } catch (error$1) {
799
+ throw new error.MastraError(
800
+ {
801
+ id: "STORAGE_MONGODB_STORE_UPDATE_THREAD_FAILED",
802
+ domain: error.ErrorDomain.STORAGE,
803
+ category: error.ErrorCategory.THIRD_PARTY,
804
+ details: { threadId: id }
805
+ },
806
+ error$1
807
+ );
581
808
  }
582
809
  return updatedThread;
583
810
  }
@@ -587,9 +814,16 @@ var MongoDBStore = class extends storage.MastraStorage {
587
814
  await collectionMessages.deleteMany({ thread_id: threadId });
588
815
  const collectionThreads = await this.getCollection(storage.TABLE_THREADS);
589
816
  await collectionThreads.deleteOne({ id: threadId });
590
- } catch (error) {
591
- this.logger.error(`Error deleting thread ${threadId}: ${error}`);
592
- throw error;
817
+ } catch (error$1) {
818
+ throw new error.MastraError(
819
+ {
820
+ id: "STORAGE_MONGODB_STORE_DELETE_THREAD_FAILED",
821
+ domain: error.ErrorDomain.STORAGE,
822
+ category: error.ErrorCategory.THIRD_PARTY,
823
+ details: { threadId }
824
+ },
825
+ error$1
826
+ );
593
827
  }
594
828
  }
595
829
  async getMessages({
@@ -598,7 +832,7 @@ var MongoDBStore = class extends storage.MastraStorage {
598
832
  format
599
833
  }) {
600
834
  try {
601
- const limit = typeof selectBy?.last === "number" ? selectBy.last : 40;
835
+ const limit = this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
602
836
  const include = selectBy?.include || [];
603
837
  let messages = [];
604
838
  let allMessages = [];
@@ -638,9 +872,16 @@ var MongoDBStore = class extends storage.MastraStorage {
638
872
  const list = new agent.MessageList().add(messages.slice(0, limit), "memory");
639
873
  if (format === `v2`) return list.get.all.v2();
640
874
  return list.get.all.v1();
641
- } catch (error) {
642
- this.logger.error("Error getting messages:", error);
643
- throw error;
875
+ } catch (error$1) {
876
+ throw new error.MastraError(
877
+ {
878
+ id: "STORAGE_MONGODB_STORE_GET_MESSAGES_FAILED",
879
+ domain: error.ErrorDomain.STORAGE,
880
+ category: error.ErrorCategory.THIRD_PARTY,
881
+ details: { threadId }
882
+ },
883
+ error$1
884
+ );
644
885
  }
645
886
  }
646
887
  async saveMessages({
@@ -671,7 +912,15 @@ var MongoDBStore = class extends storage.MastraStorage {
671
912
  const collection = await this.getCollection(storage.TABLE_MESSAGES);
672
913
  const threadsCollection = await this.getCollection(storage.TABLE_THREADS);
673
914
  await Promise.all([
674
- collection.insertMany(messagesToInsert),
915
+ collection.bulkWrite(
916
+ messagesToInsert.map((msg) => ({
917
+ updateOne: {
918
+ filter: { id: msg.id },
919
+ update: { $set: msg },
920
+ upsert: true
921
+ }
922
+ }))
923
+ ),
675
924
  threadsCollection.updateOne({ id: threadId }, { $set: { updatedAt: /* @__PURE__ */ new Date() } })
676
925
  ]);
677
926
  const list = new agent.MessageList().add(messages, "memory");
@@ -697,41 +946,52 @@ var MongoDBStore = class extends storage.MastraStorage {
697
946
  const offset = page * perPage;
698
947
  const query = {};
699
948
  if (name) {
700
- query["name"] = `%${name}%`;
949
+ query["name"] = new RegExp(name);
701
950
  }
702
951
  if (scope) {
703
952
  query["scope"] = scope;
704
953
  }
705
954
  if (attributes) {
706
- Object.keys(attributes).forEach((key) => {
707
- query[`attributes.${key}`] = attributes[key];
708
- });
955
+ query["$and"] = Object.entries(attributes).map(([key, value]) => ({
956
+ attributes: new RegExp(`"${key}":"${value}"`)
957
+ }));
709
958
  }
710
959
  if (filters) {
711
960
  Object.entries(filters).forEach(([key, value]) => {
712
961
  query[key] = value;
713
962
  });
714
963
  }
715
- const collection = await this.getCollection(storage.TABLE_TRACES);
716
- const result = await collection.find(query, {
717
- sort: { startTime: -1 }
718
- }).limit(limit).skip(offset).toArray();
719
- return result.map((row) => ({
720
- id: row.id,
721
- parentSpanId: row.parentSpanId,
722
- traceId: row.traceId,
723
- name: row.name,
724
- scope: row.scope,
725
- kind: row.kind,
726
- status: safelyParseJSON(row.status),
727
- events: safelyParseJSON(row.events),
728
- links: safelyParseJSON(row.links),
729
- attributes: safelyParseJSON(row.attributes),
730
- startTime: row.startTime,
731
- endTime: row.endTime,
732
- other: safelyParseJSON(row.other),
733
- createdAt: row.createdAt
734
- }));
964
+ try {
965
+ const collection = await this.getCollection(storage.TABLE_TRACES);
966
+ const result = await collection.find(query, {
967
+ sort: { startTime: -1 }
968
+ }).limit(limit).skip(offset).toArray();
969
+ return result.map((row) => ({
970
+ id: row.id,
971
+ parentSpanId: row.parentSpanId,
972
+ traceId: row.traceId,
973
+ name: row.name,
974
+ scope: row.scope,
975
+ kind: row.kind,
976
+ status: safelyParseJSON(row.status),
977
+ events: safelyParseJSON(row.events),
978
+ links: safelyParseJSON(row.links),
979
+ attributes: safelyParseJSON(row.attributes),
980
+ startTime: row.startTime,
981
+ endTime: row.endTime,
982
+ other: safelyParseJSON(row.other),
983
+ createdAt: row.createdAt
984
+ }));
985
+ } catch (error$1) {
986
+ throw new error.MastraError(
987
+ {
988
+ id: "STORAGE_MONGODB_STORE_GET_TRACES_FAILED",
989
+ domain: error.ErrorDomain.STORAGE,
990
+ category: error.ErrorCategory.THIRD_PARTY
991
+ },
992
+ error$1
993
+ );
994
+ }
735
995
  }
736
996
  async getWorkflowRuns({
737
997
  workflowName,
@@ -753,37 +1013,48 @@ var MongoDBStore = class extends storage.MastraStorage {
753
1013
  query["createdAt"]["$lte"] = toDate;
754
1014
  }
755
1015
  }
756
- const collection = await this.getCollection(storage.TABLE_WORKFLOW_SNAPSHOT);
757
- let total = 0;
758
- if (limit !== void 0 && offset !== void 0) {
759
- total = await collection.countDocuments(query);
760
- }
761
- const request = collection.find(query).sort({ createdAt: "desc" });
762
- if (limit) {
763
- request.limit(limit);
764
- }
765
- if (offset) {
766
- request.skip(offset);
767
- }
768
- const result = await request.toArray();
769
- const runs = result.map((row) => {
770
- let parsedSnapshot = row.snapshot;
771
- if (typeof parsedSnapshot === "string") {
772
- try {
773
- parsedSnapshot = JSON.parse(row.snapshot);
774
- } catch (e) {
775
- console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
776
- }
1016
+ try {
1017
+ const collection = await this.getCollection(storage.TABLE_WORKFLOW_SNAPSHOT);
1018
+ let total = 0;
1019
+ if (limit !== void 0 && offset !== void 0) {
1020
+ total = await collection.countDocuments(query);
777
1021
  }
778
- return {
779
- workflowName: row.workflow_name,
780
- runId: row.run_id,
781
- snapshot: parsedSnapshot,
782
- createdAt: new Date(row.createdAt),
783
- updatedAt: new Date(row.updatedAt)
784
- };
785
- });
786
- return { runs, total: total || runs.length };
1022
+ const request = collection.find(query).sort({ createdAt: "desc" });
1023
+ if (limit) {
1024
+ request.limit(limit);
1025
+ }
1026
+ if (offset) {
1027
+ request.skip(offset);
1028
+ }
1029
+ const result = await request.toArray();
1030
+ const runs = result.map((row) => {
1031
+ let parsedSnapshot = row.snapshot;
1032
+ if (typeof parsedSnapshot === "string") {
1033
+ try {
1034
+ parsedSnapshot = JSON.parse(row.snapshot);
1035
+ } catch (e) {
1036
+ console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
1037
+ }
1038
+ }
1039
+ return {
1040
+ workflowName: row.workflow_name,
1041
+ runId: row.run_id,
1042
+ snapshot: parsedSnapshot,
1043
+ createdAt: new Date(row.createdAt),
1044
+ updatedAt: new Date(row.updatedAt)
1045
+ };
1046
+ });
1047
+ return { runs, total: total || runs.length };
1048
+ } catch (error$1) {
1049
+ throw new error.MastraError(
1050
+ {
1051
+ id: "STORAGE_MONGODB_STORE_GET_WORKFLOW_RUNS_FAILED",
1052
+ domain: error.ErrorDomain.STORAGE,
1053
+ category: error.ErrorCategory.THIRD_PARTY
1054
+ },
1055
+ error$1
1056
+ );
1057
+ }
787
1058
  }
788
1059
  async getEvalsByAgentName(agentName, type) {
789
1060
  try {
@@ -808,12 +1079,19 @@ var MongoDBStore = class extends storage.MastraStorage {
808
1079
  }
809
1080
  return true;
810
1081
  });
811
- } catch (error) {
812
- if (error instanceof Error && error.message.includes("no such table")) {
1082
+ } catch (error$1) {
1083
+ if (error$1 instanceof Error && error$1.message.includes("no such table")) {
813
1084
  return [];
814
1085
  }
815
- this.logger.error("Failed to get evals for the specified agent: " + error?.message);
816
- throw error;
1086
+ throw new error.MastraError(
1087
+ {
1088
+ id: "STORAGE_MONGODB_STORE_GET_EVALS_BY_AGENT_NAME_FAILED",
1089
+ domain: error.ErrorDomain.STORAGE,
1090
+ category: error.ErrorCategory.THIRD_PARTY,
1091
+ details: { agentName }
1092
+ },
1093
+ error$1
1094
+ );
817
1095
  }
818
1096
  }
819
1097
  async persistWorkflowSnapshot({
@@ -837,9 +1115,16 @@ var MongoDBStore = class extends storage.MastraStorage {
837
1115
  },
838
1116
  { upsert: true }
839
1117
  );
840
- } catch (error) {
841
- this.logger.error(`Error persisting workflow snapshot: ${error}`);
842
- throw error;
1118
+ } catch (error$1) {
1119
+ throw new error.MastraError(
1120
+ {
1121
+ id: "STORAGE_MONGODB_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
1122
+ domain: error.ErrorDomain.STORAGE,
1123
+ category: error.ErrorCategory.THIRD_PARTY,
1124
+ details: { workflowName, runId }
1125
+ },
1126
+ error$1
1127
+ );
843
1128
  }
844
1129
  }
845
1130
  async loadWorkflowSnapshot({
@@ -858,9 +1143,16 @@ var MongoDBStore = class extends storage.MastraStorage {
858
1143
  return null;
859
1144
  }
860
1145
  return JSON.parse(result[0].snapshot);
861
- } catch (error) {
862
- console.error("Error loading workflow snapshot:", error);
863
- throw error;
1146
+ } catch (error$1) {
1147
+ throw new error.MastraError(
1148
+ {
1149
+ id: "STORAGE_MONGODB_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
1150
+ domain: error.ErrorDomain.STORAGE,
1151
+ category: error.ErrorCategory.THIRD_PARTY,
1152
+ details: { workflowName, runId }
1153
+ },
1154
+ error$1
1155
+ );
864
1156
  }
865
1157
  }
866
1158
  async getWorkflowRunById({
@@ -881,9 +1173,16 @@ var MongoDBStore = class extends storage.MastraStorage {
881
1173
  return null;
882
1174
  }
883
1175
  return this.parseWorkflowRun(result);
884
- } catch (error) {
885
- console.error("Error getting workflow run by ID:", error);
886
- throw error;
1176
+ } catch (error$1) {
1177
+ throw new error.MastraError(
1178
+ {
1179
+ id: "STORAGE_MONGODB_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
1180
+ domain: error.ErrorDomain.STORAGE,
1181
+ category: error.ErrorCategory.THIRD_PARTY,
1182
+ details: { runId }
1183
+ },
1184
+ error$1
1185
+ );
887
1186
  }
888
1187
  }
889
1188
  parseWorkflowRun(row) {
@@ -929,10 +1228,19 @@ var MongoDBStore = class extends storage.MastraStorage {
929
1228
  console.warn("Failed to parse test_info:", e);
930
1229
  }
931
1230
  }
1231
+ const resultValue = JSON.parse(row.result);
1232
+ if (!resultValue || typeof resultValue !== "object" || !("score" in resultValue)) {
1233
+ throw new error.MastraError({
1234
+ id: "STORAGE_MONGODB_STORE_INVALID_METRIC_FORMAT",
1235
+ text: `Invalid MetricResult format: ${JSON.stringify(resultValue)}`,
1236
+ domain: error.ErrorDomain.STORAGE,
1237
+ category: error.ErrorCategory.USER
1238
+ });
1239
+ }
932
1240
  return {
933
1241
  input: row.input,
934
1242
  output: row.output,
935
- result: row.result,
1243
+ result: resultValue,
936
1244
  agentName: row.agent_name,
937
1245
  metricName: row.metric_name,
938
1246
  instructions: row.instructions,
@@ -943,16 +1251,42 @@ var MongoDBStore = class extends storage.MastraStorage {
943
1251
  };
944
1252
  }
945
1253
  async getTracesPaginated(_args) {
946
- throw new Error("Method not implemented.");
1254
+ throw new error.MastraError({
1255
+ id: "STORAGE_MONGODB_STORE_GET_TRACES_PAGINATED_FAILED",
1256
+ domain: error.ErrorDomain.STORAGE,
1257
+ category: error.ErrorCategory.THIRD_PARTY,
1258
+ text: "Method not implemented."
1259
+ });
947
1260
  }
948
1261
  async getThreadsByResourceIdPaginated(_args) {
949
- throw new Error("Method not implemented.");
1262
+ throw new error.MastraError({
1263
+ id: "STORAGE_MONGODB_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
1264
+ domain: error.ErrorDomain.STORAGE,
1265
+ category: error.ErrorCategory.THIRD_PARTY,
1266
+ text: "Method not implemented."
1267
+ });
950
1268
  }
951
1269
  async getMessagesPaginated(_args) {
952
- throw new Error("Method not implemented.");
1270
+ throw new error.MastraError({
1271
+ id: "STORAGE_MONGODB_STORE_GET_MESSAGES_PAGINATED_FAILED",
1272
+ domain: error.ErrorDomain.STORAGE,
1273
+ category: error.ErrorCategory.THIRD_PARTY,
1274
+ text: "Method not implemented."
1275
+ });
953
1276
  }
954
1277
  async close() {
955
- await this.#client.close();
1278
+ try {
1279
+ await this.#client.close();
1280
+ } catch (error$1) {
1281
+ throw new error.MastraError(
1282
+ {
1283
+ id: "STORAGE_MONGODB_STORE_CLOSE_FAILED",
1284
+ domain: error.ErrorDomain.STORAGE,
1285
+ category: error.ErrorCategory.USER
1286
+ },
1287
+ error$1
1288
+ );
1289
+ }
956
1290
  }
957
1291
  async updateMessages(_args) {
958
1292
  this.logger.error("updateMessages is not yet implemented in MongoDBStore");