@mastra/mongodb 0.14.9 → 1.0.0-beta.1

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
@@ -7,13 +7,13 @@ var uuid = require('uuid');
7
7
  var filter = require('@mastra/core/vector/filter');
8
8
  var storage = require('@mastra/core/storage');
9
9
  var agent = require('@mastra/core/agent');
10
- var scores = require('@mastra/core/scores');
10
+ var evals = require('@mastra/core/evals');
11
11
 
12
12
  // src/vector/index.ts
13
13
 
14
14
  // package.json
15
15
  var package_default = {
16
- version: "0.14.9"};
16
+ version: "1.0.0-beta.1"};
17
17
  var MongoDBFilterTranslator = class extends filter.BaseFilterTranslator {
18
18
  getSupportedOperators() {
19
19
  return {
@@ -116,8 +116,8 @@ var MongoDBVector = class extends vector.MastraVector {
116
116
  euclidean: "euclidean",
117
117
  dotproduct: "dotProduct"
118
118
  };
119
- constructor({ uri, dbName, options }) {
120
- super();
119
+ constructor({ id, uri, dbName, options }) {
120
+ super({ id });
121
121
  const client = new mongodb.MongoClient(uri, {
122
122
  ...options,
123
123
  driverInfo: {
@@ -695,155 +695,6 @@ var MongoDBConnector = class _MongoDBConnector {
695
695
  }
696
696
  }
697
697
  };
698
- function transformEvalRow(row) {
699
- let testInfoValue = null;
700
- if (row.test_info) {
701
- try {
702
- testInfoValue = typeof row.test_info === "string" ? storage.safelyParseJSON(row.test_info) : row.test_info;
703
- } catch (e) {
704
- console.warn("Failed to parse test_info:", e);
705
- }
706
- }
707
- let resultValue;
708
- try {
709
- resultValue = typeof row.result === "string" ? storage.safelyParseJSON(row.result) : row.result;
710
- } catch (e) {
711
- console.warn("Failed to parse result:", e);
712
- throw new Error("Invalid result format");
713
- }
714
- return {
715
- agentName: row.agent_name,
716
- input: row.input,
717
- output: row.output,
718
- result: resultValue,
719
- metricName: row.metric_name,
720
- instructions: row.instructions,
721
- testInfo: testInfoValue,
722
- globalRunId: row.global_run_id,
723
- runId: row.run_id,
724
- createdAt: row.createdAt
725
- };
726
- }
727
- var LegacyEvalsMongoDB = class extends storage.LegacyEvalsStorage {
728
- operations;
729
- constructor({ operations }) {
730
- super();
731
- this.operations = operations;
732
- }
733
- /** @deprecated use getEvals instead */
734
- async getEvalsByAgentName(agentName, type) {
735
- try {
736
- const query = {
737
- agent_name: agentName
738
- };
739
- if (type === "test") {
740
- query["test_info"] = { $ne: null };
741
- }
742
- if (type === "live") {
743
- query["test_info"] = null;
744
- }
745
- const collection = await this.operations.getCollection(storage.TABLE_EVALS);
746
- const documents = await collection.find(query).sort({ created_at: "desc" }).toArray();
747
- const result = documents.map((row) => transformEvalRow(row));
748
- return result.filter((row) => {
749
- if (type === "live") {
750
- return !Boolean(row.testInfo?.testPath);
751
- }
752
- if (type === "test") {
753
- return row.testInfo?.testPath !== null;
754
- }
755
- return true;
756
- });
757
- } catch (error$1) {
758
- if (error$1 instanceof Error && error$1.message.includes("no such table")) {
759
- return [];
760
- }
761
- throw new error.MastraError(
762
- {
763
- id: "STORAGE_MONGODB_STORE_GET_EVALS_BY_AGENT_NAME_FAILED",
764
- domain: error.ErrorDomain.STORAGE,
765
- category: error.ErrorCategory.THIRD_PARTY,
766
- details: { agentName }
767
- },
768
- error$1
769
- );
770
- }
771
- }
772
- async getEvals(options = {}) {
773
- const { agentName, type, page = 0, perPage = 100, dateRange } = options;
774
- const fromDate = dateRange?.start;
775
- const toDate = dateRange?.end;
776
- const currentOffset = page * perPage;
777
- const query = {};
778
- if (agentName) {
779
- query["agent_name"] = agentName;
780
- }
781
- if (type === "test") {
782
- query["test_info"] = { $ne: null };
783
- } else if (type === "live") {
784
- query["test_info"] = null;
785
- }
786
- if (fromDate || toDate) {
787
- query["createdAt"] = {};
788
- if (fromDate) {
789
- query["createdAt"]["$gte"] = fromDate;
790
- }
791
- if (toDate) {
792
- query["createdAt"]["$lte"] = toDate;
793
- }
794
- }
795
- try {
796
- const collection = await this.operations.getCollection(storage.TABLE_EVALS);
797
- let total = 0;
798
- if (page === 0 || perPage < 1e3) {
799
- total = await collection.countDocuments(query);
800
- }
801
- if (total === 0) {
802
- return {
803
- evals: [],
804
- total: 0,
805
- page,
806
- perPage,
807
- hasMore: false
808
- };
809
- }
810
- const documents = await collection.find(query).sort({ created_at: "desc" }).skip(currentOffset).limit(perPage).toArray();
811
- const evals = documents.map((row) => transformEvalRow(row));
812
- const filteredEvals = evals.filter((row) => {
813
- if (type === "live") {
814
- return !Boolean(row.testInfo?.testPath);
815
- }
816
- if (type === "test") {
817
- return row.testInfo?.testPath !== null;
818
- }
819
- return true;
820
- });
821
- const hasMore = currentOffset + filteredEvals.length < total;
822
- return {
823
- evals: filteredEvals,
824
- total,
825
- page,
826
- perPage,
827
- hasMore
828
- };
829
- } catch (error$1) {
830
- throw new error.MastraError(
831
- {
832
- id: "STORAGE_MONGODB_STORE_GET_EVALS_FAILED",
833
- domain: error.ErrorDomain.STORAGE,
834
- category: error.ErrorCategory.THIRD_PARTY,
835
- details: {
836
- agentName: agentName || "all",
837
- type: type || "all",
838
- page,
839
- perPage
840
- }
841
- },
842
- error$1
843
- );
844
- }
845
- }
846
- };
847
698
 
848
699
  // src/storage/domains/utils.ts
849
700
  function formatDateForMongoDB(date) {
@@ -878,10 +729,9 @@ var MemoryStorageMongoDB = class extends storage.MemoryStorage {
878
729
  }
879
730
  async _getIncludedMessages({
880
731
  threadId,
881
- selectBy
732
+ include
882
733
  }) {
883
734
  if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
884
- const include = selectBy?.include;
885
735
  if (!include) return null;
886
736
  const collection = await this.operations.getCollection(storage.TABLE_MESSAGES);
887
737
  const includedMessages = [];
@@ -905,151 +755,147 @@ var MemoryStorageMongoDB = class extends storage.MemoryStorage {
905
755
  });
906
756
  return dedupedMessages.map((row) => this.parseRow(row));
907
757
  }
908
- async getMessages({
909
- threadId,
910
- resourceId,
911
- selectBy,
912
- format
913
- }) {
758
+ async listMessagesById({ messageIds }) {
759
+ if (messageIds.length === 0) return { messages: [] };
914
760
  try {
915
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
916
- const messages = [];
917
- const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
918
- if (selectBy?.include?.length) {
919
- const includeMessages = await this._getIncludedMessages({ threadId, selectBy });
920
- if (includeMessages) {
921
- messages.push(...includeMessages);
922
- }
923
- }
924
- const excludeIds = messages.map((m) => m.id);
925
761
  const collection = await this.operations.getCollection(storage.TABLE_MESSAGES);
926
- const query = { thread_id: threadId };
927
- if (excludeIds.length > 0) {
928
- query.id = { $nin: excludeIds };
929
- }
930
- if (limit > 0) {
931
- const remainingMessages = await collection.find(query).sort({ createdAt: -1 }).limit(limit).toArray();
932
- messages.push(...remainingMessages.map((row) => this.parseRow(row)));
933
- }
934
- messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
935
- const list = new agent.MessageList().add(messages, "memory");
936
- if (format === "v2") return list.get.all.v2();
937
- return list.get.all.v1();
762
+ const rawMessages = await collection.find({ id: { $in: messageIds } }).sort({ createdAt: -1 }).toArray();
763
+ const list = new agent.MessageList().add(
764
+ rawMessages.map(this.parseRow),
765
+ "memory"
766
+ );
767
+ return { messages: list.get.all.db() };
938
768
  } catch (error$1) {
939
769
  throw new error.MastraError(
940
770
  {
941
- id: "MONGODB_STORE_GET_MESSAGES_FAILED",
771
+ id: "MONGODB_STORE_LIST_MESSAGES_BY_ID_FAILED",
942
772
  domain: error.ErrorDomain.STORAGE,
943
773
  category: error.ErrorCategory.THIRD_PARTY,
944
- details: { threadId, resourceId: resourceId ?? "" }
774
+ details: { messageIds: JSON.stringify(messageIds) }
945
775
  },
946
776
  error$1
947
777
  );
948
778
  }
949
779
  }
950
- async getMessagesById({
951
- messageIds,
952
- format
953
- }) {
954
- if (messageIds.length === 0) return [];
955
- try {
956
- const collection = await this.operations.getCollection(storage.TABLE_MESSAGES);
957
- const rawMessages = await collection.find({ id: { $in: messageIds } }).sort({ createdAt: -1 }).toArray();
958
- const list = new agent.MessageList().add(rawMessages.map(this.parseRow), "memory");
959
- if (format === `v1`) return list.get.all.v1();
960
- return list.get.all.v2();
961
- } catch (error$1) {
780
+ async listMessages(args) {
781
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
782
+ if (!threadId.trim()) {
962
783
  throw new error.MastraError(
963
784
  {
964
- id: "MONGODB_STORE_GET_MESSAGES_BY_ID_FAILED",
785
+ id: "STORAGE_MONGODB_LIST_MESSAGES_INVALID_THREAD_ID",
965
786
  domain: error.ErrorDomain.STORAGE,
966
787
  category: error.ErrorCategory.THIRD_PARTY,
967
- details: { messageIds: JSON.stringify(messageIds) }
788
+ details: { threadId }
968
789
  },
969
- error$1
790
+ new Error("threadId must be a non-empty string")
970
791
  );
971
792
  }
972
- }
973
- async getMessagesPaginated(args) {
974
- const { threadId, resourceId, format, selectBy } = args;
975
- const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
976
- const perPage = perPageInput !== void 0 ? perPageInput : storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
977
- const fromDate = dateRange?.start;
978
- const toDate = dateRange?.end;
979
- const messages = [];
980
- if (selectBy?.include?.length) {
981
- try {
982
- const includeMessages = await this._getIncludedMessages({ threadId, selectBy });
983
- if (includeMessages) {
984
- messages.push(...includeMessages);
985
- }
986
- } catch (error$1) {
987
- throw new error.MastraError(
988
- {
989
- id: "MONGODB_STORE_GET_MESSAGES_PAGINATED_GET_INCLUDE_MESSAGES_FAILED",
990
- domain: error.ErrorDomain.STORAGE,
991
- category: error.ErrorCategory.THIRD_PARTY,
992
- details: { threadId, resourceId: resourceId ?? "" }
993
- },
994
- error$1
995
- );
996
- }
793
+ if (page < 0) {
794
+ throw new error.MastraError(
795
+ {
796
+ id: "STORAGE_MONGODB_LIST_MESSAGES_INVALID_PAGE",
797
+ domain: error.ErrorDomain.STORAGE,
798
+ category: error.ErrorCategory.USER,
799
+ details: { page }
800
+ },
801
+ new Error("page must be >= 0")
802
+ );
997
803
  }
804
+ const perPage = storage.normalizePerPage(perPageInput, 40);
805
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
998
806
  try {
999
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1000
- const currentOffset = page * perPage;
807
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
808
+ const sortOrder = direction === "ASC" ? 1 : -1;
1001
809
  const collection = await this.operations.getCollection(storage.TABLE_MESSAGES);
1002
810
  const query = { thread_id: threadId };
1003
- if (fromDate) {
1004
- query.createdAt = { ...query.createdAt, $gte: fromDate };
811
+ if (resourceId) {
812
+ query.resourceId = resourceId;
813
+ }
814
+ if (filter?.dateRange?.start) {
815
+ query.createdAt = { ...query.createdAt, $gte: filter.dateRange.start };
1005
816
  }
1006
- if (toDate) {
1007
- query.createdAt = { ...query.createdAt, $lte: toDate };
817
+ if (filter?.dateRange?.end) {
818
+ query.createdAt = { ...query.createdAt, $lte: filter.dateRange.end };
1008
819
  }
1009
820
  const total = await collection.countDocuments(query);
1010
- if (total === 0 && messages.length === 0) {
821
+ const messages = [];
822
+ if (perPage !== 0) {
823
+ const sortObj = { [field]: sortOrder };
824
+ let cursor = collection.find(query).sort(sortObj).skip(offset);
825
+ if (perPageInput !== false) {
826
+ cursor = cursor.limit(perPage);
827
+ }
828
+ const dataResult = await cursor.toArray();
829
+ messages.push(...dataResult.map((row) => this.parseRow(row)));
830
+ }
831
+ if (total === 0 && messages.length === 0 && (!include || include.length === 0)) {
1011
832
  return {
1012
833
  messages: [],
1013
834
  total: 0,
1014
835
  page,
1015
- perPage,
836
+ perPage: perPageForResponse,
1016
837
  hasMore: false
1017
838
  };
1018
839
  }
1019
- const excludeIds = messages.map((m) => m.id);
1020
- if (excludeIds.length > 0) {
1021
- query.id = { $nin: excludeIds };
840
+ const messageIds = new Set(messages.map((m) => m.id));
841
+ if (include && include.length > 0) {
842
+ const includeMessages = await this._getIncludedMessages({ threadId, include });
843
+ if (includeMessages) {
844
+ for (const includeMsg of includeMessages) {
845
+ if (!messageIds.has(includeMsg.id)) {
846
+ messages.push(includeMsg);
847
+ messageIds.add(includeMsg.id);
848
+ }
849
+ }
850
+ }
1022
851
  }
1023
- const dataResult = await collection.find(query).sort({ createdAt: -1 }).skip(currentOffset).limit(perPage).toArray();
1024
- messages.push(...dataResult.map((row) => this.parseRow(row)));
1025
- const messagesToReturn = format === "v1" ? new agent.MessageList().add(messages, "memory").get.all.v1() : new agent.MessageList().add(messages, "memory").get.all.v2();
852
+ const list = new agent.MessageList().add(messages, "memory");
853
+ let finalMessages = list.get.all.db();
854
+ finalMessages = finalMessages.sort((a, b) => {
855
+ const isDateField = field === "createdAt" || field === "updatedAt";
856
+ const aValue = isDateField ? new Date(a[field]).getTime() : a[field];
857
+ const bValue = isDateField ? new Date(b[field]).getTime() : b[field];
858
+ if (typeof aValue === "number" && typeof bValue === "number") {
859
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
860
+ }
861
+ return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
862
+ });
863
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
864
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
865
+ const hasMore = perPageInput !== false && !allThreadMessagesReturned && offset + perPage < total;
1026
866
  return {
1027
- messages: messagesToReturn,
867
+ messages: finalMessages,
1028
868
  total,
1029
869
  page,
1030
- perPage,
1031
- hasMore: (page + 1) * perPage < total
870
+ perPage: perPageForResponse,
871
+ hasMore
1032
872
  };
1033
873
  } catch (error$1) {
1034
874
  const mastraError = new error.MastraError(
1035
875
  {
1036
- id: "MONGODB_STORE_GET_MESSAGES_PAGINATED_FAILED",
876
+ id: "MONGODB_STORE_LIST_MESSAGES_FAILED",
1037
877
  domain: error.ErrorDomain.STORAGE,
1038
878
  category: error.ErrorCategory.THIRD_PARTY,
1039
- details: { threadId, resourceId: resourceId ?? "" }
879
+ details: {
880
+ threadId,
881
+ resourceId: resourceId ?? ""
882
+ }
1040
883
  },
1041
884
  error$1
1042
885
  );
1043
- this.logger?.trackException?.(mastraError);
1044
886
  this.logger?.error?.(mastraError.toString());
1045
- return { messages: [], total: 0, page, perPage, hasMore: false };
887
+ this.logger?.trackException?.(mastraError);
888
+ return {
889
+ messages: [],
890
+ total: 0,
891
+ page,
892
+ perPage: perPageForResponse,
893
+ hasMore: false
894
+ };
1046
895
  }
1047
896
  }
1048
- async saveMessages({
1049
- messages,
1050
- format
1051
- }) {
1052
- if (messages.length === 0) return messages;
897
+ async saveMessages({ messages }) {
898
+ if (messages.length === 0) return { messages: [] };
1053
899
  try {
1054
900
  const threadId = messages[0]?.threadId;
1055
901
  if (!threadId) {
@@ -1092,8 +938,7 @@ var MemoryStorageMongoDB = class extends storage.MemoryStorage {
1092
938
  threadsCollection.updateOne({ id: threadId }, { $set: { updatedAt: /* @__PURE__ */ new Date() } })
1093
939
  ]);
1094
940
  const list = new agent.MessageList().add(messages, "memory");
1095
- if (format === "v2") return list.get.all.v2();
1096
- return list.get.all.v1();
941
+ return { messages: list.get.all.db() };
1097
942
  } catch (error$1) {
1098
943
  throw new error.MastraError(
1099
944
  {
@@ -1298,36 +1143,41 @@ var MemoryStorageMongoDB = class extends storage.MemoryStorage {
1298
1143
  );
1299
1144
  }
1300
1145
  }
1301
- async getThreadsByResourceId({ resourceId }) {
1146
+ async listThreadsByResourceId(args) {
1302
1147
  try {
1303
- const collection = await this.operations.getCollection(storage.TABLE_THREADS);
1304
- const results = await collection.find({ resourceId }).sort({ updatedAt: -1 }).toArray();
1305
- if (!results.length) {
1306
- return [];
1148
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
1149
+ if (page < 0) {
1150
+ throw new error.MastraError(
1151
+ {
1152
+ id: "STORAGE_MONGODB_LIST_THREADS_BY_RESOURCE_ID_INVALID_PAGE",
1153
+ domain: error.ErrorDomain.STORAGE,
1154
+ category: error.ErrorCategory.USER,
1155
+ details: { page }
1156
+ },
1157
+ new Error("page must be >= 0")
1158
+ );
1307
1159
  }
1308
- return results.map((result) => ({
1309
- ...result,
1310
- metadata: typeof result.metadata === "string" ? storage.safelyParseJSON(result.metadata) : result.metadata
1311
- }));
1312
- } catch (error$1) {
1313
- throw new error.MastraError(
1314
- {
1315
- id: "STORAGE_MONGODB_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
1316
- domain: error.ErrorDomain.STORAGE,
1317
- category: error.ErrorCategory.THIRD_PARTY,
1318
- details: { resourceId }
1319
- },
1320
- error$1
1321
- );
1322
- }
1323
- }
1324
- async getThreadsByResourceIdPaginated(args) {
1325
- try {
1326
- const { resourceId, page, perPage } = args;
1160
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1161
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1162
+ const { field, direction } = this.parseOrderBy(orderBy);
1327
1163
  const collection = await this.operations.getCollection(storage.TABLE_THREADS);
1328
1164
  const query = { resourceId };
1329
1165
  const total = await collection.countDocuments(query);
1330
- const threads = await collection.find(query).sort({ updatedAt: -1 }).skip(page * perPage).limit(perPage).toArray();
1166
+ if (perPage === 0) {
1167
+ return {
1168
+ threads: [],
1169
+ total,
1170
+ page,
1171
+ perPage: perPageForResponse,
1172
+ hasMore: offset < total
1173
+ };
1174
+ }
1175
+ const sortOrder = direction === "ASC" ? 1 : -1;
1176
+ let cursor = collection.find(query).sort({ [field]: sortOrder }).skip(offset);
1177
+ if (perPageInput !== false) {
1178
+ cursor = cursor.limit(perPage);
1179
+ }
1180
+ const threads = await cursor.toArray();
1331
1181
  return {
1332
1182
  threads: threads.map((thread) => ({
1333
1183
  id: thread.id,
@@ -1339,13 +1189,13 @@ var MemoryStorageMongoDB = class extends storage.MemoryStorage {
1339
1189
  })),
1340
1190
  total,
1341
1191
  page,
1342
- perPage,
1343
- hasMore: (page + 1) * perPage < total
1192
+ perPage: perPageForResponse,
1193
+ hasMore: perPageInput === false ? false : offset + perPage < total
1344
1194
  };
1345
1195
  } catch (error$1) {
1346
1196
  throw new error.MastraError(
1347
1197
  {
1348
- id: "MONGODB_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
1198
+ id: "MONGODB_STORE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
1349
1199
  domain: error.ErrorDomain.STORAGE,
1350
1200
  category: error.ErrorCategory.THIRD_PARTY,
1351
1201
  details: { resourceId: args.resourceId }
@@ -1452,13 +1302,13 @@ var ObservabilityMongoDB = class extends storage.ObservabilityStorage {
1452
1302
  super();
1453
1303
  this.operations = operations;
1454
1304
  }
1455
- get aiTracingStrategy() {
1305
+ get tracingStrategy() {
1456
1306
  return {
1457
1307
  preferred: "batch-with-updates",
1458
1308
  supported: ["batch-with-updates", "insert-only"]
1459
1309
  };
1460
1310
  }
1461
- async createAISpan(span) {
1311
+ async createSpan(span) {
1462
1312
  try {
1463
1313
  const startedAt = span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt;
1464
1314
  const endedAt = span.endedAt instanceof Date ? span.endedAt.toISOString() : span.endedAt;
@@ -1469,11 +1319,11 @@ var ObservabilityMongoDB = class extends storage.ObservabilityStorage {
1469
1319
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1470
1320
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1471
1321
  };
1472
- return this.operations.insert({ tableName: storage.TABLE_AI_SPANS, record });
1322
+ return this.operations.insert({ tableName: storage.TABLE_SPANS, record });
1473
1323
  } catch (error$1) {
1474
1324
  throw new error.MastraError(
1475
1325
  {
1476
- id: "MONGODB_STORE_CREATE_AI_SPAN_FAILED",
1326
+ id: "MONGODB_STORE_CREATE_SPAN_FAILED",
1477
1327
  domain: error.ErrorDomain.STORAGE,
1478
1328
  category: error.ErrorCategory.USER,
1479
1329
  details: {
@@ -1487,9 +1337,9 @@ var ObservabilityMongoDB = class extends storage.ObservabilityStorage {
1487
1337
  );
1488
1338
  }
1489
1339
  }
1490
- async getAITrace(traceId) {
1340
+ async getTrace(traceId) {
1491
1341
  try {
1492
- const collection = await this.operations.getCollection(storage.TABLE_AI_SPANS);
1342
+ const collection = await this.operations.getCollection(storage.TABLE_SPANS);
1493
1343
  const spans = await collection.find({ traceId }).sort({ startedAt: -1 }).toArray();
1494
1344
  if (!spans || spans.length === 0) {
1495
1345
  return null;
@@ -1501,7 +1351,7 @@ var ObservabilityMongoDB = class extends storage.ObservabilityStorage {
1501
1351
  } catch (error$1) {
1502
1352
  throw new error.MastraError(
1503
1353
  {
1504
- id: "MONGODB_STORE_GET_AI_TRACE_FAILED",
1354
+ id: "MONGODB_STORE_GET_TRACE_FAILED",
1505
1355
  domain: error.ErrorDomain.STORAGE,
1506
1356
  category: error.ErrorCategory.USER,
1507
1357
  details: {
@@ -1512,7 +1362,7 @@ var ObservabilityMongoDB = class extends storage.ObservabilityStorage {
1512
1362
  );
1513
1363
  }
1514
1364
  }
1515
- async updateAISpan({
1365
+ async updateSpan({
1516
1366
  spanId,
1517
1367
  traceId,
1518
1368
  updates
@@ -1530,14 +1380,14 @@ var ObservabilityMongoDB = class extends storage.ObservabilityStorage {
1530
1380
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1531
1381
  };
1532
1382
  await this.operations.update({
1533
- tableName: storage.TABLE_AI_SPANS,
1383
+ tableName: storage.TABLE_SPANS,
1534
1384
  keys: { spanId, traceId },
1535
1385
  data: updateData
1536
1386
  });
1537
1387
  } catch (error$1) {
1538
1388
  throw new error.MastraError(
1539
1389
  {
1540
- id: "MONGODB_STORE_UPDATE_AI_SPAN_FAILED",
1390
+ id: "MONGODB_STORE_UPDATE_SPAN_FAILED",
1541
1391
  domain: error.ErrorDomain.STORAGE,
1542
1392
  category: error.ErrorCategory.USER,
1543
1393
  details: {
@@ -1549,7 +1399,7 @@ var ObservabilityMongoDB = class extends storage.ObservabilityStorage {
1549
1399
  );
1550
1400
  }
1551
1401
  }
1552
- async getAITracesPaginated({
1402
+ async getTracesPaginated({
1553
1403
  filters,
1554
1404
  pagination
1555
1405
  }) {
@@ -1557,7 +1407,7 @@ var ObservabilityMongoDB = class extends storage.ObservabilityStorage {
1557
1407
  const perPage = pagination?.perPage ?? 10;
1558
1408
  const { entityId, entityType, ...actualFilters } = filters || {};
1559
1409
  try {
1560
- const collection = await this.operations.getCollection(storage.TABLE_AI_SPANS);
1410
+ const collection = await this.operations.getCollection(storage.TABLE_SPANS);
1561
1411
  const mongoFilter = {
1562
1412
  parentSpanId: null,
1563
1413
  // Only get root spans for traces
@@ -1583,7 +1433,7 @@ var ObservabilityMongoDB = class extends storage.ObservabilityStorage {
1583
1433
  name = `agent run: '${entityId}'`;
1584
1434
  } else {
1585
1435
  const error$1 = new error.MastraError({
1586
- id: "MONGODB_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1436
+ id: "MONGODB_STORE_GET_TRACES_PAGINATED_FAILED",
1587
1437
  domain: error.ErrorDomain.STORAGE,
1588
1438
  category: error.ErrorCategory.USER,
1589
1439
  details: {
@@ -1620,7 +1470,7 @@ var ObservabilityMongoDB = class extends storage.ObservabilityStorage {
1620
1470
  } catch (error$1) {
1621
1471
  throw new error.MastraError(
1622
1472
  {
1623
- id: "MONGODB_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1473
+ id: "MONGODB_STORE_GET_TRACES_PAGINATED_FAILED",
1624
1474
  domain: error.ErrorDomain.STORAGE,
1625
1475
  category: error.ErrorCategory.USER
1626
1476
  },
@@ -1628,7 +1478,7 @@ var ObservabilityMongoDB = class extends storage.ObservabilityStorage {
1628
1478
  );
1629
1479
  }
1630
1480
  }
1631
- async batchCreateAISpans(args) {
1481
+ async batchCreateSpans(args) {
1632
1482
  try {
1633
1483
  const records = args.records.map((record) => {
1634
1484
  const startedAt = record.startedAt instanceof Date ? record.startedAt.toISOString() : record.startedAt;
@@ -1642,13 +1492,13 @@ var ObservabilityMongoDB = class extends storage.ObservabilityStorage {
1642
1492
  };
1643
1493
  });
1644
1494
  return this.operations.batchInsert({
1645
- tableName: storage.TABLE_AI_SPANS,
1495
+ tableName: storage.TABLE_SPANS,
1646
1496
  records
1647
1497
  });
1648
1498
  } catch (error$1) {
1649
1499
  throw new error.MastraError(
1650
1500
  {
1651
- id: "MONGODB_STORE_BATCH_CREATE_AI_SPANS_FAILED",
1501
+ id: "MONGODB_STORE_BATCH_CREATE_SPANS_FAILED",
1652
1502
  domain: error.ErrorDomain.STORAGE,
1653
1503
  category: error.ErrorCategory.USER
1654
1504
  },
@@ -1656,10 +1506,10 @@ var ObservabilityMongoDB = class extends storage.ObservabilityStorage {
1656
1506
  );
1657
1507
  }
1658
1508
  }
1659
- async batchUpdateAISpans(args) {
1509
+ async batchUpdateSpans(args) {
1660
1510
  try {
1661
1511
  return this.operations.batchUpdate({
1662
- tableName: storage.TABLE_AI_SPANS,
1512
+ tableName: storage.TABLE_SPANS,
1663
1513
  updates: args.records.map((record) => {
1664
1514
  const data = { ...record.updates };
1665
1515
  if (data.endedAt instanceof Date) {
@@ -1681,7 +1531,7 @@ var ObservabilityMongoDB = class extends storage.ObservabilityStorage {
1681
1531
  } catch (error$1) {
1682
1532
  throw new error.MastraError(
1683
1533
  {
1684
- id: "MONGODB_STORE_BATCH_UPDATE_AI_SPANS_FAILED",
1534
+ id: "MONGODB_STORE_BATCH_UPDATE_SPANS_FAILED",
1685
1535
  domain: error.ErrorDomain.STORAGE,
1686
1536
  category: error.ErrorCategory.USER
1687
1537
  },
@@ -1689,16 +1539,16 @@ var ObservabilityMongoDB = class extends storage.ObservabilityStorage {
1689
1539
  );
1690
1540
  }
1691
1541
  }
1692
- async batchDeleteAITraces(args) {
1542
+ async batchDeleteTraces(args) {
1693
1543
  try {
1694
- const collection = await this.operations.getCollection(storage.TABLE_AI_SPANS);
1544
+ const collection = await this.operations.getCollection(storage.TABLE_SPANS);
1695
1545
  await collection.deleteMany({
1696
1546
  traceId: { $in: args.traceIds }
1697
1547
  });
1698
1548
  } catch (error$1) {
1699
1549
  throw new error.MastraError(
1700
1550
  {
1701
- id: "MONGODB_STORE_BATCH_DELETE_AI_TRACES_FAILED",
1551
+ id: "MONGODB_STORE_BATCH_DELETE_TRACES_FAILED",
1702
1552
  domain: error.ErrorDomain.STORAGE,
1703
1553
  category: error.ErrorCategory.USER
1704
1554
  },
@@ -1707,7 +1557,7 @@ var ObservabilityMongoDB = class extends storage.ObservabilityStorage {
1707
1557
  }
1708
1558
  }
1709
1559
  /**
1710
- * Transform MongoDB document to AISpanRecord format
1560
+ * Transform MongoDB document to SpanRecord format
1711
1561
  */
1712
1562
  transformSpanFromMongo(doc) {
1713
1563
  const { _id, ...span } = doc;
@@ -1955,12 +1805,12 @@ function transformScoreRow(row) {
1955
1805
  console.warn("Failed to parse entity:", e);
1956
1806
  }
1957
1807
  }
1958
- let runtimeContextValue = null;
1959
- if (row.runtimeContext) {
1808
+ let requestContextValue = null;
1809
+ if (row.requestContext) {
1960
1810
  try {
1961
- runtimeContextValue = typeof row.runtimeContext === "string" ? storage.safelyParseJSON(row.runtimeContext) : row.runtimeContext;
1811
+ requestContextValue = typeof row.requestContext === "string" ? storage.safelyParseJSON(row.requestContext) : row.requestContext;
1962
1812
  } catch (e) {
1963
- console.warn("Failed to parse runtimeContext:", e);
1813
+ console.warn("Failed to parse requestContext:", e);
1964
1814
  }
1965
1815
  }
1966
1816
  let metadataValue = null;
@@ -1991,7 +1841,7 @@ function transformScoreRow(row) {
1991
1841
  input: inputValue,
1992
1842
  output: outputValue,
1993
1843
  additionalContext: row.additionalContext,
1994
- runtimeContext: runtimeContextValue,
1844
+ requestContext: requestContextValue,
1995
1845
  entity: entityValue,
1996
1846
  source: row.source,
1997
1847
  resourceId: row.resourceId,
@@ -2029,7 +1879,7 @@ var ScoresStorageMongoDB = class extends storage.ScoresStorage {
2029
1879
  async saveScore(score) {
2030
1880
  let validatedScore;
2031
1881
  try {
2032
- validatedScore = scores.saveScorePayloadSchema.parse(score);
1882
+ validatedScore = evals.saveScorePayloadSchema.parse(score);
2033
1883
  } catch (error$1) {
2034
1884
  throw new error.MastraError(
2035
1885
  {
@@ -2063,7 +1913,7 @@ var ScoresStorageMongoDB = class extends storage.ScoresStorage {
2063
1913
  input: typeof validatedScore.input === "string" ? storage.safelyParseJSON(validatedScore.input) : validatedScore.input,
2064
1914
  output: typeof validatedScore.output === "string" ? storage.safelyParseJSON(validatedScore.output) : validatedScore.output,
2065
1915
  additionalContext: validatedScore.additionalContext,
2066
- runtimeContext: typeof validatedScore.runtimeContext === "string" ? storage.safelyParseJSON(validatedScore.runtimeContext) : validatedScore.runtimeContext,
1916
+ requestContext: typeof validatedScore.requestContext === "string" ? storage.safelyParseJSON(validatedScore.requestContext) : validatedScore.requestContext,
2067
1917
  entity: typeof validatedScore.entity === "string" ? storage.safelyParseJSON(validatedScore.entity) : validatedScore.entity,
2068
1918
  source: validatedScore.source,
2069
1919
  resourceId: validatedScore.resourceId || "",
@@ -2092,7 +1942,7 @@ var ScoresStorageMongoDB = class extends storage.ScoresStorage {
2092
1942
  );
2093
1943
  }
2094
1944
  }
2095
- async getScoresByScorerId({
1945
+ async listScoresByScorerId({
2096
1946
  scorerId,
2097
1947
  pagination,
2098
1948
  entityId,
@@ -2100,6 +1950,9 @@ var ScoresStorageMongoDB = class extends storage.ScoresStorage {
2100
1950
  source
2101
1951
  }) {
2102
1952
  try {
1953
+ const { page, perPage: perPageInput } = pagination;
1954
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1955
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2103
1956
  const query = { scorerId };
2104
1957
  if (entityId) {
2105
1958
  query.entityId = entityId;
@@ -2112,28 +1965,31 @@ var ScoresStorageMongoDB = class extends storage.ScoresStorage {
2112
1965
  }
2113
1966
  const collection = await this.operations.getCollection(storage.TABLE_SCORERS);
2114
1967
  const total = await collection.countDocuments(query);
2115
- const currentOffset = pagination.page * pagination.perPage;
2116
1968
  if (total === 0) {
2117
1969
  return {
2118
1970
  scores: [],
2119
1971
  pagination: {
2120
1972
  total: 0,
2121
- page: pagination.page,
2122
- perPage: pagination.perPage,
1973
+ page,
1974
+ perPage: perPageInput,
2123
1975
  hasMore: false
2124
1976
  }
2125
1977
  };
2126
1978
  }
2127
- const documents = await collection.find(query).sort({ createdAt: "desc" }).skip(currentOffset).limit(pagination.perPage).toArray();
1979
+ const end = perPageInput === false ? total : start + perPage;
1980
+ let cursor = collection.find(query).sort({ createdAt: "desc" }).skip(start);
1981
+ if (perPageInput !== false) {
1982
+ cursor = cursor.limit(perPage);
1983
+ }
1984
+ const documents = await cursor.toArray();
2128
1985
  const scores = documents.map((row) => transformScoreRow(row));
2129
- const hasMore = currentOffset + scores.length < total;
2130
1986
  return {
2131
1987
  scores,
2132
1988
  pagination: {
2133
1989
  total,
2134
- page: pagination.page,
2135
- perPage: pagination.perPage,
2136
- hasMore
1990
+ page,
1991
+ perPage: perPageForResponse,
1992
+ hasMore: end < total
2137
1993
  }
2138
1994
  };
2139
1995
  } catch (error$1) {
@@ -2148,35 +2004,41 @@ var ScoresStorageMongoDB = class extends storage.ScoresStorage {
2148
2004
  );
2149
2005
  }
2150
2006
  }
2151
- async getScoresByRunId({
2007
+ async listScoresByRunId({
2152
2008
  runId,
2153
2009
  pagination
2154
2010
  }) {
2155
2011
  try {
2012
+ const { page, perPage: perPageInput } = pagination;
2013
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2014
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2156
2015
  const collection = await this.operations.getCollection(storage.TABLE_SCORERS);
2157
2016
  const total = await collection.countDocuments({ runId });
2158
- const currentOffset = pagination.page * pagination.perPage;
2159
2017
  if (total === 0) {
2160
2018
  return {
2161
2019
  scores: [],
2162
2020
  pagination: {
2163
2021
  total: 0,
2164
- page: pagination.page,
2165
- perPage: pagination.perPage,
2022
+ page,
2023
+ perPage: perPageInput,
2166
2024
  hasMore: false
2167
2025
  }
2168
2026
  };
2169
2027
  }
2170
- const documents = await collection.find({ runId }).sort({ createdAt: "desc" }).skip(currentOffset).limit(pagination.perPage).toArray();
2028
+ const end = perPageInput === false ? total : start + perPage;
2029
+ let cursor = collection.find({ runId }).sort({ createdAt: "desc" }).skip(start);
2030
+ if (perPageInput !== false) {
2031
+ cursor = cursor.limit(perPage);
2032
+ }
2033
+ const documents = await cursor.toArray();
2171
2034
  const scores = documents.map((row) => transformScoreRow(row));
2172
- const hasMore = currentOffset + scores.length < total;
2173
2035
  return {
2174
2036
  scores,
2175
2037
  pagination: {
2176
2038
  total,
2177
- page: pagination.page,
2178
- perPage: pagination.perPage,
2179
- hasMore
2039
+ page,
2040
+ perPage: perPageForResponse,
2041
+ hasMore: end < total
2180
2042
  }
2181
2043
  };
2182
2044
  } catch (error$1) {
@@ -2191,36 +2053,42 @@ var ScoresStorageMongoDB = class extends storage.ScoresStorage {
2191
2053
  );
2192
2054
  }
2193
2055
  }
2194
- async getScoresByEntityId({
2056
+ async listScoresByEntityId({
2195
2057
  entityId,
2196
2058
  entityType,
2197
2059
  pagination
2198
2060
  }) {
2199
2061
  try {
2062
+ const { page, perPage: perPageInput } = pagination;
2063
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2064
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2200
2065
  const collection = await this.operations.getCollection(storage.TABLE_SCORERS);
2201
2066
  const total = await collection.countDocuments({ entityId, entityType });
2202
- const currentOffset = pagination.page * pagination.perPage;
2203
2067
  if (total === 0) {
2204
2068
  return {
2205
2069
  scores: [],
2206
2070
  pagination: {
2207
2071
  total: 0,
2208
- page: pagination.page,
2209
- perPage: pagination.perPage,
2072
+ page,
2073
+ perPage: perPageInput,
2210
2074
  hasMore: false
2211
2075
  }
2212
2076
  };
2213
2077
  }
2214
- const documents = await collection.find({ entityId, entityType }).sort({ createdAt: "desc" }).skip(currentOffset).limit(pagination.perPage).toArray();
2078
+ const end = perPageInput === false ? total : start + perPage;
2079
+ let cursor = collection.find({ entityId, entityType }).sort({ createdAt: "desc" }).skip(start);
2080
+ if (perPageInput !== false) {
2081
+ cursor = cursor.limit(perPage);
2082
+ }
2083
+ const documents = await cursor.toArray();
2215
2084
  const scores = documents.map((row) => transformScoreRow(row));
2216
- const hasMore = currentOffset + scores.length < total;
2217
2085
  return {
2218
2086
  scores,
2219
2087
  pagination: {
2220
2088
  total,
2221
- page: pagination.page,
2222
- perPage: pagination.perPage,
2223
- hasMore
2089
+ page,
2090
+ perPage: perPageForResponse,
2091
+ hasMore: end < total
2224
2092
  }
2225
2093
  };
2226
2094
  } catch (error$1) {
@@ -2235,37 +2103,43 @@ var ScoresStorageMongoDB = class extends storage.ScoresStorage {
2235
2103
  );
2236
2104
  }
2237
2105
  }
2238
- async getScoresBySpan({
2106
+ async listScoresBySpan({
2239
2107
  traceId,
2240
2108
  spanId,
2241
2109
  pagination
2242
2110
  }) {
2243
2111
  try {
2112
+ const { page, perPage: perPageInput } = pagination;
2113
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2114
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2244
2115
  const query = { traceId, spanId };
2245
2116
  const collection = await this.operations.getCollection(storage.TABLE_SCORERS);
2246
2117
  const total = await collection.countDocuments(query);
2247
- const currentOffset = pagination.page * pagination.perPage;
2248
2118
  if (total === 0) {
2249
2119
  return {
2250
2120
  scores: [],
2251
2121
  pagination: {
2252
2122
  total: 0,
2253
- page: pagination.page,
2254
- perPage: pagination.perPage,
2123
+ page,
2124
+ perPage: perPageInput,
2255
2125
  hasMore: false
2256
2126
  }
2257
2127
  };
2258
2128
  }
2259
- const documents = await collection.find(query).sort({ createdAt: "desc" }).skip(currentOffset).limit(pagination.perPage).toArray();
2129
+ const end = perPageInput === false ? total : start + perPage;
2130
+ let cursor = collection.find(query).sort({ createdAt: "desc" }).skip(start);
2131
+ if (perPageInput !== false) {
2132
+ cursor = cursor.limit(perPage);
2133
+ }
2134
+ const documents = await cursor.toArray();
2260
2135
  const scores = documents.map((row) => transformScoreRow(row));
2261
- const hasMore = currentOffset + scores.length < total;
2262
2136
  return {
2263
2137
  scores,
2264
2138
  pagination: {
2265
2139
  total,
2266
- page: pagination.page,
2267
- perPage: pagination.perPage,
2268
- hasMore
2140
+ page,
2141
+ perPage: perPageForResponse,
2142
+ hasMore: end < total
2269
2143
  }
2270
2144
  };
2271
2145
  } catch (error$1) {
@@ -2281,121 +2155,6 @@ var ScoresStorageMongoDB = class extends storage.ScoresStorage {
2281
2155
  }
2282
2156
  }
2283
2157
  };
2284
- var TracesStorageMongoDB = class extends storage.TracesStorage {
2285
- operations;
2286
- constructor({ operations }) {
2287
- super();
2288
- this.operations = operations;
2289
- }
2290
- async getTraces(args) {
2291
- if (args.fromDate || args.toDate) {
2292
- args.dateRange = {
2293
- start: args.fromDate,
2294
- end: args.toDate
2295
- };
2296
- }
2297
- try {
2298
- const result = await this.getTracesPaginated(args);
2299
- return result.traces;
2300
- } catch (error$1) {
2301
- throw new error.MastraError(
2302
- {
2303
- id: "STORAGE_MONGODB_STORE_GET_TRACES_FAILED",
2304
- domain: error.ErrorDomain.STORAGE,
2305
- category: error.ErrorCategory.THIRD_PARTY
2306
- },
2307
- error$1
2308
- );
2309
- }
2310
- }
2311
- async getTracesPaginated(args) {
2312
- const { name, scope, page = 0, perPage = 100, attributes, filters, dateRange } = args;
2313
- const fromDate = dateRange?.start;
2314
- const toDate = dateRange?.end;
2315
- const currentOffset = page * perPage;
2316
- const query = {};
2317
- if (name) {
2318
- query["name"] = new RegExp(name);
2319
- }
2320
- if (scope) {
2321
- query["scope"] = scope;
2322
- }
2323
- if (attributes) {
2324
- query["$and"] = Object.entries(attributes).map(([key, value]) => ({
2325
- [`attributes.${key}`]: value
2326
- }));
2327
- }
2328
- if (filters) {
2329
- Object.entries(filters).forEach(([key, value]) => {
2330
- query[key] = value;
2331
- });
2332
- }
2333
- if (fromDate || toDate) {
2334
- query["createdAt"] = {};
2335
- if (fromDate) {
2336
- query["createdAt"]["$gte"] = fromDate;
2337
- }
2338
- if (toDate) {
2339
- query["createdAt"]["$lte"] = toDate;
2340
- }
2341
- }
2342
- try {
2343
- const collection = await this.operations.getCollection(storage.TABLE_TRACES);
2344
- const total = await collection.countDocuments(query);
2345
- if (total === 0) {
2346
- return {
2347
- traces: [],
2348
- total: 0,
2349
- page,
2350
- perPage,
2351
- hasMore: false
2352
- };
2353
- }
2354
- const result = await collection.find(query, {
2355
- sort: { startTime: -1 }
2356
- }).limit(perPage).skip(currentOffset).toArray();
2357
- const traces = result.map((row) => ({
2358
- id: row.id,
2359
- parentSpanId: row.parentSpanId,
2360
- traceId: row.traceId,
2361
- name: row.name,
2362
- scope: row.scope,
2363
- kind: row.kind,
2364
- status: storage.safelyParseJSON(row.status),
2365
- events: storage.safelyParseJSON(row.events),
2366
- links: storage.safelyParseJSON(row.links),
2367
- attributes: storage.safelyParseJSON(row.attributes),
2368
- startTime: row.startTime,
2369
- endTime: row.endTime,
2370
- other: storage.safelyParseJSON(row.other),
2371
- createdAt: row.createdAt
2372
- }));
2373
- return {
2374
- traces,
2375
- total,
2376
- page,
2377
- perPage,
2378
- hasMore: currentOffset + traces.length < total
2379
- };
2380
- } catch (error$1) {
2381
- throw new error.MastraError(
2382
- {
2383
- id: "STORAGE_MONGODB_STORE_GET_TRACES_PAGINATED_FAILED",
2384
- domain: error.ErrorDomain.STORAGE,
2385
- category: error.ErrorCategory.THIRD_PARTY
2386
- },
2387
- error$1
2388
- );
2389
- }
2390
- }
2391
- async batchTraceInsert({ records }) {
2392
- this.logger.debug("Batch inserting traces", { count: records.length });
2393
- await this.operations.batchInsert({
2394
- tableName: storage.TABLE_TRACES,
2395
- records
2396
- });
2397
- }
2398
- };
2399
2158
  var WorkflowsStorageMongoDB = class extends storage.WorkflowsStorage {
2400
2159
  operations;
2401
2160
  constructor({ operations }) {
@@ -2407,7 +2166,7 @@ var WorkflowsStorageMongoDB = class extends storage.WorkflowsStorage {
2407
2166
  // runId,
2408
2167
  // stepId,
2409
2168
  // result,
2410
- // runtimeContext,
2169
+ // requestContext,
2411
2170
  }) {
2412
2171
  throw new Error("Method not implemented.");
2413
2172
  }
@@ -2480,13 +2239,16 @@ var WorkflowsStorageMongoDB = class extends storage.WorkflowsStorage {
2480
2239
  );
2481
2240
  }
2482
2241
  }
2483
- async getWorkflowRuns(args) {
2242
+ async listWorkflowRuns(args) {
2484
2243
  const options = args || {};
2485
2244
  try {
2486
2245
  const query = {};
2487
2246
  if (options.workflowName) {
2488
2247
  query["workflow_name"] = options.workflowName;
2489
2248
  }
2249
+ if (options.status) {
2250
+ query["snapshot.status"] = options.status;
2251
+ }
2490
2252
  if (options.fromDate) {
2491
2253
  query["createdAt"] = { $gte: options.fromDate };
2492
2254
  }
@@ -2501,24 +2263,39 @@ var WorkflowsStorageMongoDB = class extends storage.WorkflowsStorage {
2501
2263
  query["resourceId"] = options.resourceId;
2502
2264
  }
2503
2265
  const collection = await this.operations.getCollection(storage.TABLE_WORKFLOW_SNAPSHOT);
2504
- const total = await collection.countDocuments(query);
2266
+ let total = 0;
2505
2267
  let cursor = collection.find(query).sort({ createdAt: -1 });
2506
- if (options.offset) {
2507
- cursor = cursor.skip(options.offset);
2508
- }
2509
- if (options.limit) {
2510
- cursor = cursor.limit(options.limit);
2268
+ if (options.page !== void 0 && typeof options.perPage === "number") {
2269
+ if (options.page < 0) {
2270
+ throw new error.MastraError(
2271
+ {
2272
+ id: "STORAGE_MONGODB_INVALID_PAGE",
2273
+ domain: error.ErrorDomain.STORAGE,
2274
+ category: error.ErrorCategory.USER,
2275
+ details: { page: options.page }
2276
+ },
2277
+ new Error("page must be >= 0")
2278
+ );
2279
+ }
2280
+ total = await collection.countDocuments(query);
2281
+ const normalizedPerPage = storage.normalizePerPage(options.perPage, Number.MAX_SAFE_INTEGER);
2282
+ if (normalizedPerPage === 0) {
2283
+ return { runs: [], total };
2284
+ }
2285
+ const offset = options.page * normalizedPerPage;
2286
+ cursor = cursor.skip(offset);
2287
+ cursor = cursor.limit(Math.min(normalizedPerPage, 2147483647));
2511
2288
  }
2512
2289
  const results = await cursor.toArray();
2513
2290
  const runs = results.map((row) => this.parseWorkflowRun(row));
2514
2291
  return {
2515
2292
  runs,
2516
- total
2293
+ total: total || runs.length
2517
2294
  };
2518
2295
  } catch (error$1) {
2519
2296
  throw new error.MastraError(
2520
2297
  {
2521
- id: "STORAGE_MONGODB_STORE_GET_WORKFLOW_RUNS_FAILED",
2298
+ id: "STORAGE_MONGODB_STORE_LIST_WORKFLOW_RUNS_FAILED",
2522
2299
  domain: error.ErrorDomain.STORAGE,
2523
2300
  category: error.ErrorCategory.THIRD_PARTY,
2524
2301
  details: { workflowName: options.workflowName || "unknown" }
@@ -2593,6 +2370,7 @@ var loadConnector = (config) => {
2593
2370
  }
2594
2371
  try {
2595
2372
  return MongoDBConnector.fromDatabaseConfig({
2373
+ id: config.id,
2596
2374
  options: config.options,
2597
2375
  url: config.url,
2598
2376
  dbName: config.dbName
@@ -2619,11 +2397,11 @@ var MongoDBStore = class extends storage.MastraStorage {
2619
2397
  hasColumn: false,
2620
2398
  createTable: false,
2621
2399
  deleteMessages: false,
2622
- getScoresBySpan: true
2400
+ listScoresBySpan: true
2623
2401
  };
2624
2402
  }
2625
2403
  constructor(config) {
2626
- super({ name: "MongoDBStore" });
2404
+ super({ id: config.id, name: "MongoDBStore" });
2627
2405
  this.stores = {};
2628
2406
  this.#connector = loadConnector(config);
2629
2407
  const operations = new StoreOperationsMongoDB({
@@ -2632,12 +2410,6 @@ var MongoDBStore = class extends storage.MastraStorage {
2632
2410
  const memory = new MemoryStorageMongoDB({
2633
2411
  operations
2634
2412
  });
2635
- const traces = new TracesStorageMongoDB({
2636
- operations
2637
- });
2638
- const legacyEvals = new LegacyEvalsMongoDB({
2639
- operations
2640
- });
2641
2413
  const scores = new ScoresStorageMongoDB({
2642
2414
  operations
2643
2415
  });
@@ -2650,8 +2422,6 @@ var MongoDBStore = class extends storage.MastraStorage {
2650
2422
  this.stores = {
2651
2423
  operations,
2652
2424
  memory,
2653
- traces,
2654
- legacyEvals,
2655
2425
  scores,
2656
2426
  workflows,
2657
2427
  observability
@@ -2684,12 +2454,6 @@ var MongoDBStore = class extends storage.MastraStorage {
2684
2454
  async getThreadById({ threadId }) {
2685
2455
  return this.stores.memory.getThreadById({ threadId });
2686
2456
  }
2687
- async getThreadsByResourceId({ resourceId }) {
2688
- return this.stores.memory.getThreadsByResourceId({ resourceId });
2689
- }
2690
- async getThreadsByResourceIdPaginated(_args) {
2691
- return this.stores.memory.getThreadsByResourceIdPaginated(_args);
2692
- }
2693
2457
  async saveThread({ thread }) {
2694
2458
  return this.stores.memory.saveThread({ thread });
2695
2459
  }
@@ -2703,21 +2467,8 @@ var MongoDBStore = class extends storage.MastraStorage {
2703
2467
  async deleteThread({ threadId }) {
2704
2468
  return this.stores.memory.deleteThread({ threadId });
2705
2469
  }
2706
- async getMessages({
2707
- threadId,
2708
- selectBy,
2709
- format
2710
- }) {
2711
- return this.stores.memory.getMessages({ threadId, selectBy, format });
2712
- }
2713
- async getMessagesPaginated(_args) {
2714
- return this.stores.memory.getMessagesPaginated(_args);
2715
- }
2716
- async getMessagesById({
2717
- messageIds,
2718
- format
2719
- }) {
2720
- return this.stores.memory.getMessagesById({ messageIds, format });
2470
+ async listMessagesById({ messageIds }) {
2471
+ return this.stores.memory.listMessagesById({ messageIds });
2721
2472
  }
2722
2473
  async saveMessages(args) {
2723
2474
  return this.stores.memory.saveMessages(args);
@@ -2725,32 +2476,17 @@ var MongoDBStore = class extends storage.MastraStorage {
2725
2476
  async updateMessages(_args) {
2726
2477
  return this.stores.memory.updateMessages(_args);
2727
2478
  }
2728
- async getTraces(args) {
2729
- return this.stores.traces.getTraces(args);
2730
- }
2731
- async getTracesPaginated(args) {
2732
- return this.stores.traces.getTracesPaginated(args);
2733
- }
2734
- async batchTraceInsert({ records }) {
2735
- return this.stores.traces.batchTraceInsert({ records });
2736
- }
2737
- async getWorkflowRuns(args) {
2738
- return this.stores.workflows.getWorkflowRuns(args);
2739
- }
2740
- async getEvals(options = {}) {
2741
- return this.stores.legacyEvals.getEvals(options);
2742
- }
2743
- async getEvalsByAgentName(agentName, type) {
2744
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2479
+ async listWorkflowRuns(args) {
2480
+ return this.stores.workflows.listWorkflowRuns(args);
2745
2481
  }
2746
2482
  async updateWorkflowResults({
2747
2483
  workflowName,
2748
2484
  runId,
2749
2485
  stepId,
2750
2486
  result,
2751
- runtimeContext
2487
+ requestContext
2752
2488
  }) {
2753
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2489
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
2754
2490
  }
2755
2491
  async updateWorkflowState({
2756
2492
  workflowName,
@@ -2802,34 +2538,34 @@ var MongoDBStore = class extends storage.MastraStorage {
2802
2538
  async saveScore(score) {
2803
2539
  return this.stores.scores.saveScore(score);
2804
2540
  }
2805
- async getScoresByRunId({
2541
+ async listScoresByRunId({
2806
2542
  runId,
2807
2543
  pagination
2808
2544
  }) {
2809
- return this.stores.scores.getScoresByRunId({ runId, pagination });
2545
+ return this.stores.scores.listScoresByRunId({ runId, pagination });
2810
2546
  }
2811
- async getScoresByEntityId({
2547
+ async listScoresByEntityId({
2812
2548
  entityId,
2813
2549
  entityType,
2814
2550
  pagination
2815
2551
  }) {
2816
- return this.stores.scores.getScoresByEntityId({ entityId, entityType, pagination });
2552
+ return this.stores.scores.listScoresByEntityId({ entityId, entityType, pagination });
2817
2553
  }
2818
- async getScoresByScorerId({
2554
+ async listScoresByScorerId({
2819
2555
  scorerId,
2820
2556
  pagination,
2821
2557
  entityId,
2822
2558
  entityType,
2823
2559
  source
2824
2560
  }) {
2825
- return this.stores.scores.getScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2561
+ return this.stores.scores.listScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2826
2562
  }
2827
- async getScoresBySpan({
2563
+ async listScoresBySpan({
2828
2564
  traceId,
2829
2565
  spanId,
2830
2566
  pagination
2831
2567
  }) {
2832
- return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
2568
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
2833
2569
  }
2834
2570
  /**
2835
2571
  * RESOURCES
@@ -2852,9 +2588,9 @@ var MongoDBStore = class extends storage.MastraStorage {
2852
2588
  });
2853
2589
  }
2854
2590
  /**
2855
- * AI Tracing/Observability
2591
+ * Tracing/Observability
2856
2592
  */
2857
- async createAISpan(span) {
2593
+ async createSpan(span) {
2858
2594
  if (!this.stores.observability) {
2859
2595
  throw new error.MastraError({
2860
2596
  id: "MONGODB_STORE_OBSERVABILITY_NOT_INITIALIZED",
@@ -2863,9 +2599,9 @@ var MongoDBStore = class extends storage.MastraStorage {
2863
2599
  text: "Observability storage is not initialized"
2864
2600
  });
2865
2601
  }
2866
- return this.stores.observability.createAISpan(span);
2602
+ return this.stores.observability.createSpan(span);
2867
2603
  }
2868
- async updateAISpan({
2604
+ async updateSpan({
2869
2605
  spanId,
2870
2606
  traceId,
2871
2607
  updates
@@ -2878,9 +2614,9 @@ var MongoDBStore = class extends storage.MastraStorage {
2878
2614
  text: "Observability storage is not initialized"
2879
2615
  });
2880
2616
  }
2881
- return this.stores.observability.updateAISpan({ spanId, traceId, updates });
2617
+ return this.stores.observability.updateSpan({ spanId, traceId, updates });
2882
2618
  }
2883
- async getAITrace(traceId) {
2619
+ async getTrace(traceId) {
2884
2620
  if (!this.stores.observability) {
2885
2621
  throw new error.MastraError({
2886
2622
  id: "MONGODB_STORE_OBSERVABILITY_NOT_INITIALIZED",
@@ -2889,9 +2625,9 @@ var MongoDBStore = class extends storage.MastraStorage {
2889
2625
  text: "Observability storage is not initialized"
2890
2626
  });
2891
2627
  }
2892
- return this.stores.observability.getAITrace(traceId);
2628
+ return this.stores.observability.getTrace(traceId);
2893
2629
  }
2894
- async getAITracesPaginated(args) {
2630
+ async getTracesPaginated(args) {
2895
2631
  if (!this.stores.observability) {
2896
2632
  throw new error.MastraError({
2897
2633
  id: "MONGODB_STORE_OBSERVABILITY_NOT_INITIALIZED",
@@ -2900,9 +2636,9 @@ var MongoDBStore = class extends storage.MastraStorage {
2900
2636
  text: "Observability storage is not initialized"
2901
2637
  });
2902
2638
  }
2903
- return this.stores.observability.getAITracesPaginated(args);
2639
+ return this.stores.observability.getTracesPaginated(args);
2904
2640
  }
2905
- async batchCreateAISpans(args) {
2641
+ async batchCreateSpans(args) {
2906
2642
  if (!this.stores.observability) {
2907
2643
  throw new error.MastraError({
2908
2644
  id: "MONGODB_STORE_OBSERVABILITY_NOT_INITIALIZED",
@@ -2911,9 +2647,9 @@ var MongoDBStore = class extends storage.MastraStorage {
2911
2647
  text: "Observability storage is not initialized"
2912
2648
  });
2913
2649
  }
2914
- return this.stores.observability.batchCreateAISpans(args);
2650
+ return this.stores.observability.batchCreateSpans(args);
2915
2651
  }
2916
- async batchUpdateAISpans(args) {
2652
+ async batchUpdateSpans(args) {
2917
2653
  if (!this.stores.observability) {
2918
2654
  throw new error.MastraError({
2919
2655
  id: "MONGODB_STORE_OBSERVABILITY_NOT_INITIALIZED",
@@ -2922,9 +2658,9 @@ var MongoDBStore = class extends storage.MastraStorage {
2922
2658
  text: "Observability storage is not initialized"
2923
2659
  });
2924
2660
  }
2925
- return this.stores.observability.batchUpdateAISpans(args);
2661
+ return this.stores.observability.batchUpdateSpans(args);
2926
2662
  }
2927
- async batchDeleteAITraces(args) {
2663
+ async batchDeleteTraces(args) {
2928
2664
  if (!this.stores.observability) {
2929
2665
  throw new error.MastraError({
2930
2666
  id: "MONGODB_STORE_OBSERVABILITY_NOT_INITIALIZED",
@@ -2933,7 +2669,7 @@ var MongoDBStore = class extends storage.MastraStorage {
2933
2669
  text: "Observability storage is not initialized"
2934
2670
  });
2935
2671
  }
2936
- return this.stores.observability.batchDeleteAITraces(args);
2672
+ return this.stores.observability.batchDeleteTraces(args);
2937
2673
  }
2938
2674
  };
2939
2675