@mastra/mongodb 0.0.0-vnext-inngest-20250508122351 → 0.0.0-vnext-20251104230439

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.
Files changed (49) hide show
  1. package/CHANGELOG.md +1150 -2
  2. package/LICENSE.md +11 -42
  3. package/README.md +50 -0
  4. package/dist/index.cjs +2504 -139
  5. package/dist/index.cjs.map +1 -0
  6. package/dist/index.d.ts +5 -7
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +2500 -136
  9. package/dist/index.js.map +1 -0
  10. package/dist/storage/connectors/MongoDBConnector.d.ts +23 -0
  11. package/dist/storage/connectors/MongoDBConnector.d.ts.map +1 -0
  12. package/dist/storage/connectors/base.d.ts +6 -0
  13. package/dist/storage/connectors/base.d.ts.map +1 -0
  14. package/dist/storage/domains/memory/index.d.ts +66 -0
  15. package/dist/storage/domains/memory/index.d.ts.map +1 -0
  16. package/dist/storage/domains/observability/index.d.ts +43 -0
  17. package/dist/storage/domains/observability/index.d.ts.map +1 -0
  18. package/dist/storage/domains/operations/index.d.ts +50 -0
  19. package/dist/storage/domains/operations/index.d.ts.map +1 -0
  20. package/dist/storage/domains/scores/index.d.ts +50 -0
  21. package/dist/storage/domains/scores/index.d.ts.map +1 -0
  22. package/dist/storage/domains/utils.d.ts +8 -0
  23. package/dist/storage/domains/utils.d.ts.map +1 -0
  24. package/dist/storage/domains/workflows/index.d.ts +45 -0
  25. package/dist/storage/domains/workflows/index.d.ts.map +1 -0
  26. package/dist/storage/index.d.ts +201 -0
  27. package/dist/storage/index.d.ts.map +1 -0
  28. package/dist/storage/types.d.ts +11 -0
  29. package/dist/storage/types.d.ts.map +1 -0
  30. package/dist/vector/filter.d.ts +21 -0
  31. package/dist/vector/filter.d.ts.map +1 -0
  32. package/dist/vector/index.d.ts +93 -0
  33. package/dist/vector/index.d.ts.map +1 -0
  34. package/dist/vector/prompt.d.ts +6 -0
  35. package/dist/vector/prompt.d.ts.map +1 -0
  36. package/package.json +34 -16
  37. package/dist/_tsup-dts-rollup.d.cts +0 -96
  38. package/dist/_tsup-dts-rollup.d.ts +0 -96
  39. package/dist/index.d.cts +0 -7
  40. package/docker-compose.yml +0 -8
  41. package/eslint.config.js +0 -6
  42. package/src/index.ts +0 -2
  43. package/src/vector/filter.test.ts +0 -410
  44. package/src/vector/filter.ts +0 -122
  45. package/src/vector/index.test.ts +0 -459
  46. package/src/vector/index.ts +0 -380
  47. package/src/vector/prompt.ts +0 -97
  48. package/tsconfig.json +0 -5
  49. package/vitest.config.ts +0 -11
package/dist/index.cjs CHANGED
@@ -1,11 +1,19 @@
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');
6
7
  var filter = require('@mastra/core/vector/filter');
8
+ var storage = require('@mastra/core/storage');
9
+ var agent = require('@mastra/core/agent');
10
+ var evals = require('@mastra/core/evals');
7
11
 
8
12
  // src/vector/index.ts
