@mastra/mongodb 1.2.0-alpha.0 → 1.3.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -14,7 +14,7 @@ var evals = require('@mastra/core/evals');
14
14
 
15
15
  // package.json
16
16
  var package_default = {
17
- version: "1.2.0-alpha.0"};
17
+ version: "1.3.0-alpha.0"};
18
18
  var MongoDBFilterTranslator = class extends filter.BaseFilterTranslator {
19
19
  getSupportedOperators() {
20
20
  return {
@@ -973,6 +973,42 @@ var MongoDBAgentsStorage = class _MongoDBAgentsStorage extends storage.AgentsSto
973
973
  async init() {
974
974
  await this.createDefaultIndexes();
975
975
  await this.createCustomIndexes();
976
+ await this.#migrateToolsToJsonbFormat();
977
+ }
978
+ /**
979
+ * Migrates the tools field from string[] format to object format { "tool-key": { "description": "..." } }.
980
+ * This handles the transition from the old format where tools were stored as an array of string keys
981
+ * to the new format where tools can have per-agent description overrides.
982
+ */
983
+ async #migrateToolsToJsonbFormat() {
984
+ try {
985
+ const versionsCollection = await this.getCollection(storage.TABLE_AGENT_VERSIONS);
986
+ const cursor = versionsCollection.find({ tools: { $type: "array" } });
987
+ const updates = [];
988
+ for await (const doc of cursor) {
989
+ if (Array.isArray(doc.tools)) {
990
+ const toolsObject = {};
991
+ for (const toolKey of doc.tools) {
992
+ if (typeof toolKey === "string") {
993
+ toolsObject[toolKey] = {};
994
+ }
995
+ }
996
+ updates.push({ id: doc.id, tools: toolsObject });
997
+ }
998
+ }
999
+ if (updates.length > 0) {
1000
+ const bulkOps = updates.map((update) => ({
1001
+ updateOne: {
1002
+ filter: { id: update.id },
1003
+ update: { $set: { tools: update.tools } }
1004
+ }
1005
+ }));
1006
+ await versionsCollection.bulkWrite(bulkOps);
1007
+ this.logger?.info?.(`Migrated ${updates.length} agent version tools from array to object format`);
1008
+ }
1009
+ } catch (error) {
1010
+ this.logger?.warn?.("Failed to migrate tools to object format:", error);
1011
+ }
976
1012
  }
977
1013
  async dangerouslyClearAll() {
978
1014
  const versionsCollection = await this.getCollection(storage.TABLE_AGENT_VERSIONS);
@@ -980,7 +1016,7 @@ var MongoDBAgentsStorage = class _MongoDBAgentsStorage extends storage.AgentsSto
980
1016
  const agentsCollection = await this.getCollection(storage.TABLE_AGENTS);
981
1017
  await agentsCollection.deleteMany({});
982
1018
  }
983
- async getAgentById({ id }) {
1019
+ async getById(id) {
984
1020
  try {
985
1021
  const collection = await this.getCollection(storage.TABLE_AGENTS);
986
1022
  const result = await collection.findOne({ id });
@@ -1000,7 +1036,8 @@ var MongoDBAgentsStorage = class _MongoDBAgentsStorage extends storage.AgentsSto
1000
1036
  );
1001
1037
  }
1002
1038
  }
1003
- async createAgent({ agent }) {
1039
+ async create(input) {
1040
+ const { agent } = input;
1004
1041
  try {
1005
1042
  const collection = await this.getCollection(storage.TABLE_AGENTS);
1006
1043
  const existing = await collection.findOne({ id: agent.id });
@@ -1050,7 +1087,8 @@ var MongoDBAgentsStorage = class _MongoDBAgentsStorage extends storage.AgentsSto
1050
1087
  );
1051
1088
  }
1052
1089
  }
1053
- async updateAgent({ id, ...updates }) {
1090
+ async update(input) {
1091
+ const { id, ...updates } = input;
1054
1092
  try {
1055
1093
  const collection = await this.getCollection(storage.TABLE_AGENTS);
1056
1094
  const existingAgent = await collection.findOne({ id });
@@ -1089,14 +1127,17 @@ var MongoDBAgentsStorage = class _MongoDBAgentsStorage extends storage.AgentsSto
1089
1127
  details: { id }
1090
1128
  });
1091
1129
  }
1130
+ const sanitizedConfigFields = Object.fromEntries(
1131
+ Object.entries(configFields).map(([key, value]) => [key, value === null ? void 0 : value])
1132
+ );
1092
1133
  const versionInput = {
1093
1134
  id: crypto.randomUUID(),
1094
1135
  agentId: id,
1095
1136
  versionNumber: nextVersionNumber,
1096
1137
  ...this.extractSnapshotFields(latestVersion),
1097
1138
  // Start from latest version
1098
- ...configFields,
1099
- // Apply updates
1139
+ ...sanitizedConfigFields,
1140
+ // Apply updates (null values converted to undefined)
1100
1141
  changedFields: Object.keys(configFields),
1101
1142
  changeMessage: `Updated: ${Object.keys(configFields).join(", ")}`
1102
1143
  };
@@ -1137,9 +1178,9 @@ var MongoDBAgentsStorage = class _MongoDBAgentsStorage extends storage.AgentsSto
1137
1178
  );
1138
1179
  }
1139
1180
  }
1140
- async deleteAgent({ id }) {
1181
+ async delete(id) {
1141
1182
  try {
1142
- await this.deleteVersionsByAgentId(id);
1183
+ await this.deleteVersionsByParentId(id);
1143
1184
  const collection = await this.getCollection(storage.TABLE_AGENTS);
1144
1185
  await collection.deleteOne({ id });
1145
1186
  } catch (error$1) {
@@ -1154,7 +1195,7 @@ var MongoDBAgentsStorage = class _MongoDBAgentsStorage extends storage.AgentsSto
1154
1195
  );
1155
1196
  }
1156
1197
  }
1157
- async listAgents(args) {
1198
+ async list(args) {
1158
1199
  try {
1159
1200
  const { page = 0, perPage: perPageInput, orderBy } = args || {};
1160
1201
  const { field, direction } = this.parseOrderBy(orderBy);
@@ -1210,123 +1251,6 @@ var MongoDBAgentsStorage = class _MongoDBAgentsStorage extends storage.AgentsSto
1210
1251
  );
1211
1252
  }
1212
1253
  }
