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