13
+
14
+ // package.json
15
+ var package_default = {
16
+ version: "0.14.6"};
9
17
  var MongoDBFilterTranslator = class extends filter.BaseFilterTranslator {
10
18
  getSupportedOperators() {
11
19
  return {
@@ -110,35 +118,81 @@ var MongoDBVector = class extends vector.MastraVector {
110
118
  };
111
119
  constructor({ uri, dbName, options }) {
112
120
  super();
113
- this.client = new mongodb.MongoClient(uri, options);
121
+ const client = new mongodb.MongoClient(uri, {
122
+ ...options,
123
+ driverInfo: {
124
+ name: "mastra-vector",
125
+ version: package_default.version
126
+ }
127
+ });
128
+ this.client = client;
114
129
  this.db = this.client.db(dbName);
115
130
  this.collections = /* @__PURE__ */ new Map();
116
131
  }
117
132
  // Public methods
118
133
  async connect() {
119
- await this.client.connect();
134
+ try {
135
+ await this.client.connect();
136
+ } catch (error$1) {
137
+ throw new error.MastraError(
138
+ {
139
+ id: "STORAGE_MONGODB_VECTOR_CONNECT_FAILED",
140
+ domain: error.ErrorDomain.STORAGE,
141
+ category: error.ErrorCategory.THIRD_PARTY
142
+ },
143
+ error$1
144
+ );
145
+ }
120
146
  }
121
147
  async disconnect() {
122
- await this.client.close();
123
- }
124
- async createIndex(params) {
125
- const { indexName, dimension, metric = "cosine" } = params;
126
- if (!Number.isInteger(dimension) || dimension <= 0) {
127
- throw new Error("Dimension must be a positive integer");
128
- }
129
- const mongoMetric = this.mongoMetricMap[metric];
130
- if (!mongoMetric) {
131
- throw new Error(`Invalid metric: "${metric}". Must be one of: cosine, euclidean, dotproduct`);
148
+ try {
149
+ await this.client.close();
150
+ } catch (error$1) {
151
+ throw new error.MastraError(
152
+ {
153
+ id: "STORAGE_MONGODB_VECTOR_DISCONNECT_FAILED",
154
+ domain: error.ErrorDomain.STORAGE,
155
+ category: error.ErrorCategory.THIRD_PARTY
156
+ },
157
+ error$1
158
+ );
132
159
  }
133
- const collectionExists = await this.db.listCollections({ name: indexName }).hasNext();
134
- if (!collectionExists) {
135
- await this.db.createCollection(indexName);
160
+ }
161
+ async createIndex({ indexName, dimension, metric = "cosine" }) {
162
+ let mongoMetric;
163
+ try {
164
+ if (!Number.isInteger(dimension) || dimension <= 0) {
165
+ throw new Error("Dimension must be a positive integer");
166
+ }
167
+ mongoMetric = this.mongoMetricMap[metric];
168
+ if (!mongoMetric) {
169
+ throw new Error(`Invalid metric: "${metric}". Must be one of: cosine, euclidean, dotproduct`);
170
+ }
171
+ } catch (error$1) {
172
+ throw new error.MastraError(
173
+ {
174
+ id: "STORAGE_MONGODB_VECTOR_CREATE_INDEX_INVALID_ARGS",
175
+ domain: error.ErrorDomain.STORAGE,
176
+ category: error.ErrorCategory.USER,
177
+ details: {
178
+ indexName,
179
+ dimension,
180
+ metric
181
+ }
182
+ },
183
+ error$1
184
+ );
136
185
  }
137
- const collection = await this.getCollection(indexName);
138
- const indexNameInternal = `${indexName}_vector_index`;
139
- const embeddingField = this.embeddingFieldName;
140
- const numDimensions = dimension;
186
+ let collection;
141
187
  try {
188
+ const collectionExists = await this.db.listCollections({ name: indexName }).hasNext();
189
+ if (!collectionExists) {
190
+ await this.db.createCollection(indexName);
191
+ }
192
+ collection = await this.getCollection(indexName);
193
+ const indexNameInternal = `${indexName}_vector_index`;
194
+ const embeddingField = this.embeddingFieldName;
195
+ const numDimensions = dimension;
142
196
  await collection.createSearchIndex({
143
197
  definition: {
144
198
  fields: [
@@ -147,20 +201,66 @@ var MongoDBVector = class extends vector.MastraVector {
147
201
  path: embeddingField,
148
202
  numDimensions,
149
203
  similarity: mongoMetric
204
+ },
205
+ {
206
+ type: "filter",
207
+ path: "_id"
150
208
  }
151
209
  ]
152
210
  },
153
211
  name: indexNameInternal,
154
212
  type: "vectorSearch"
155
213
  });
156
- } catch (error) {
157
- if (error.codeName !== "IndexAlreadyExists") {
158
- throw error;
214
+ await collection.createSearchIndex({
215
+ definition: {
216
+ mappings: {
217
+ dynamic: true
218
+ }
219
+ },
220
+ name: `${indexName}_search_index`,
221
+ type: "search"
222
+ });
223
+ } catch (error$1) {
224
+ if (error$1.codeName !== "IndexAlreadyExists") {
225
+ throw new error.MastraError(
226
+ {
227
+ id: "STORAGE_MONGODB_VECTOR_CREATE_INDEX_FAILED",
228
+ domain: error.ErrorDomain.STORAGE,
229
+ category: error.ErrorCategory.THIRD_PARTY
230
+ },
231
+ error$1
232
+ );
159
233
  }
160
234
  }
161
- await collection.updateOne({ _id: "__index_metadata__" }, { $set: { dimension, metric } }, { upsert: true });
235
+ try {
236
+ await collection?.updateOne({ _id: "__index_metadata__" }, { $set: { dimension, metric } }, { upsert: true });
237
+ } catch (error$1) {
238
+ throw new error.MastraError(
239
+ {
240
+ id: "STORAGE_MONGODB_VECTOR_CREATE_INDEX_FAILED_STORE_METADATA",
241
+ domain: error.ErrorDomain.STORAGE,
242
+ category: error.ErrorCategory.THIRD_PARTY,
243
+ details: {
244
+ indexName
245
+ }
246
+ },
247
+ error$1
248
+ );
249
+ }
162
250
  }
163
- async waitForIndexReady(indexName, timeoutMs = 6e4, checkIntervalMs = 2e3) {
251
+ /**
252
+ * Waits for the index to be ready.
253
+ *
254
+ * @param {string} indexName - The name of the index to wait for
255
+ * @param {number} timeoutMs - The maximum time in milliseconds to wait for the index to be ready (default: 60000)
256
+ * @param {number} checkIntervalMs - The interval in milliseconds at which to check if the index is ready (default: 2000)
257
+ * @returns A promise that resolves when the index is ready
258
+ */
259
+ async waitForIndexReady({
260
+ indexName,
261
+ timeoutMs = 6e4,
262
+ checkIntervalMs = 2e3
263
+ }) {
164
264
  const collection = await this.getCollection(indexName, true);
165
265
  const indexNameInternal = `${indexName}_vector_index`;
166
266
  const startTime = Date.now();
@@ -175,83 +275,110 @@ var MongoDBVector = class extends vector.MastraVector {
175
275
  }
176
276
  throw new Error(`Index "${indexNameInternal}" did not become ready within timeout`);
177
277
  }
178
- async upsert(params) {
179
- const { indexName, vectors, metadata, ids, documents } = params;
180
- const collection = await this.getCollection(indexName);
181
- this.collectionForValidation = collection;
182
- const stats = await this.describeIndex(indexName);
183
- await this.validateVectorDimensions(vectors, stats.dimension);
184
- const generatedIds = ids || vectors.map(() => uuid.v4());
185
- const operations = vectors.map((vector, idx) => {
186
- const id = generatedIds[idx];
187
- const meta = metadata?.[idx] || {};
188
- const doc = documents?.[idx];
189
- const normalizedMeta = Object.keys(meta).reduce(
190
- (acc, key) => {
191
- acc[key] = meta[key] instanceof Date ? meta[key].toISOString() : meta[key];
192
- return acc;
193
- },
194
- {}
195
- );
196
- const updateDoc = {
197
- [this.embeddingFieldName]: vector,
198
- [this.metadataFieldName]: normalizedMeta
199
- };
200
- if (doc !== void 0) {
201
- updateDoc[this.documentFieldName] = doc;
202
- }
203
- return {
204
- updateOne: {
205
- filter: { _id: id },
206
- // '_id' is a string as per MongoDBDocument interface
207
- update: { $set: updateDoc },
208
- upsert: true
278
+ async upsert({ indexName, vectors, metadata, ids, documents }) {
279
+ try {
280
+ const collection = await this.getCollection(indexName);
281
+ this.collectionForValidation = collection;
282
+ const stats = await this.describeIndex({ indexName });
283
+ await this.validateVectorDimensions(vectors, stats.dimension);
284
+ const generatedIds = ids || vectors.map(() => uuid.v4());
285
+ const operations = vectors.map((vector, idx) => {
286
+ const id = generatedIds[idx];
287
+ const meta = metadata?.[idx] || {};
288
+ const doc = documents?.[idx];
289
+ const normalizedMeta = Object.keys(meta).reduce(
290
+ (acc, key) => {
291
+ acc[key] = meta[key] instanceof Date ? meta[key].toISOString() : meta[key];
292
+ return acc;
293
+ },
294
+ {}
295
+ );
296
+ const updateDoc = {
297
+ [this.embeddingFieldName]: vector,
298
+ [this.metadataFieldName]: normalizedMeta
299
+ };
300
+ if (doc !== void 0) {
301
+ updateDoc[this.documentFieldName] = doc;
209
302
  }
210
- };
211
- });
212
- await collection.bulkWrite(operations);
213
- return generatedIds;
303
+ return {
304
+ updateOne: {
305
+ filter: { _id: id },
306
+ // '_id' is a string as per MongoDBDocument interface
307
+ update: { $set: updateDoc },
308
+ upsert: true
309
+ }
310
+ };
311
+ });
312
+ await collection.bulkWrite(operations);
313
+ return generatedIds;
314
+ } catch (error$1) {
315
+ throw new error.MastraError(
316
+ {
317
+ id: "STORAGE_MONGODB_VECTOR_UPSERT_FAILED",
318
+ domain: error.ErrorDomain.STORAGE,
319
+ category: error.ErrorCategory.THIRD_PARTY,
320
+ details: {
321
+ indexName
322
+ }
323
+ },
324
+ error$1
325
+ );
326
+ }
214
327
  }
215
- async query(params) {
216
- const { indexName, queryVector, topK = 10, filter, includeVector = false, documentFilter } = params;
217
- const collection = await this.getCollection(indexName, true);
218
- const indexNameInternal = `${indexName}_vector_index`;
219
- const mongoFilter = this.transformFilter(filter);
220
- const documentMongoFilter = documentFilter ? { [this.documentFieldName]: documentFilter } : {};
221
- let combinedFilter = {};
222
- if (Object.keys(mongoFilter).length > 0 && Object.keys(documentMongoFilter).length > 0) {
223
- combinedFilter = { $and: [mongoFilter, documentMongoFilter] };
224
- } else if (Object.keys(mongoFilter).length > 0) {
225
- combinedFilter = mongoFilter;
226
- } else if (Object.keys(documentMongoFilter).length > 0) {
227
- combinedFilter = documentMongoFilter;
228
- }
229
- const pipeline = [
230
- {
231
- $vectorSearch: {
232
- index: indexNameInternal,
233
- queryVector,
234
- path: this.embeddingFieldName,
235
- numCandidates: 100,
236
- limit: topK
237
- }
238
- },
239
- // Apply the filter using $match stage
240
- ...Object.keys(combinedFilter).length > 0 ? [{ $match: combinedFilter }] : [],
241
- {
242
- $set: { score: { $meta: "vectorSearchScore" } }
243
- },
244
- {
245
- $project: {
246
- _id: 1,
247
- score: 1,
248
- metadata: `$${this.metadataFieldName}`,
249
- document: `$${this.documentFieldName}`,
250
- ...includeVector && { vector: `$${this.embeddingFieldName}` }
328
+ async query({
329
+ indexName,
330
+ queryVector,
331
+ topK = 10,
332
+ filter,
333
+ includeVector = false,
334
+ documentFilter
335
+ }) {
336
+ try {
337
+ const collection = await this.getCollection(indexName, true);
338
+ const indexNameInternal = `${indexName}_vector_index`;
339
+ const mongoFilter = this.transformFilter(filter);
340
+ const documentMongoFilter = documentFilter ? { [this.documentFieldName]: documentFilter } : {};
341
+ const transformedMongoFilter = this.transformMetadataFilter(mongoFilter);
342
+ let combinedFilter = {};
343
+ if (Object.keys(transformedMongoFilter).length > 0 && Object.keys(documentMongoFilter).length > 0) {
344
+ combinedFilter = { $and: [transformedMongoFilter, documentMongoFilter] };
345
+ } else if (Object.keys(transformedMongoFilter).length > 0) {
346
+ combinedFilter = transformedMongoFilter;
347
+ } else if (Object.keys(documentMongoFilter).length > 0) {
348
+ combinedFilter = documentMongoFilter;
349
+ }
350
+ const vectorSearch = {
351
+ index: indexNameInternal,
352
+ queryVector,
353
+ path: this.embeddingFieldName,
354
+ numCandidates: 100,
355
+ limit: topK
356
+ };
357
+ if (Object.keys(combinedFilter).length > 0) {
358
+ const candidateIds = await collection.aggregate([{ $match: combinedFilter }, { $project: { _id: 1 } }]).map((doc) => doc._id).toArray();
359
+ if (candidateIds.length > 0) {
360
+ vectorSearch.filter = { _id: { $in: candidateIds } };
361
+ } else {
362
+ return [];
251
363
  }
252
364
  }
253
- ];
254
- try {
365
+ const pipeline = [
366
+ {
367
+ $vectorSearch: vectorSearch
368
+ },
369
+ {
370
+ $set: { score: { $meta: "vectorSearchScore" } }
371
+ },
372
+ {
373
+ $project: {
374
+ _id: 1,
375
+ score: 1,
376
+ metadata: `$${this.metadataFieldName}`,
377
+ document: `$${this.documentFieldName}`,
378
+ ...includeVector && { vector: `$${this.embeddingFieldName}` }
379
+ }
380
+ }
381
+ ];
255
382
  const results = await collection.aggregate(pipeline).toArray();
256
383
  return results.map((result) => ({
257
384
  id: result._id,
@@ -260,63 +387,162 @@ var MongoDBVector = class extends vector.MastraVector {
260
387
  vector: includeVector ? result.vector : void 0,
261
388
  document: result.document
262
389
  }));
263
- } catch (error) {
264
- console.error("Error during vector search:", error);
265
- throw error;
390
+ } catch (error$1) {
391
+ throw new error.MastraError(
392
+ {
393
+ id: "STORAGE_MONGODB_VECTOR_QUERY_FAILED",
394
+ domain: error.ErrorDomain.STORAGE,
395
+ category: error.ErrorCategory.THIRD_PARTY,
396
+ details: {
397
+ indexName
398
+ }
399
+ },
400
+ error$1
401
+ );
266
402
  }
267
403
  }
268
404
  async listIndexes() {
269
- const collections = await this.db.listCollections().toArray();
270
- return collections.map((col) => col.name);
405
+ try {
406
+ const collections = await this.db.listCollections().toArray();
407
+ return collections.map((col) => col.name);
408
+ } catch (error$1) {
409
+ throw new error.MastraError(
410
+ {
411
+ id: "STORAGE_MONGODB_VECTOR_LIST_INDEXES_FAILED",
412
+ domain: error.ErrorDomain.STORAGE,
413
+ category: error.ErrorCategory.THIRD_PARTY
414
+ },
415
+ error$1
416
+ );
417
+ }
271
418
  }
272
- async describeIndex(indexName) {
273
- const collection = await this.getCollection(indexName, true);
274
- const count = await collection.countDocuments({ _id: { $ne: "__index_metadata__" } });
275
- const metadataDoc = await collection.findOne({ _id: "__index_metadata__" });
276
- const dimension = metadataDoc?.dimension || 0;
277
- const metric = metadataDoc?.metric || "cosine";
278
- return {
279
- dimension,
280
- count,
281
- metric
282
- };
419
+ /**
420
+ * Retrieves statistics about a vector index.
421
+ *
422
+ * @param {string} indexName - The name of the index to describe
423
+ * @returns A promise that resolves to the index statistics including dimension, count and metric
424
+ */
425
+ async describeIndex({ indexName }) {
426
+ try {
427
+ const collection = await this.getCollection(indexName, true);
428
+ const count = await collection.countDocuments({ _id: { $ne: "__index_metadata__" } });
429
+ const metadataDoc = await collection.findOne({ _id: "__index_metadata__" });
430
+ const dimension = metadataDoc?.dimension || 0;
431
+ const metric = metadataDoc?.metric || "cosine";
432
+ return {
433
+ dimension,
434
+ count,
435
+ metric
436
+ };
437
+ } catch (error$1) {
438
+ throw new error.MastraError(
439
+ {
440
+ id: "STORAGE_MONGODB_VECTOR_DESCRIBE_INDEX_FAILED",
441
+ domain: error.ErrorDomain.STORAGE,
442
+ category: error.ErrorCategory.THIRD_PARTY,
443
+ details: {
444
+ indexName
445
+ }
446
+ },
447
+ error$1
448
+ );
449
+ }
283
450
  }
284
- async deleteIndex(indexName) {
451
+ async deleteIndex({ indexName }) {
285
452
  const collection = await this.getCollection(indexName, false);
286
- if (collection) {
287
- await collection.drop();
288
- this.collections.delete(indexName);
289
- } else {
290
- throw new Error(`Index (Collection) "${indexName}" does not exist`);
453
+ try {
454
+ if (collection) {
455
+ await collection.drop();
456
+ this.collections.delete(indexName);
457
+ } else {
458
+ throw new Error(`Index (Collection) "${indexName}" does not exist`);
459
+ }
460
+ } catch (error$1) {
461
+ throw new error.MastraError(
462
+ {
463
+ id: "STORAGE_MONGODB_VECTOR_DELETE_INDEX_FAILED",
464
+ domain: error.ErrorDomain.STORAGE,
465
+ category: error.ErrorCategory.THIRD_PARTY,
466
+ details: {
467
+ indexName
468
+ }
469
+ },
470
+ error$1
471
+ );
291
472
  }
292
473
  }
293
- async updateIndexById(indexName, id, update) {
294
- if (!update.vector && !update.metadata) {
295
- throw new Error("No updates provided");
296
- }
297
- const collection = await this.getCollection(indexName, true);
298
- const updateDoc = {};
299
- if (update.vector) {
300
- updateDoc[this.embeddingFieldName] = update.vector;
301
- }
302
- if (update.metadata) {
303
- const normalizedMeta = Object.keys(update.metadata).reduce(
304
- (acc, key) => {
305
- acc[key] = update.metadata[key] instanceof Date ? update.metadata[key].toISOString() : update.metadata[key];
306
- return acc;
474
+ /**
475
+ * Updates a vector by its ID with the provided vector and/or metadata.
476
+ * @param indexName - The name of the index containing the vector.
477
+ * @param id - The ID of the vector to update.
478
+ * @param update - An object containing the vector and/or metadata to update.
479
+ * @param update.vector - An optional array of numbers representing the new vector.
480
+ * @param update.metadata - An optional record containing the new metadata.
481
+ * @returns A promise that resolves when the update is complete.
482
+ * @throws Will throw an error if no updates are provided or if the update operation fails.
483
+ */
484
+ async updateVector({ indexName, id, update }) {
485
+ try {
486
+ if (!update.vector && !update.metadata) {
487
+ throw new Error("No updates provided");
488
+ }
489
+ const collection = await this.getCollection(indexName, true);
490
+ const updateDoc = {};
491
+ if (update.vector) {
492
+ const stats = await this.describeIndex({ indexName });
493
+ await this.validateVectorDimensions([update.vector], stats.dimension);
494
+ updateDoc[this.embeddingFieldName] = update.vector;
495
+ }
496
+ if (update.metadata) {
497
+ const normalizedMeta = Object.keys(update.metadata).reduce(
498
+ (acc, key) => {
499
+ acc[key] = update.metadata[key] instanceof Date ? update.metadata[key].toISOString() : update.metadata[key];
500
+ return acc;
501
+ },
502
+ {}
503
+ );
504
+ updateDoc[this.metadataFieldName] = normalizedMeta;
505
+ }
506
+ await collection.findOneAndUpdate({ _id: id }, { $set: updateDoc });
507
+ } catch (error$1) {
508
+ throw new error.MastraError(
509
+ {
510
+ id: "STORAGE_MONGODB_VECTOR_UPDATE_VECTOR_FAILED",
511
+ domain: error.ErrorDomain.STORAGE,
512
+ category: error.ErrorCategory.THIRD_PARTY,
513
+ details: {
514
+ indexName,
515
+ id
516
+ }
307
517
  },
308
- {}
518
+ error$1
309
519
  );
310
- updateDoc[this.metadataFieldName] = normalizedMeta;
311
520
  }
312
- await collection.findOneAndUpdate({ _id: id }, { $set: updateDoc });
313
521
  }
314
- async deleteIndexById(indexName, id) {
522
+ /**
523
+ * Deletes a vector by its ID.
524
+ * @param indexName - The name of the index containing the vector.
525
+ * @param id - The ID of the vector to delete.
526
+ * @returns A promise that resolves when the deletion is complete.
527
+ * @throws Will throw an error if the deletion operation fails.
528
+ */
529
+ async deleteVector({ indexName, id }) {
315
530
  try {
316
531
  const collection = await this.getCollection(indexName, true);
317
532
  await collection.deleteOne({ _id: id });
318
- } catch (error) {
319
- throw new Error(`Failed to delete index by id: ${id} for index name: ${indexName}: ${error.message}`);
533
+ } catch (error$1) {
534
+ throw new error.MastraError(
535
+ {
536
+ id: "STORAGE_MONGODB_VECTOR_DELETE_VECTOR_FAILED",
537
+ domain: error.ErrorDomain.STORAGE,
538
+ category: error.ErrorCategory.THIRD_PARTY,
539
+ details: {
540
+ indexName,
541
+ id
542
+ }
543
+ },
544
+ error$1
545
+ );
320
546
  }
321
547
  }
322
548
  // Private methods
@@ -356,6 +582,2142 @@ var MongoDBVector = class extends vector.MastraVector {
356
582
  if (!filter) return {};
357
583
  return translator.translate(filter);
358
584
  }
585
+ /**
586
+ * Transform metadata field filters to use MongoDB dot notation.
587
+ * Fields that are stored in the metadata subdocument need to be prefixed with 'metadata.'
588
+ * This handles filters from the Memory system which expects direct field access.
589
+ *
590
+ * @param filter - The filter object to transform
591
+ * @returns Transformed filter with metadata fields properly prefixed
592
+ */
593
+ transformMetadataFilter(filter) {
594
+ if (!filter || typeof filter !== "object") return filter;
595
+ const transformed = {};
596
+ for (const [key, value] of Object.entries(filter)) {
597
+ if (key.startsWith("$")) {
598
+ if (Array.isArray(value)) {
599
+ transformed[key] = value.map((item) => this.transformMetadataFilter(item));
600
+ } else {
601
+ transformed[key] = this.transformMetadataFilter(value);
602
+ }
603
+ } else if (key.startsWith("metadata.")) {
604
+ transformed[key] = value;
605
+ } else if (this.isMetadataField(key)) {
606
+ transformed[`metadata.${key}`] = value;
607
+ } else {
608
+ transformed[key] = value;
609
+ }
610
+ }
611
+ return transformed;
612
+ }
613
+ /**
614
+ * Determine if a field should be treated as a metadata field.
615
+ * Common metadata fields include thread_id, resource_id, message_id, and any field
616
+ * that doesn't start with underscore (MongoDB system fields).
617
+ */
618
+ isMetadataField(key) {
619
+ if (key.startsWith("_")) return false;
620
+ const documentFields = ["_id", this.embeddingFieldName, this.documentFieldName];
621
+ if (documentFields.includes(key)) return false;
622
+ return true;
623
+ }
624
+ };
625
+ var MongoDBConnector = class _MongoDBConnector {
626
+ #client;
627
+ #dbName;
628
+ #handler;
629
+ #isConnected;
630
+ #db;
631
+ constructor(options) {
632
+ this.#client = options.client;
633
+ this.#dbName = options.dbName;
634
+ this.#handler = options.handler;
635
+ this.#isConnected = false;
636
+ }
637
+ static fromDatabaseConfig(config) {
638
+ if (!config.url?.trim().length) {
639
+ throw new Error(
640
+ "MongoDBStore: url must be provided and cannot be empty. Passing an empty string may cause fallback to local MongoDB defaults."
641
+ );
642
+ }
643
+ if (!config.dbName?.trim().length) {
644
+ throw new Error(
645
+ "MongoDBStore: dbName must be provided and cannot be empty. Passing an empty string may cause fallback to local MongoDB defaults."
646
+ );
647
+ }
648
+ const client = new mongodb.MongoClient(config.url, {
649
+ ...config.options,
650
+ driverInfo: {
651
+ name: "mastra-storage",
652
+ version: package_default.version
653
+ }
654
+ });
655
+ return new _MongoDBConnector({
656
+ client,
657
+ dbName: config.dbName,
658
+ handler: void 0
659
+ });
660
+ }
661
+ static fromConnectionHandler(handler) {
662
+ return new _MongoDBConnector({
663
+ client: void 0,
664
+ dbName: void 0,
665
+ handler
666
+ });
667
+ }
668
+ async getConnection() {
669
+ if (this.#client) {
670
+ if (this.#isConnected && this.#db) {
671
+ return this.#db;
672
+ }
673
+ await this.#client.connect();
674
+ this.#db = this.#client.db(this.#dbName);
675
+ this.#isConnected = true;
676
+ return this.#db;
677
+ }
678
+ throw new Error("MongoDBStore: client cannot be empty. Check your MongoDBConnector configuration.");
679
+ }
680
+ async getCollection(collectionName) {
681
+ if (this.#handler) {
682
+ return this.#handler.getCollection(collectionName);
683
+ }
684
+ const db = await this.getConnection();
685
+ return db.collection(collectionName);
686
+ }
687
+ async close() {
688
+ if (this.#client) {
689
+ await this.#client.close();
690
+ this.#isConnected = false;
691
+ return;
692
+ }
693
+ if (this.#handler) {
694
+ await this.#handler.close();
695
+ }
696
+ }
697
+ };
698
+
699
+ // src/storage/domains/utils.ts
700
+ function formatDateForMongoDB(date) {
701
+ return typeof date === "string" ? new Date(date) : date;
702
+ }
703
+
704
+ // src/storage/domains/memory/index.ts
705
+ var MemoryStorageMongoDB = class extends storage.MemoryStorage {
706
+ operations;
707
+ constructor({ operations }) {
708
+ super();
709
+ this.operations = operations;
710
+ }
711
+ parseRow(row) {
712
+ let content = row.content;
713
+ if (typeof content === "string") {
714
+ try {
715
+ content = JSON.parse(content);
716
+ } catch {
717
+ }
718
+ }
719
+ const result = {
720
+ id: row.id,
721
+ content,
722
+ role: row.role,
723
+ createdAt: formatDateForMongoDB(row.createdAt),
724
+ threadId: row.thread_id,
725
+ resourceId: row.resourceId
726
+ };
727
+ if (row.type && row.type !== "v2") result.type = row.type;
728
+ return result;
729
+ }
730
+ async _getIncludedMessages({
731
+ threadId,
732
+ selectBy
733
+ }) {
734
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
735
+ const include = selectBy?.include;
736
+ if (!include) return null;
737
+ const collection = await this.operations.getCollection(storage.TABLE_MESSAGES);
738
+ const includedMessages = [];
739
+ for (const inc of include) {
740
+ const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
741
+ const searchThreadId = inc.threadId || threadId;
742
+ const allMessages = await collection.find({ thread_id: searchThreadId }).sort({ createdAt: 1 }).toArray();
743
+ const targetIndex = allMessages.findIndex((msg) => msg.id === id);
744
+ if (targetIndex === -1) continue;
745
+ const startIndex = Math.max(0, targetIndex - withPreviousMessages);
746
+ const endIndex = Math.min(allMessages.length - 1, targetIndex + withNextMessages);
747
+ for (let i = startIndex; i <= endIndex; i++) {
748
+ includedMessages.push(allMessages[i]);
749
+ }
750
+ }
751
+ const seen = /* @__PURE__ */ new Set();
752
+ const dedupedMessages = includedMessages.filter((msg) => {
753
+ if (seen.has(msg.id)) return false;
754
+ seen.add(msg.id);
755
+ return true;
756
+ });
757
+ return dedupedMessages.map((row) => this.parseRow(row));
758
+ }
759
+ /**
760
+ * @deprecated use listMessages instead for paginated results.
761
+ */
762
+ async getMessages({
763
+ threadId,
764
+ resourceId,
765
+ selectBy
766
+ }) {
767
+ try {
768
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
769
+ const messages = [];
770
+ const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
771
+ if (selectBy?.include?.length) {
772
+ const includeMessages = await this._getIncludedMessages({ threadId, selectBy });
773
+ if (includeMessages) {
774
+ messages.push(...includeMessages);
775
+ }
776
+ }
777
+ const excludeIds = messages.map((m) => m.id);
778
+ const collection = await this.operations.getCollection(storage.TABLE_MESSAGES);
779
+ const query = { thread_id: threadId };
780
+ if (resourceId) {
781
+ query.resourceId = resourceId;
782
+ }
783
+ if (excludeIds.length > 0) {
784
+ query.id = { $nin: excludeIds };
785
+ }
786
+ if (limit > 0) {
787
+ const remainingMessages = await collection.find(query).sort({ createdAt: -1 }).limit(limit).toArray();
788
+ messages.push(...remainingMessages.map((row) => this.parseRow(row)));
789
+ }
790
+ messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
791
+ const list = new agent.MessageList().add(messages, "memory");
792
+ return { messages: list.get.all.db() };
793
+ } catch (error$1) {
794
+ throw new error.MastraError(
795
+ {
796
+ id: "MONGODB_STORE_GET_MESSAGES_FAILED",
797
+ domain: error.ErrorDomain.STORAGE,
798
+ category: error.ErrorCategory.THIRD_PARTY,
799
+ details: { threadId, resourceId: resourceId ?? "" }
800
+ },
801
+ error$1
802
+ );
803
+ }
804
+ }
805
+ async listMessagesById({ messageIds }) {
806
+ if (messageIds.length === 0) return { messages: [] };
807
+ try {
808
+ const collection = await this.operations.getCollection(storage.TABLE_MESSAGES);
809
+ const rawMessages = await collection.find({ id: { $in: messageIds } }).sort({ createdAt: -1 }).toArray();
810
+ const list = new agent.MessageList().add(
811
+ rawMessages.map(this.parseRow),
812
+ "memory"
813
+ );
814
+ return { messages: list.get.all.db() };
815
+ } catch (error$1) {
816
+ throw new error.MastraError(
817
+ {
818
+ id: "MONGODB_STORE_LIST_MESSAGES_BY_ID_FAILED",
819
+ domain: error.ErrorDomain.STORAGE,
820
+ category: error.ErrorCategory.THIRD_PARTY,
821
+ details: { messageIds: JSON.stringify(messageIds) }
822
+ },
823
+ error$1
824
+ );
825
+ }
826
+ }
827
+ async listMessages(args) {
828
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
829
+ if (!threadId.trim()) {
830
+ throw new error.MastraError(
831
+ {
832
+ id: "STORAGE_MONGODB_LIST_MESSAGES_INVALID_THREAD_ID",
833
+ domain: error.ErrorDomain.STORAGE,
834
+ category: error.ErrorCategory.THIRD_PARTY,
835
+ details: { threadId }
836
+ },
837
+ new Error("threadId must be a non-empty string")
838
+ );
839
+ }
840
+ if (page < 0) {
841
+ throw new error.MastraError(
842
+ {
843
+ id: "STORAGE_MONGODB_LIST_MESSAGES_INVALID_PAGE",
844
+ domain: error.ErrorDomain.STORAGE,
845
+ category: error.ErrorCategory.USER,
846
+ details: { page }
847
+ },
848
+ new Error("page must be >= 0")
849
+ );
850
+ }
851
+ const perPage = storage.normalizePerPage(perPageInput, 40);
852
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
853
+ try {
854
+ const { field, direction } = this.parseOrderBy(orderBy);
855
+ const sortOrder = direction === "ASC" ? 1 : -1;
856
+ const collection = await this.operations.getCollection(storage.TABLE_MESSAGES);
857
+ const query = { thread_id: threadId };
858
+ if (resourceId) {
859
+ query.resourceId = resourceId;
860
+ }
861
+ if (filter?.dateRange?.start) {
862
+ query.createdAt = { ...query.createdAt, $gte: filter.dateRange.start };
863
+ }
864
+ if (filter?.dateRange?.end) {
865
+ query.createdAt = { ...query.createdAt, $lte: filter.dateRange.end };
866
+ }
867
+ const total = await collection.countDocuments(query);
868
+ const messages = [];
869
+ if (perPage !== 0) {
870
+ const sortObj = { [field]: sortOrder };
871
+ let cursor = collection.find(query).sort(sortObj).skip(offset);
872
+ if (perPageInput !== false) {
873
+ cursor = cursor.limit(perPage);
874
+ }
875
+ const dataResult = await cursor.toArray();
876
+ messages.push(...dataResult.map((row) => this.parseRow(row)));
877
+ }
878
+ if (total === 0 && messages.length === 0 && (!include || include.length === 0)) {
879
+ return {
880
+ messages: [],
881
+ total: 0,
882
+ page,
883
+ perPage: perPageForResponse,
884
+ hasMore: false
885
+ };
886
+ }
887
+ const messageIds = new Set(messages.map((m) => m.id));
888
+ if (include && include.length > 0) {
889
+ const selectBy = { include };
890
+ const includeMessages = await this._getIncludedMessages({ threadId, selectBy });
891
+ if (includeMessages) {
892
+ for (const includeMsg of includeMessages) {
893
+ if (!messageIds.has(includeMsg.id)) {
894
+ messages.push(includeMsg);
895
+ messageIds.add(includeMsg.id);
896
+ }
897
+ }
898
+ }
899
+ }
900
+ const list = new agent.MessageList().add(messages, "memory");
901
+ let finalMessages = list.get.all.db();
902
+ finalMessages = finalMessages.sort((a, b) => {
903
+ const isDateField = field === "createdAt" || field === "updatedAt";
904
+ const aValue = isDateField ? new Date(a[field]).getTime() : a[field];
905
+ const bValue = isDateField ? new Date(b[field]).getTime() : b[field];
906
+ if (typeof aValue === "number" && typeof bValue === "number") {
907
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
908
+ }
909
+ return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
910
+ });
911
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
912
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
913
+ const hasMore = perPageInput !== false && !allThreadMessagesReturned && offset + perPage < total;
914
+ return {
915
+ messages: finalMessages,
916
+ total,
917
+ page,
918
+ perPage: perPageForResponse,
919
+ hasMore
920
+ };
921
+ } catch (error$1) {
922
+ const mastraError = new error.MastraError(
923
+ {
924
+ id: "MONGODB_STORE_LIST_MESSAGES_FAILED",
925
+ domain: error.ErrorDomain.STORAGE,
926
+ category: error.ErrorCategory.THIRD_PARTY,
927
+ details: {
928
+ threadId,
929
+ resourceId: resourceId ?? ""
930
+ }
931
+ },
932
+ error$1
933
+ );
934
+ this.logger?.error?.(mastraError.toString());
935
+ this.logger?.trackException?.(mastraError);
936
+ return {
937
+ messages: [],
938
+ total: 0,
939
+ page,
940
+ perPage: perPageForResponse,
941
+ hasMore: false
942
+ };
943
+ }
944
+ }
945
+ async saveMessages({ messages }) {
946
+ if (messages.length === 0) return { messages: [] };
947
+ try {
948
+ const threadId = messages[0]?.threadId;
949
+ if (!threadId) {
950
+ throw new Error("Thread ID is required");
951
+ }
952
+ const collection = await this.operations.getCollection(storage.TABLE_MESSAGES);
953
+ const threadsCollection = await this.operations.getCollection(storage.TABLE_THREADS);
954
+ const messagesToInsert = messages.map((message) => {
955
+ const time = message.createdAt || /* @__PURE__ */ new Date();
956
+ if (!message.threadId) {
957
+ throw new Error(
958
+ "Expected to find a threadId for message, but couldn't find one. An unexpected error has occurred."
959
+ );
960
+ }
961
+ if (!message.resourceId) {
962
+ throw new Error(
963
+ "Expected to find a resourceId for message, but couldn't find one. An unexpected error has occurred."
964
+ );
965
+ }
966
+ return {
967
+ updateOne: {
968
+ filter: { id: message.id },
969
+ update: {
970
+ $set: {
971
+ id: message.id,
972
+ thread_id: message.threadId,
973
+ content: typeof message.content === "object" ? JSON.stringify(message.content) : message.content,
974
+ role: message.role,
975
+ type: message.type || "v2",
976
+ createdAt: formatDateForMongoDB(time),
977
+ resourceId: message.resourceId
978
+ }
979
+ },
980
+ upsert: true
981
+ }
982
+ };
983
+ });
984
+ await Promise.all([
985
+ collection.bulkWrite(messagesToInsert),
986
+ threadsCollection.updateOne({ id: threadId }, { $set: { updatedAt: /* @__PURE__ */ new Date() } })
987
+ ]);
988
+ const list = new agent.MessageList().add(messages, "memory");
989
+ return { messages: list.get.all.db() };
990
+ } catch (error$1) {
991
+ throw new error.MastraError(
992
+ {
993
+ id: "MONGODB_STORE_SAVE_MESSAGES_FAILED",
994
+ domain: error.ErrorDomain.STORAGE,
995
+ category: error.ErrorCategory.THIRD_PARTY
996
+ },
997
+ error$1
998
+ );
999
+ }
1000
+ }
1001
+ async updateMessages({
1002
+ messages
1003
+ }) {
1004
+ if (messages.length === 0) {
1005
+ return [];
1006
+ }
1007
+ const messageIds = messages.map((m) => m.id);
1008
+ const collection = await this.operations.getCollection(storage.TABLE_MESSAGES);
1009
+ const existingMessages = await collection.find({ id: { $in: messageIds } }).toArray();
1010
+ const existingMessagesParsed = existingMessages.map((msg) => this.parseRow(msg));
1011
+ if (existingMessagesParsed.length === 0) {
1012
+ return [];
1013
+ }
1014
+ const threadIdsToUpdate = /* @__PURE__ */ new Set();
1015
+ const bulkOps = [];
1016
+ for (const existingMessage of existingMessagesParsed) {
1017
+ const updatePayload = messages.find((m) => m.id === existingMessage.id);
1018
+ if (!updatePayload) continue;
1019
+ const { id, ...fieldsToUpdate } = updatePayload;
1020
+ if (Object.keys(fieldsToUpdate).length === 0) continue;
1021
+ threadIdsToUpdate.add(existingMessage.threadId);
1022
+ if (updatePayload.threadId && updatePayload.threadId !== existingMessage.threadId) {
1023
+ threadIdsToUpdate.add(updatePayload.threadId);
1024
+ }
1025
+ const updateDoc = {};
1026
+ const updatableFields = { ...fieldsToUpdate };
1027
+ if (updatableFields.content) {
1028
+ const newContent = {
1029
+ ...existingMessage.content,
1030
+ ...updatableFields.content,
1031
+ // Deep merge metadata if it exists on both
1032
+ ...existingMessage.content?.metadata && updatableFields.content.metadata ? {
1033
+ metadata: {
1034
+ ...existingMessage.content.metadata,
1035
+ ...updatableFields.content.metadata
1036
+ }
1037
+ } : {}
1038
+ };
1039
+ updateDoc.content = JSON.stringify(newContent);
1040
+ delete updatableFields.content;
1041
+ }
1042
+ for (const key in updatableFields) {
1043
+ if (Object.prototype.hasOwnProperty.call(updatableFields, key)) {
1044
+ const dbKey = key === "threadId" ? "thread_id" : key;
1045
+ let value = updatableFields[key];
1046
+ if (typeof value === "object" && value !== null) {
1047
+ value = JSON.stringify(value);
1048
+ }
1049
+ updateDoc[dbKey] = value;
1050
+ }
1051
+ }
1052
+ if (Object.keys(updateDoc).length > 0) {
1053
+ bulkOps.push({
1054
+ updateOne: {
1055
+ filter: { id },
1056
+ update: { $set: updateDoc }
1057
+ }
1058
+ });
1059
+ }
1060
+ }
1061
+ if (bulkOps.length > 0) {
1062
+ await collection.bulkWrite(bulkOps);
1063
+ }
1064
+ if (threadIdsToUpdate.size > 0) {
1065
+ const threadsCollection = await this.operations.getCollection(storage.TABLE_THREADS);
1066
+ await threadsCollection.updateMany(
1067
+ { id: { $in: Array.from(threadIdsToUpdate) } },
1068
+ { $set: { updatedAt: /* @__PURE__ */ new Date() } }
1069
+ );
1070
+ }
1071
+ const updatedMessages = await collection.find({ id: { $in: messageIds } }).toArray();
1072
+ return updatedMessages.map((row) => this.parseRow(row));
1073
+ }
1074
+ async getResourceById({ resourceId }) {
1075
+ try {
1076
+ const collection = await this.operations.getCollection(storage.TABLE_RESOURCES);
1077
+ const result = await collection.findOne({ id: resourceId });
1078
+ if (!result) {
1079
+ return null;
1080
+ }
1081
+ return {
1082
+ id: result.id,
1083
+ workingMemory: result.workingMemory || "",
1084
+ metadata: typeof result.metadata === "string" ? storage.safelyParseJSON(result.metadata) : result.metadata,
1085
+ createdAt: formatDateForMongoDB(result.createdAt),
1086
+ updatedAt: formatDateForMongoDB(result.updatedAt)
1087
+ };
1088
+ } catch (error$1) {
1089
+ throw new error.MastraError(
1090
+ {
1091
+ id: "STORAGE_MONGODB_STORE_GET_RESOURCE_BY_ID_FAILED",
1092
+ domain: error.ErrorDomain.STORAGE,
1093
+ category: error.ErrorCategory.THIRD_PARTY,
1094
+ details: { resourceId }
1095
+ },
1096
+ error$1
1097
+ );
1098
+ }
1099
+ }
1100
+ async saveResource({ resource }) {
1101
+ try {
1102
+ const collection = await this.operations.getCollection(storage.TABLE_RESOURCES);
1103
+ await collection.updateOne(
1104
+ { id: resource.id },
1105
+ {
1106
+ $set: {
1107
+ ...resource,
1108
+ metadata: JSON.stringify(resource.metadata)
1109
+ }
1110
+ },
1111
+ { upsert: true }
1112
+ );
1113
+ return resource;
1114
+ } catch (error$1) {
1115
+ throw new error.MastraError(
1116
+ {
1117
+ id: "STORAGE_MONGODB_STORE_SAVE_RESOURCE_FAILED",
1118
+ domain: error.ErrorDomain.STORAGE,
1119
+ category: error.ErrorCategory.THIRD_PARTY,
1120
+ details: { resourceId: resource.id }
1121
+ },
1122
+ error$1
1123
+ );
1124
+ }
1125
+ }
1126
+ async updateResource({
1127
+ resourceId,
1128
+ workingMemory,
1129
+ metadata
1130
+ }) {
1131
+ try {
1132
+ const existingResource = await this.getResourceById({ resourceId });
1133
+ if (!existingResource) {
1134
+ const newResource = {
1135
+ id: resourceId,
1136
+ workingMemory: workingMemory || "",
1137
+ metadata: metadata || {},
1138
+ createdAt: /* @__PURE__ */ new Date(),
1139
+ updatedAt: /* @__PURE__ */ new Date()
1140
+ };
1141
+ return this.saveResource({ resource: newResource });
1142
+ }
1143
+ const updatedResource = {
1144
+ ...existingResource,
1145
+ workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
1146
+ metadata: metadata ? { ...existingResource.metadata, ...metadata } : existingResource.metadata,
1147
+ updatedAt: /* @__PURE__ */ new Date()
1148
+ };
1149
+ const collection = await this.operations.getCollection(storage.TABLE_RESOURCES);
1150
+ const updateDoc = { updatedAt: updatedResource.updatedAt };
1151
+ if (workingMemory !== void 0) {
1152
+ updateDoc.workingMemory = workingMemory;
1153
+ }
1154
+ if (metadata) {
1155
+ updateDoc.metadata = JSON.stringify(updatedResource.metadata);
1156
+ }
1157
+ await collection.updateOne({ id: resourceId }, { $set: updateDoc });
1158
+ return updatedResource;
1159
+ } catch (error$1) {
1160
+ throw new error.MastraError(
1161
+ {
1162
+ id: "STORAGE_MONGODB_STORE_UPDATE_RESOURCE_FAILED",
1163
+ domain: error.ErrorDomain.STORAGE,
1164
+ category: error.ErrorCategory.THIRD_PARTY,
1165
+ details: { resourceId }
1166
+ },
1167
+ error$1
1168
+ );
1169
+ }
1170
+ }
1171
+ async getThreadById({ threadId }) {
1172
+ try {
1173
+ const collection = await this.operations.getCollection(storage.TABLE_THREADS);
1174
+ const result = await collection.findOne({ id: threadId });
1175
+ if (!result) {
1176
+ return null;
1177
+ }
1178
+ return {
1179
+ ...result,
1180
+ metadata: typeof result.metadata === "string" ? storage.safelyParseJSON(result.metadata) : result.metadata
1181
+ };
1182
+ } catch (error$1) {
1183
+ throw new error.MastraError(
1184
+ {
1185
+ id: "STORAGE_MONGODB_STORE_GET_THREAD_BY_ID_FAILED",
1186
+ domain: error.ErrorDomain.STORAGE,
1187
+ category: error.ErrorCategory.THIRD_PARTY,
1188
+ details: { threadId }
1189
+ },
1190
+ error$1
1191
+ );
1192
+ }
1193
+ }
1194
+ async listThreadsByResourceId(args) {
1195
+ try {
1196
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
1197
+ if (page < 0) {
1198
+ throw new error.MastraError(
1199
+ {
1200
+ id: "STORAGE_MONGODB_LIST_THREADS_BY_RESOURCE_ID_INVALID_PAGE",
1201
+ domain: error.ErrorDomain.STORAGE,
1202
+ category: error.ErrorCategory.USER,
1203
+ details: { page }
1204
+ },
1205
+ new Error("page must be >= 0")
1206
+ );
1207
+ }
1208
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1209
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1210
+ const { field, direction } = this.parseOrderBy(orderBy);
1211
+ const collection = await this.operations.getCollection(storage.TABLE_THREADS);
1212
+ const query = { resourceId };
1213
+ const total = await collection.countDocuments(query);
1214
+ if (perPage === 0) {
1215
+ return {
1216
+ threads: [],
1217
+ total,
1218
+ page,
1219
+ perPage: perPageForResponse,
1220
+ hasMore: offset < total
1221
+ };
1222
+ }
1223
+ const sortOrder = direction === "ASC" ? 1 : -1;
1224
+ let cursor = collection.find(query).sort({ [field]: sortOrder }).skip(offset);
1225
+ if (perPageInput !== false) {
1226
+ cursor = cursor.limit(perPage);
1227
+ }
1228
+ const threads = await cursor.toArray();
1229
+ return {
1230
+ threads: threads.map((thread) => ({
1231
+ id: thread.id,
1232
+ title: thread.title,
1233
+ resourceId: thread.resourceId,
1234
+ createdAt: formatDateForMongoDB(thread.createdAt),
1235
+ updatedAt: formatDateForMongoDB(thread.updatedAt),
1236
+ metadata: thread.metadata || {}
1237
+ })),
1238
+ total,
1239
+ page,
1240
+ perPage: perPageForResponse,
1241
+ hasMore: perPageInput === false ? false : offset + perPage < total
1242
+ };
1243
+ } catch (error$1) {
1244
+ throw new error.MastraError(
1245
+ {
1246
+ id: "MONGODB_STORE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
1247
+ domain: error.ErrorDomain.STORAGE,
1248
+ category: error.ErrorCategory.THIRD_PARTY,
1249
+ details: { resourceId: args.resourceId }
1250
+ },
1251
+ error$1
1252
+ );
1253
+ }
1254
+ }
1255
+ async saveThread({ thread }) {
1256
+ try {
1257
+ const collection = await this.operations.getCollection(storage.TABLE_THREADS);
1258
+ await collection.updateOne(
1259
+ { id: thread.id },
1260
+ {
1261
+ $set: {
1262
+ ...thread,
1263
+ metadata: thread.metadata
1264
+ }
1265
+ },
1266
+ { upsert: true }
1267
+ );
1268
+ return thread;
1269
+ } catch (error$1) {
1270
+ throw new error.MastraError(
1271
+ {
1272
+ id: "STORAGE_MONGODB_STORE_SAVE_THREAD_FAILED",
1273
+ domain: error.ErrorDomain.STORAGE,
1274
+ category: error.ErrorCategory.THIRD_PARTY,
1275
+ details: { threadId: thread.id }
1276
+ },
1277
+ error$1
1278
+ );
1279
+ }
1280
+ }
1281
+ async updateThread({
1282
+ id,
1283
+ title,
1284
+ metadata
1285
+ }) {
1286
+ const thread = await this.getThreadById({ threadId: id });
1287
+ if (!thread) {
1288
+ throw new error.MastraError({
1289
+ id: "STORAGE_MONGODB_STORE_UPDATE_THREAD_NOT_FOUND",
1290
+ domain: error.ErrorDomain.STORAGE,
1291
+ category: error.ErrorCategory.THIRD_PARTY,
1292
+ details: { threadId: id, status: 404 },
1293
+ text: `Thread ${id} not found`
1294
+ });
1295
+ }
1296
+ const updatedThread = {
1297
+ ...thread,
1298
+ title,
1299
+ metadata: {
1300
+ ...thread.metadata,
1301
+ ...metadata
1302
+ }
1303
+ };
1304
+ try {
1305
+ const collection = await this.operations.getCollection(storage.TABLE_THREADS);
1306
+ await collection.updateOne(
1307
+ { id },
1308
+ {
1309
+ $set: {
1310
+ title,
1311
+ metadata: updatedThread.metadata
1312
+ }
1313
+ }
1314
+ );
1315
+ } catch (error$1) {
1316
+ throw new error.MastraError(
1317
+ {
1318
+ id: "STORAGE_MONGODB_STORE_UPDATE_THREAD_FAILED",
1319
+ domain: error.ErrorDomain.STORAGE,
1320
+ category: error.ErrorCategory.THIRD_PARTY,
1321
+ details: { threadId: id }
1322
+ },
1323
+ error$1
1324
+ );
1325
+ }
1326
+ return updatedThread;
1327
+ }
1328
+ async deleteThread({ threadId }) {
1329
+ try {
1330
+ const collectionMessages = await this.operations.getCollection(storage.TABLE_MESSAGES);
1331
+ await collectionMessages.deleteMany({ thread_id: threadId });
1332
+ const collectionThreads = await this.operations.getCollection(storage.TABLE_THREADS);
1333
+ await collectionThreads.deleteOne({ id: threadId });
1334
+ } catch (error$1) {
1335
+ throw new error.MastraError(
1336
+ {
1337
+ id: "STORAGE_MONGODB_STORE_DELETE_THREAD_FAILED",
1338
+ domain: error.ErrorDomain.STORAGE,
1339
+ category: error.ErrorCategory.THIRD_PARTY,
1340
+ details: { threadId }
1341
+ },
1342
+ error$1
1343
+ );
1344
+ }
1345
+ }
1346
+ };
1347
+ var ObservabilityMongoDB = class extends storage.ObservabilityStorage {
1348
+ operations;
1349
+ constructor({ operations }) {
1350
+ super();
1351
+ this.operations = operations;
1352
+ }
1353
+ get aiTracingStrategy() {
1354
+ return {
1355
+ preferred: "batch-with-updates",
1356
+ supported: ["batch-with-updates", "insert-only"]
1357
+ };
1358
+ }
1359
+ async createAISpan(span) {
1360
+ try {
1361
+ const startedAt = span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt;
1362
+ const endedAt = span.endedAt instanceof Date ? span.endedAt.toISOString() : span.endedAt;
1363
+ const record = {
1364
+ ...span,
1365
+ startedAt,
1366
+ endedAt,
1367
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1368
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1369
+ };
1370
+ return this.operations.insert({ tableName: storage.TABLE_AI_SPANS, record });
1371
+ } catch (error$1) {
1372
+ throw new error.MastraError(
1373
+ {
1374
+ id: "MONGODB_STORE_CREATE_AI_SPAN_FAILED",
1375
+ domain: error.ErrorDomain.STORAGE,
1376
+ category: error.ErrorCategory.USER,
1377
+ details: {
1378
+ spanId: span.spanId,
1379
+ traceId: span.traceId,
1380
+ spanType: span.spanType,
1381
+ spanName: span.name
1382
+ }
1383
+ },
1384
+ error$1
1385
+ );
1386
+ }
1387
+ }
1388
+ async getAITrace(traceId) {
1389
+ try {
1390
+ const collection = await this.operations.getCollection(storage.TABLE_AI_SPANS);
1391
+ const spans = await collection.find({ traceId }).sort({ startedAt: -1 }).toArray();
1392
+ if (!spans || spans.length === 0) {
1393
+ return null;
1394
+ }
1395
+ return {
1396
+ traceId,
1397
+ spans: spans.map((span) => this.transformSpanFromMongo(span))
1398
+ };
1399
+ } catch (error$1) {
1400
+ throw new error.MastraError(
1401
+ {
1402
+ id: "MONGODB_STORE_GET_AI_TRACE_FAILED",
1403
+ domain: error.ErrorDomain.STORAGE,
1404
+ category: error.ErrorCategory.USER,
1405
+ details: {
1406
+ traceId
1407
+ }
1408
+ },
1409
+ error$1
1410
+ );
1411
+ }
1412
+ }
1413
+ async updateAISpan({
1414
+ spanId,
1415
+ traceId,
1416
+ updates
1417
+ }) {
1418
+ try {
1419
+ const data = { ...updates };
1420
+ if (data.endedAt instanceof Date) {
1421
+ data.endedAt = data.endedAt.toISOString();
1422
+ }
1423
+ if (data.startedAt instanceof Date) {
1424
+ data.startedAt = data.startedAt.toISOString();
1425
+ }
1426
+ const updateData = {
1427
+ ...data,
1428
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1429
+ };
1430
+ await this.operations.update({
1431
+ tableName: storage.TABLE_AI_SPANS,
1432
+ keys: { spanId, traceId },
1433
+ data: updateData
1434
+ });
1435
+ } catch (error$1) {
1436
+ throw new error.MastraError(
1437
+ {
1438
+ id: "MONGODB_STORE_UPDATE_AI_SPAN_FAILED",
1439
+ domain: error.ErrorDomain.STORAGE,
1440
+ category: error.ErrorCategory.USER,
1441
+ details: {
1442
+ spanId,
1443
+ traceId
1444
+ }
1445
+ },
1446
+ error$1
1447
+ );
1448
+ }
1449
+ }
1450
+ async getAITracesPaginated({
1451
+ filters,
1452
+ pagination
1453
+ }) {
1454
+ const page = pagination?.page ?? 0;
1455
+ const perPage = pagination?.perPage ?? 10;
1456
+ const { entityId, entityType, ...actualFilters } = filters || {};
1457
+ try {
1458
+ const collection = await this.operations.getCollection(storage.TABLE_AI_SPANS);
1459
+ const mongoFilter = {
1460
+ parentSpanId: null,
1461
+ // Only get root spans for traces
1462
+ ...actualFilters
1463
+ };
1464
+ if (pagination?.dateRange) {
1465
+ const dateFilter = {};
1466
+ if (pagination.dateRange.start) {
1467
+ dateFilter.$gte = pagination.dateRange.start instanceof Date ? pagination.dateRange.start.toISOString() : pagination.dateRange.start;
1468
+ }
1469
+ if (pagination.dateRange.end) {
1470
+ dateFilter.$lte = pagination.dateRange.end instanceof Date ? pagination.dateRange.end.toISOString() : pagination.dateRange.end;
1471
+ }
1472
+ if (Object.keys(dateFilter).length > 0) {
1473
+ mongoFilter.startedAt = dateFilter;
1474
+ }
1475
+ }
1476
+ if (entityId && entityType) {
1477
+ let name = "";
1478
+ if (entityType === "workflow") {
1479
+ name = `workflow run: '${entityId}'`;
1480
+ } else if (entityType === "agent") {
1481
+ name = `agent run: '${entityId}'`;
1482
+ } else {
1483
+ const error$1 = new error.MastraError({
1484
+ id: "MONGODB_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1485
+ domain: error.ErrorDomain.STORAGE,
1486
+ category: error.ErrorCategory.USER,
1487
+ details: {
1488
+ entityType
1489
+ },
1490
+ text: `Cannot filter by entity type: ${entityType}`
1491
+ });
1492
+ throw error$1;
1493
+ }
1494
+ mongoFilter.name = name;
1495
+ }
1496
+ const count = await collection.countDocuments(mongoFilter);
1497
+ if (count === 0) {
1498
+ return {
1499
+ pagination: {
1500
+ total: 0,
1501
+ page,
1502
+ perPage,
1503
+ hasMore: false
1504
+ },
1505
+ spans: []
1506
+ };
1507
+ }
1508
+ const spans = await collection.find(mongoFilter).sort({ startedAt: -1 }).skip(page * perPage).limit(perPage).toArray();
1509
+ return {
1510
+ pagination: {
1511
+ total: count,
1512
+ page,
1513
+ perPage,
1514
+ hasMore: spans.length === perPage
1515
+ },
1516
+ spans: spans.map((span) => this.transformSpanFromMongo(span))
1517
+ };
1518
+ } catch (error$1) {
1519
+ throw new error.MastraError(
1520
+ {
1521
+ id: "MONGODB_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1522
+ domain: error.ErrorDomain.STORAGE,
1523
+ category: error.ErrorCategory.USER
1524
+ },
1525
+ error$1
1526
+ );
1527
+ }
1528
+ }
1529
+ async batchCreateAISpans(args) {
1530
+ try {
1531
+ const records = args.records.map((record) => {
1532
+ const startedAt = record.startedAt instanceof Date ? record.startedAt.toISOString() : record.startedAt;
1533
+ const endedAt = record.endedAt instanceof Date ? record.endedAt.toISOString() : record.endedAt;
1534
+ return {
1535
+ ...record,
1536
+ startedAt,
1537
+ endedAt,
1538
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1539
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1540
+ };
1541
+ });
1542
+ return this.operations.batchInsert({
1543
+ tableName: storage.TABLE_AI_SPANS,
1544
+ records
1545
+ });
1546
+ } catch (error$1) {
1547
+ throw new error.MastraError(
1548
+ {
1549
+ id: "MONGODB_STORE_BATCH_CREATE_AI_SPANS_FAILED",
1550
+ domain: error.ErrorDomain.STORAGE,
1551
+ category: error.ErrorCategory.USER
1552
+ },
1553
+ error$1
1554
+ );
1555
+ }
1556
+ }
1557
+ async batchUpdateAISpans(args) {
1558
+ try {
1559
+ return this.operations.batchUpdate({
1560
+ tableName: storage.TABLE_AI_SPANS,
1561
+ updates: args.records.map((record) => {
1562
+ const data = { ...record.updates };
1563
+ if (data.endedAt instanceof Date) {
1564
+ data.endedAt = data.endedAt.toISOString();
1565
+ }
1566
+ if (data.startedAt instanceof Date) {
1567
+ data.startedAt = data.startedAt.toISOString();
1568
+ }
1569
+ const updateData = {
1570
+ ...data,
1571
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1572
+ };
1573
+ return {
1574
+ keys: { spanId: record.spanId, traceId: record.traceId },
1575
+ data: updateData
1576
+ };
1577
+ })
1578
+ });
1579
+ } catch (error$1) {
1580
+ throw new error.MastraError(
1581
+ {
1582
+ id: "MONGODB_STORE_BATCH_UPDATE_AI_SPANS_FAILED",
1583
+ domain: error.ErrorDomain.STORAGE,
1584
+ category: error.ErrorCategory.USER
1585
+ },
1586
+ error$1
1587
+ );
1588
+ }
1589
+ }
1590
+ async batchDeleteAITraces(args) {
1591
+ try {
1592
+ const collection = await this.operations.getCollection(storage.TABLE_AI_SPANS);
1593
+ await collection.deleteMany({
1594
+ traceId: { $in: args.traceIds }
1595
+ });
1596
+ } catch (error$1) {
1597
+ throw new error.MastraError(
1598
+ {
1599
+ id: "MONGODB_STORE_BATCH_DELETE_AI_TRACES_FAILED",
1600
+ domain: error.ErrorDomain.STORAGE,
1601
+ category: error.ErrorCategory.USER
1602
+ },
1603
+ error$1
1604
+ );
1605
+ }
1606
+ }
1607
+ /**
1608
+ * Transform MongoDB document to AISpanRecord format
1609
+ */
1610
+ transformSpanFromMongo(doc) {
1611
+ const { _id, ...span } = doc;
1612
+ if (span.startedAt && typeof span.startedAt === "string") {
1613
+ span.startedAt = span.startedAt;
1614
+ }
1615
+ if (span.endedAt && typeof span.endedAt === "string") {
1616
+ span.endedAt = span.endedAt;
1617
+ }
1618
+ if (span.createdAt && typeof span.createdAt === "string") {
1619
+ span.createdAt = new Date(span.createdAt);
1620
+ }
1621
+ if (span.updatedAt && typeof span.updatedAt === "string") {
1622
+ span.updatedAt = new Date(span.updatedAt);
1623
+ }
1624
+ return span;
1625
+ }
1626
+ };
1627
+ var StoreOperationsMongoDB = class extends storage.StoreOperations {
1628
+ #connector;
1629
+ constructor(config) {
1630
+ super();
1631
+ this.#connector = config.connector;
1632
+ }
1633
+ async getCollection(collectionName) {
1634
+ return this.#connector.getCollection(collectionName);
1635
+ }
1636
+ async hasColumn(_table, _column) {
1637
+ return true;
1638
+ }
1639
+ async createTable() {
1640
+ }
1641
+ async alterTable(_args) {
1642
+ }
1643
+ async clearTable({ tableName }) {
1644
+ try {
1645
+ const collection = await this.getCollection(tableName);
1646
+ await collection.deleteMany({});
1647
+ } catch (error$1) {
1648
+ const mastraError = new error.MastraError(
1649
+ {
1650
+ id: "STORAGE_MONGODB_STORE_CLEAR_TABLE_FAILED",
1651
+ domain: error.ErrorDomain.STORAGE,
1652
+ category: error.ErrorCategory.THIRD_PARTY,
1653
+ details: { tableName }
1654
+ },
1655
+ error$1
1656
+ );
1657
+ this.logger.error(mastraError.message);
1658
+ this.logger?.trackException(mastraError);
1659
+ throw mastraError;
1660
+ }
1661
+ }
1662
+ async dropTable({ tableName }) {
1663
+ try {
1664
+ const collection = await this.getCollection(tableName);
1665
+ await collection.drop();
1666
+ } catch (error$1) {
1667
+ if (error$1 instanceof Error && error$1.message.includes("ns not found")) {
1668
+ return;
1669
+ }
1670
+ throw new error.MastraError(
1671
+ {
1672
+ id: "MONGODB_STORE_DROP_TABLE_FAILED",
1673
+ domain: error.ErrorDomain.STORAGE,
1674
+ category: error.ErrorCategory.THIRD_PARTY,
1675
+ details: { tableName }
1676
+ },
1677
+ error$1
1678
+ );
1679
+ }
1680
+ }
1681
+ processJsonbFields(tableName, record) {
1682
+ const schema = storage.TABLE_SCHEMAS[tableName];
1683
+ if (!schema) {
1684
+ return record;
1685
+ }
1686
+ return Object.fromEntries(
1687
+ Object.entries(schema).map(([key, value]) => {
1688
+ if (value.type === "jsonb" && record[key] && typeof record[key] === "string") {
1689
+ return [key, storage.safelyParseJSON(record[key])];
1690
+ }
1691
+ return [key, record[key]];
1692
+ })
1693
+ );
1694
+ }
1695
+ async insert({ tableName, record }) {
1696
+ try {
1697
+ const collection = await this.getCollection(tableName);
1698
+ const recordToInsert = this.processJsonbFields(tableName, record);
1699
+ await collection.insertOne(recordToInsert);
1700
+ } catch (error$1) {
1701
+ const mastraError = new error.MastraError(
1702
+ {
1703
+ id: "STORAGE_MONGODB_STORE_INSERT_FAILED",
1704
+ domain: error.ErrorDomain.STORAGE,
1705
+ category: error.ErrorCategory.THIRD_PARTY,
1706
+ details: { tableName }
1707
+ },
1708
+ error$1
1709
+ );
1710
+ this.logger.error(mastraError.message);
1711
+ this.logger?.trackException(mastraError);
1712
+ throw mastraError;
1713
+ }
1714
+ }
1715
+ async batchInsert({ tableName, records }) {
1716
+ if (!records.length) {
1717
+ return;
1718
+ }
1719
+ try {
1720
+ const collection = await this.getCollection(tableName);
1721
+ const processedRecords = records.map((record) => this.processJsonbFields(tableName, record));
1722
+ await collection.insertMany(processedRecords);
1723
+ } catch (error$1) {
1724
+ throw new error.MastraError(
1725
+ {
1726
+ id: "STORAGE_MONGODB_STORE_BATCH_INSERT_FAILED",
1727
+ domain: error.ErrorDomain.STORAGE,
1728
+ category: error.ErrorCategory.THIRD_PARTY,
1729
+ details: { tableName }
1730
+ },
1731
+ error$1
1732
+ );
1733
+ }
1734
+ }
1735
+ async load({ tableName, keys }) {
1736
+ this.logger.info(`Loading ${tableName} with keys ${JSON.stringify(keys)}`);
1737
+ try {
1738
+ const collection = await this.getCollection(tableName);
1739
+ return await collection.find(keys).toArray();
1740
+ } catch (error$1) {
1741
+ throw new error.MastraError(
1742
+ {
1743
+ id: "STORAGE_MONGODB_STORE_LOAD_FAILED",
1744
+ domain: error.ErrorDomain.STORAGE,
1745
+ category: error.ErrorCategory.THIRD_PARTY,
1746
+ details: { tableName }
1747
+ },
1748
+ error$1
1749
+ );
1750
+ }
1751
+ }
1752
+ async update({
1753
+ tableName,
1754
+ keys,
1755
+ data
1756
+ }) {
1757
+ try {
1758
+ const collection = await this.getCollection(tableName);
1759
+ const processedData = this.processJsonbFields(tableName, data);
1760
+ const cleanData = Object.fromEntries(Object.entries(processedData).filter(([_, value]) => value !== void 0));
1761
+ await collection.updateOne(keys, { $set: cleanData });
1762
+ } catch (error$1) {
1763
+ throw new error.MastraError(
1764
+ {
1765
+ id: "STORAGE_MONGODB_STORE_UPDATE_FAILED",
1766
+ domain: error.ErrorDomain.STORAGE,
1767
+ category: error.ErrorCategory.THIRD_PARTY,
1768
+ details: { tableName }
1769
+ },
1770
+ error$1
1771
+ );
1772
+ }
1773
+ }
1774
+ async batchUpdate({
1775
+ tableName,
1776
+ updates
1777
+ }) {
1778
+ if (!updates.length) {
1779
+ return;
1780
+ }
1781
+ try {
1782
+ const collection = await this.getCollection(tableName);
1783
+ const bulkOps = updates.map(({ keys, data }) => {
1784
+ const processedData = this.processJsonbFields(tableName, data);
1785
+ const cleanData = Object.fromEntries(Object.entries(processedData).filter(([_, value]) => value !== void 0));
1786
+ return {
1787
+ updateOne: {
1788
+ filter: keys,
1789
+ update: { $set: cleanData }
1790
+ }
1791
+ };
1792
+ });
1793
+ await collection.bulkWrite(bulkOps);
1794
+ } catch (error$1) {
1795
+ throw new error.MastraError(
1796
+ {
1797
+ id: "STORAGE_MONGODB_STORE_BATCH_UPDATE_FAILED",
1798
+ domain: error.ErrorDomain.STORAGE,
1799
+ category: error.ErrorCategory.THIRD_PARTY,
1800
+ details: { tableName }
1801
+ },
1802
+ error$1
1803
+ );
1804
+ }
1805
+ }
1806
+ };
1807
+ function transformScoreRow(row) {
1808
+ let scorerValue = null;
1809
+ if (row.scorer) {
1810
+ try {
1811
+ scorerValue = typeof row.scorer === "string" ? storage.safelyParseJSON(row.scorer) : row.scorer;
1812
+ } catch (e) {
1813
+ console.warn("Failed to parse scorer:", e);
1814
+ }
1815
+ }
1816
+ let preprocessStepResultValue = null;
1817
+ if (row.preprocessStepResult) {
1818
+ try {
1819
+ preprocessStepResultValue = typeof row.preprocessStepResult === "string" ? storage.safelyParseJSON(row.preprocessStepResult) : row.preprocessStepResult;
1820
+ } catch (e) {
1821
+ console.warn("Failed to parse preprocessStepResult:", e);
1822
+ }
1823
+ }
1824
+ let analyzeStepResultValue = null;
1825
+ if (row.analyzeStepResult) {
1826
+ try {
1827
+ analyzeStepResultValue = typeof row.analyzeStepResult === "string" ? storage.safelyParseJSON(row.analyzeStepResult) : row.analyzeStepResult;
1828
+ } catch (e) {
1829
+ console.warn("Failed to parse analyzeStepResult:", e);
1830
+ }
1831
+ }
1832
+ let inputValue = null;
1833
+ if (row.input) {
1834
+ try {
1835
+ inputValue = typeof row.input === "string" ? storage.safelyParseJSON(row.input) : row.input;
1836
+ } catch (e) {
1837
+ console.warn("Failed to parse input:", e);
1838
+ }
1839
+ }
1840
+ let outputValue = null;
1841
+ if (row.output) {
1842
+ try {
1843
+ outputValue = typeof row.output === "string" ? storage.safelyParseJSON(row.output) : row.output;
1844
+ } catch (e) {
1845
+ console.warn("Failed to parse output:", e);
1846
+ }
1847
+ }
1848
+ let entityValue = null;
1849
+ if (row.entity) {
1850
+ try {
1851
+ entityValue = typeof row.entity === "string" ? storage.safelyParseJSON(row.entity) : row.entity;
1852
+ } catch (e) {
1853
+ console.warn("Failed to parse entity:", e);
1854
+ }
1855
+ }
1856
+ let requestContextValue = null;
1857
+ if (row.requestContext) {
1858
+ try {
1859
+ requestContextValue = typeof row.requestContext === "string" ? storage.safelyParseJSON(row.requestContext) : row.requestContext;
1860
+ } catch (e) {
1861
+ console.warn("Failed to parse requestContext:", e);
1862
+ }
1863
+ }
1864
+ let metadataValue = null;
1865
+ if (row.metadata) {
1866
+ try {
1867
+ metadataValue = typeof row.metadata === "string" ? storage.safelyParseJSON(row.metadata) : row.metadata;
1868
+ } catch (e) {
1869
+ console.warn("Failed to parse metadata:", e);
1870
+ }
1871
+ }
1872
+ return {
1873
+ id: row.id,
1874
+ entityId: row.entityId,
1875
+ entityType: row.entityType,
1876
+ scorerId: row.scorerId,
1877
+ traceId: row.traceId,
1878
+ spanId: row.spanId,
1879
+ runId: row.runId,
1880
+ scorer: scorerValue,
1881
+ preprocessStepResult: preprocessStepResultValue,
1882
+ preprocessPrompt: row.preprocessPrompt,
1883
+ analyzeStepResult: analyzeStepResultValue,
1884
+ generateScorePrompt: row.generateScorePrompt,
1885
+ score: row.score,
1886
+ analyzePrompt: row.analyzePrompt,
1887
+ reasonPrompt: row.reasonPrompt,
1888
+ metadata: metadataValue,
1889
+ input: inputValue,
1890
+ output: outputValue,
1891
+ additionalContext: row.additionalContext,
1892
+ requestContext: requestContextValue,
1893
+ entity: entityValue,
1894
+ source: row.source,
1895
+ resourceId: row.resourceId,
1896
+ threadId: row.threadId,
1897
+ createdAt: new Date(row.createdAt),
1898
+ updatedAt: new Date(row.updatedAt)
1899
+ };
1900
+ }
1901
+ var ScoresStorageMongoDB = class extends storage.ScoresStorage {
1902
+ operations;
1903
+ constructor({ operations }) {
1904
+ super();
1905
+ this.operations = operations;
1906
+ }
1907
+ async getScoreById({ id }) {
1908
+ try {
1909
+ const collection = await this.operations.getCollection(storage.TABLE_SCORERS);
1910
+ const document = await collection.findOne({ id });
1911
+ if (!document) {
1912
+ return null;
1913
+ }
1914
+ return transformScoreRow(document);
1915
+ } catch (error$1) {
1916
+ throw new error.MastraError(
1917
+ {
1918
+ id: "STORAGE_MONGODB_STORE_GET_SCORE_BY_ID_FAILED",
1919
+ domain: error.ErrorDomain.STORAGE,
1920
+ category: error.ErrorCategory.THIRD_PARTY,
1921
+ details: { id }
1922
+ },
1923
+ error$1
1924
+ );
1925
+ }
1926
+ }
1927
+ async saveScore(score) {
1928
+ let validatedScore;
1929
+ try {
1930
+ validatedScore = evals.saveScorePayloadSchema.parse(score);
1931
+ } catch (error$1) {
1932
+ throw new error.MastraError(
1933
+ {
1934
+ id: "STORAGE_MONGODB_STORE_SAVE_SCORE_VALIDATION_FAILED",
1935
+ domain: error.ErrorDomain.STORAGE,
1936
+ category: error.ErrorCategory.THIRD_PARTY
1937
+ },
1938
+ error$1
1939
+ );
1940
+ }
1941
+ try {
1942
+ const now = /* @__PURE__ */ new Date();
1943
+ const scoreId = `score-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
1944
+ const scoreData = {
1945
+ id: scoreId,
1946
+ entityId: validatedScore.entityId,
1947
+ entityType: validatedScore.entityType,
1948
+ scorerId: validatedScore.scorerId,
1949
+ traceId: validatedScore.traceId || "",
1950
+ spanId: validatedScore.spanId || "",
1951
+ runId: validatedScore.runId,
1952
+ scorer: typeof validatedScore.scorer === "string" ? storage.safelyParseJSON(validatedScore.scorer) : validatedScore.scorer,
1953
+ preprocessStepResult: typeof validatedScore.preprocessStepResult === "string" ? storage.safelyParseJSON(validatedScore.preprocessStepResult) : validatedScore.preprocessStepResult,
1954
+ analyzeStepResult: typeof validatedScore.analyzeStepResult === "string" ? storage.safelyParseJSON(validatedScore.analyzeStepResult) : validatedScore.analyzeStepResult,
1955
+ score: validatedScore.score,
1956
+ reason: validatedScore.reason,
1957
+ preprocessPrompt: validatedScore.preprocessPrompt,
1958
+ generateScorePrompt: validatedScore.generateScorePrompt,
1959
+ generateReasonPrompt: validatedScore.generateReasonPrompt,
1960
+ analyzePrompt: validatedScore.analyzePrompt,
1961
+ input: typeof validatedScore.input === "string" ? storage.safelyParseJSON(validatedScore.input) : validatedScore.input,
1962
+ output: typeof validatedScore.output === "string" ? storage.safelyParseJSON(validatedScore.output) : validatedScore.output,
1963
+ additionalContext: validatedScore.additionalContext,
1964
+ requestContext: typeof validatedScore.requestContext === "string" ? storage.safelyParseJSON(validatedScore.requestContext) : validatedScore.requestContext,
1965
+ entity: typeof validatedScore.entity === "string" ? storage.safelyParseJSON(validatedScore.entity) : validatedScore.entity,
1966
+ source: validatedScore.source,
1967
+ resourceId: validatedScore.resourceId || "",
1968
+ threadId: validatedScore.threadId || "",
1969
+ createdAt: now,
1970
+ updatedAt: now
1971
+ };
1972
+ const collection = await this.operations.getCollection(storage.TABLE_SCORERS);
1973
+ await collection.insertOne(scoreData);
1974
+ const savedScore = {
1975
+ ...score,
1976
+ id: scoreId,
1977
+ createdAt: now,
1978
+ updatedAt: now
1979
+ };
1980
+ return { score: savedScore };
1981
+ } catch (error$1) {
1982
+ throw new error.MastraError(
1983
+ {
1984
+ id: "STORAGE_MONGODB_STORE_SAVE_SCORE_FAILED",
1985
+ domain: error.ErrorDomain.STORAGE,
1986
+ category: error.ErrorCategory.THIRD_PARTY,
1987
+ details: { scorerId: score.scorerId, runId: score.runId }
1988
+ },
1989
+ error$1
1990
+ );
1991
+ }
1992
+ }
1993
+ async listScoresByScorerId({
1994
+ scorerId,
1995
+ pagination,
1996
+ entityId,
1997
+ entityType,
1998
+ source
1999
+ }) {
2000
+ try {
2001
+ const { page, perPage: perPageInput } = pagination;
2002
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2003
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2004
+ const query = { scorerId };
2005
+ if (entityId) {
2006
+ query.entityId = entityId;
2007
+ }
2008
+ if (entityType) {
2009
+ query.entityType = entityType;
2010
+ }
2011
+ if (source) {
2012
+ query.source = source;
2013
+ }
2014
+ const collection = await this.operations.getCollection(storage.TABLE_SCORERS);
2015
+ const total = await collection.countDocuments(query);
2016
+ if (total === 0) {
2017
+ return {
2018
+ scores: [],
2019
+ pagination: {
2020
+ total: 0,
2021
+ page,
2022
+ perPage: perPageInput,
2023
+ hasMore: false
2024
+ }
2025
+ };
2026
+ }
2027
+ const end = perPageInput === false ? total : start + perPage;
2028
+ let cursor = collection.find(query).sort({ createdAt: "desc" }).skip(start);
2029
+ if (perPageInput !== false) {
2030
+ cursor = cursor.limit(perPage);
2031
+ }
2032
+ const documents = await cursor.toArray();
2033
+ const scores = documents.map((row) => transformScoreRow(row));
2034
+ return {
2035
+ scores,
2036
+ pagination: {
2037
+ total,
2038
+ page,
2039
+ perPage: perPageForResponse,
2040
+ hasMore: end < total
2041
+ }
2042
+ };
2043
+ } catch (error$1) {
2044
+ throw new error.MastraError(
2045
+ {
2046
+ id: "STORAGE_MONGODB_STORE_GET_SCORES_BY_SCORER_ID_FAILED",
2047
+ domain: error.ErrorDomain.STORAGE,
2048
+ category: error.ErrorCategory.THIRD_PARTY,
2049
+ details: { scorerId, page: pagination.page, perPage: pagination.perPage }
2050
+ },
2051
+ error$1
2052
+ );
2053
+ }
2054
+ }
2055
+ async listScoresByRunId({
2056
+ runId,
2057
+ pagination
2058
+ }) {
2059
+ try {
2060
+ const { page, perPage: perPageInput } = pagination;
2061
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2062
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2063
+ const collection = await this.operations.getCollection(storage.TABLE_SCORERS);
2064
+ const total = await collection.countDocuments({ runId });
2065
+ if (total === 0) {
2066
+ return {
2067
+ scores: [],
2068
+ pagination: {
2069
+ total: 0,
2070
+ page,
2071
+ perPage: perPageInput,
2072
+ hasMore: false
2073
+ }
2074
+ };
2075
+ }
2076
+ const end = perPageInput === false ? total : start + perPage;
2077
+ let cursor = collection.find({ runId }).sort({ createdAt: "desc" }).skip(start);
2078
+ if (perPageInput !== false) {
2079
+ cursor = cursor.limit(perPage);
2080
+ }
2081
+ const documents = await cursor.toArray();
2082
+ const scores = documents.map((row) => transformScoreRow(row));
2083
+ return {
2084
+ scores,
2085
+ pagination: {
2086
+ total,
2087
+ page,
2088
+ perPage: perPageForResponse,
2089
+ hasMore: end < total
2090
+ }
2091
+ };
2092
+ } catch (error$1) {
2093
+ throw new error.MastraError(
2094
+ {
2095
+ id: "STORAGE_MONGODB_STORE_GET_SCORES_BY_RUN_ID_FAILED",
2096
+ domain: error.ErrorDomain.STORAGE,
2097
+ category: error.ErrorCategory.THIRD_PARTY,
2098
+ details: { runId, page: pagination.page, perPage: pagination.perPage }
2099
+ },
2100
+ error$1
2101
+ );
2102
+ }
2103
+ }
2104
+ async listScoresByEntityId({
2105
+ entityId,
2106
+ entityType,
2107
+ pagination
2108
+ }) {
2109
+ try {
2110
+ const { page, perPage: perPageInput } = pagination;
2111
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2112
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2113
+ const collection = await this.operations.getCollection(storage.TABLE_SCORERS);
2114
+ const total = await collection.countDocuments({ entityId, entityType });
2115
+ if (total === 0) {
2116
+ return {
2117
+ scores: [],
2118
+ pagination: {
2119
+ total: 0,
2120
+ page,
2121
+ perPage: perPageInput,
2122
+ hasMore: false
2123
+ }
2124
+ };
2125
+ }
2126
+ const end = perPageInput === false ? total : start + perPage;
2127
+ let cursor = collection.find({ entityId, entityType }).sort({ createdAt: "desc" }).skip(start);
2128
+ if (perPageInput !== false) {
2129
+ cursor = cursor.limit(perPage);
2130
+ }
2131
+ const documents = await cursor.toArray();
2132
+ const scores = documents.map((row) => transformScoreRow(row));
2133
+ return {
2134
+ scores,
2135
+ pagination: {
2136
+ total,
2137
+ page,
2138
+ perPage: perPageForResponse,
2139
+ hasMore: end < total
2140
+ }
2141
+ };
2142
+ } catch (error$1) {
2143
+ throw new error.MastraError(
2144
+ {
2145
+ id: "STORAGE_MONGODB_STORE_GET_SCORES_BY_ENTITY_ID_FAILED",
2146
+ domain: error.ErrorDomain.STORAGE,
2147
+ category: error.ErrorCategory.THIRD_PARTY,
2148
+ details: { entityId, entityType, page: pagination.page, perPage: pagination.perPage }
2149
+ },
2150
+ error$1
2151
+ );
2152
+ }
2153
+ }
2154
+ async listScoresBySpan({
2155
+ traceId,
2156
+ spanId,
2157
+ pagination
2158
+ }) {
2159
+ try {
2160
+ const { page, perPage: perPageInput } = pagination;
2161
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2162
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2163
+ const query = { traceId, spanId };
2164
+ const collection = await this.operations.getCollection(storage.TABLE_SCORERS);
2165
+ const total = await collection.countDocuments(query);
2166
+ if (total === 0) {
2167
+ return {
2168
+ scores: [],
2169
+ pagination: {
2170
+ total: 0,
2171
+ page,
2172
+ perPage: perPageInput,
2173
+ hasMore: false
2174
+ }
2175
+ };
2176
+ }
2177
+ const end = perPageInput === false ? total : start + perPage;
2178
+ let cursor = collection.find(query).sort({ createdAt: "desc" }).skip(start);
2179
+ if (perPageInput !== false) {
2180
+ cursor = cursor.limit(perPage);
2181
+ }
2182
+ const documents = await cursor.toArray();
2183
+ const scores = documents.map((row) => transformScoreRow(row));
2184
+ return {
2185
+ scores,
2186
+ pagination: {
2187
+ total,
2188
+ page,
2189
+ perPage: perPageForResponse,
2190
+ hasMore: end < total
2191
+ }
2192
+ };
2193
+ } catch (error$1) {
2194
+ throw new error.MastraError(
2195
+ {
2196
+ id: "STORAGE_MONGODB_STORE_GET_SCORES_BY_SPAN_FAILED",
2197
+ domain: error.ErrorDomain.STORAGE,
2198
+ category: error.ErrorCategory.THIRD_PARTY,
2199
+ details: { traceId, spanId, page: pagination.page, perPage: pagination.perPage }
2200
+ },
2201
+ error$1
2202
+ );
2203
+ }
2204
+ }
2205
+ };
2206
+ var WorkflowsStorageMongoDB = class extends storage.WorkflowsStorage {
2207
+ operations;
2208
+ constructor({ operations }) {
2209
+ super();
2210
+ this.operations = operations;
2211
+ }
2212
+ updateWorkflowResults({
2213
+ // workflowName,
2214
+ // runId,
2215
+ // stepId,
2216
+ // result,
2217
+ // requestContext,
2218
+ }) {
2219
+ throw new Error("Method not implemented.");
2220
+ }
2221
+ updateWorkflowState({
2222
+ // workflowName,
2223
+ // runId,
2224
+ // opts,
2225
+ }) {
2226
+ throw new Error("Method not implemented.");
2227
+ }
2228
+ async persistWorkflowSnapshot({
2229
+ workflowName,
2230
+ runId,
2231
+ resourceId,
2232
+ snapshot
2233
+ }) {
2234
+ try {
2235
+ const collection = await this.operations.getCollection(storage.TABLE_WORKFLOW_SNAPSHOT);
2236
+ await collection.updateOne(
2237
+ { workflow_name: workflowName, run_id: runId },
2238
+ {
2239
+ $set: {
2240
+ workflow_name: workflowName,
2241
+ run_id: runId,
2242
+ resourceId,
2243
+ snapshot,
2244
+ createdAt: /* @__PURE__ */ new Date(),
2245
+ updatedAt: /* @__PURE__ */ new Date()
2246
+ }
2247
+ },
2248
+ { upsert: true }
2249
+ );
2250
+ } catch (error$1) {
2251
+ throw new error.MastraError(
2252
+ {
2253
+ id: "STORAGE_MONGODB_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
2254
+ domain: error.ErrorDomain.STORAGE,
2255
+ category: error.ErrorCategory.THIRD_PARTY,
2256
+ details: { workflowName, runId }
2257
+ },
2258
+ error$1
2259
+ );
2260
+ }
2261
+ }
2262
+ async loadWorkflowSnapshot({
2263
+ workflowName,
2264
+ runId
2265
+ }) {
2266
+ try {
2267
+ const result = await this.operations.load({
2268
+ tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
2269
+ keys: {
2270
+ workflow_name: workflowName,
2271
+ run_id: runId
2272
+ }
2273
+ });
2274
+ if (!result?.length) {
2275
+ return null;
2276
+ }
2277
+ return typeof result[0].snapshot === "string" ? storage.safelyParseJSON(result[0].snapshot) : result[0].snapshot;
2278
+ } catch (error$1) {
2279
+ throw new error.MastraError(
2280
+ {
2281
+ id: "STORAGE_MONGODB_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
2282
+ domain: error.ErrorDomain.STORAGE,
2283
+ category: error.ErrorCategory.THIRD_PARTY,
2284
+ details: { workflowName, runId }
2285
+ },
2286
+ error$1
2287
+ );
2288
+ }
2289
+ }
2290
+ async listWorkflowRuns(args) {
2291
+ const options = args || {};
2292
+ try {
2293
+ const query = {};
2294
+ if (options.workflowName) {
2295
+ query["workflow_name"] = options.workflowName;
2296
+ }
2297
+ if (options.fromDate) {
2298
+ query["createdAt"] = { $gte: options.fromDate };
2299
+ }
2300
+ if (options.toDate) {
2301
+ if (query["createdAt"]) {
2302
+ query["createdAt"].$lte = options.toDate;
2303
+ } else {
2304
+ query["createdAt"] = { $lte: options.toDate };
2305
+ }
2306
+ }
2307
+ if (options.resourceId) {
2308
+ query["resourceId"] = options.resourceId;
2309
+ }
2310
+ const collection = await this.operations.getCollection(storage.TABLE_WORKFLOW_SNAPSHOT);
2311
+ let total = 0;
2312
+ let cursor = collection.find(query).sort({ createdAt: -1 });
2313
+ if (options.page !== void 0 && typeof options.perPage === "number") {
2314
+ if (options.page < 0) {
2315
+ throw new error.MastraError(
2316
+ {
2317
+ id: "STORAGE_MONGODB_INVALID_PAGE",
2318
+ domain: error.ErrorDomain.STORAGE,
2319
+ category: error.ErrorCategory.USER,
2320
+ details: { page: options.page }
2321
+ },
2322
+ new Error("page must be >= 0")
2323
+ );
2324
+ }
2325
+ total = await collection.countDocuments(query);
2326
+ const normalizedPerPage = storage.normalizePerPage(options.perPage, Number.MAX_SAFE_INTEGER);
2327
+ if (normalizedPerPage === 0) {
2328
+ return { runs: [], total };
2329
+ }
2330
+ const offset = options.page * normalizedPerPage;
2331
+ cursor = cursor.skip(offset);
2332
+ cursor = cursor.limit(Math.min(normalizedPerPage, 2147483647));
2333
+ }
2334
+ const results = await cursor.toArray();
2335
+ const runs = results.map((row) => this.parseWorkflowRun(row));
2336
+ return {
2337
+ runs,
2338
+ total: total || runs.length
2339
+ };
2340
+ } catch (error$1) {
2341
+ throw new error.MastraError(
2342
+ {
2343
+ id: "STORAGE_MONGODB_STORE_LIST_WORKFLOW_RUNS_FAILED",
2344
+ domain: error.ErrorDomain.STORAGE,
2345
+ category: error.ErrorCategory.THIRD_PARTY,
2346
+ details: { workflowName: options.workflowName || "unknown" }
2347
+ },
2348
+ error$1
2349
+ );
2350
+ }
2351
+ }
2352
+ async getWorkflowRunById(args) {
2353
+ try {
2354
+ const query = {};
2355
+ if (args.runId) {
2356
+ query["run_id"] = args.runId;
2357
+ }
2358
+ if (args.workflowName) {
2359
+ query["workflow_name"] = args.workflowName;
2360
+ }
2361
+ const collection = await this.operations.getCollection(storage.TABLE_WORKFLOW_SNAPSHOT);
2362
+ const result = await collection.findOne(query);
2363
+ if (!result) {
2364
+ return null;
2365
+ }
2366
+ return this.parseWorkflowRun(result);
2367
+ } catch (error$1) {
2368
+ throw new error.MastraError(
2369
+ {
2370
+ id: "STORAGE_MONGODB_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
2371
+ domain: error.ErrorDomain.STORAGE,
2372
+ category: error.ErrorCategory.THIRD_PARTY,
2373
+ details: { runId: args.runId }
2374
+ },
2375
+ error$1
2376
+ );
2377
+ }
2378
+ }
2379
+ parseWorkflowRun(row) {
2380
+ let parsedSnapshot = row.snapshot;
2381
+ if (typeof parsedSnapshot === "string") {
2382
+ try {
2383
+ parsedSnapshot = typeof row.snapshot === "string" ? storage.safelyParseJSON(row.snapshot) : row.snapshot;
2384
+ } catch (e) {
2385
+ console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
2386
+ }
2387
+ }
2388
+ return {
2389
+ workflowName: row.workflow_name,
2390
+ runId: row.run_id,
2391
+ snapshot: parsedSnapshot,
2392
+ createdAt: new Date(row.createdAt),
2393
+ updatedAt: new Date(row.updatedAt),
2394
+ resourceId: row.resourceId
2395
+ };
2396
+ }
2397
+ };
2398
+
2399
+ // src/storage/index.ts
2400
+ var loadConnector = (config) => {
2401
+ try {
2402
+ if ("connectorHandler" in config) {
2403
+ return MongoDBConnector.fromConnectionHandler(config.connectorHandler);
2404
+ }
2405
+ } catch (error$1) {
2406
+ throw new error.MastraError(
2407
+ {
2408
+ id: "STORAGE_MONGODB_STORE_CONSTRUCTOR_FAILED",
2409
+ domain: error.ErrorDomain.STORAGE,
2410
+ category: error.ErrorCategory.USER,
2411
+ details: { connectionHandler: true }
2412
+ },
2413
+ error$1
2414
+ );
2415
+ }
2416
+ try {
2417
+ return MongoDBConnector.fromDatabaseConfig({
2418
+ options: config.options,
2419
+ url: config.url,
2420
+ dbName: config.dbName
2421
+ });
2422
+ } catch (error$1) {
2423
+ throw new error.MastraError(
2424
+ {
2425
+ id: "STORAGE_MONGODB_STORE_CONSTRUCTOR_FAILED",
2426
+ domain: error.ErrorDomain.STORAGE,
2427
+ category: error.ErrorCategory.USER,
2428
+ details: { url: config?.url, dbName: config?.dbName }
2429
+ },
2430
+ error$1
2431
+ );
2432
+ }
2433
+ };
2434
+ var MongoDBStore = class extends storage.MastraStorage {
2435
+ #connector;
2436
+ stores;
2437
+ get supports() {
2438
+ return {
2439
+ selectByIncludeResourceScope: true,
2440
+ resourceWorkingMemory: true,
2441
+ hasColumn: false,
2442
+ createTable: false,
2443
+ deleteMessages: false,
2444
+ listScoresBySpan: true
2445
+ };
2446
+ }
2447
+ constructor(config) {
2448
+ super({ name: "MongoDBStore" });
2449
+ this.stores = {};
2450
+ this.#connector = loadConnector(config);
2451
+ const operations = new StoreOperationsMongoDB({
2452
+ connector: this.#connector
2453
+ });
2454
+ const memory = new MemoryStorageMongoDB({
2455
+ operations
2456
+ });
2457
+ const scores = new ScoresStorageMongoDB({
2458
+ operations
2459
+ });
2460
+ const workflows = new WorkflowsStorageMongoDB({
2461
+ operations
2462
+ });
2463
+ const observability = new ObservabilityMongoDB({
2464
+ operations
2465
+ });
2466
+ this.stores = {
2467
+ operations,
2468
+ memory,
2469
+ scores,
2470
+ workflows,
2471
+ observability
2472
+ };
2473
+ }
2474
+ async createTable({
2475
+ tableName,
2476
+ schema
2477
+ }) {
2478
+ return this.stores.operations.createTable({ tableName, schema });
2479
+ }
2480
+ async alterTable(_args) {
2481
+ return this.stores.operations.alterTable(_args);
2482
+ }
2483
+ async dropTable({ tableName }) {
2484
+ return this.stores.operations.dropTable({ tableName });
2485
+ }
2486
+ async clearTable({ tableName }) {
2487
+ return this.stores.operations.clearTable({ tableName });
2488
+ }
2489
+ async insert({ tableName, record }) {
2490
+ return this.stores.operations.insert({ tableName, record });
2491
+ }
2492
+ async batchInsert({ tableName, records }) {
2493
+ return this.stores.operations.batchInsert({ tableName, records });
2494
+ }
2495
+ async load({ tableName, keys }) {
2496
+ return this.stores.operations.load({ tableName, keys });
2497
+ }
2498
+ async getThreadById({ threadId }) {
2499
+ return this.stores.memory.getThreadById({ threadId });
2500
+ }
2501
+ async saveThread({ thread }) {
2502
+ return this.stores.memory.saveThread({ thread });
2503
+ }
2504
+ async updateThread({
2505
+ id,
2506
+ title,
2507
+ metadata
2508
+ }) {
2509
+ return this.stores.memory.updateThread({ id, title, metadata });
2510
+ }
2511
+ async deleteThread({ threadId }) {
2512
+ return this.stores.memory.deleteThread({ threadId });
2513
+ }
2514
+ async getMessages(args) {
2515
+ return this.stores.memory.getMessages(args);
2516
+ }
2517
+ async listMessagesById({ messageIds }) {
2518
+ return this.stores.memory.listMessagesById({ messageIds });
2519
+ }
2520
+ async saveMessages(args) {
2521
+ return this.stores.memory.saveMessages(args);
2522
+ }
2523
+ async updateMessages(_args) {
2524
+ return this.stores.memory.updateMessages(_args);
2525
+ }
2526
+ async listWorkflowRuns(args) {
2527
+ return this.stores.workflows.listWorkflowRuns(args);
2528
+ }
2529
+ async updateWorkflowResults({
2530
+ workflowName,
2531
+ runId,
2532
+ stepId,
2533
+ result,
2534
+ requestContext
2535
+ }) {
2536
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
2537
+ }
2538
+ async updateWorkflowState({
2539
+ workflowName,
2540
+ runId,
2541
+ opts
2542
+ }) {
2543
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2544
+ }
2545
+ async persistWorkflowSnapshot({
2546
+ workflowName,
2547
+ runId,
2548
+ resourceId,
2549
+ snapshot
2550
+ }) {
2551
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
2552
+ }
2553
+ async loadWorkflowSnapshot({
2554
+ workflowName,
2555
+ runId
2556
+ }) {
2557
+ return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
2558
+ }
2559
+ async getWorkflowRunById({
2560
+ runId,
2561
+ workflowName
2562
+ }) {
2563
+ return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
2564
+ }
2565
+ async close() {
2566
+ try {
2567
+ await this.#connector.close();
2568
+ } catch (error$1) {
2569
+ throw new error.MastraError(
2570
+ {
2571
+ id: "STORAGE_MONGODB_STORE_CLOSE_FAILED",
2572
+ domain: error.ErrorDomain.STORAGE,
2573
+ category: error.ErrorCategory.USER
2574
+ },
2575
+ error$1
2576
+ );
2577
+ }
2578
+ }
2579
+ /**
2580
+ * SCORERS
2581
+ */
2582
+ async getScoreById({ id }) {
2583
+ return this.stores.scores.getScoreById({ id });
2584
+ }
2585
+ async saveScore(score) {
2586
+ return this.stores.scores.saveScore(score);
2587
+ }
2588
+ async listScoresByRunId({
2589
+ runId,
2590
+ pagination
2591
+ }) {
2592
+ return this.stores.scores.listScoresByRunId({ runId, pagination });
2593
+ }
2594
+ async listScoresByEntityId({
2595
+ entityId,
2596
+ entityType,
2597
+ pagination
2598
+ }) {
2599
+ return this.stores.scores.listScoresByEntityId({ entityId, entityType, pagination });
2600
+ }
2601
+ async listScoresByScorerId({
2602
+ scorerId,
2603
+ pagination,
2604
+ entityId,
2605
+ entityType,
2606
+ source
2607
+ }) {
2608
+ return this.stores.scores.listScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2609
+ }
2610
+ async listScoresBySpan({
2611
+ traceId,
2612
+ spanId,
2613
+ pagination
2614
+ }) {
2615
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
2616
+ }
2617
+ /**
2618
+ * RESOURCES
2619
+ */
2620
+ async getResourceById({ resourceId }) {
2621
+ return this.stores.memory.getResourceById({ resourceId });
2622
+ }
2623
+ async saveResource({ resource }) {
2624
+ return this.stores.memory.saveResource({ resource });
2625
+ }
2626
+ async updateResource({
2627
+ resourceId,
2628
+ workingMemory,
2629
+ metadata
2630
+ }) {
2631
+ return this.stores.memory.updateResource({
2632
+ resourceId,
2633
+ workingMemory,
2634
+ metadata
2635
+ });
2636
+ }
2637
+ /**
2638
+ * AI Tracing/Observability
2639
+ */
2640
+ async createAISpan(span) {
2641
+ if (!this.stores.observability) {
2642
+ throw new error.MastraError({
2643
+ id: "MONGODB_STORE_OBSERVABILITY_NOT_INITIALIZED",
2644
+ domain: error.ErrorDomain.STORAGE,
2645
+ category: error.ErrorCategory.SYSTEM,
2646
+ text: "Observability storage is not initialized"
2647
+ });
2648
+ }
2649
+ return this.stores.observability.createAISpan(span);
2650
+ }
2651
+ async updateAISpan({
2652
+ spanId,
2653
+ traceId,
2654
+ updates
2655
+ }) {
2656
+ if (!this.stores.observability) {
2657
+ throw new error.MastraError({
2658
+ id: "MONGODB_STORE_OBSERVABILITY_NOT_INITIALIZED",
2659
+ domain: error.ErrorDomain.STORAGE,
2660
+ category: error.ErrorCategory.SYSTEM,
2661
+ text: "Observability storage is not initialized"
2662
+ });
2663
+ }
2664
+ return this.stores.observability.updateAISpan({ spanId, traceId, updates });
2665
+ }
2666
+ async getAITrace(traceId) {
2667
+ if (!this.stores.observability) {
2668
+ throw new error.MastraError({
2669
+ id: "MONGODB_STORE_OBSERVABILITY_NOT_INITIALIZED",
2670
+ domain: error.ErrorDomain.STORAGE,
2671
+ category: error.ErrorCategory.SYSTEM,
2672
+ text: "Observability storage is not initialized"
2673
+ });
2674
+ }
2675
+ return this.stores.observability.getAITrace(traceId);
2676
+ }
2677
+ async getAITracesPaginated(args) {
2678
+ if (!this.stores.observability) {
2679
+ throw new error.MastraError({
2680
+ id: "MONGODB_STORE_OBSERVABILITY_NOT_INITIALIZED",
2681
+ domain: error.ErrorDomain.STORAGE,
2682
+ category: error.ErrorCategory.SYSTEM,
2683
+ text: "Observability storage is not initialized"
2684
+ });
2685
+ }
2686
+ return this.stores.observability.getAITracesPaginated(args);
2687
+ }
2688
+ async batchCreateAISpans(args) {
2689
+ if (!this.stores.observability) {
2690
+ throw new error.MastraError({
2691
+ id: "MONGODB_STORE_OBSERVABILITY_NOT_INITIALIZED",
2692
+ domain: error.ErrorDomain.STORAGE,
2693
+ category: error.ErrorCategory.SYSTEM,
2694
+ text: "Observability storage is not initialized"
2695
+ });
2696
+ }
2697
+ return this.stores.observability.batchCreateAISpans(args);
2698
+ }
2699
+ async batchUpdateAISpans(args) {
2700
+ if (!this.stores.observability) {
2701
+ throw new error.MastraError({
2702
+ id: "MONGODB_STORE_OBSERVABILITY_NOT_INITIALIZED",
2703
+ domain: error.ErrorDomain.STORAGE,
2704
+ category: error.ErrorCategory.SYSTEM,
2705
+ text: "Observability storage is not initialized"
2706
+ });
2707
+ }
2708
+ return this.stores.observability.batchUpdateAISpans(args);
2709
+ }
2710
+ async batchDeleteAITraces(args) {
2711
+ if (!this.stores.observability) {
2712
+ throw new error.MastraError({
2713
+ id: "MONGODB_STORE_OBSERVABILITY_NOT_INITIALIZED",
2714
+ domain: error.ErrorDomain.STORAGE,
2715
+ category: error.ErrorCategory.SYSTEM,
2716
+ text: "Observability storage is not initialized"
2717
+ });
2718
+ }
2719
+ return this.stores.observability.batchDeleteAITraces(args);
2720
+ }
359
2721
  };
360
2722
 
361
2723
  // src/vector/prompt.ts
@@ -454,4 +2816,7 @@ Example Complex Query:
454
2816
  }`;
455
2817
 
456
2818
  exports.MONGODB_PROMPT = MONGODB_PROMPT;
2819
+ exports.MongoDBStore = MongoDBStore;
457
2820
  exports.MongoDBVector = MongoDBVector;
2821
+ //# sourceMappingURL=index.cjs.map
2822
+ //# sourceMappingURL=index.cjs.map