1213
- async listAgentsResolved(args) {
1214
- try {
1215
- const { page = 0, perPage: perPageInput, orderBy } = args || {};
1216
- const { field, direction } = this.parseOrderBy(orderBy);
1217
- if (page < 0) {
1218
- throw new error.MastraError(
1219
- {
1220
- id: storage.createStorageErrorId("MONGODB", "LIST_AGENTS_RESOLVED", "INVALID_PAGE"),
1221
- domain: error.ErrorDomain.STORAGE,
1222
- category: error.ErrorCategory.USER,
1223
- details: { page }
1224
- },
1225
- new Error("page must be >= 0")
1226
- );
1227
- }
1228
- const perPage = storage.normalizePerPage(perPageInput, 100);
1229
- const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1230
- const agentsCollection = await this.getCollection(storage.TABLE_AGENTS);
1231
- const total = await agentsCollection.countDocuments({});
1232
- if (total === 0 || perPage === 0) {
1233
- return {
1234
- agents: [],
1235
- total,
1236
- page,
1237
- perPage: perPageForResponse,
1238
- hasMore: false
1239
- };
1240
- }
1241
- const sortOrder = direction === "ASC" ? 1 : -1;
1242
- const pipeline = [
1243
- // Sort agents
1244
- { $sort: { [field]: sortOrder } },
1245
- // Paginate
1246
- { $skip: offset }
1247
- ];
1248
- if (perPageInput !== false) {
1249
- pipeline.push({ $limit: perPage });
1250
- }
1251
- pipeline.push({
1252
- $lookup: {
1253
- from: storage.TABLE_AGENT_VERSIONS,
1254
- localField: "activeVersionId",
1255
- foreignField: "id",
1256
- as: "activeVersion"
1257
- }
1258
- });
1259
- pipeline.push({
1260
- $lookup: {
1261
- from: storage.TABLE_AGENT_VERSIONS,
1262
- let: { agentId: "$id" },
1263
- pipeline: [
1264
- { $match: { $expr: { $eq: ["$agentId", "$$agentId"] } } },
1265
- { $sort: { versionNumber: -1 } },
1266
- { $limit: 1 }
1267
- ],
1268
- as: "latestVersion"
1269
- }
1270
- });
1271
- pipeline.push({
1272
- $addFields: {
1273
- version: {
1274
- $cond: {
1275
- if: { $gt: [{ $size: "$activeVersion" }, 0] },
1276
- then: { $arrayElemAt: ["$activeVersion", 0] },
1277
- else: { $arrayElemAt: ["$latestVersion", 0] }
1278
- }
1279
- }
1280
- }
1281
- });
1282
- pipeline.push({
1283
- $project: {
1284
- activeVersion: 0,
1285
- latestVersion: 0
1286
- }
1287
- });
1288
- const results = await agentsCollection.aggregate(pipeline).toArray();
1289
- const resolvedAgents = results.map((doc) => {
1290
- const agent = this.transformAgent(doc);
1291
- if (doc.version) {
1292
- const version = this.transformVersion(doc.version);
1293
- const {
1294
- id: _versionId,
1295
- agentId: _agentId,
1296
- versionNumber: _versionNumber,
1297
- changedFields: _changedFields,
1298
- changeMessage: _changeMessage,
1299
- createdAt: _createdAt,
1300
- ...snapshotConfig
1301
- } = version;
1302
- return {
1303
- ...agent,
1304
- ...snapshotConfig
1305
- };
1306
- }
1307
- return agent;
1308
- });
1309
- return {
1310
- agents: resolvedAgents,
1311
- total,
1312
- page,
1313
- perPage: perPageForResponse,
1314
- hasMore: perPageInput !== false && offset + perPage < total
1315
- };
1316
- } catch (error$1) {
1317
- if (error$1 instanceof error.MastraError) {
1318
- throw error$1;
1319
- }
1320
- throw new error.MastraError(
1321
- {
1322
- id: storage.createStorageErrorId("MONGODB", "LIST_AGENTS_RESOLVED", "FAILED"),
1323
- domain: error.ErrorDomain.STORAGE,
1324
- category: error.ErrorCategory.THIRD_PARTY
1325
- },
1326
- error$1
1327
- );
1328
- }
1329
- }
1330
1254
  /**
1331
1255
  * Transforms a raw MongoDB document into a thin StorageAgentType record.
1332
1256
  * Only returns metadata-level fields (no config/snapshot fields).
@@ -1525,7 +1449,7 @@ var MongoDBAgentsStorage = class _MongoDBAgentsStorage extends storage.AgentsSto
1525
1449
  );
1526
1450
  }
1527
1451
  }
1528
- async deleteVersionsByAgentId(agentId) {
1452
+ async deleteVersionsByParentId(agentId) {
1529
1453
  try {
1530
1454
  const collection = await this.getCollection(storage.TABLE_AGENT_VERSIONS);
1531
1455
  await collection.deleteMany({ agentId });
@@ -2460,12 +2384,26 @@ var MemoryStorageMongoDB = class _MemoryStorageMongoDB extends storage.MemorySto
2460
2384
  originType: doc.originType || "initial",
2461
2385
  generationCount: Number(doc.generationCount || 0),
2462
2386
  activeObservations: doc.activeObservations || "",
2387
+ // Handle new chunk-based structure
2388
+ bufferedObservationChunks: doc.bufferedObservationChunks || void 0,
2389
+ // Deprecated fields (for backward compatibility)
2463
2390
  bufferedObservations: doc.activeObservationsPendingUpdate || void 0,
2391
+ bufferedObservationTokens: doc.bufferedObservationTokens ? Number(doc.bufferedObservationTokens) : void 0,
2392
+ bufferedMessageIds: void 0,
2393
+ // Use bufferedObservationChunks instead
2394
+ bufferedReflection: doc.bufferedReflection || void 0,
2395
+ bufferedReflectionTokens: doc.bufferedReflectionTokens ? Number(doc.bufferedReflectionTokens) : void 0,
2396
+ bufferedReflectionInputTokens: doc.bufferedReflectionInputTokens ? Number(doc.bufferedReflectionInputTokens) : void 0,
2397
+ reflectedObservationLineCount: doc.reflectedObservationLineCount ? Number(doc.reflectedObservationLineCount) : void 0,
2464
2398
  totalTokensObserved: Number(doc.totalTokensObserved || 0),
2465
2399
  observationTokenCount: Number(doc.observationTokenCount || 0),
2466
2400
  pendingMessageTokens: Number(doc.pendingMessageTokens || 0),
2467
2401
  isReflecting: Boolean(doc.isReflecting),
2468
2402
  isObserving: Boolean(doc.isObserving),
2403
+ isBufferingObservation: Boolean(doc.isBufferingObservation),
2404
+ isBufferingReflection: Boolean(doc.isBufferingReflection),
2405
+ lastBufferedAtTokens: typeof doc.lastBufferedAtTokens === "number" ? doc.lastBufferedAtTokens : parseInt(String(doc.lastBufferedAtTokens ?? "0"), 10) || 0,
2406
+ lastBufferedAtTime: doc.lastBufferedAtTime ? new Date(doc.lastBufferedAtTime) : null,
2469
2407
  config: doc.config || {},
2470
2408
  metadata: doc.metadata || void 0,
2471
2409
  observedMessageIds: doc.observedMessageIds || void 0,
@@ -2530,6 +2468,10 @@ var MemoryStorageMongoDB = class _MemoryStorageMongoDB extends storage.MemorySto
2530
2468
  pendingMessageTokens: 0,
2531
2469
  isReflecting: false,
2532
2470
  isObserving: false,
2471
+ isBufferingObservation: false,
2472
+ isBufferingReflection: false,
2473
+ lastBufferedAtTokens: 0,
2474
+ lastBufferedAtTime: null,
2533
2475
  config: input.config,
2534
2476
  observedTimezone: input.observedTimezone
2535
2477
  };
@@ -2552,6 +2494,10 @@ var MemoryStorageMongoDB = class _MemoryStorageMongoDB extends storage.MemorySto
2552
2494
  observationTokenCount: 0,
2553
2495
  isObserving: false,
2554
2496
  isReflecting: false,
2497
+ isBufferingObservation: false,
2498
+ isBufferingReflection: false,
2499
+ lastBufferedAtTokens: 0,
2500
+ lastBufferedAtTime: null,
2555
2501
  observedTimezone: input.observedTimezone || null,
2556
2502
  createdAt: now,
2557
2503
  updatedAt: now
@@ -2634,6 +2580,10 @@ var MemoryStorageMongoDB = class _MemoryStorageMongoDB extends storage.MemorySto
2634
2580
  pendingMessageTokens: 0,
2635
2581
  isReflecting: false,
2636
2582
  isObserving: false,
2583
+ isBufferingObservation: false,
2584
+ isBufferingReflection: false,
2585
+ lastBufferedAtTokens: 0,
2586
+ lastBufferedAtTime: null,
2637
2587
  config: input.currentRecord.config,
2638
2588
  metadata: input.currentRecord.metadata,
2639
2589
  observedTimezone: input.currentRecord.observedTimezone
@@ -2657,6 +2607,10 @@ var MemoryStorageMongoDB = class _MemoryStorageMongoDB extends storage.MemorySto
2657
2607
  observationTokenCount: record.observationTokenCount,
2658
2608
  isObserving: false,
2659
2609
  isReflecting: false,
2610
+ isBufferingObservation: false,
2611
+ isBufferingReflection: false,
2612
+ lastBufferedAtTokens: 0,
2613
+ lastBufferedAtTime: null,
2660
2614
  observedTimezone: record.observedTimezone || null,
2661
2615
  createdAt: now,
2662
2616
  updatedAt: now,
@@ -2731,6 +2685,72 @@ var MemoryStorageMongoDB = class _MemoryStorageMongoDB extends storage.MemorySto
2731
2685
  );
2732
2686
  }
2733
2687
  }
2688
+ async setBufferingObservationFlag(id, isBuffering, lastBufferedAtTokens) {
2689
+ try {
2690
+ const collection = await this.getCollection(OM_TABLE);
2691
+ const updateDoc = {
2692
+ isBufferingObservation: isBuffering,
2693
+ updatedAt: /* @__PURE__ */ new Date()
2694
+ };
2695
+ if (lastBufferedAtTokens !== void 0) {
2696
+ updateDoc.lastBufferedAtTokens = lastBufferedAtTokens;
2697
+ }
2698
+ const result = await collection.updateOne({ id }, { $set: updateDoc });
2699
+ if (result.matchedCount === 0) {
2700
+ throw new error.MastraError({
2701
+ id: storage.createStorageErrorId("MONGODB", "SET_BUFFERING_OBSERVATION_FLAG", "NOT_FOUND"),
2702
+ text: `Observational memory record not found: ${id}`,
2703
+ domain: error.ErrorDomain.STORAGE,
2704
+ category: error.ErrorCategory.THIRD_PARTY,
2705
+ details: { id, isBuffering, lastBufferedAtTokens: lastBufferedAtTokens ?? null }
2706
+ });
2707
+ }
2708
+ } catch (error$1) {
2709
+ if (error$1 instanceof error.MastraError) {
2710
+ throw error$1;
2711
+ }
2712
+ throw new error.MastraError(
2713
+ {
2714
+ id: storage.createStorageErrorId("MONGODB", "SET_BUFFERING_OBSERVATION_FLAG", "FAILED"),
2715
+ domain: error.ErrorDomain.STORAGE,
2716
+ category: error.ErrorCategory.THIRD_PARTY,
2717
+ details: { id, isBuffering, lastBufferedAtTokens: lastBufferedAtTokens ?? null }
2718
+ },
2719
+ error$1
2720
+ );
2721
+ }
2722
+ }
2723
+ async setBufferingReflectionFlag(id, isBuffering) {
2724
+ try {
2725
+ const collection = await this.getCollection(OM_TABLE);
2726
+ const result = await collection.updateOne(
2727
+ { id },
2728
+ { $set: { isBufferingReflection: isBuffering, updatedAt: /* @__PURE__ */ new Date() } }
2729
+ );
2730
+ if (result.matchedCount === 0) {
2731
+ throw new error.MastraError({
2732
+ id: storage.createStorageErrorId("MONGODB", "SET_BUFFERING_REFLECTION_FLAG", "NOT_FOUND"),
2733
+ text: `Observational memory record not found: ${id}`,
2734
+ domain: error.ErrorDomain.STORAGE,
2735
+ category: error.ErrorCategory.THIRD_PARTY,
2736
+ details: { id, isBuffering }
2737
+ });
2738
+ }
2739
+ } catch (error$1) {
2740
+ if (error$1 instanceof error.MastraError) {
2741
+ throw error$1;
2742
+ }
2743
+ throw new error.MastraError(
2744
+ {
2745
+ id: storage.createStorageErrorId("MONGODB", "SET_BUFFERING_REFLECTION_FLAG", "FAILED"),
2746
+ domain: error.ErrorDomain.STORAGE,
2747
+ category: error.ErrorCategory.THIRD_PARTY,
2748
+ details: { id, isBuffering }
2749
+ },
2750
+ error$1
2751
+ );
2752
+ }
2753
+ }
2734
2754
  async clearObservationalMemory(threadId, resourceId) {
2735
2755
  try {
2736
2756
  const lookupKey = this.getOMKey(threadId, resourceId);
@@ -2791,116 +2811,405 @@ var MemoryStorageMongoDB = class _MemoryStorageMongoDB extends storage.MemorySto
2791
2811
  );
2792
2812
  }
2793
2813
  }
2794
- };
2795
- var ObservabilityMongoDB = class _ObservabilityMongoDB extends storage.ObservabilityStorage {
2796
- #connector;
2797
- #skipDefaultIndexes;
2798
- #indexes;
2799
- /** Collections managed by this domain */
2800
- static MANAGED_COLLECTIONS = [storage.TABLE_SPANS];
2801
- constructor(config) {
2802
- super();
2803
- this.#connector = resolveMongoDBConfig(config);
2804
- this.#skipDefaultIndexes = config.skipDefaultIndexes;
2805
- this.#indexes = config.indexes?.filter(
2806
- (idx) => _ObservabilityMongoDB.MANAGED_COLLECTIONS.includes(idx.collection)
2807
- );
2808
- }
2809
- async getCollection(name) {
2810
- return this.#connector.getCollection(name);
2811
- }
2812
- /**
2813
- * Returns default index definitions for the observability domain collections.
2814
- * These indexes optimize common query patterns for span and trace lookups.
2815
- */
2816
- getDefaultIndexDefinitions() {
2817
- return [
2818
- { collection: storage.TABLE_SPANS, keys: { spanId: 1, traceId: 1 }, options: { unique: true } },
2819
- { collection: storage.TABLE_SPANS, keys: { traceId: 1 } },
2820
- { collection: storage.TABLE_SPANS, keys: { parentSpanId: 1 } },
2821
- { collection: storage.TABLE_SPANS, keys: { startedAt: -1 } },
2822
- { collection: storage.TABLE_SPANS, keys: { spanType: 1 } },
2823
- { collection: storage.TABLE_SPANS, keys: { name: 1 } }
2824
- ];
2825
- }
2826
- async createDefaultIndexes() {
2827
- if (this.#skipDefaultIndexes) {
2828
- return;
2829
- }
2830
- for (const indexDef of this.getDefaultIndexDefinitions()) {
2831
- try {
2832
- const collection = await this.getCollection(indexDef.collection);
2833
- await collection.createIndex(indexDef.keys, indexDef.options);
2834
- } catch (error) {
2835
- this.logger?.warn?.(`Failed to create index on ${indexDef.collection}:`, error);
2836
- }
2837
- }
2838
- }
2839
- /**
2840
- * Creates custom user-defined indexes for this domain's collections.
2841
- */
2842
- async createCustomIndexes() {
2843
- if (!this.#indexes || this.#indexes.length === 0) {
2844
- return;
2845
- }
2846
- for (const indexDef of this.#indexes) {
2847
- try {
2848
- const collection = await this.getCollection(indexDef.collection);
2849
- await collection.createIndex(indexDef.keys, indexDef.options);
2850
- } catch (error) {
2851
- this.logger?.warn?.(`Failed to create custom index on ${indexDef.collection}:`, error);
2814
+ // ============================================
2815
+ // Async Buffering Methods
2816
+ // ============================================
2817
+ async updateBufferedObservations(input) {
2818
+ try {
2819
+ const collection = await this.getCollection(OM_TABLE);
2820
+ const newChunk = {
2821
+ id: `ombuf-${crypto.randomUUID()}`,
2822
+ cycleId: input.chunk.cycleId,
2823
+ observations: input.chunk.observations,
2824
+ tokenCount: input.chunk.tokenCount,
2825
+ messageIds: input.chunk.messageIds,
2826
+ messageTokens: input.chunk.messageTokens,
2827
+ lastObservedAt: input.chunk.lastObservedAt,
2828
+ createdAt: /* @__PURE__ */ new Date(),
2829
+ suggestedContinuation: input.chunk.suggestedContinuation,
2830
+ currentTask: input.chunk.currentTask
2831
+ };
2832
+ const $set = { updatedAt: /* @__PURE__ */ new Date() };
2833
+ if (input.lastBufferedAtTime) {
2834
+ $set.lastBufferedAtTime = input.lastBufferedAtTime;
2852
2835
  }
2853
- }
2854
- }
2855
- async init() {
2856
- const uniqueIndexExists = await this.spansUniqueIndexExists();
2857
- if (!uniqueIndexExists) {
2858
- const duplicateInfo = await this.checkForDuplicateSpans();
2859
- if (duplicateInfo.hasDuplicates) {
2860
- const errorMessage = `
2861
- ===========================================================================
2862
- MIGRATION REQUIRED: Duplicate spans detected in ${storage.TABLE_SPANS} collection
2863
- ===========================================================================
2864
-
2865
- Found ${duplicateInfo.duplicateCount} duplicate (traceId, spanId) combinations.
2866
-
2867
- The spans collection requires a unique index on (traceId, spanId), but your
2868
- database contains duplicate entries that must be resolved first.
2869
-
2870
- To fix this, run the manual migration command:
2871
-
2872
- npx mastra migrate
2873
-
2874
- This command will:
2875
- 1. Remove duplicate spans (keeping the most complete/recent version)
2876
- 2. Add the required unique index
2877
-
2878
- Note: This migration may take some time for large collections.
2879
- ===========================================================================
2880
- `;
2836
+ const result = await collection.updateOne(
2837
+ { id: input.id },
2838
+ {
2839
+ $push: { bufferedObservationChunks: newChunk },
2840
+ $set
2841
+ }
2842
+ );
2843
+ if (result.matchedCount === 0) {
2881
2844
  throw new error.MastraError({
2882
- id: storage.createStorageErrorId("MONGODB", "MIGRATION_REQUIRED", "DUPLICATE_SPANS"),
2845
+ id: storage.createStorageErrorId("MONGODB", "UPDATE_BUFFERED_OBSERVATIONS", "NOT_FOUND"),
2846
+ text: `Observational memory record not found: ${input.id}`,
2883
2847
  domain: error.ErrorDomain.STORAGE,
2884
- category: error.ErrorCategory.USER,
2885
- text: errorMessage
2848
+ category: error.ErrorCategory.THIRD_PARTY,
2849
+ details: { id: input.id }
2886
2850
  });
2887
2851
  }
2852
+ } catch (error$1) {
2853
+ if (error$1 instanceof error.MastraError) {
2854
+ throw error$1;
2855
+ }
2856
+ throw new error.MastraError(
2857
+ {
2858
+ id: storage.createStorageErrorId("MONGODB", "UPDATE_BUFFERED_OBSERVATIONS", "FAILED"),
2859
+ domain: error.ErrorDomain.STORAGE,
2860
+ category: error.ErrorCategory.THIRD_PARTY,
2861
+ details: { id: input.id }
2862
+ },
2863
+ error$1
2864
+ );
2888
2865
  }
2889
- await this.createDefaultIndexes();
2890
- await this.createCustomIndexes();
2891
2866
  }
2892
- /**
2893
- * Checks if the unique index on (spanId, traceId) already exists on the spans collection.
2894
- * Used to skip deduplication when the index already exists (migration already complete).
2895
- */
2896
- async spansUniqueIndexExists() {
2867
+ async swapBufferedToActive(input) {
2897
2868
  try {
2898
- const collection = await this.getCollection(storage.TABLE_SPANS);
2899
- const indexes = await collection.indexes();
2900
- return indexes.some((idx) => idx.unique === true && idx.key?.spanId === 1 && idx.key?.traceId === 1);
2901
- } catch {
2902
- return false;
2903
- }
2869
+ const collection = await this.getCollection(OM_TABLE);
2870
+ const doc = await collection.findOne({ id: input.id });
2871
+ if (!doc) {
2872
+ throw new error.MastraError({
2873
+ id: storage.createStorageErrorId("MONGODB", "SWAP_BUFFERED_TO_ACTIVE", "NOT_FOUND"),
2874
+ text: `Observational memory record not found: ${input.id}`,
2875
+ domain: error.ErrorDomain.STORAGE,
2876
+ category: error.ErrorCategory.THIRD_PARTY,
2877
+ details: { id: input.id }
2878
+ });
2879
+ }
2880
+ const chunks = Array.isArray(doc.bufferedObservationChunks) ? doc.bufferedObservationChunks : [];
2881
+ if (chunks.length === 0) {
2882
+ return {
2883
+ chunksActivated: 0,
2884
+ messageTokensActivated: 0,
2885
+ observationTokensActivated: 0,
2886
+ messagesActivated: 0,
2887
+ activatedCycleIds: [],
2888
+ activatedMessageIds: []
2889
+ };
2890
+ }
2891
+ const retentionFloor = input.messageTokensThreshold * (1 - input.activationRatio);
2892
+ const targetMessageTokens = Math.max(0, input.currentPendingTokens - retentionFloor);
2893
+ let cumulativeMessageTokens = 0;
2894
+ let bestBoundary = 0;
2895
+ let bestBoundaryMessageTokens = 0;
2896
+ for (let i = 0; i < chunks.length; i++) {
2897
+ cumulativeMessageTokens += chunks[i].messageTokens ?? 0;
2898
+ const boundary = i + 1;
2899
+ const isUnder = cumulativeMessageTokens <= targetMessageTokens;
2900
+ const bestIsUnder = bestBoundaryMessageTokens <= targetMessageTokens;
2901
+ if (bestBoundary === 0) {
2902
+ bestBoundary = boundary;
2903
+ bestBoundaryMessageTokens = cumulativeMessageTokens;
2904
+ } else if (isUnder && !bestIsUnder) {
2905
+ bestBoundary = boundary;
2906
+ bestBoundaryMessageTokens = cumulativeMessageTokens;
2907
+ } else if (isUnder && bestIsUnder) {
2908
+ if (cumulativeMessageTokens > bestBoundaryMessageTokens) {
2909
+ bestBoundary = boundary;
2910
+ bestBoundaryMessageTokens = cumulativeMessageTokens;
2911
+ }
2912
+ } else if (!isUnder && !bestIsUnder) {
2913
+ if (cumulativeMessageTokens < bestBoundaryMessageTokens) {
2914
+ bestBoundary = boundary;
2915
+ bestBoundaryMessageTokens = cumulativeMessageTokens;
2916
+ }
2917
+ }
2918
+ }
2919
+ const chunksToActivate = bestBoundary === 0 ? 1 : bestBoundary;
2920
+ const activatedChunks = chunks.slice(0, chunksToActivate);
2921
+ const remainingChunks = chunks.slice(chunksToActivate);
2922
+ const activatedContent = activatedChunks.map((c) => c.observations).join("\n\n");
2923
+ const activatedTokens = activatedChunks.reduce((sum, c) => sum + c.tokenCount, 0);
2924
+ const activatedMessageTokens = activatedChunks.reduce((sum, c) => sum + (c.messageTokens ?? 0), 0);
2925
+ const activatedMessageCount = activatedChunks.reduce((sum, c) => sum + c.messageIds.length, 0);
2926
+ const activatedCycleIds = activatedChunks.map((c) => c.cycleId).filter((id) => !!id);
2927
+ const activatedMessageIds = activatedChunks.flatMap((c) => c.messageIds ?? []);
2928
+ const latestChunk = activatedChunks[activatedChunks.length - 1];
2929
+ const lastObservedAt = input.lastObservedAt ?? (latestChunk?.lastObservedAt ? new Date(latestChunk.lastObservedAt) : /* @__PURE__ */ new Date());
2930
+ const existingActive = doc.activeObservations || "";
2931
+ const existingTokenCount = Number(doc.observationTokenCount || 0);
2932
+ const newActive = existingActive ? `${existingActive}
2933
+
2934
+ ${activatedContent}` : activatedContent;
2935
+ const newTokenCount = existingTokenCount + activatedTokens;
2936
+ const existingPending = Number(doc.pendingMessageTokens || 0);
2937
+ const newPending = Math.max(0, existingPending - activatedMessageTokens);
2938
+ await collection.updateOne(
2939
+ { id: input.id },
2940
+ {
2941
+ $set: {
2942
+ activeObservations: newActive,
2943
+ observationTokenCount: newTokenCount,
2944
+ pendingMessageTokens: newPending,
2945
+ bufferedObservationChunks: remainingChunks.length > 0 ? remainingChunks : null,
2946
+ lastObservedAt,
2947
+ updatedAt: /* @__PURE__ */ new Date()
2948
+ }
2949
+ }
2950
+ );
2951
+ return {
2952
+ chunksActivated: activatedChunks.length,
2953
+ messageTokensActivated: activatedMessageTokens,
2954
+ observationTokensActivated: activatedTokens,
2955
+ messagesActivated: activatedMessageCount,
2956
+ activatedCycleIds,
2957
+ activatedMessageIds,
2958
+ observations: activatedContent,
2959
+ perChunk: activatedChunks.map((c) => ({
2960
+ cycleId: c.cycleId ?? "",
2961
+ messageTokens: c.messageTokens ?? 0,
2962
+ observationTokens: c.tokenCount,
2963
+ messageCount: c.messageIds.length,
2964
+ observations: c.observations
2965
+ }))
2966
+ };
2967
+ } catch (error$1) {
2968
+ if (error$1 instanceof error.MastraError) {
2969
+ throw error$1;
2970
+ }
2971
+ throw new error.MastraError(
2972
+ {
2973
+ id: storage.createStorageErrorId("MONGODB", "SWAP_BUFFERED_TO_ACTIVE", "FAILED"),
2974
+ domain: error.ErrorDomain.STORAGE,
2975
+ category: error.ErrorCategory.THIRD_PARTY,
2976
+ details: { id: input.id }
2977
+ },
2978
+ error$1
2979
+ );
2980
+ }
2981
+ }
2982
+ async updateBufferedReflection(input) {
2983
+ try {
2984
+ const collection = await this.getCollection(OM_TABLE);
2985
+ const doc = await collection.findOne({ id: input.id });
2986
+ if (!doc) {
2987
+ throw new error.MastraError({
2988
+ id: storage.createStorageErrorId("MONGODB", "UPDATE_BUFFERED_REFLECTION", "NOT_FOUND"),
2989
+ text: `Observational memory record not found: ${input.id}`,
2990
+ domain: error.ErrorDomain.STORAGE,
2991
+ category: error.ErrorCategory.THIRD_PARTY,
2992
+ details: { id: input.id }
2993
+ });
2994
+ }
2995
+ const existingContent = doc.bufferedReflection || "";
2996
+ const existingTokens = Number(doc.bufferedReflectionTokens || 0);
2997
+ const existingInputTokens = Number(doc.bufferedReflectionInputTokens || 0);
2998
+ const newContent = existingContent ? `${existingContent}
2999
+
3000
+ ${input.reflection}` : input.reflection;
3001
+ const newTokens = existingTokens + input.tokenCount;
3002
+ const newInputTokens = existingInputTokens + input.inputTokenCount;
3003
+ const result = await collection.updateOne(
3004
+ { id: input.id },
3005
+ {
3006
+ $set: {
3007
+ bufferedReflection: newContent,
3008
+ bufferedReflectionTokens: newTokens,
3009
+ bufferedReflectionInputTokens: newInputTokens,
3010
+ reflectedObservationLineCount: input.reflectedObservationLineCount,
3011
+ updatedAt: /* @__PURE__ */ new Date()
3012
+ }
3013
+ }
3014
+ );
3015
+ if (result.matchedCount === 0) {
3016
+ throw new error.MastraError({
3017
+ id: storage.createStorageErrorId("MONGODB", "UPDATE_BUFFERED_REFLECTION", "NOT_FOUND"),
3018
+ text: `Observational memory record not found: ${input.id}`,
3019
+ domain: error.ErrorDomain.STORAGE,
3020
+ category: error.ErrorCategory.THIRD_PARTY,
3021
+ details: { id: input.id }
3022
+ });
3023
+ }
3024
+ } catch (error$1) {
3025
+ if (error$1 instanceof error.MastraError) {
3026
+ throw error$1;
3027
+ }
3028
+ throw new error.MastraError(
3029
+ {
3030
+ id: storage.createStorageErrorId("MONGODB", "UPDATE_BUFFERED_REFLECTION", "FAILED"),
3031
+ domain: error.ErrorDomain.STORAGE,
3032
+ category: error.ErrorCategory.THIRD_PARTY,
3033
+ details: { id: input.id }
3034
+ },
3035
+ error$1
3036
+ );
3037
+ }
3038
+ }
3039
+ async swapBufferedReflectionToActive(input) {
3040
+ try {
3041
+ const collection = await this.getCollection(OM_TABLE);
3042
+ const doc = await collection.findOne({ id: input.currentRecord.id });
3043
+ if (!doc) {
3044
+ throw new error.MastraError({
3045
+ id: storage.createStorageErrorId("MONGODB", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NOT_FOUND"),
3046
+ text: `Observational memory record not found: ${input.currentRecord.id}`,
3047
+ domain: error.ErrorDomain.STORAGE,
3048
+ category: error.ErrorCategory.THIRD_PARTY,
3049
+ details: { id: input.currentRecord.id }
3050
+ });
3051
+ }
3052
+ const bufferedReflection = doc.bufferedReflection || "";
3053
+ const reflectedLineCount = Number(doc.reflectedObservationLineCount || 0);
3054
+ if (!bufferedReflection) {
3055
+ throw new error.MastraError({
3056
+ id: storage.createStorageErrorId("MONGODB", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NO_CONTENT"),
3057
+ text: "No buffered reflection to swap",
3058
+ domain: error.ErrorDomain.STORAGE,
3059
+ category: error.ErrorCategory.USER,
3060
+ details: { id: input.currentRecord.id }
3061
+ });
3062
+ }
3063
+ const currentObservations = doc.activeObservations || "";
3064
+ const allLines = currentObservations.split("\n");
3065
+ const unreflectedLines = allLines.slice(reflectedLineCount);
3066
+ const unreflectedContent = unreflectedLines.join("\n").trim();
3067
+ const newObservations = unreflectedContent ? `${bufferedReflection}
3068
+
3069
+ ${unreflectedContent}` : bufferedReflection;
3070
+ const newRecord = await this.createReflectionGeneration({
3071
+ currentRecord: input.currentRecord,
3072
+ reflection: newObservations,
3073
+ tokenCount: input.tokenCount
3074
+ });
3075
+ await collection.updateOne(
3076
+ { id: input.currentRecord.id },
3077
+ {
3078
+ $set: {
3079
+ bufferedReflection: null,
3080
+ bufferedReflectionTokens: null,
3081
+ bufferedReflectionInputTokens: null,
3082
+ reflectedObservationLineCount: null,
3083
+ updatedAt: /* @__PURE__ */ new Date()
3084
+ }
3085
+ }
3086
+ );
3087
+ return newRecord;
3088
+ } catch (error$1) {
3089
+ if (error$1 instanceof error.MastraError) {
3090
+ throw error$1;
3091
+ }
3092
+ throw new error.MastraError(
3093
+ {
3094
+ id: storage.createStorageErrorId("MONGODB", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "FAILED"),
3095
+ domain: error.ErrorDomain.STORAGE,
3096
+ category: error.ErrorCategory.THIRD_PARTY,
3097
+ details: { id: input.currentRecord.id }
3098
+ },
3099
+ error$1
3100
+ );
3101
+ }
3102
+ }
3103
+ };
3104
+ var ObservabilityMongoDB = class _ObservabilityMongoDB extends storage.ObservabilityStorage {
3105
+ #connector;
3106
+ #skipDefaultIndexes;
3107
+ #indexes;
3108
+ /** Collections managed by this domain */
3109
+ static MANAGED_COLLECTIONS = [storage.TABLE_SPANS];
3110
+ constructor(config) {
3111
+ super();
3112
+ this.#connector = resolveMongoDBConfig(config);
3113
+ this.#skipDefaultIndexes = config.skipDefaultIndexes;
3114
+ this.#indexes = config.indexes?.filter(
3115
+ (idx) => _ObservabilityMongoDB.MANAGED_COLLECTIONS.includes(idx.collection)
3116
+ );
3117
+ }
3118
+ async getCollection(name) {
3119
+ return this.#connector.getCollection(name);
3120
+ }
3121
+ /**
3122
+ * Returns default index definitions for the observability domain collections.
3123
+ * These indexes optimize common query patterns for span and trace lookups.
3124
+ */
3125
+ getDefaultIndexDefinitions() {
3126
+ return [
3127
+ { collection: storage.TABLE_SPANS, keys: { spanId: 1, traceId: 1 }, options: { unique: true } },
3128
+ { collection: storage.TABLE_SPANS, keys: { traceId: 1 } },
3129
+ { collection: storage.TABLE_SPANS, keys: { parentSpanId: 1 } },
3130
+ { collection: storage.TABLE_SPANS, keys: { startedAt: -1 } },
3131
+ { collection: storage.TABLE_SPANS, keys: { spanType: 1 } },
3132
+ { collection: storage.TABLE_SPANS, keys: { name: 1 } }
3133
+ ];
3134
+ }
3135
+ async createDefaultIndexes() {
3136
+ if (this.#skipDefaultIndexes) {
3137
+ return;
3138
+ }
3139
+ for (const indexDef of this.getDefaultIndexDefinitions()) {
3140
+ try {
3141
+ const collection = await this.getCollection(indexDef.collection);
3142
+ await collection.createIndex(indexDef.keys, indexDef.options);
3143
+ } catch (error) {
3144
+ this.logger?.warn?.(`Failed to create index on ${indexDef.collection}:`, error);
3145
+ }
3146
+ }
3147
+ }
3148
+ /**
3149
+ * Creates custom user-defined indexes for this domain's collections.
3150
+ */
3151
+ async createCustomIndexes() {
3152
+ if (!this.#indexes || this.#indexes.length === 0) {
3153
+ return;
3154
+ }
3155
+ for (const indexDef of this.#indexes) {
3156
+ try {
3157
+ const collection = await this.getCollection(indexDef.collection);
3158
+ await collection.createIndex(indexDef.keys, indexDef.options);
3159
+ } catch (error) {
3160
+ this.logger?.warn?.(`Failed to create custom index on ${indexDef.collection}:`, error);
3161
+ }
3162
+ }
3163
+ }
3164
+ async init() {
3165
+ const uniqueIndexExists = await this.spansUniqueIndexExists();
3166
+ if (!uniqueIndexExists) {
3167
+ const duplicateInfo = await this.checkForDuplicateSpans();
3168
+ if (duplicateInfo.hasDuplicates) {
3169
+ const errorMessage = `
3170
+ ===========================================================================
3171
+ MIGRATION REQUIRED: Duplicate spans detected in ${storage.TABLE_SPANS} collection
3172
+ ===========================================================================
3173
+
3174
+ Found ${duplicateInfo.duplicateCount} duplicate (traceId, spanId) combinations.
3175
+
3176
+ The spans collection requires a unique index on (traceId, spanId), but your
3177
+ database contains duplicate entries that must be resolved first.
3178
+
3179
+ To fix this, run the manual migration command:
3180
+
3181
+ npx mastra migrate
3182
+
3183
+ This command will:
3184
+ 1. Remove duplicate spans (keeping the most complete/recent version)
3185
+ 2. Add the required unique index
3186
+
3187
+ Note: This migration may take some time for large collections.
3188
+ ===========================================================================
3189
+ `;
3190
+ throw new error.MastraError({
3191
+ id: storage.createStorageErrorId("MONGODB", "MIGRATION_REQUIRED", "DUPLICATE_SPANS"),
3192
+ domain: error.ErrorDomain.STORAGE,
3193
+ category: error.ErrorCategory.USER,
3194
+ text: errorMessage
3195
+ });
3196
+ }
3197
+ }
3198
+ await this.createDefaultIndexes();
3199
+ await this.createCustomIndexes();
3200
+ }
3201
+ /**
3202
+ * Checks if the unique index on (spanId, traceId) already exists on the spans collection.
3203
+ * Used to skip deduplication when the index already exists (migration already complete).
3204
+ */
3205
+ async spansUniqueIndexExists() {
3206
+ try {
3207
+ const collection = await this.getCollection(storage.TABLE_SPANS);
3208
+ const indexes = await collection.indexes();
3209
+ return indexes.some((idx) => idx.unique === true && idx.key?.spanId === 1 && idx.key?.traceId === 1);
3210
+ } catch {
3211
+ return false;
3212
+ }
2904
3213
  }
2905
3214
  /**
2906
3215
  * Checks for duplicate (traceId, spanId) combinations in the spans collection.
@@ -3551,6 +3860,1161 @@ Note: This migration may take some time for large collections.
3551
3860
  return span;
3552
3861
  }
3553
3862
  };
3863
+ var SNAPSHOT_FIELDS2 = ["name", "description", "content", "rules"];
3864
+ var MongoDBPromptBlocksStorage = class _MongoDBPromptBlocksStorage extends storage.PromptBlocksStorage {
3865
+ #connector;
3866
+ #skipDefaultIndexes;
3867
+ #indexes;
3868
+ static MANAGED_COLLECTIONS = [storage.TABLE_PROMPT_BLOCKS, storage.TABLE_PROMPT_BLOCK_VERSIONS];
3869
+ constructor(config) {
3870
+ super();
3871
+ this.#connector = resolveMongoDBConfig(config);
3872
+ this.#skipDefaultIndexes = config.skipDefaultIndexes;
3873
+ this.#indexes = config.indexes?.filter(
3874
+ (idx) => _MongoDBPromptBlocksStorage.MANAGED_COLLECTIONS.includes(idx.collection)
3875
+ );
3876
+ }
3877
+ async getCollection(name) {
3878
+ return this.#connector.getCollection(name);
3879
+ }
3880
+ getDefaultIndexDefinitions() {
3881
+ return [
3882
+ { collection: storage.TABLE_PROMPT_BLOCKS, keys: { id: 1 }, options: { unique: true } },
3883
+ { collection: storage.TABLE_PROMPT_BLOCKS, keys: { createdAt: -1 } },
3884
+ { collection: storage.TABLE_PROMPT_BLOCKS, keys: { updatedAt: -1 } },
3885
+ { collection: storage.TABLE_PROMPT_BLOCKS, keys: { authorId: 1 } },
3886
+ { collection: storage.TABLE_PROMPT_BLOCK_VERSIONS, keys: { id: 1 }, options: { unique: true } },
3887
+ {
3888
+ collection: storage.TABLE_PROMPT_BLOCK_VERSIONS,
3889
+ keys: { blockId: 1, versionNumber: -1 },
3890
+ options: { unique: true }
3891
+ },
3892
+ { collection: storage.TABLE_PROMPT_BLOCK_VERSIONS, keys: { blockId: 1, createdAt: -1 } }
3893
+ ];
3894
+ }
3895
+ async createDefaultIndexes() {
3896
+ if (this.#skipDefaultIndexes) {
3897
+ return;
3898
+ }
3899
+ for (const indexDef of this.getDefaultIndexDefinitions()) {
3900
+ try {
3901
+ const collection = await this.getCollection(indexDef.collection);
3902
+ await collection.createIndex(indexDef.keys, indexDef.options);
3903
+ } catch (error) {
3904
+ this.logger?.warn?.(`Failed to create index on ${indexDef.collection}:`, error);
3905
+ }
3906
+ }
3907
+ }
3908
+ async createCustomIndexes() {
3909
+ if (!this.#indexes || this.#indexes.length === 0) {
3910
+ return;
3911
+ }
3912
+ for (const indexDef of this.#indexes) {
3913
+ try {
3914
+ const collection = await this.getCollection(indexDef.collection);
3915
+ await collection.createIndex(indexDef.keys, indexDef.options);
3916
+ } catch (error) {
3917
+ this.logger?.warn?.(`Failed to create custom index on ${indexDef.collection}:`, error);
3918
+ }
3919
+ }
3920
+ }
3921
+ async init() {
3922
+ await this.createDefaultIndexes();
3923
+ await this.createCustomIndexes();
3924
+ }
3925
+ async dangerouslyClearAll() {
3926
+ const versionsCollection = await this.getCollection(storage.TABLE_PROMPT_BLOCK_VERSIONS);
3927
+ await versionsCollection.deleteMany({});
3928
+ const blocksCollection = await this.getCollection(storage.TABLE_PROMPT_BLOCKS);
3929
+ await blocksCollection.deleteMany({});
3930
+ }
3931
+ // ==========================================================================
3932
+ // Prompt Block CRUD
3933
+ // ==========================================================================
3934
+ async getById(id) {
3935
+ try {
3936
+ const collection = await this.getCollection(storage.TABLE_PROMPT_BLOCKS);
3937
+ const result = await collection.findOne({ id });
3938
+ if (!result) {
3939
+ return null;
3940
+ }
3941
+ return this.transformBlock(result);
3942
+ } catch (error$1) {
3943
+ throw new error.MastraError(
3944
+ {
3945
+ id: storage.createStorageErrorId("MONGODB", "GET_PROMPT_BLOCK_BY_ID", "FAILED"),
3946
+ domain: error.ErrorDomain.STORAGE,
3947
+ category: error.ErrorCategory.THIRD_PARTY,
3948
+ details: { id }
3949
+ },
3950
+ error$1
3951
+ );
3952
+ }
3953
+ }
3954
+ async create(input) {
3955
+ const { promptBlock } = input;
3956
+ try {
3957
+ const collection = await this.getCollection(storage.TABLE_PROMPT_BLOCKS);
3958
+ const existing = await collection.findOne({ id: promptBlock.id });
3959
+ if (existing) {
3960
+ throw new error.MastraError({
3961
+ id: storage.createStorageErrorId("MONGODB", "CREATE_PROMPT_BLOCK", "ALREADY_EXISTS"),
3962
+ domain: error.ErrorDomain.STORAGE,
3963
+ category: error.ErrorCategory.USER,
3964
+ details: { id: promptBlock.id },
3965
+ text: `Prompt block with id ${promptBlock.id} already exists`
3966
+ });
3967
+ }
3968
+ const now = /* @__PURE__ */ new Date();
3969
+ const newBlock = {
3970
+ id: promptBlock.id,
3971
+ status: "draft",
3972
+ activeVersionId: void 0,
3973
+ authorId: promptBlock.authorId,
3974
+ metadata: promptBlock.metadata,
3975
+ createdAt: now,
3976
+ updatedAt: now
3977
+ };
3978
+ await collection.insertOne(this.serializeBlock(newBlock));
3979
+ const snapshotConfig = {};
3980
+ for (const field of SNAPSHOT_FIELDS2) {
3981
+ if (promptBlock[field] !== void 0) {
3982
+ snapshotConfig[field] = promptBlock[field];
3983
+ }
3984
+ }
3985
+ const versionId = crypto.randomUUID();
3986
+ await this.createVersion({
3987
+ id: versionId,
3988
+ blockId: promptBlock.id,
3989
+ versionNumber: 1,
3990
+ ...snapshotConfig,
3991
+ changedFields: Object.keys(snapshotConfig),
3992
+ changeMessage: "Initial version"
3993
+ });
3994
+ return newBlock;
3995
+ } catch (error$1) {
3996
+ if (error$1 instanceof error.MastraError) {
3997
+ throw error$1;
3998
+ }
3999
+ throw new error.MastraError(
4000
+ {
4001
+ id: storage.createStorageErrorId("MONGODB", "CREATE_PROMPT_BLOCK", "FAILED"),
4002
+ domain: error.ErrorDomain.STORAGE,
4003
+ category: error.ErrorCategory.THIRD_PARTY,
4004
+ details: { id: promptBlock.id }
4005
+ },
4006
+ error$1
4007
+ );
4008
+ }
4009
+ }
4010
+ async update(input) {
4011
+ const { id, ...updates } = input;
4012
+ try {
4013
+ const collection = await this.getCollection(storage.TABLE_PROMPT_BLOCKS);
4014
+ const existingBlock = await collection.findOne({ id });
4015
+ if (!existingBlock) {
4016
+ throw new error.MastraError({
4017
+ id: storage.createStorageErrorId("MONGODB", "UPDATE_PROMPT_BLOCK", "NOT_FOUND"),
4018
+ domain: error.ErrorDomain.STORAGE,
4019
+ category: error.ErrorCategory.USER,
4020
+ details: { id },
4021
+ text: `Prompt block with id ${id} not found`
4022
+ });
4023
+ }
4024
+ const updateDoc = {
4025
+ updatedAt: /* @__PURE__ */ new Date()
4026
+ };
4027
+ const metadataFields = {
4028
+ authorId: updates.authorId,
4029
+ activeVersionId: updates.activeVersionId,
4030
+ metadata: updates.metadata,
4031
+ status: updates.status
4032
+ };
4033
+ const configFields = {};
4034
+ for (const field of SNAPSHOT_FIELDS2) {
4035
+ if (updates[field] !== void 0) {
4036
+ configFields[field] = updates[field];
4037
+ }
4038
+ }
4039
+ if (Object.keys(configFields).length > 0) {
4040
+ const latestVersion = await this.getLatestVersion(id);
4041
+ if (!latestVersion) {
4042
+ throw new error.MastraError({
4043
+ id: storage.createStorageErrorId("MONGODB", "UPDATE_PROMPT_BLOCK", "NO_VERSION"),
4044
+ domain: error.ErrorDomain.STORAGE,
4045
+ category: error.ErrorCategory.USER,
4046
+ text: `Cannot update config fields for prompt block ${id} - no versions exist`,
4047
+ details: { id }
4048
+ });
4049
+ }
4050
+ const existingSnapshot = this.extractSnapshotFields(latestVersion);
4051
+ await this.createVersion({
4052
+ id: crypto.randomUUID(),
4053
+ blockId: id,
4054
+ versionNumber: latestVersion.versionNumber + 1,
4055
+ ...existingSnapshot,
4056
+ ...configFields,
4057
+ changedFields: Object.keys(configFields),
4058
+ changeMessage: `Updated: ${Object.keys(configFields).join(", ")}`
4059
+ });
4060
+ }
4061
+ if (metadataFields.authorId !== void 0) updateDoc.authorId = metadataFields.authorId;
4062
+ if (metadataFields.activeVersionId !== void 0) {
4063
+ updateDoc.activeVersionId = metadataFields.activeVersionId;
4064
+ if (metadataFields.status === void 0) {
4065
+ updateDoc.status = "published";
4066
+ }
4067
+ }
4068
+ if (metadataFields.status !== void 0) {
4069
+ updateDoc.status = metadataFields.status;
4070
+ }
4071
+ if (metadataFields.metadata !== void 0) {
4072
+ const existingMetadata = existingBlock.metadata || {};
4073
+ updateDoc.metadata = { ...existingMetadata, ...metadataFields.metadata };
4074
+ }
4075
+ await collection.updateOne({ id }, { $set: updateDoc });
4076
+ const updatedBlock = await collection.findOne({ id });
4077
+ if (!updatedBlock) {
4078
+ throw new error.MastraError({
4079
+ id: storage.createStorageErrorId("MONGODB", "UPDATE_PROMPT_BLOCK", "NOT_FOUND_AFTER_UPDATE"),
4080
+ domain: error.ErrorDomain.STORAGE,
4081
+ category: error.ErrorCategory.SYSTEM,
4082
+ text: `Prompt block with id ${id} was deleted during update`,
4083
+ details: { id }
4084
+ });
4085
+ }
4086
+ return this.transformBlock(updatedBlock);
4087
+ } catch (error$1) {
4088
+ if (error$1 instanceof error.MastraError) {
4089
+ throw error$1;
4090
+ }
4091
+ throw new error.MastraError(
4092
+ {
4093
+ id: storage.createStorageErrorId("MONGODB", "UPDATE_PROMPT_BLOCK", "FAILED"),
4094
+ domain: error.ErrorDomain.STORAGE,
4095
+ category: error.ErrorCategory.THIRD_PARTY,
4096
+ details: { id }
4097
+ },
4098
+ error$1
4099
+ );
4100
+ }
4101
+ }
4102
+ async delete(id) {
4103
+ try {
4104
+ await this.deleteVersionsByParentId(id);
4105
+ const collection = await this.getCollection(storage.TABLE_PROMPT_BLOCKS);
4106
+ await collection.deleteOne({ id });
4107
+ } catch (error$1) {
4108
+ throw new error.MastraError(
4109
+ {
4110
+ id: storage.createStorageErrorId("MONGODB", "DELETE_PROMPT_BLOCK", "FAILED"),
4111
+ domain: error.ErrorDomain.STORAGE,
4112
+ category: error.ErrorCategory.THIRD_PARTY,
4113
+ details: { id }
4114
+ },
4115
+ error$1
4116
+ );
4117
+ }
4118
+ }
4119
+ async list(args) {
4120
+ try {
4121
+ const { page = 0, perPage: perPageInput, orderBy, authorId, metadata } = args || {};
4122
+ const { field, direction } = this.parseOrderBy(orderBy);
4123
+ if (page < 0) {
4124
+ throw new error.MastraError(
4125
+ {
4126
+ id: storage.createStorageErrorId("MONGODB", "LIST_PROMPT_BLOCKS", "INVALID_PAGE"),
4127
+ domain: error.ErrorDomain.STORAGE,
4128
+ category: error.ErrorCategory.USER,
4129
+ details: { page }
4130
+ },
4131
+ new Error("page must be >= 0")
4132
+ );
4133
+ }
4134
+ const perPage = storage.normalizePerPage(perPageInput, 100);
4135
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
4136
+ const collection = await this.getCollection(storage.TABLE_PROMPT_BLOCKS);
4137
+ const filter = {};
4138
+ if (authorId) {
4139
+ filter.authorId = authorId;
4140
+ }
4141
+ if (metadata) {
4142
+ for (const [key, value] of Object.entries(metadata)) {
4143
+ filter[`metadata.${key}`] = value;
4144
+ }
4145
+ }
4146
+ const total = await collection.countDocuments(filter);
4147
+ if (total === 0 || perPage === 0) {
4148
+ return {
4149
+ promptBlocks: [],
4150
+ total,
4151
+ page,
4152
+ perPage: perPageForResponse,
4153
+ hasMore: false
4154
+ };
4155
+ }
4156
+ const sortOrder = direction === "ASC" ? 1 : -1;
4157
+ let cursor = collection.find(filter).sort({ [field]: sortOrder }).skip(offset);
4158
+ if (perPageInput !== false) {
4159
+ cursor = cursor.limit(perPage);
4160
+ }
4161
+ const results = await cursor.toArray();
4162
+ const promptBlocks = results.map((doc) => this.transformBlock(doc));
4163
+ return {
4164
+ promptBlocks,
4165
+ total,
4166
+ page,
4167
+ perPage: perPageForResponse,
4168
+ hasMore: perPageInput !== false && offset + perPage < total
4169
+ };
4170
+ } catch (error$1) {
4171
+ if (error$1 instanceof error.MastraError) {
4172
+ throw error$1;
4173
+ }
4174
+ throw new error.MastraError(
4175
+ {
4176
+ id: storage.createStorageErrorId("MONGODB", "LIST_PROMPT_BLOCKS", "FAILED"),
4177
+ domain: error.ErrorDomain.STORAGE,
4178
+ category: error.ErrorCategory.THIRD_PARTY
4179
+ },
4180
+ error$1
4181
+ );
4182
+ }
4183
+ }
4184
+ // ==========================================================================
4185
+ // Prompt Block Version Methods
4186
+ // ==========================================================================
4187
+ async createVersion(input) {
4188
+ try {
4189
+ const collection = await this.getCollection(storage.TABLE_PROMPT_BLOCK_VERSIONS);
4190
+ const now = /* @__PURE__ */ new Date();
4191
+ const versionDoc = {
4192
+ id: input.id,
4193
+ blockId: input.blockId,
4194
+ versionNumber: input.versionNumber,
4195
+ changedFields: input.changedFields ?? void 0,
4196
+ changeMessage: input.changeMessage ?? void 0,
4197
+ createdAt: now
4198
+ };
4199
+ for (const field of SNAPSHOT_FIELDS2) {
4200
+ if (input[field] !== void 0) {
4201
+ versionDoc[field] = input[field];
4202
+ }
4203
+ }
4204
+ await collection.insertOne(versionDoc);
4205
+ return {
4206
+ ...input,
4207
+ createdAt: now
4208
+ };
4209
+ } catch (error$1) {
4210
+ throw new error.MastraError(
4211
+ {
4212
+ id: storage.createStorageErrorId("MONGODB", "CREATE_PROMPT_BLOCK_VERSION", "FAILED"),
4213
+ domain: error.ErrorDomain.STORAGE,
4214
+ category: error.ErrorCategory.THIRD_PARTY,
4215
+ details: { versionId: input.id, blockId: input.blockId }
4216
+ },
4217
+ error$1
4218
+ );
4219
+ }
4220
+ }
4221
+ async getVersion(id) {
4222
+ try {
4223
+ const collection = await this.getCollection(storage.TABLE_PROMPT_BLOCK_VERSIONS);
4224
+ const result = await collection.findOne({ id });
4225
+ if (!result) {
4226
+ return null;
4227
+ }
4228
+ return this.transformVersion(result);
4229
+ } catch (error$1) {
4230
+ throw new error.MastraError(
4231
+ {
4232
+ id: storage.createStorageErrorId("MONGODB", "GET_PROMPT_BLOCK_VERSION", "FAILED"),
4233
+ domain: error.ErrorDomain.STORAGE,
4234
+ category: error.ErrorCategory.THIRD_PARTY,
4235
+ details: { versionId: id }
4236
+ },
4237
+ error$1
4238
+ );
4239
+ }
4240
+ }
4241
+ async getVersionByNumber(blockId, versionNumber) {
4242
+ try {
4243
+ const collection = await this.getCollection(storage.TABLE_PROMPT_BLOCK_VERSIONS);
4244
+ const result = await collection.findOne({ blockId, versionNumber });
4245
+ if (!result) {
4246
+ return null;
4247
+ }
4248
+ return this.transformVersion(result);
4249
+ } catch (error$1) {
4250
+ throw new error.MastraError(
4251
+ {
4252
+ id: storage.createStorageErrorId("MONGODB", "GET_PROMPT_BLOCK_VERSION_BY_NUMBER", "FAILED"),
4253
+ domain: error.ErrorDomain.STORAGE,
4254
+ category: error.ErrorCategory.THIRD_PARTY,
4255
+ details: { blockId, versionNumber }
4256
+ },
4257
+ error$1
4258
+ );
4259
+ }
4260
+ }
4261
+ async getLatestVersion(blockId) {
4262
+ try {
4263
+ const collection = await this.getCollection(storage.TABLE_PROMPT_BLOCK_VERSIONS);
4264
+ const result = await collection.find({ blockId }).sort({ versionNumber: -1 }).limit(1).toArray();
4265
+ if (!result || result.length === 0) {
4266
+ return null;
4267
+ }
4268
+ return this.transformVersion(result[0]);
4269
+ } catch (error$1) {
4270
+ throw new error.MastraError(
4271
+ {
4272
+ id: storage.createStorageErrorId("MONGODB", "GET_LATEST_PROMPT_BLOCK_VERSION", "FAILED"),
4273
+ domain: error.ErrorDomain.STORAGE,
4274
+ category: error.ErrorCategory.THIRD_PARTY,
4275
+ details: { blockId }
4276
+ },
4277
+ error$1
4278
+ );
4279
+ }
4280
+ }
4281
+ async listVersions(input) {
4282
+ const { blockId, page = 0, perPage: perPageInput, orderBy } = input;
4283
+ if (page < 0) {
4284
+ throw new error.MastraError(
4285
+ {
4286
+ id: storage.createStorageErrorId("MONGODB", "LIST_PROMPT_BLOCK_VERSIONS", "INVALID_PAGE"),
4287
+ domain: error.ErrorDomain.STORAGE,
4288
+ category: error.ErrorCategory.USER,
4289
+ details: { page }
4290
+ },
4291
+ new Error("page must be >= 0")
4292
+ );
4293
+ }
4294
+ const perPage = storage.normalizePerPage(perPageInput, 20);
4295
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
4296
+ try {
4297
+ const { field, direction } = this.parseVersionOrderBy(orderBy);
4298
+ const collection = await this.getCollection(storage.TABLE_PROMPT_BLOCK_VERSIONS);
4299
+ const total = await collection.countDocuments({ blockId });
4300
+ if (total === 0 || perPage === 0) {
4301
+ return {
4302
+ versions: [],
4303
+ total,
4304
+ page,
4305
+ perPage: perPageForResponse,
4306
+ hasMore: false
4307
+ };
4308
+ }
4309
+ const sortOrder = direction === "ASC" ? 1 : -1;
4310
+ let cursor = collection.find({ blockId }).sort({ [field]: sortOrder }).skip(offset);
4311
+ if (perPageInput !== false) {
4312
+ cursor = cursor.limit(perPage);
4313
+ }
4314
+ const results = await cursor.toArray();
4315
+ const versions = results.map((doc) => this.transformVersion(doc));
4316
+ return {
4317
+ versions,
4318
+ total,
4319
+ page,
4320
+ perPage: perPageForResponse,
4321
+ hasMore: perPageInput !== false && offset + perPage < total
4322
+ };
4323
+ } catch (error$1) {
4324
+ throw new error.MastraError(
4325
+ {
4326
+ id: storage.createStorageErrorId("MONGODB", "LIST_PROMPT_BLOCK_VERSIONS", "FAILED"),
4327
+ domain: error.ErrorDomain.STORAGE,
4328
+ category: error.ErrorCategory.THIRD_PARTY,
4329
+ details: { blockId }
4330
+ },
4331
+ error$1
4332
+ );
4333
+ }
4334
+ }
4335
+ async deleteVersion(id) {
4336
+ try {
4337
+ const collection = await this.getCollection(storage.TABLE_PROMPT_BLOCK_VERSIONS);
4338
+ await collection.deleteOne({ id });
4339
+ } catch (error$1) {
4340
+ throw new error.MastraError(
4341
+ {
4342
+ id: storage.createStorageErrorId("MONGODB", "DELETE_PROMPT_BLOCK_VERSION", "FAILED"),
4343
+ domain: error.ErrorDomain.STORAGE,
4344
+ category: error.ErrorCategory.THIRD_PARTY,
4345
+ details: { versionId: id }
4346
+ },
4347
+ error$1
4348
+ );
4349
+ }
4350
+ }
4351
+ async deleteVersionsByParentId(blockId) {
4352
+ try {
4353
+ const collection = await this.getCollection(storage.TABLE_PROMPT_BLOCK_VERSIONS);
4354
+ await collection.deleteMany({ blockId });
4355
+ } catch (error$1) {
4356
+ throw new error.MastraError(
4357
+ {
4358
+ id: storage.createStorageErrorId("MONGODB", "DELETE_VERSIONS_BY_BLOCK_ID", "FAILED"),
4359
+ domain: error.ErrorDomain.STORAGE,
4360
+ category: error.ErrorCategory.THIRD_PARTY,
4361
+ details: { blockId }
4362
+ },
4363
+ error$1
4364
+ );
4365
+ }
4366
+ }
4367
+ async countVersions(blockId) {
4368
+ try {
4369
+ const collection = await this.getCollection(storage.TABLE_PROMPT_BLOCK_VERSIONS);
4370
+ return await collection.countDocuments({ blockId });
4371
+ } catch (error$1) {
4372
+ throw new error.MastraError(
4373
+ {
4374
+ id: storage.createStorageErrorId("MONGODB", "COUNT_PROMPT_BLOCK_VERSIONS", "FAILED"),
4375
+ domain: error.ErrorDomain.STORAGE,
4376
+ category: error.ErrorCategory.THIRD_PARTY,
4377
+ details: { blockId }
4378
+ },
4379
+ error$1
4380
+ );
4381
+ }
4382
+ }
4383
+ // ==========================================================================
4384
+ // Private Helper Methods
4385
+ // ==========================================================================
4386
+ transformBlock(doc) {
4387
+ const { _id, ...rest } = doc;
4388
+ return {
4389
+ id: rest.id,
4390
+ status: rest.status,
4391
+ activeVersionId: rest.activeVersionId,
4392
+ authorId: rest.authorId,
4393
+ metadata: rest.metadata,
4394
+ createdAt: rest.createdAt instanceof Date ? rest.createdAt : new Date(rest.createdAt),
4395
+ updatedAt: rest.updatedAt instanceof Date ? rest.updatedAt : new Date(rest.updatedAt)
4396
+ };
4397
+ }
4398
+ serializeBlock(block) {
4399
+ return {
4400
+ id: block.id,
4401
+ status: block.status,
4402
+ activeVersionId: block.activeVersionId,
4403
+ authorId: block.authorId,
4404
+ metadata: block.metadata,
4405
+ createdAt: block.createdAt,
4406
+ updatedAt: block.updatedAt
4407
+ };
4408
+ }
4409
+ transformVersion(doc) {
4410
+ const { _id, ...version } = doc;
4411
+ const result = {
4412
+ id: version.id,
4413
+ blockId: version.blockId,
4414
+ versionNumber: version.versionNumber,
4415
+ changedFields: version.changedFields,
4416
+ changeMessage: version.changeMessage,
4417
+ createdAt: version.createdAt instanceof Date ? version.createdAt : new Date(version.createdAt)
4418
+ };
4419
+ for (const field of SNAPSHOT_FIELDS2) {
4420
+ if (version[field] !== void 0) {
4421
+ result[field] = version[field];
4422
+ }
4423
+ }
4424
+ return result;
4425
+ }
4426
+ extractSnapshotFields(version) {
4427
+ const result = {};
4428
+ for (const field of SNAPSHOT_FIELDS2) {
4429
+ if (version[field] !== void 0) {
4430
+ result[field] = version[field];
4431
+ }
4432
+ }
4433
+ return result;
4434
+ }
4435
+ };
4436
+ var SNAPSHOT_FIELDS3 = [
4437
+ "name",
4438
+ "description",
4439
+ "type",
4440
+ "model",
4441
+ "instructions",
4442
+ "scoreRange",
4443
+ "presetConfig",
4444
+ "defaultSampling"
4445
+ ];
4446
+ var MongoDBScorerDefinitionsStorage = class _MongoDBScorerDefinitionsStorage extends storage.ScorerDefinitionsStorage {
4447
+ #connector;
4448
+ #skipDefaultIndexes;
4449
+ #indexes;
4450
+ static MANAGED_COLLECTIONS = [storage.TABLE_SCORER_DEFINITIONS, storage.TABLE_SCORER_DEFINITION_VERSIONS];
4451
+ constructor(config) {
4452
+ super();
4453
+ this.#connector = resolveMongoDBConfig(config);
4454
+ this.#skipDefaultIndexes = config.skipDefaultIndexes;
4455
+ this.#indexes = config.indexes?.filter(
4456
+ (idx) => _MongoDBScorerDefinitionsStorage.MANAGED_COLLECTIONS.includes(idx.collection)
4457
+ );
4458
+ }
4459
+ async getCollection(name) {
4460
+ return this.#connector.getCollection(name);
4461
+ }
4462
+ getDefaultIndexDefinitions() {
4463
+ return [
4464
+ { collection: storage.TABLE_SCORER_DEFINITIONS, keys: { id: 1 }, options: { unique: true } },
4465
+ { collection: storage.TABLE_SCORER_DEFINITIONS, keys: { createdAt: -1 } },
4466
+ { collection: storage.TABLE_SCORER_DEFINITIONS, keys: { updatedAt: -1 } },
4467
+ { collection: storage.TABLE_SCORER_DEFINITIONS, keys: { authorId: 1 } },
4468
+ { collection: storage.TABLE_SCORER_DEFINITION_VERSIONS, keys: { id: 1 }, options: { unique: true } },
4469
+ {
4470
+ collection: storage.TABLE_SCORER_DEFINITION_VERSIONS,
4471
+ keys: { scorerDefinitionId: 1, versionNumber: -1 },
4472
+ options: { unique: true }
4473
+ },
4474
+ { collection: storage.TABLE_SCORER_DEFINITION_VERSIONS, keys: { scorerDefinitionId: 1, createdAt: -1 } }
4475
+ ];
4476
+ }
4477
+ async createDefaultIndexes() {
4478
+ if (this.#skipDefaultIndexes) {
4479
+ return;
4480
+ }
4481
+ for (const indexDef of this.getDefaultIndexDefinitions()) {
4482
+ try {
4483
+ const collection = await this.getCollection(indexDef.collection);
4484
+ await collection.createIndex(indexDef.keys, indexDef.options);
4485
+ } catch (error) {
4486
+ this.logger?.warn?.(`Failed to create index on ${indexDef.collection}:`, error);
4487
+ }
4488
+ }
4489
+ }
4490
+ async createCustomIndexes() {
4491
+ if (!this.#indexes || this.#indexes.length === 0) {
4492
+ return;
4493
+ }
4494
+ for (const indexDef of this.#indexes) {
4495
+ try {
4496
+ const collection = await this.getCollection(indexDef.collection);
4497
+ await collection.createIndex(indexDef.keys, indexDef.options);
4498
+ } catch (error) {
4499
+ this.logger?.warn?.(`Failed to create custom index on ${indexDef.collection}:`, error);
4500
+ }
4501
+ }
4502
+ }
4503
+ async init() {
4504
+ await this.createDefaultIndexes();
4505
+ await this.createCustomIndexes();
4506
+ }
4507
+ async dangerouslyClearAll() {
4508
+ const versionsCollection = await this.getCollection(storage.TABLE_SCORER_DEFINITION_VERSIONS);
4509
+ await versionsCollection.deleteMany({});
4510
+ const scorerDefinitionsCollection = await this.getCollection(storage.TABLE_SCORER_DEFINITIONS);
4511
+ await scorerDefinitionsCollection.deleteMany({});
4512
+ }
4513
+ // ==========================================================================
4514
+ // Scorer Definition CRUD
4515
+ // ==========================================================================
4516
+ async getById(id) {
4517
+ try {
4518
+ const collection = await this.getCollection(storage.TABLE_SCORER_DEFINITIONS);
4519
+ const result = await collection.findOne({ id });
4520
+ if (!result) {
4521
+ return null;
4522
+ }
4523
+ return this.transformScorerDefinition(result);
4524
+ } catch (error$1) {
4525
+ throw new error.MastraError(
4526
+ {
4527
+ id: storage.createStorageErrorId("MONGODB", "GET_SCORER_DEFINITION_BY_ID", "FAILED"),
4528
+ domain: error.ErrorDomain.STORAGE,
4529
+ category: error.ErrorCategory.THIRD_PARTY,
4530
+ details: { id }
4531
+ },
4532
+ error$1
4533
+ );
4534
+ }
4535
+ }
4536
+ async create(input) {
4537
+ const { scorerDefinition } = input;
4538
+ try {
4539
+ const collection = await this.getCollection(storage.TABLE_SCORER_DEFINITIONS);
4540
+ const existing = await collection.findOne({ id: scorerDefinition.id });
4541
+ if (existing) {
4542
+ throw new error.MastraError({
4543
+ id: storage.createStorageErrorId("MONGODB", "CREATE_SCORER_DEFINITION", "ALREADY_EXISTS"),
4544
+ domain: error.ErrorDomain.STORAGE,
4545
+ category: error.ErrorCategory.USER,
4546
+ details: { id: scorerDefinition.id },
4547
+ text: `Scorer definition with id ${scorerDefinition.id} already exists`
4548
+ });
4549
+ }
4550
+ const now = /* @__PURE__ */ new Date();
4551
+ const newScorerDefinition = {
4552
+ id: scorerDefinition.id,
4553
+ status: "draft",
4554
+ activeVersionId: void 0,
4555
+ authorId: scorerDefinition.authorId,
4556
+ metadata: scorerDefinition.metadata,
4557
+ createdAt: now,
4558
+ updatedAt: now
4559
+ };
4560
+ await collection.insertOne(this.serializeScorerDefinition(newScorerDefinition));
4561
+ const snapshotConfig = {};
4562
+ for (const field of SNAPSHOT_FIELDS3) {
4563
+ if (scorerDefinition[field] !== void 0) {
4564
+ snapshotConfig[field] = scorerDefinition[field];
4565
+ }
4566
+ }
4567
+ const versionId = crypto.randomUUID();
4568
+ await this.createVersion({
4569
+ id: versionId,
4570
+ scorerDefinitionId: scorerDefinition.id,
4571
+ versionNumber: 1,
4572
+ ...snapshotConfig,
4573
+ changedFields: Object.keys(snapshotConfig),
4574
+ changeMessage: "Initial version"
4575
+ });
4576
+ return newScorerDefinition;
4577
+ } catch (error$1) {
4578
+ if (error$1 instanceof error.MastraError) {
4579
+ throw error$1;
4580
+ }
4581
+ throw new error.MastraError(
4582
+ {
4583
+ id: storage.createStorageErrorId("MONGODB", "CREATE_SCORER_DEFINITION", "FAILED"),
4584
+ domain: error.ErrorDomain.STORAGE,
4585
+ category: error.ErrorCategory.THIRD_PARTY,
4586
+ details: { id: scorerDefinition.id }
4587
+ },
4588
+ error$1
4589
+ );
4590
+ }
4591
+ }
4592
+ async update(input) {
4593
+ const { id, ...updates } = input;
4594
+ try {
4595
+ const collection = await this.getCollection(storage.TABLE_SCORER_DEFINITIONS);
4596
+ const existingScorerDefinition = await collection.findOne({ id });
4597
+ if (!existingScorerDefinition) {
4598
+ throw new error.MastraError({
4599
+ id: storage.createStorageErrorId("MONGODB", "UPDATE_SCORER_DEFINITION", "NOT_FOUND"),
4600
+ domain: error.ErrorDomain.STORAGE,
4601
+ category: error.ErrorCategory.USER,
4602
+ details: { id },
4603
+ text: `Scorer definition with id ${id} not found`
4604
+ });
4605
+ }
4606
+ const updateDoc = {
4607
+ updatedAt: /* @__PURE__ */ new Date()
4608
+ };
4609
+ const metadataFields = {
4610
+ authorId: updates.authorId,
4611
+ activeVersionId: updates.activeVersionId,
4612
+ metadata: updates.metadata,
4613
+ status: updates.status
4614
+ };
4615
+ const configFields = {};
4616
+ for (const field of SNAPSHOT_FIELDS3) {
4617
+ if (updates[field] !== void 0) {
4618
+ configFields[field] = updates[field];
4619
+ }
4620
+ }
4621
+ if (Object.keys(configFields).length > 0) {
4622
+ const latestVersion = await this.getLatestVersion(id);
4623
+ if (!latestVersion) {
4624
+ throw new error.MastraError({
4625
+ id: storage.createStorageErrorId("MONGODB", "UPDATE_SCORER_DEFINITION", "NO_VERSION"),
4626
+ domain: error.ErrorDomain.STORAGE,
4627
+ category: error.ErrorCategory.USER,
4628
+ text: `Cannot update config fields for scorer definition ${id} - no versions exist`,
4629
+ details: { id }
4630
+ });
4631
+ }
4632
+ const existingSnapshot = this.extractSnapshotFields(latestVersion);
4633
+ await this.createVersion({
4634
+ id: crypto.randomUUID(),
4635
+ scorerDefinitionId: id,
4636
+ versionNumber: latestVersion.versionNumber + 1,
4637
+ ...existingSnapshot,
4638
+ ...configFields,
4639
+ changedFields: Object.keys(configFields),
4640
+ changeMessage: `Updated: ${Object.keys(configFields).join(", ")}`
4641
+ });
4642
+ }
4643
+ if (metadataFields.authorId !== void 0) updateDoc.authorId = metadataFields.authorId;
4644
+ if (metadataFields.activeVersionId !== void 0) {
4645
+ updateDoc.activeVersionId = metadataFields.activeVersionId;
4646
+ if (metadataFields.status === void 0) {
4647
+ updateDoc.status = "published";
4648
+ }
4649
+ }
4650
+ if (metadataFields.status !== void 0) {
4651
+ updateDoc.status = metadataFields.status;
4652
+ }
4653
+ if (metadataFields.metadata !== void 0) {
4654
+ const existingMetadata = existingScorerDefinition.metadata || {};
4655
+ updateDoc.metadata = { ...existingMetadata, ...metadataFields.metadata };
4656
+ }
4657
+ await collection.updateOne({ id }, { $set: updateDoc });
4658
+ const updatedScorerDefinition = await collection.findOne({ id });
4659
+ if (!updatedScorerDefinition) {
4660
+ throw new error.MastraError({
4661
+ id: storage.createStorageErrorId("MONGODB", "UPDATE_SCORER_DEFINITION", "NOT_FOUND_AFTER_UPDATE"),
4662
+ domain: error.ErrorDomain.STORAGE,
4663
+ category: error.ErrorCategory.SYSTEM,
4664
+ text: `Scorer definition with id ${id} was deleted during update`,
4665
+ details: { id }
4666
+ });
4667
+ }
4668
+ return this.transformScorerDefinition(updatedScorerDefinition);
4669
+ } catch (error$1) {
4670
+ if (error$1 instanceof error.MastraError) {
4671
+ throw error$1;
4672
+ }
4673
+ throw new error.MastraError(
4674
+ {
4675
+ id: storage.createStorageErrorId("MONGODB", "UPDATE_SCORER_DEFINITION", "FAILED"),
4676
+ domain: error.ErrorDomain.STORAGE,
4677
+ category: error.ErrorCategory.THIRD_PARTY,
4678
+ details: { id }
4679
+ },
4680
+ error$1
4681
+ );
4682
+ }
4683
+ }
4684
+ async delete(id) {
4685
+ try {
4686
+ await this.deleteVersionsByParentId(id);
4687
+ const collection = await this.getCollection(storage.TABLE_SCORER_DEFINITIONS);
4688
+ await collection.deleteOne({ id });
4689
+ } catch (error$1) {
4690
+ throw new error.MastraError(
4691
+ {
4692
+ id: storage.createStorageErrorId("MONGODB", "DELETE_SCORER_DEFINITION", "FAILED"),
4693
+ domain: error.ErrorDomain.STORAGE,
4694
+ category: error.ErrorCategory.THIRD_PARTY,
4695
+ details: { id }
4696
+ },
4697
+ error$1
4698
+ );
4699
+ }
4700
+ }
4701
+ async list(args) {
4702
+ try {
4703
+ const { page = 0, perPage: perPageInput, orderBy, authorId, metadata } = args || {};
4704
+ const { field, direction } = this.parseOrderBy(orderBy);
4705
+ if (page < 0) {
4706
+ throw new error.MastraError(
4707
+ {
4708
+ id: storage.createStorageErrorId("MONGODB", "LIST_SCORER_DEFINITIONS", "INVALID_PAGE"),
4709
+ domain: error.ErrorDomain.STORAGE,
4710
+ category: error.ErrorCategory.USER,
4711
+ details: { page }
4712
+ },
4713
+ new Error("page must be >= 0")
4714
+ );
4715
+ }
4716
+ const perPage = storage.normalizePerPage(perPageInput, 100);
4717
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
4718
+ const collection = await this.getCollection(storage.TABLE_SCORER_DEFINITIONS);
4719
+ const filter = {};
4720
+ if (authorId) {
4721
+ filter.authorId = authorId;
4722
+ }
4723
+ if (metadata) {
4724
+ for (const [key, value] of Object.entries(metadata)) {
4725
+ filter[`metadata.${key}`] = value;
4726
+ }
4727
+ }
4728
+ const total = await collection.countDocuments(filter);
4729
+ if (total === 0 || perPage === 0) {
4730
+ return {
4731
+ scorerDefinitions: [],
4732
+ total,
4733
+ page,
4734
+ perPage: perPageForResponse,
4735
+ hasMore: false
4736
+ };
4737
+ }
4738
+ const sortOrder = direction === "ASC" ? 1 : -1;
4739
+ let cursor = collection.find(filter).sort({ [field]: sortOrder }).skip(offset);
4740
+ if (perPageInput !== false) {
4741
+ cursor = cursor.limit(perPage);
4742
+ }
4743
+ const results = await cursor.toArray();
4744
+ const scorerDefinitions = results.map((doc) => this.transformScorerDefinition(doc));
4745
+ return {
4746
+ scorerDefinitions,
4747
+ total,
4748
+ page,
4749
+ perPage: perPageForResponse,
4750
+ hasMore: perPageInput !== false && offset + perPage < total
4751
+ };
4752
+ } catch (error$1) {
4753
+ if (error$1 instanceof error.MastraError) {
4754
+ throw error$1;
4755
+ }
4756
+ throw new error.MastraError(
4757
+ {
4758
+ id: storage.createStorageErrorId("MONGODB", "LIST_SCORER_DEFINITIONS", "FAILED"),
4759
+ domain: error.ErrorDomain.STORAGE,
4760
+ category: error.ErrorCategory.THIRD_PARTY
4761
+ },
4762
+ error$1
4763
+ );
4764
+ }
4765
+ }
4766
+ // ==========================================================================
4767
+ // Scorer Definition Version Methods
4768
+ // ==========================================================================
4769
+ async createVersion(input) {
4770
+ try {
4771
+ const collection = await this.getCollection(storage.TABLE_SCORER_DEFINITION_VERSIONS);
4772
+ const now = /* @__PURE__ */ new Date();
4773
+ const versionDoc = {
4774
+ id: input.id,
4775
+ scorerDefinitionId: input.scorerDefinitionId,
4776
+ versionNumber: input.versionNumber,
4777
+ changedFields: input.changedFields ?? void 0,
4778
+ changeMessage: input.changeMessage ?? void 0,
4779
+ createdAt: now
4780
+ };
4781
+ for (const field of SNAPSHOT_FIELDS3) {
4782
+ if (input[field] !== void 0) {
4783
+ versionDoc[field] = input[field];
4784
+ }
4785
+ }
4786
+ await collection.insertOne(versionDoc);
4787
+ return {
4788
+ ...input,
4789
+ createdAt: now
4790
+ };
4791
+ } catch (error$1) {
4792
+ throw new error.MastraError(
4793
+ {
4794
+ id: storage.createStorageErrorId("MONGODB", "CREATE_SCORER_DEFINITION_VERSION", "FAILED"),
4795
+ domain: error.ErrorDomain.STORAGE,
4796
+ category: error.ErrorCategory.THIRD_PARTY,
4797
+ details: { versionId: input.id, scorerDefinitionId: input.scorerDefinitionId }
4798
+ },
4799
+ error$1
4800
+ );
4801
+ }
4802
+ }
4803
+ async getVersion(id) {
4804
+ try {
4805
+ const collection = await this.getCollection(storage.TABLE_SCORER_DEFINITION_VERSIONS);
4806
+ const result = await collection.findOne({ id });
4807
+ if (!result) {
4808
+ return null;
4809
+ }
4810
+ return this.transformVersion(result);
4811
+ } catch (error$1) {
4812
+ throw new error.MastraError(
4813
+ {
4814
+ id: storage.createStorageErrorId("MONGODB", "GET_SCORER_DEFINITION_VERSION", "FAILED"),
4815
+ domain: error.ErrorDomain.STORAGE,
4816
+ category: error.ErrorCategory.THIRD_PARTY,
4817
+ details: { versionId: id }
4818
+ },
4819
+ error$1
4820
+ );
4821
+ }
4822
+ }
4823
+ async getVersionByNumber(scorerDefinitionId, versionNumber) {
4824
+ try {
4825
+ const collection = await this.getCollection(storage.TABLE_SCORER_DEFINITION_VERSIONS);
4826
+ const result = await collection.findOne({ scorerDefinitionId, versionNumber });
4827
+ if (!result) {
4828
+ return null;
4829
+ }
4830
+ return this.transformVersion(result);
4831
+ } catch (error$1) {
4832
+ throw new error.MastraError(
4833
+ {
4834
+ id: storage.createStorageErrorId("MONGODB", "GET_SCORER_DEFINITION_VERSION_BY_NUMBER", "FAILED"),
4835
+ domain: error.ErrorDomain.STORAGE,
4836
+ category: error.ErrorCategory.THIRD_PARTY,
4837
+ details: { scorerDefinitionId, versionNumber }
4838
+ },
4839
+ error$1
4840
+ );
4841
+ }
4842
+ }
4843
+ async getLatestVersion(scorerDefinitionId) {
4844
+ try {
4845
+ const collection = await this.getCollection(storage.TABLE_SCORER_DEFINITION_VERSIONS);
4846
+ const result = await collection.find({ scorerDefinitionId }).sort({ versionNumber: -1 }).limit(1).toArray();
4847
+ if (!result || result.length === 0) {
4848
+ return null;
4849
+ }
4850
+ return this.transformVersion(result[0]);
4851
+ } catch (error$1) {
4852
+ throw new error.MastraError(
4853
+ {
4854
+ id: storage.createStorageErrorId("MONGODB", "GET_LATEST_SCORER_DEFINITION_VERSION", "FAILED"),
4855
+ domain: error.ErrorDomain.STORAGE,
4856
+ category: error.ErrorCategory.THIRD_PARTY,
4857
+ details: { scorerDefinitionId }
4858
+ },
4859
+ error$1
4860
+ );
4861
+ }
4862
+ }
4863
+ async listVersions(input) {
4864
+ const { scorerDefinitionId, page = 0, perPage: perPageInput, orderBy } = input;
4865
+ if (page < 0) {
4866
+ throw new error.MastraError(
4867
+ {
4868
+ id: storage.createStorageErrorId("MONGODB", "LIST_SCORER_DEFINITION_VERSIONS", "INVALID_PAGE"),
4869
+ domain: error.ErrorDomain.STORAGE,
4870
+ category: error.ErrorCategory.USER,
4871
+ details: { page }
4872
+ },
4873
+ new Error("page must be >= 0")
4874
+ );
4875
+ }
4876
+ const perPage = storage.normalizePerPage(perPageInput, 20);
4877
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
4878
+ try {
4879
+ const { field, direction } = this.parseVersionOrderBy(orderBy);
4880
+ const collection = await this.getCollection(storage.TABLE_SCORER_DEFINITION_VERSIONS);
4881
+ const total = await collection.countDocuments({ scorerDefinitionId });
4882
+ if (total === 0 || perPage === 0) {
4883
+ return {
4884
+ versions: [],
4885
+ total,
4886
+ page,
4887
+ perPage: perPageForResponse,
4888
+ hasMore: false
4889
+ };
4890
+ }
4891
+ const sortOrder = direction === "ASC" ? 1 : -1;
4892
+ let cursor = collection.find({ scorerDefinitionId }).sort({ [field]: sortOrder }).skip(offset);
4893
+ if (perPageInput !== false) {
4894
+ cursor = cursor.limit(perPage);
4895
+ }
4896
+ const results = await cursor.toArray();
4897
+ const versions = results.map((doc) => this.transformVersion(doc));
4898
+ return {
4899
+ versions,
4900
+ total,
4901
+ page,
4902
+ perPage: perPageForResponse,
4903
+ hasMore: perPageInput !== false && offset + perPage < total
4904
+ };
4905
+ } catch (error$1) {
4906
+ throw new error.MastraError(
4907
+ {
4908
+ id: storage.createStorageErrorId("MONGODB", "LIST_SCORER_DEFINITION_VERSIONS", "FAILED"),
4909
+ domain: error.ErrorDomain.STORAGE,
4910
+ category: error.ErrorCategory.THIRD_PARTY,
4911
+ details: { scorerDefinitionId }
4912
+ },
4913
+ error$1
4914
+ );
4915
+ }
4916
+ }
4917
+ async deleteVersion(id) {
4918
+ try {
4919
+ const collection = await this.getCollection(storage.TABLE_SCORER_DEFINITION_VERSIONS);
4920
+ await collection.deleteOne({ id });
4921
+ } catch (error$1) {
4922
+ throw new error.MastraError(
4923
+ {
4924
+ id: storage.createStorageErrorId("MONGODB", "DELETE_SCORER_DEFINITION_VERSION", "FAILED"),
4925
+ domain: error.ErrorDomain.STORAGE,
4926
+ category: error.ErrorCategory.THIRD_PARTY,
4927
+ details: { versionId: id }
4928
+ },
4929
+ error$1
4930
+ );
4931
+ }
4932
+ }
4933
+ async deleteVersionsByParentId(scorerDefinitionId) {
4934
+ try {
4935
+ const collection = await this.getCollection(storage.TABLE_SCORER_DEFINITION_VERSIONS);
4936
+ await collection.deleteMany({ scorerDefinitionId });
4937
+ } catch (error$1) {
4938
+ throw new error.MastraError(
4939
+ {
4940
+ id: storage.createStorageErrorId("MONGODB", "DELETE_VERSIONS_BY_SCORER_DEFINITION_ID", "FAILED"),
4941
+ domain: error.ErrorDomain.STORAGE,
4942
+ category: error.ErrorCategory.THIRD_PARTY,
4943
+ details: { scorerDefinitionId }
4944
+ },
4945
+ error$1
4946
+ );
4947
+ }
4948
+ }
4949
+ async countVersions(scorerDefinitionId) {
4950
+ try {
4951
+ const collection = await this.getCollection(storage.TABLE_SCORER_DEFINITION_VERSIONS);
4952
+ return await collection.countDocuments({ scorerDefinitionId });
4953
+ } catch (error$1) {
4954
+ throw new error.MastraError(
4955
+ {
4956
+ id: storage.createStorageErrorId("MONGODB", "COUNT_SCORER_DEFINITION_VERSIONS", "FAILED"),
4957
+ domain: error.ErrorDomain.STORAGE,
4958
+ category: error.ErrorCategory.THIRD_PARTY,
4959
+ details: { scorerDefinitionId }
4960
+ },
4961
+ error$1
4962
+ );
4963
+ }
4964
+ }
4965
+ // ==========================================================================
4966
+ // Private Helper Methods
4967
+ // ==========================================================================
4968
+ transformScorerDefinition(doc) {
4969
+ const { _id, ...rest } = doc;
4970
+ return {
4971
+ id: rest.id,
4972
+ status: rest.status,
4973
+ activeVersionId: rest.activeVersionId,
4974
+ authorId: rest.authorId,
4975
+ metadata: rest.metadata,
4976
+ createdAt: rest.createdAt instanceof Date ? rest.createdAt : new Date(rest.createdAt),
4977
+ updatedAt: rest.updatedAt instanceof Date ? rest.updatedAt : new Date(rest.updatedAt)
4978
+ };
4979
+ }
4980
+ serializeScorerDefinition(scorerDefinition) {
4981
+ return {
4982
+ id: scorerDefinition.id,
4983
+ status: scorerDefinition.status,
4984
+ activeVersionId: scorerDefinition.activeVersionId,
4985
+ authorId: scorerDefinition.authorId,
4986
+ metadata: scorerDefinition.metadata,
4987
+ createdAt: scorerDefinition.createdAt,
4988
+ updatedAt: scorerDefinition.updatedAt
4989
+ };
4990
+ }
4991
+ transformVersion(doc) {
4992
+ const { _id, ...version } = doc;
4993
+ const result = {
4994
+ id: version.id,
4995
+ scorerDefinitionId: version.scorerDefinitionId,
4996
+ versionNumber: version.versionNumber,
4997
+ changedFields: version.changedFields,
4998
+ changeMessage: version.changeMessage,
4999
+ createdAt: version.createdAt instanceof Date ? version.createdAt : new Date(version.createdAt)
5000
+ };
5001
+ for (const field of SNAPSHOT_FIELDS3) {
5002
+ if (version[field] !== void 0) {
5003
+ result[field] = version[field];
5004
+ }
5005
+ }
5006
+ return result;
5007
+ }
5008
+ extractSnapshotFields(version) {
5009
+ const result = {};
5010
+ for (const field of SNAPSHOT_FIELDS3) {
5011
+ if (version[field] !== void 0) {
5012
+ result[field] = version[field];
5013
+ }
5014
+ }
5015
+ return result;
5016
+ }
5017
+ };
3554
5018
  function transformScoreRow(row) {
3555
5019
  return storage.transformScoreRow(row, {
3556
5020
  convertTimestamps: true
@@ -4215,12 +5679,16 @@ var MongoDBStore = class extends storage.MastraCompositeStore {
4215
5679
  const workflows = new WorkflowsStorageMongoDB(domainConfig);
4216
5680
  const observability = new ObservabilityMongoDB(domainConfig);
4217
5681
  const agents = new MongoDBAgentsStorage(domainConfig);
5682
+ const promptBlocks = new MongoDBPromptBlocksStorage(domainConfig);
5683
+ const scorerDefinitions = new MongoDBScorerDefinitionsStorage(domainConfig);
4218
5684
  this.stores = {
4219
5685
  memory,
4220
5686
  scores,
4221
5687
  workflows,
4222
5688
  observability,
4223
- agents
5689
+ agents,
5690
+ promptBlocks,
5691
+ scorerDefinitions
4224
5692
  };
4225
5693
  }
4226
5694
  /**
@@ -4342,6 +5810,8 @@ Example Complex Query:
4342
5810
  exports.MONGODB_PROMPT = MONGODB_PROMPT;
4343
5811
  exports.MemoryStorageMongoDB = MemoryStorageMongoDB;
4344
5812
  exports.MongoDBAgentsStorage = MongoDBAgentsStorage;
5813
+ exports.MongoDBPromptBlocksStorage = MongoDBPromptBlocksStorage;
5814
+ exports.MongoDBScorerDefinitionsStorage = MongoDBScorerDefinitionsStorage;
4345
5815
  exports.MongoDBStore = MongoDBStore;
4346
5816
  exports.MongoDBVector = MongoDBVector;
4347
5817
  exports.ObservabilityMongoDB = ObservabilityMongoDB;