@mastra/dynamodb 0.0.0-scorers-api-v2-20250801171841 → 0.0.0-scorers-logs-20251208093427

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +1605 -0
  2. package/README.md +0 -4
  3. package/dist/entities/index.d.ts +20 -1
  4. package/dist/entities/index.d.ts.map +1 -1
  5. package/dist/entities/score.d.ts +20 -1
  6. package/dist/entities/score.d.ts.map +1 -1
  7. package/dist/index.cjs +474 -728
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.ts +1 -1
  10. package/dist/index.js +475 -729
  11. package/dist/index.js.map +1 -1
  12. package/dist/storage/domains/memory/index.d.ts +15 -31
  13. package/dist/storage/domains/memory/index.d.ts.map +1 -1
  14. package/dist/storage/domains/operations/index.d.ts.map +1 -1
  15. package/dist/storage/domains/score/index.d.ts +22 -5
  16. package/dist/storage/domains/score/index.d.ts.map +1 -1
  17. package/dist/storage/domains/workflows/index.d.ts +23 -11
  18. package/dist/storage/domains/workflows/index.d.ts.map +1 -1
  19. package/dist/storage/index.d.ts +73 -69
  20. package/dist/storage/index.d.ts.map +1 -1
  21. package/package.json +29 -16
  22. package/dist/storage/domains/legacy-evals/index.d.ts +0 -19
  23. package/dist/storage/domains/legacy-evals/index.d.ts.map +0 -1
  24. package/dist/storage/domains/traces/index.d.ts +0 -28
  25. package/dist/storage/domains/traces/index.d.ts.map +0 -1
  26. package/src/entities/eval.ts +0 -102
  27. package/src/entities/index.ts +0 -27
  28. package/src/entities/message.ts +0 -143
  29. package/src/entities/resource.ts +0 -57
  30. package/src/entities/score.ts +0 -317
  31. package/src/entities/thread.ts +0 -66
  32. package/src/entities/trace.ts +0 -129
  33. package/src/entities/utils.ts +0 -51
  34. package/src/entities/workflow-snapshot.ts +0 -56
  35. package/src/index.ts +0 -1
  36. package/src/storage/docker-compose.yml +0 -16
  37. package/src/storage/domains/legacy-evals/index.ts +0 -243
  38. package/src/storage/domains/memory/index.ts +0 -894
  39. package/src/storage/domains/operations/index.ts +0 -433
  40. package/src/storage/domains/score/index.ts +0 -288
  41. package/src/storage/domains/traces/index.ts +0 -286
  42. package/src/storage/domains/workflows/index.ts +0 -297
  43. package/src/storage/index.test.ts +0 -1420
  44. package/src/storage/index.ts +0 -483
package/dist/index.cjs CHANGED
@@ -6,6 +6,7 @@ var error = require('@mastra/core/error');
6
6
  var storage = require('@mastra/core/storage');
7
7
  var electrodb = require('electrodb');
8
8
  var agent = require('@mastra/core/agent');
9
+ var evals = require('@mastra/core/evals');
9
10
 
10
11
  // src/storage/index.ts
11
12
 
@@ -372,6 +373,10 @@ var scoreEntity = new electrodb.Entity({
372
373
  type: "string",
373
374
  required: false
374
375
  },
376
+ spanId: {
377
+ type: "string",
378
+ required: false
379
+ },
375
380
  runId: {
376
381
  type: "string",
377
382
  required: true
@@ -420,6 +425,10 @@ var scoreEntity = new electrodb.Entity({
420
425
  return value;
421
426
  }
422
427
  },
428
+ preprocessPrompt: {
429
+ type: "string",
430
+ required: false
431
+ },
423
432
  preprocessStepResult: {
424
433
  type: "string",
425
434
  required: false,
@@ -559,7 +568,7 @@ var scoreEntity = new electrodb.Entity({
559
568
  return value;
560
569
  }
561
570
  },
562
- runtimeContext: {
571
+ requestContext: {
563
572
  type: "string",
564
573
  required: false,
565
574
  set: (value) => {
@@ -658,6 +667,11 @@ var scoreEntity = new electrodb.Entity({
658
667
  index: "gsi6",
659
668
  pk: { field: "gsi6pk", composite: ["entity", "threadId"] },
660
669
  sk: { field: "gsi6sk", composite: ["createdAt"] }
670
+ },
671
+ bySpan: {
672
+ index: "gsi7",
673
+ pk: { field: "gsi7pk", composite: ["entity", "traceId", "spanId"] },
674
+ sk: { field: "gsi7sk", composite: ["createdAt"] }
661
675
  }
662
676
  }
663
677
  });
@@ -925,187 +939,6 @@ function getElectroDbService(client, tableName) {
925
939
  }
926
940
  );
927
941
  }
928
- var LegacyEvalsDynamoDB = class extends storage.LegacyEvalsStorage {
929
- service;
930
- tableName;
931
- constructor({ service, tableName }) {
932
- super();
933
- this.service = service;
934
- this.tableName = tableName;
935
- }
936
- // Eval operations
937
- async getEvalsByAgentName(agentName, type) {
938
- this.logger.debug("Getting evals for agent", { agentName, type });
939
- try {
940
- const query = this.service.entities.eval.query.byAgent({ entity: "eval", agent_name: agentName });
941
- const results = await query.go({ order: "desc", limit: 100 });
942
- if (!results.data.length) {
943
- return [];
944
- }
945
- let filteredData = results.data;
946
- if (type) {
947
- filteredData = filteredData.filter((evalRecord) => {
948
- try {
949
- const testInfo = evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0;
950
- if (type === "test" && !testInfo) {
951
- return false;
952
- }
953
- if (type === "live" && testInfo) {
954
- return false;
955
- }
956
- } catch (e) {
957
- this.logger.warn("Failed to parse test_info during filtering", { record: evalRecord, error: e });
958
- }
959
- return true;
960
- });
961
- }
962
- return filteredData.map((evalRecord) => {
963
- try {
964
- return {
965
- input: evalRecord.input,
966
- output: evalRecord.output,
967
- // Safely parse result and test_info
968
- result: evalRecord.result && typeof evalRecord.result === "string" ? JSON.parse(evalRecord.result) : void 0,
969
- agentName: evalRecord.agent_name,
970
- createdAt: evalRecord.created_at,
971
- // Keep as string from DDB?
972
- metricName: evalRecord.metric_name,
973
- instructions: evalRecord.instructions,
974
- runId: evalRecord.run_id,
975
- globalRunId: evalRecord.global_run_id,
976
- testInfo: evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0
977
- };
978
- } catch (parseError) {
979
- this.logger.error("Failed to parse eval record", { record: evalRecord, error: parseError });
980
- return {
981
- agentName: evalRecord.agent_name,
982
- createdAt: evalRecord.created_at,
983
- runId: evalRecord.run_id,
984
- globalRunId: evalRecord.global_run_id
985
- };
986
- }
987
- });
988
- } catch (error$1) {
989
- throw new error.MastraError(
990
- {
991
- id: "STORAGE_DYNAMODB_STORE_GET_EVALS_BY_AGENT_NAME_FAILED",
992
- domain: error.ErrorDomain.STORAGE,
993
- category: error.ErrorCategory.THIRD_PARTY,
994
- details: { agentName }
995
- },
996
- error$1
997
- );
998
- }
999
- }
1000
- async getEvals(options = {}) {
1001
- const { agentName, type, page = 0, perPage = 100, dateRange } = options;
1002
- this.logger.debug("Getting evals with pagination", { agentName, type, page, perPage, dateRange });
1003
- try {
1004
- let query;
1005
- if (agentName) {
1006
- query = this.service.entities.eval.query.byAgent({ entity: "eval", agent_name: agentName });
1007
- } else {
1008
- query = this.service.entities.eval.query.byEntity({ entity: "eval" });
1009
- }
1010
- const results = await query.go({
1011
- order: "desc",
1012
- pages: "all"
1013
- // Get all pages to apply filtering and pagination
1014
- });
1015
- if (!results.data.length) {
1016
- return {
1017
- evals: [],
1018
- total: 0,
1019
- page,
1020
- perPage,
1021
- hasMore: false
1022
- };
1023
- }
1024
- let filteredData = results.data;
1025
- if (type) {
1026
- filteredData = filteredData.filter((evalRecord) => {
1027
- try {
1028
- const testInfo = evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0;
1029
- if (type === "test" && !testInfo) {
1030
- return false;
1031
- }
1032
- if (type === "live" && testInfo) {
1033
- return false;
1034
- }
1035
- } catch (e) {
1036
- this.logger.warn("Failed to parse test_info during filtering", { record: evalRecord, error: e });
1037
- }
1038
- return true;
1039
- });
1040
- }
1041
- if (dateRange) {
1042
- const fromDate = dateRange.start;
1043
- const toDate = dateRange.end;
1044
- filteredData = filteredData.filter((evalRecord) => {
1045
- const recordDate = new Date(evalRecord.created_at);
1046
- if (fromDate && recordDate < fromDate) {
1047
- return false;
1048
- }
1049
- if (toDate && recordDate > toDate) {
1050
- return false;
1051
- }
1052
- return true;
1053
- });
1054
- }
1055
- const total = filteredData.length;
1056
- const start = page * perPage;
1057
- const end = start + perPage;
1058
- const paginatedData = filteredData.slice(start, end);
1059
- const evals = paginatedData.map((evalRecord) => {
1060
- try {
1061
- return {
1062
- input: evalRecord.input,
1063
- output: evalRecord.output,
1064
- result: evalRecord.result && typeof evalRecord.result === "string" ? JSON.parse(evalRecord.result) : void 0,
1065
- agentName: evalRecord.agent_name,
1066
- createdAt: evalRecord.created_at,
1067
- metricName: evalRecord.metric_name,
1068
- instructions: evalRecord.instructions,
1069
- runId: evalRecord.run_id,
1070
- globalRunId: evalRecord.global_run_id,
1071
- testInfo: evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0
1072
- };
1073
- } catch (parseError) {
1074
- this.logger.error("Failed to parse eval record", { record: evalRecord, error: parseError });
1075
- return {
1076
- agentName: evalRecord.agent_name,
1077
- createdAt: evalRecord.created_at,
1078
- runId: evalRecord.run_id,
1079
- globalRunId: evalRecord.global_run_id
1080
- };
1081
- }
1082
- });
1083
- const hasMore = end < total;
1084
- return {
1085
- evals,
1086
- total,
1087
- page,
1088
- perPage,
1089
- hasMore
1090
- };
1091
- } catch (error$1) {
1092
- throw new error.MastraError(
1093
- {
1094
- id: "STORAGE_DYNAMODB_STORE_GET_EVALS_FAILED",
1095
- domain: error.ErrorDomain.STORAGE,
1096
- category: error.ErrorCategory.THIRD_PARTY,
1097
- details: {
1098
- agentName: agentName || "all",
1099
- type: type || "all",
1100
- page,
1101
- perPage
1102
- }
1103
- },
1104
- error$1
1105
- );
1106
- }
1107
- }
1108
- };
1109
942
  var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1110
943
  service;
1111
944
  constructor({ service }) {
@@ -1123,6 +956,20 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1123
956
  // transformed by the ElectroDB entity getters.
1124
957
  };
1125
958
  }
959
+ // Helper function to transform and sort threads
960
+ transformAndSortThreads(rawThreads, field, direction) {
961
+ return rawThreads.map((data) => ({
962
+ ...data,
963
+ // Convert date strings back to Date objects for consistency
964
+ createdAt: typeof data.createdAt === "string" ? new Date(data.createdAt) : data.createdAt,
965
+ updatedAt: typeof data.updatedAt === "string" ? new Date(data.updatedAt) : data.updatedAt
966
+ })).sort((a, b) => {
967
+ const fieldA = field === "createdAt" ? a.createdAt : a.updatedAt;
968
+ const fieldB = field === "createdAt" ? b.createdAt : b.updatedAt;
969
+ const comparison = fieldA.getTime() - fieldB.getTime();
970
+ return direction === "DESC" ? -comparison : comparison;
971
+ });
972
+ }
1126
973
  async getThreadById({ threadId }) {
1127
974
  this.logger.debug("Getting thread by ID", { threadId });
1128
975
  try {
@@ -1142,7 +989,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1142
989
  } catch (error$1) {
1143
990
  throw new error.MastraError(
1144
991
  {
1145
- id: "STORAGE_DYNAMODB_STORE_GET_THREAD_BY_ID_FAILED",
992
+ id: storage.createStorageErrorId("DYNAMODB", "GET_THREAD_BY_ID", "FAILED"),
1146
993
  domain: error.ErrorDomain.STORAGE,
1147
994
  category: error.ErrorCategory.THIRD_PARTY,
1148
995
  details: { threadId }
@@ -1151,33 +998,6 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1151
998
  );
1152
999
  }
1153
1000
  }
1154
- async getThreadsByResourceId({ resourceId }) {
1155
- this.logger.debug("Getting threads by resource ID", { resourceId });
1156
- try {
1157
- const result = await this.service.entities.thread.query.byResource({ entity: "thread", resourceId }).go();
1158
- if (!result.data.length) {
1159
- return [];
1160
- }
1161
- return result.data.map((data) => ({
1162
- ...data,
1163
- // Convert date strings back to Date objects for consistency
1164
- createdAt: typeof data.createdAt === "string" ? new Date(data.createdAt) : data.createdAt,
1165
- updatedAt: typeof data.updatedAt === "string" ? new Date(data.updatedAt) : data.updatedAt
1166
- // metadata: data.metadata ? JSON.parse(data.metadata) : undefined, // REMOVED by AI
1167
- // metadata is already transformed by the entity's getter
1168
- }));
1169
- } catch (error$1) {
1170
- throw new error.MastraError(
1171
- {
1172
- id: "STORAGE_DYNAMODB_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
1173
- domain: error.ErrorDomain.STORAGE,
1174
- category: error.ErrorCategory.THIRD_PARTY,
1175
- details: { resourceId }
1176
- },
1177
- error$1
1178
- );
1179
- }
1180
- }
1181
1001
  async saveThread({ thread }) {
1182
1002
  this.logger.debug("Saving thread", { threadId: thread.id });
1183
1003
  const now = /* @__PURE__ */ new Date();
@@ -1187,7 +1007,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1187
1007
  resourceId: thread.resourceId,
1188
1008
  title: thread.title || `Thread ${thread.id}`,
1189
1009
  createdAt: thread.createdAt?.toISOString() || now.toISOString(),
1190
- updatedAt: now.toISOString(),
1010
+ updatedAt: thread.updatedAt?.toISOString() || now.toISOString(),
1191
1011
  metadata: thread.metadata ? JSON.stringify(thread.metadata) : void 0
1192
1012
  };
1193
1013
  try {
@@ -1197,13 +1017,13 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1197
1017
  resourceId: thread.resourceId,
1198
1018
  title: threadData.title,
1199
1019
  createdAt: thread.createdAt || now,
1200
- updatedAt: now,
1020
+ updatedAt: thread.updatedAt || now,
1201
1021
  metadata: thread.metadata
1202
1022
  };
1203
1023
  } catch (error$1) {
1204
1024
  throw new error.MastraError(
1205
1025
  {
1206
- id: "STORAGE_DYNAMODB_STORE_SAVE_THREAD_FAILED",
1026
+ id: storage.createStorageErrorId("DYNAMODB", "SAVE_THREAD", "FAILED"),
1207
1027
  domain: error.ErrorDomain.STORAGE,
1208
1028
  category: error.ErrorCategory.THIRD_PARTY,
1209
1029
  details: { threadId: thread.id }
@@ -1245,7 +1065,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1245
1065
  } catch (error$1) {
1246
1066
  throw new error.MastraError(
1247
1067
  {
1248
- id: "STORAGE_DYNAMODB_STORE_UPDATE_THREAD_FAILED",
1068
+ id: storage.createStorageErrorId("DYNAMODB", "UPDATE_THREAD", "FAILED"),
1249
1069
  domain: error.ErrorDomain.STORAGE,
1250
1070
  category: error.ErrorCategory.THIRD_PARTY,
1251
1071
  details: { threadId: id }
@@ -1257,7 +1077,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1257
1077
  async deleteThread({ threadId }) {
1258
1078
  this.logger.debug("Deleting thread", { threadId });
1259
1079
  try {
1260
- const messages = await this.getMessages({ threadId });
1080
+ const { messages } = await this.listMessages({ threadId, perPage: false });
1261
1081
  if (messages.length > 0) {
1262
1082
  const batchSize = 25;
1263
1083
  for (let i = 0; i < messages.length; i += batchSize) {
@@ -1277,7 +1097,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1277
1097
  } catch (error$1) {
1278
1098
  throw new error.MastraError(
1279
1099
  {
1280
- id: "STORAGE_DYNAMODB_STORE_DELETE_THREAD_FAILED",
1100
+ id: storage.createStorageErrorId("DYNAMODB", "DELETE_THREAD", "FAILED"),
1281
1101
  domain: error.ErrorDomain.STORAGE,
1282
1102
  category: error.ErrorCategory.THIRD_PARTY,
1283
1103
  details: { threadId }
@@ -1286,73 +1106,176 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1286
1106
  );
1287
1107
  }
1288
1108
  }
1289
- async getMessages({
1290
- threadId,
1291
- resourceId,
1292
- selectBy,
1293
- format
1294
- }) {
1295
- this.logger.debug("Getting messages", { threadId, selectBy });
1109
+ async listMessagesById({ messageIds }) {
1110
+ this.logger.debug("Getting messages by ID", { messageIds });
1111
+ if (messageIds.length === 0) return { messages: [] };
1296
1112
  try {
1297
- const messages = [];
1298
- const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: Number.MAX_SAFE_INTEGER });
1299
- if (selectBy?.include?.length) {
1300
- const includeMessages = await this._getIncludedMessages(threadId, selectBy);
1301
- if (includeMessages) {
1302
- messages.push(...includeMessages);
1303
- }
1113
+ const results = await Promise.all(
1114
+ messageIds.map((id) => this.service.entities.message.query.primary({ entity: "message", id }).go())
1115
+ );
1116
+ const data = results.map((result) => result.data).flat(1);
1117
+ let parsedMessages = data.map((data2) => this.parseMessageData(data2)).filter((msg) => "content" in msg);
1118
+ const uniqueMessages = parsedMessages.filter(
1119
+ (message, index, self) => index === self.findIndex((m) => m.id === message.id)
1120
+ );
1121
+ const list = new agent.MessageList().add(uniqueMessages, "memory");
1122
+ return { messages: list.get.all.db() };
1123
+ } catch (error$1) {
1124
+ throw new error.MastraError(
1125
+ {
1126
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_MESSAGES_BY_ID", "FAILED"),
1127
+ domain: error.ErrorDomain.STORAGE,
1128
+ category: error.ErrorCategory.THIRD_PARTY,
1129
+ details: { messageIds: JSON.stringify(messageIds) }
1130
+ },
1131
+ error$1
1132
+ );
1133
+ }
1134
+ }
1135
+ async listMessages(args) {
1136
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
1137
+ const threadIds = Array.isArray(threadId) ? threadId : [threadId];
1138
+ if (threadIds.length === 0 || threadIds.some((id) => !id.trim())) {
1139
+ throw new error.MastraError(
1140
+ {
1141
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_MESSAGES", "INVALID_THREAD_ID"),
1142
+ domain: error.ErrorDomain.STORAGE,
1143
+ category: error.ErrorCategory.THIRD_PARTY,
1144
+ details: { threadId: Array.isArray(threadId) ? threadId.join(",") : threadId }
1145
+ },
1146
+ new Error("threadId must be a non-empty string or array of non-empty strings")
1147
+ );
1148
+ }
1149
+ const perPage = storage.normalizePerPage(perPageInput, 40);
1150
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1151
+ try {
1152
+ if (page < 0) {
1153
+ throw new error.MastraError(
1154
+ {
1155
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_MESSAGES", "INVALID_PAGE"),
1156
+ domain: error.ErrorDomain.STORAGE,
1157
+ category: error.ErrorCategory.USER,
1158
+ details: { page }
1159
+ },
1160
+ new Error("page must be >= 0")
1161
+ );
1304
1162
  }
1305
- if (limit !== 0) {
1306
- const query = this.service.entities.message.query.byThread({ entity: "message", threadId });
1307
- let results;
1308
- if (limit !== Number.MAX_SAFE_INTEGER && limit > 0) {
1309
- results = await query.go({ limit, order: "desc" });
1310
- results.data = results.data.reverse();
1311
- } else {
1312
- results = await query.go();
1313
- }
1314
- let allThreadMessages = results.data.map((data) => this.parseMessageData(data)).filter((msg) => "content" in msg);
1315
- allThreadMessages.sort((a, b) => {
1316
- const timeA = a.createdAt.getTime();
1317
- const timeB = b.createdAt.getTime();
1318
- if (timeA === timeB) {
1319
- return a.id.localeCompare(b.id);
1163
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
1164
+ this.logger.debug("Getting messages with listMessages", {
1165
+ threadId,
1166
+ resourceId,
1167
+ perPageInput,
1168
+ offset,
1169
+ perPage,
1170
+ page,
1171
+ field,
1172
+ direction
1173
+ });
1174
+ const query = this.service.entities.message.query.byThread({ entity: "message", threadId });
1175
+ const results = await query.go();
1176
+ let allThreadMessages = results.data.map((data) => this.parseMessageData(data)).filter((msg) => "content" in msg && typeof msg.content === "object");
1177
+ if (resourceId) {
1178
+ allThreadMessages = allThreadMessages.filter((msg) => msg.resourceId === resourceId);
1179
+ }
1180
+ if (filter?.dateRange) {
1181
+ const dateRange = filter.dateRange;
1182
+ allThreadMessages = allThreadMessages.filter((msg) => {
1183
+ const createdAt = new Date(msg.createdAt).getTime();
1184
+ if (dateRange.start) {
1185
+ const startTime = dateRange.start instanceof Date ? dateRange.start.getTime() : new Date(dateRange.start).getTime();
1186
+ if (createdAt < startTime) return false;
1320
1187
  }
1321
- return timeA - timeB;
1188
+ if (dateRange.end) {
1189
+ const endTime = dateRange.end instanceof Date ? dateRange.end.getTime() : new Date(dateRange.end).getTime();
1190
+ if (createdAt > endTime) return false;
1191
+ }
1192
+ return true;
1322
1193
  });
1323
- messages.push(...allThreadMessages);
1324
1194
  }
1325
- messages.sort((a, b) => {
1326
- const timeA = a.createdAt.getTime();
1327
- const timeB = b.createdAt.getTime();
1328
- if (timeA === timeB) {
1195
+ allThreadMessages.sort((a, b) => {
1196
+ const aValue = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
1197
+ const bValue = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
1198
+ if (aValue === bValue) {
1329
1199
  return a.id.localeCompare(b.id);
1330
1200
  }
1331
- return timeA - timeB;
1201
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
1332
1202
  });
1333
- const uniqueMessages = messages.filter(
1334
- (message, index, self) => index === self.findIndex((m) => m.id === message.id)
1335
- );
1336
- const list = new agent.MessageList({ threadId, resourceId }).add(uniqueMessages, "memory");
1337
- if (format === `v2`) return list.get.all.v2();
1338
- return list.get.all.v1();
1203
+ const total = allThreadMessages.length;
1204
+ const paginatedMessages = allThreadMessages.slice(offset, offset + perPage);
1205
+ const paginatedCount = paginatedMessages.length;
1206
+ if (total === 0 && paginatedCount === 0 && (!include || include.length === 0)) {
1207
+ return {
1208
+ messages: [],
1209
+ total: 0,
1210
+ page,
1211
+ perPage: perPageForResponse,
1212
+ hasMore: false
1213
+ };
1214
+ }
1215
+ const messageIds = new Set(paginatedMessages.map((m) => m.id));
1216
+ let includeMessages = [];
1217
+ if (include && include.length > 0) {
1218
+ const selectBy = { include };
1219
+ includeMessages = await this._getIncludedMessages(selectBy);
1220
+ for (const includeMsg of includeMessages) {
1221
+ if (!messageIds.has(includeMsg.id)) {
1222
+ paginatedMessages.push(includeMsg);
1223
+ messageIds.add(includeMsg.id);
1224
+ }
1225
+ }
1226
+ }
1227
+ const list = new agent.MessageList().add(paginatedMessages, "memory");
1228
+ let finalMessages = list.get.all.db();
1229
+ finalMessages = finalMessages.sort((a, b) => {
1230
+ const aValue = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
1231
+ const bValue = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
1232
+ if (aValue === bValue) {
1233
+ return a.id.localeCompare(b.id);
1234
+ }
1235
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
1236
+ });
1237
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
1238
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
1239
+ let hasMore = false;
1240
+ if (perPageInput !== false && !allThreadMessagesReturned) {
1241
+ hasMore = offset + paginatedCount < total;
1242
+ }
1243
+ return {
1244
+ messages: finalMessages,
1245
+ total,
1246
+ page,
1247
+ perPage: perPageForResponse,
1248
+ hasMore
1249
+ };
1339
1250
  } catch (error$1) {
1340
- throw new error.MastraError(
1251
+ const mastraError = new error.MastraError(
1341
1252
  {
1342
- id: "STORAGE_DYNAMODB_STORE_GET_MESSAGES_FAILED",
1253
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_MESSAGES", "FAILED"),
1343
1254
  domain: error.ErrorDomain.STORAGE,
1344
1255
  category: error.ErrorCategory.THIRD_PARTY,
1345
- details: { threadId }
1256
+ details: {
1257
+ threadId: Array.isArray(threadId) ? threadId.join(",") : threadId,
1258
+ resourceId: resourceId ?? ""
1259
+ }
1346
1260
  },
1347
1261
  error$1
1348
1262
  );
1263
+ this.logger?.error?.(mastraError.toString());
1264
+ this.logger?.trackException?.(mastraError);
1265
+ return {
1266
+ messages: [],
1267
+ total: 0,
1268
+ page,
1269
+ perPage: perPageForResponse,
1270
+ hasMore: false
1271
+ };
1349
1272
  }
1350
1273
  }
1351
1274
  async saveMessages(args) {
1352
- const { messages, format = "v1" } = args;
1275
+ const { messages } = args;
1353
1276
  this.logger.debug("Saving messages", { count: messages.length });
1354
1277
  if (!messages.length) {
1355
- return [];
1278
+ return { messages: [] };
1356
1279
  }
1357
1280
  const threadId = messages[0]?.threadId;
1358
1281
  if (!threadId) {
@@ -1406,12 +1329,11 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1406
1329
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1407
1330
  }).go();
1408
1331
  const list = new agent.MessageList().add(messages, "memory");
1409
- if (format === `v1`) return list.get.all.v1();
1410
- return list.get.all.v2();
1332
+ return { messages: list.get.all.db() };
1411
1333
  } catch (error$1) {
1412
1334
  throw new error.MastraError(
1413
1335
  {
1414
- id: "STORAGE_DYNAMODB_STORE_SAVE_MESSAGES_FAILED",
1336
+ id: storage.createStorageErrorId("DYNAMODB", "SAVE_MESSAGES", "FAILED"),
1415
1337
  domain: error.ErrorDomain.STORAGE,
1416
1338
  category: error.ErrorCategory.THIRD_PARTY,
1417
1339
  details: { count: messages.length }
@@ -1420,124 +1342,74 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1420
1342
  );
1421
1343
  }
1422
1344
  }
1423
- async getThreadsByResourceIdPaginated(args) {
1424
- const { resourceId, page = 0, perPage = 100 } = args;
1425
- this.logger.debug("Getting threads by resource ID with pagination", { resourceId, page, perPage });
1426
- try {
1427
- const query = this.service.entities.thread.query.byResource({ entity: "thread", resourceId });
1428
- const results = await query.go();
1429
- const allThreads = results.data;
1430
- const startIndex = page * perPage;
1431
- const endIndex = startIndex + perPage;
1432
- const paginatedThreads = allThreads.slice(startIndex, endIndex);
1433
- const total = allThreads.length;
1434
- const hasMore = endIndex < total;
1435
- return {
1436
- threads: paginatedThreads,
1437
- total,
1438
- page,
1439
- perPage,
1440
- hasMore
1441
- };
1442
- } catch (error$1) {
1345
+ async listThreadsByResourceId(args) {
1346
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
1347
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1348
+ if (page < 0) {
1443
1349
  throw new error.MastraError(
1444
1350
  {
1445
- id: "STORAGE_DYNAMODB_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
1351
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_THREADS_BY_RESOURCE_ID", "INVALID_PAGE"),
1446
1352
  domain: error.ErrorDomain.STORAGE,
1447
- category: error.ErrorCategory.THIRD_PARTY,
1448
- details: { resourceId, page, perPage }
1353
+ category: error.ErrorCategory.USER,
1354
+ details: { page }
1449
1355
  },
1450
- error$1
1356
+ new Error("page must be >= 0")
1451
1357
  );
1452
1358
  }
1453
- }
1454
- async getMessagesPaginated(args) {
1455
- const { threadId, resourceId, selectBy, format = "v1" } = args;
1456
- const { page = 0, perPage = 40, dateRange } = selectBy?.pagination || {};
1457
- const fromDate = dateRange?.start;
1458
- const toDate = dateRange?.end;
1459
- const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: Number.MAX_SAFE_INTEGER });
1460
- this.logger.debug("Getting messages with pagination", { threadId, page, perPage, fromDate, toDate, limit });
1359
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1360
+ const { field, direction } = this.parseOrderBy(orderBy);
1361
+ this.logger.debug("Getting threads by resource ID with pagination", {
1362
+ resourceId,
1363
+ page,
1364
+ perPage,
1365
+ field,
1366
+ direction
1367
+ });
1461
1368
  try {
1462
- let messages = [];
1463
- if (selectBy?.include?.length) {
1464
- const includeMessages = await this._getIncludedMessages(threadId, selectBy);
1465
- if (includeMessages) {
1466
- messages.push(...includeMessages);
1467
- }
1468
- }
1469
- if (limit !== 0) {
1470
- const query = this.service.entities.message.query.byThread({ entity: "message", threadId });
1471
- let results;
1472
- if (limit !== Number.MAX_SAFE_INTEGER && limit > 0) {
1473
- results = await query.go({ limit, order: "desc" });
1474
- results.data = results.data.reverse();
1475
- } else {
1476
- results = await query.go();
1477
- }
1478
- let allThreadMessages = results.data.map((data) => this.parseMessageData(data)).filter((msg) => "content" in msg);
1479
- allThreadMessages.sort((a, b) => {
1480
- const timeA = a.createdAt.getTime();
1481
- const timeB = b.createdAt.getTime();
1482
- if (timeA === timeB) {
1483
- return a.id.localeCompare(b.id);
1484
- }
1485
- return timeA - timeB;
1486
- });
1487
- const excludeIds = messages.map((m) => m.id);
1488
- if (excludeIds.length > 0) {
1489
- allThreadMessages = allThreadMessages.filter((msg) => !excludeIds.includes(msg.id));
1490
- }
1491
- messages.push(...allThreadMessages);
1492
- }
1493
- messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
1494
- if (fromDate || toDate) {
1495
- messages = messages.filter((msg) => {
1496
- const createdAt = new Date(msg.createdAt).getTime();
1497
- if (fromDate && createdAt < new Date(fromDate).getTime()) return false;
1498
- if (toDate && createdAt > new Date(toDate).getTime()) return false;
1499
- return true;
1500
- });
1501
- }
1502
- const total = messages.length;
1503
- const start = page * perPage;
1504
- const end = start + perPage;
1505
- const paginatedMessages = messages.slice(start, end);
1506
- const hasMore = end < total;
1507
- const list = new agent.MessageList({ threadId, resourceId }).add(paginatedMessages, "memory");
1508
- const finalMessages = format === "v2" ? list.get.all.v2() : list.get.all.v1();
1369
+ const query = this.service.entities.thread.query.byResource({ entity: "thread", resourceId });
1370
+ const results = await query.go();
1371
+ const allThreads = this.transformAndSortThreads(results.data, field, direction);
1372
+ const endIndex = offset + perPage;
1373
+ const paginatedThreads = allThreads.slice(offset, endIndex);
1374
+ const total = allThreads.length;
1375
+ const hasMore = offset + perPage < total;
1509
1376
  return {
1510
- messages: finalMessages,
1377
+ threads: paginatedThreads,
1511
1378
  total,
1512
1379
  page,
1513
- perPage,
1380
+ perPage: perPageForResponse,
1514
1381
  hasMore
1515
1382
  };
1516
1383
  } catch (error$1) {
1517
1384
  throw new error.MastraError(
1518
1385
  {
1519
- id: "STORAGE_DYNAMODB_STORE_GET_MESSAGES_PAGINATED_FAILED",
1386
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_THREADS_BY_RESOURCE_ID", "FAILED"),
1520
1387
  domain: error.ErrorDomain.STORAGE,
1521
1388
  category: error.ErrorCategory.THIRD_PARTY,
1522
- details: { threadId }
1389
+ details: { resourceId, page, perPage }
1523
1390
  },
1524
1391
  error$1
1525
1392
  );
1526
1393
  }
1527
1394
  }
1528
1395
  // Helper method to get included messages with context
1529
- async _getIncludedMessages(threadId, selectBy) {
1396
+ async _getIncludedMessages(selectBy) {
1530
1397
  if (!selectBy?.include?.length) {
1531
1398
  return [];
1532
1399
  }
1533
1400
  const includeMessages = [];
1534
1401
  for (const includeItem of selectBy.include) {
1535
1402
  try {
1536
- const { id, threadId: targetThreadId, withPreviousMessages = 0, withNextMessages = 0 } = includeItem;
1537
- const searchThreadId = targetThreadId || threadId;
1403
+ const { id, withPreviousMessages = 0, withNextMessages = 0 } = includeItem;
1404
+ const targetResult = await this.service.entities.message.get({ entity: "message", id }).go();
1405
+ if (!targetResult.data) {
1406
+ this.logger.warn("Target message not found", { id });
1407
+ continue;
1408
+ }
1409
+ const targetMessageData = targetResult.data;
1410
+ const searchThreadId = targetMessageData.threadId;
1538
1411
  this.logger.debug("Getting included messages for", {
1539
1412
  id,
1540
- targetThreadId,
1541
1413
  searchThreadId,
1542
1414
  withPreviousMessages,
1543
1415
  withNextMessages
@@ -1560,7 +1432,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1560
1432
  });
1561
1433
  const targetIndex = allMessages.findIndex((msg) => msg.id === id);
1562
1434
  if (targetIndex === -1) {
1563
- this.logger.warn("Target message not found", { id, threadId: searchThreadId });
1435
+ this.logger.warn("Target message not found in thread", { id, threadId: searchThreadId });
1564
1436
  continue;
1565
1437
  }
1566
1438
  this.logger.debug("Found target message at index", { id, targetIndex, totalMessages: allMessages.length });
@@ -1645,7 +1517,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1645
1517
  } catch (error$1) {
1646
1518
  throw new error.MastraError(
1647
1519
  {
1648
- id: "STORAGE_DYNAMODB_STORE_UPDATE_MESSAGES_FAILED",
1520
+ id: storage.createStorageErrorId("DYNAMODB", "UPDATE_MESSAGES", "FAILED"),
1649
1521
  domain: error.ErrorDomain.STORAGE,
1650
1522
  category: error.ErrorCategory.THIRD_PARTY,
1651
1523
  details: { count: messages.length }
@@ -1674,7 +1546,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1674
1546
  } catch (error$1) {
1675
1547
  throw new error.MastraError(
1676
1548
  {
1677
- id: "STORAGE_DYNAMODB_STORE_GET_RESOURCE_BY_ID_FAILED",
1549
+ id: storage.createStorageErrorId("DYNAMODB", "GET_RESOURCE_BY_ID", "FAILED"),
1678
1550
  domain: error.ErrorDomain.STORAGE,
1679
1551
  category: error.ErrorCategory.THIRD_PARTY,
1680
1552
  details: { resourceId }
@@ -1706,7 +1578,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1706
1578
  } catch (error$1) {
1707
1579
  throw new error.MastraError(
1708
1580
  {
1709
- id: "STORAGE_DYNAMODB_STORE_SAVE_RESOURCE_FAILED",
1581
+ id: storage.createStorageErrorId("DYNAMODB", "SAVE_RESOURCE", "FAILED"),
1710
1582
  domain: error.ErrorDomain.STORAGE,
1711
1583
  category: error.ErrorCategory.THIRD_PARTY,
1712
1584
  details: { resourceId: resource.id }
@@ -1755,7 +1627,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1755
1627
  } catch (error$1) {
1756
1628
  throw new error.MastraError(
1757
1629
  {
1758
- id: "STORAGE_DYNAMODB_STORE_UPDATE_RESOURCE_FAILED",
1630
+ id: storage.createStorageErrorId("DYNAMODB", "UPDATE_RESOURCE", "FAILED"),
1759
1631
  domain: error.ErrorDomain.STORAGE,
1760
1632
  category: error.ErrorCategory.THIRD_PARTY,
1761
1633
  details: { resourceId }
@@ -1790,10 +1662,11 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
1790
1662
  [storage.TABLE_THREADS]: "thread",
1791
1663
  [storage.TABLE_MESSAGES]: "message",
1792
1664
  [storage.TABLE_WORKFLOW_SNAPSHOT]: "workflow_snapshot",
1793
- [storage.TABLE_EVALS]: "eval",
1794
1665
  [storage.TABLE_SCORERS]: "score",
1795
1666
  [storage.TABLE_TRACES]: "trace",
1796
- [storage.TABLE_RESOURCES]: "resource"
1667
+ [storage.TABLE_RESOURCES]: "resource",
1668
+ [storage.TABLE_SPANS]: "ai_span",
1669
+ mastra_agents: "agent"
1797
1670
  };
1798
1671
  return mapping[tableName] || null;
1799
1672
  }
@@ -1855,7 +1728,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
1855
1728
  }
1856
1729
  throw new error.MastraError(
1857
1730
  {
1858
- id: "STORAGE_DYNAMODB_STORE_VALIDATE_TABLE_EXISTS_FAILED",
1731
+ id: storage.createStorageErrorId("DYNAMODB", "VALIDATE_TABLE_EXISTS", "FAILED"),
1859
1732
  domain: error.ErrorDomain.STORAGE,
1860
1733
  category: error.ErrorCategory.THIRD_PARTY,
1861
1734
  details: { tableName: this.tableName }
@@ -1888,7 +1761,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
1888
1761
  this.logger.error("Error validating table access", { tableName: this.tableName, error: error$1 });
1889
1762
  throw new error.MastraError(
1890
1763
  {
1891
- id: "STORAGE_DYNAMODB_STORE_VALIDATE_TABLE_ACCESS_FAILED",
1764
+ id: storage.createStorageErrorId("DYNAMODB", "VALIDATE_TABLE_ACCESS", "FAILED"),
1892
1765
  domain: error.ErrorDomain.STORAGE,
1893
1766
  category: error.ErrorCategory.THIRD_PARTY,
1894
1767
  details: { tableName: this.tableName }
@@ -1902,7 +1775,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
1902
1775
  const entityName = this.getEntityNameForTable(tableName);
1903
1776
  if (!entityName || !this.service.entities[entityName]) {
1904
1777
  throw new error.MastraError({
1905
- id: "STORAGE_DYNAMODB_STORE_INSERT_INVALID_ARGS",
1778
+ id: storage.createStorageErrorId("DYNAMODB", "INSERT", "INVALID_ARGS"),
1906
1779
  domain: error.ErrorDomain.STORAGE,
1907
1780
  category: error.ErrorCategory.USER,
1908
1781
  text: "No entity defined for tableName",
@@ -1915,7 +1788,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
1915
1788
  } catch (error$1) {
1916
1789
  throw new error.MastraError(
1917
1790
  {
1918
- id: "STORAGE_DYNAMODB_STORE_INSERT_FAILED",
1791
+ id: storage.createStorageErrorId("DYNAMODB", "INSERT", "FAILED"),
1919
1792
  domain: error.ErrorDomain.STORAGE,
1920
1793
  category: error.ErrorCategory.THIRD_PARTY,
1921
1794
  details: { tableName }
@@ -1934,7 +1807,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
1934
1807
  const entityName = this.getEntityNameForTable(tableName);
1935
1808
  if (!entityName || !this.service.entities[entityName]) {
1936
1809
  throw new error.MastraError({
1937
- id: "STORAGE_DYNAMODB_STORE_CLEAR_TABLE_INVALID_ARGS",
1810
+ id: storage.createStorageErrorId("DYNAMODB", "CLEAR_TABLE", "INVALID_ARGS"),
1938
1811
  domain: error.ErrorDomain.STORAGE,
1939
1812
  category: error.ErrorCategory.USER,
1940
1813
  text: "No entity defined for tableName",
@@ -1978,6 +1851,10 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
1978
1851
  if (!item.id) throw new Error(`Missing required key 'id' for entity 'score'`);
1979
1852
  key.id = item.id;
1980
1853
  break;
1854
+ case "resource":
1855
+ if (!item.id) throw new Error(`Missing required key 'id' for entity 'resource'`);
1856
+ key.id = item.id;
1857
+ break;
1981
1858
  default:
1982
1859
  this.logger.warn(`Unknown entity type encountered during clearTable: ${entityName}`);
1983
1860
  throw new Error(`Cannot construct delete key for unknown entity type: ${entityName}`);
@@ -1993,7 +1870,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
1993
1870
  } catch (error$1) {
1994
1871
  throw new error.MastraError(
1995
1872
  {
1996
- id: "STORAGE_DYNAMODB_STORE_CLEAR_TABLE_FAILED",
1873
+ id: storage.createStorageErrorId("DYNAMODB", "CLEAR_TABLE", "FAILED"),
1997
1874
  domain: error.ErrorDomain.STORAGE,
1998
1875
  category: error.ErrorCategory.THIRD_PARTY,
1999
1876
  details: { tableName }
@@ -2010,7 +1887,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
2010
1887
  const entityName = this.getEntityNameForTable(tableName);
2011
1888
  if (!entityName || !this.service.entities[entityName]) {
2012
1889
  throw new error.MastraError({
2013
- id: "STORAGE_DYNAMODB_STORE_BATCH_INSERT_INVALID_ARGS",
1890
+ id: storage.createStorageErrorId("DYNAMODB", "BATCH_INSERT", "INVALID_ARGS"),
2014
1891
  domain: error.ErrorDomain.STORAGE,
2015
1892
  category: error.ErrorCategory.USER,
2016
1893
  text: "No entity defined for tableName",
@@ -2038,7 +1915,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
2038
1915
  } catch (error$1) {
2039
1916
  throw new error.MastraError(
2040
1917
  {
2041
- id: "STORAGE_DYNAMODB_STORE_BATCH_INSERT_FAILED",
1918
+ id: storage.createStorageErrorId("DYNAMODB", "BATCH_INSERT", "FAILED"),
2042
1919
  domain: error.ErrorDomain.STORAGE,
2043
1920
  category: error.ErrorCategory.THIRD_PARTY,
2044
1921
  details: { tableName }
@@ -2055,7 +1932,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
2055
1932
  const entityName = this.getEntityNameForTable(tableName);
2056
1933
  if (!entityName || !this.service.entities[entityName]) {
2057
1934
  throw new error.MastraError({
2058
- id: "STORAGE_DYNAMODB_STORE_LOAD_INVALID_ARGS",
1935
+ id: storage.createStorageErrorId("DYNAMODB", "LOAD", "INVALID_ARGS"),
2059
1936
  domain: error.ErrorDomain.STORAGE,
2060
1937
  category: error.ErrorCategory.USER,
2061
1938
  text: "No entity defined for tableName",
@@ -2073,7 +1950,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
2073
1950
  } catch (error$1) {
2074
1951
  throw new error.MastraError(
2075
1952
  {
2076
- id: "STORAGE_DYNAMODB_STORE_LOAD_FAILED",
1953
+ id: storage.createStorageErrorId("DYNAMODB", "LOAD", "FAILED"),
2077
1954
  domain: error.ErrorDomain.STORAGE,
2078
1955
  category: error.ErrorCategory.THIRD_PARTY,
2079
1956
  details: { tableName }
@@ -2089,14 +1966,28 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2089
1966
  super();
2090
1967
  this.service = service;
2091
1968
  }
2092
- // Helper function to parse score data (handle JSON fields)
1969
+ /**
1970
+ * DynamoDB-specific score row transformation.
1971
+ *
1972
+ * Note: This implementation does NOT use coreTransformScoreRow because:
1973
+ * 1. ElectroDB already parses JSON fields via its entity getters
1974
+ * 2. DynamoDB stores empty strings for null values (which need special handling)
1975
+ * 3. 'entity' is a reserved ElectroDB key, so we use 'entityData' column
1976
+ */
2093
1977
  parseScoreData(data) {
1978
+ const result = {};
1979
+ for (const key of Object.keys(storage.SCORERS_SCHEMA)) {
1980
+ if (["traceId", "resourceId", "threadId", "spanId"].includes(key)) {
1981
+ result[key] = data[key] === "" ? null : data[key];
1982
+ continue;
1983
+ }
1984
+ result[key] = data[key];
1985
+ }
1986
+ result.entity = data.entityData ?? null;
2094
1987
  return {
2095
- ...data,
2096
- // Convert date strings back to Date objects for consistency
1988
+ ...result,
2097
1989
  createdAt: data.createdAt ? new Date(data.createdAt) : /* @__PURE__ */ new Date(),
2098
1990
  updatedAt: data.updatedAt ? new Date(data.updatedAt) : /* @__PURE__ */ new Date()
2099
- // JSON fields are already transformed by the entity's getters
2100
1991
  };
2101
1992
  }
2102
1993
  async getScoreById({ id }) {
@@ -2110,7 +2001,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2110
2001
  } catch (error$1) {
2111
2002
  throw new error.MastraError(
2112
2003
  {
2113
- id: "STORAGE_DYNAMODB_STORE_GET_SCORE_BY_ID_FAILED",
2004
+ id: storage.createStorageErrorId("DYNAMODB", "GET_SCORE_BY_ID", "FAILED"),
2114
2005
  domain: error.ErrorDomain.STORAGE,
2115
2006
  category: error.ErrorCategory.THIRD_PARTY,
2116
2007
  details: { id }
@@ -2120,50 +2011,69 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2120
2011
  }
2121
2012
  }
2122
2013
  async saveScore(score) {
2123
- this.logger.debug("Saving score", { scorerId: score.scorerId, runId: score.runId });
2014
+ let validatedScore;
2015
+ try {
2016
+ validatedScore = evals.saveScorePayloadSchema.parse(score);
2017
+ } catch (error$1) {
2018
+ throw new error.MastraError(
2019
+ {
2020
+ id: storage.createStorageErrorId("DYNAMODB", "SAVE_SCORE", "VALIDATION_FAILED"),
2021
+ domain: error.ErrorDomain.STORAGE,
2022
+ category: error.ErrorCategory.USER,
2023
+ details: {
2024
+ scorer: score.scorer?.id ?? "unknown",
2025
+ entityId: score.entityId ?? "unknown",
2026
+ entityType: score.entityType ?? "unknown",
2027
+ traceId: score.traceId ?? "",
2028
+ spanId: score.spanId ?? ""
2029
+ }
2030
+ },
2031
+ error$1
2032
+ );
2033
+ }
2124
2034
  const now = /* @__PURE__ */ new Date();
2125
- const scoreId = `score-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
2126
- const scoreData = {
2127
- entity: "score",
2128
- id: scoreId,
2129
- scorerId: score.scorerId,
2130
- traceId: score.traceId || "",
2131
- runId: score.runId,
2132
- scorer: typeof score.scorer === "string" ? score.scorer : JSON.stringify(score.scorer),
2133
- preprocessStepResult: typeof score.preprocessStepResult === "string" ? score.preprocessStepResult : JSON.stringify(score.preprocessStepResult),
2134
- analyzeStepResult: typeof score.analyzeStepResult === "string" ? score.analyzeStepResult : JSON.stringify(score.analyzeStepResult),
2135
- score: score.score,
2136
- reason: score.reason,
2137
- preprocessPrompt: score.preprocessPrompt,
2138
- generateScorePrompt: score.generateScorePrompt,
2139
- analyzePrompt: score.analyzePrompt,
2140
- reasonPrompt: score.reasonPrompt,
2141
- input: typeof score.input === "string" ? score.input : JSON.stringify(score.input),
2142
- output: typeof score.output === "string" ? score.output : JSON.stringify(score.output),
2143
- additionalContext: typeof score.additionalContext === "string" ? score.additionalContext : JSON.stringify(score.additionalContext),
2144
- runtimeContext: typeof score.runtimeContext === "string" ? score.runtimeContext : JSON.stringify(score.runtimeContext),
2145
- entityType: score.entityType,
2146
- entityData: typeof score.entity === "string" ? score.entity : JSON.stringify(score.entity),
2147
- entityId: score.entityId,
2148
- source: score.source,
2149
- resourceId: score.resourceId || "",
2150
- threadId: score.threadId || "",
2151
- createdAt: now.toISOString(),
2152
- updatedAt: now.toISOString()
2153
- };
2035
+ const scoreId = crypto.randomUUID();
2036
+ const scorer = typeof validatedScore.scorer === "string" ? validatedScore.scorer : JSON.stringify(validatedScore.scorer);
2037
+ const preprocessStepResult = typeof validatedScore.preprocessStepResult === "string" ? validatedScore.preprocessStepResult : JSON.stringify(validatedScore.preprocessStepResult);
2038
+ const analyzeStepResult = typeof validatedScore.analyzeStepResult === "string" ? validatedScore.analyzeStepResult : JSON.stringify(validatedScore.analyzeStepResult);
2039
+ const input = typeof validatedScore.input === "string" ? validatedScore.input : JSON.stringify(validatedScore.input);
2040
+ const output = typeof validatedScore.output === "string" ? validatedScore.output : JSON.stringify(validatedScore.output);
2041
+ const requestContext = typeof validatedScore.requestContext === "string" ? validatedScore.requestContext : JSON.stringify(validatedScore.requestContext);
2042
+ const entity = typeof validatedScore.entity === "string" ? validatedScore.entity : JSON.stringify(validatedScore.entity);
2043
+ const scoreData = Object.fromEntries(
2044
+ Object.entries({
2045
+ ...validatedScore,
2046
+ entity: "score",
2047
+ id: scoreId,
2048
+ scorer,
2049
+ preprocessStepResult,
2050
+ analyzeStepResult,
2051
+ input,
2052
+ output,
2053
+ requestContext,
2054
+ entityData: entity,
2055
+ traceId: validatedScore.traceId || "",
2056
+ resourceId: validatedScore.resourceId || "",
2057
+ threadId: validatedScore.threadId || "",
2058
+ spanId: validatedScore.spanId || "",
2059
+ createdAt: now.toISOString(),
2060
+ updatedAt: now.toISOString()
2061
+ }).filter(([_, value]) => value !== void 0 && value !== null)
2062
+ );
2154
2063
  try {
2155
2064
  await this.service.entities.score.upsert(scoreData).go();
2156
- const savedScore = {
2157
- ...score,
2158
- id: scoreId,
2159
- createdAt: now,
2160
- updatedAt: now
2065
+ return {
2066
+ score: {
2067
+ ...validatedScore,
2068
+ id: scoreId,
2069
+ createdAt: now,
2070
+ updatedAt: now
2071
+ }
2161
2072
  };
2162
- return { score: savedScore };
2163
2073
  } catch (error$1) {
2164
2074
  throw new error.MastraError(
2165
2075
  {
2166
- id: "STORAGE_DYNAMODB_STORE_SAVE_SCORE_FAILED",
2076
+ id: storage.createStorageErrorId("DYNAMODB", "SAVE_SCORE", "FAILED"),
2167
2077
  domain: error.ErrorDomain.STORAGE,
2168
2078
  category: error.ErrorCategory.THIRD_PARTY,
2169
2079
  details: { scorerId: score.scorerId, runId: score.runId }
@@ -2172,13 +2082,13 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2172
2082
  );
2173
2083
  }
2174
2084
  }
2175
- async getScoresByScorerId({
2085
+ async listScoresByScorerId({
2176
2086
  scorerId,
2177
2087
  pagination,
2178
2088
  entityId,
2179
- entityType
2089
+ entityType,
2090
+ source
2180
2091
  }) {
2181
- this.logger.debug("Getting scores by scorer ID", { scorerId, pagination, entityId, entityType });
2182
2092
  try {
2183
2093
  const query = this.service.entities.score.query.byScorer({ entity: "score", scorerId });
2184
2094
  const results = await query.go();
@@ -2189,31 +2099,36 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2189
2099
  if (entityType) {
2190
2100
  allScores = allScores.filter((score) => score.entityType === entityType);
2191
2101
  }
2102
+ if (source) {
2103
+ allScores = allScores.filter((score) => score.source === source);
2104
+ }
2192
2105
  allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2193
- const startIndex = pagination.page * pagination.perPage;
2194
- const endIndex = startIndex + pagination.perPage;
2195
- const paginatedScores = allScores.slice(startIndex, endIndex);
2106
+ const { page, perPage: perPageInput } = pagination;
2107
+ const perPage = storage.normalizePerPage(perPageInput, Number.MAX_SAFE_INTEGER);
2108
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2196
2109
  const total = allScores.length;
2197
- const hasMore = endIndex < total;
2110
+ const end = perPageInput === false ? allScores.length : start + perPage;
2111
+ const paginatedScores = allScores.slice(start, end);
2198
2112
  return {
2199
2113
  scores: paginatedScores,
2200
2114
  pagination: {
2201
2115
  total,
2202
- page: pagination.page,
2203
- perPage: pagination.perPage,
2204
- hasMore
2116
+ page,
2117
+ perPage: perPageForResponse,
2118
+ hasMore: end < total
2205
2119
  }
2206
2120
  };
2207
2121
  } catch (error$1) {
2208
2122
  throw new error.MastraError(
2209
2123
  {
2210
- id: "STORAGE_DYNAMODB_STORE_GET_SCORES_BY_SCORER_ID_FAILED",
2124
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_SCORES_BY_SCORER_ID", "FAILED"),
2211
2125
  domain: error.ErrorDomain.STORAGE,
2212
2126
  category: error.ErrorCategory.THIRD_PARTY,
2213
2127
  details: {
2214
2128
  scorerId: scorerId || "",
2215
2129
  entityId: entityId || "",
2216
2130
  entityType: entityType || "",
2131
+ source: source || "",
2217
2132
  page: pagination.page,
2218
2133
  perPage: pagination.perPage
2219
2134
  }
@@ -2222,7 +2137,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2222
2137
  );
2223
2138
  }
2224
2139
  }
2225
- async getScoresByRunId({
2140
+ async listScoresByRunId({
2226
2141
  runId,
2227
2142
  pagination
2228
2143
  }) {
@@ -2232,24 +2147,25 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2232
2147
  const results = await query.go();
2233
2148
  const allScores = results.data.map((data) => this.parseScoreData(data));
2234
2149
  allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2235
- const startIndex = pagination.page * pagination.perPage;
2236
- const endIndex = startIndex + pagination.perPage;
2237
- const paginatedScores = allScores.slice(startIndex, endIndex);
2150
+ const { page, perPage: perPageInput } = pagination;
2151
+ const perPage = storage.normalizePerPage(perPageInput, Number.MAX_SAFE_INTEGER);
2152
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2238
2153
  const total = allScores.length;
2239
- const hasMore = endIndex < total;
2154
+ const end = perPageInput === false ? allScores.length : start + perPage;
2155
+ const paginatedScores = allScores.slice(start, end);
2240
2156
  return {
2241
2157
  scores: paginatedScores,
2242
2158
  pagination: {
2243
2159
  total,
2244
- page: pagination.page,
2245
- perPage: pagination.perPage,
2246
- hasMore
2160
+ page,
2161
+ perPage: perPageForResponse,
2162
+ hasMore: end < total
2247
2163
  }
2248
2164
  };
2249
2165
  } catch (error$1) {
2250
2166
  throw new error.MastraError(
2251
2167
  {
2252
- id: "STORAGE_DYNAMODB_STORE_GET_SCORES_BY_RUN_ID_FAILED",
2168
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_SCORES_BY_RUN_ID", "FAILED"),
2253
2169
  domain: error.ErrorDomain.STORAGE,
2254
2170
  category: error.ErrorCategory.THIRD_PARTY,
2255
2171
  details: { runId, page: pagination.page, perPage: pagination.perPage }
@@ -2258,7 +2174,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2258
2174
  );
2259
2175
  }
2260
2176
  }
2261
- async getScoresByEntityId({
2177
+ async listScoresByEntityId({
2262
2178
  entityId,
2263
2179
  entityType,
2264
2180
  pagination
@@ -2270,24 +2186,25 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2270
2186
  let allScores = results.data.map((data) => this.parseScoreData(data));
2271
2187
  allScores = allScores.filter((score) => score.entityType === entityType);
2272
2188
  allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2273
- const startIndex = pagination.page * pagination.perPage;
2274
- const endIndex = startIndex + pagination.perPage;
2275
- const paginatedScores = allScores.slice(startIndex, endIndex);
2189
+ const { page, perPage: perPageInput } = pagination;
2190
+ const perPage = storage.normalizePerPage(perPageInput, Number.MAX_SAFE_INTEGER);
2191
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2276
2192
  const total = allScores.length;
2277
- const hasMore = endIndex < total;
2193
+ const end = perPageInput === false ? allScores.length : start + perPage;
2194
+ const paginatedScores = allScores.slice(start, end);
2278
2195
  return {
2279
2196
  scores: paginatedScores,
2280
2197
  pagination: {
2281
2198
  total,
2282
- page: pagination.page,
2283
- perPage: pagination.perPage,
2284
- hasMore
2199
+ page,
2200
+ perPage: perPageForResponse,
2201
+ hasMore: end < total
2285
2202
  }
2286
2203
  };
2287
2204
  } catch (error$1) {
2288
2205
  throw new error.MastraError(
2289
2206
  {
2290
- id: "STORAGE_DYNAMODB_STORE_GET_SCORES_BY_ENTITY_ID_FAILED",
2207
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_SCORES_BY_ENTITY_ID", "FAILED"),
2291
2208
  domain: error.ErrorDomain.STORAGE,
2292
2209
  category: error.ErrorCategory.THIRD_PARTY,
2293
2210
  details: { entityId, entityType, page: pagination.page, perPage: pagination.perPage }
@@ -2296,234 +2213,39 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2296
2213
  );
2297
2214
  }
2298
2215
  }
2299
- };
2300
- var TracesStorageDynamoDB = class extends storage.TracesStorage {
2301
- service;
2302
- operations;
2303
- constructor({ service, operations }) {
2304
- super();
2305
- this.service = service;
2306
- this.operations = operations;
2307
- }
2308
- // Trace operations
2309
- async getTraces(args) {
2310
- const { name, scope, page, perPage } = args;
2311
- this.logger.debug("Getting traces", { name, scope, page, perPage });
2312
- try {
2313
- let query;
2314
- if (name) {
2315
- query = this.service.entities.trace.query.byName({ entity: "trace", name });
2316
- } else if (scope) {
2317
- query = this.service.entities.trace.query.byScope({ entity: "trace", scope });
2318
- } else {
2319
- this.logger.warn("Performing a scan operation on traces - consider using a more specific query");
2320
- query = this.service.entities.trace.scan;
2321
- }
2322
- let items = [];
2323
- let cursor = null;
2324
- let pagesFetched = 0;
2325
- const startPage = page > 0 ? page : 1;
2326
- do {
2327
- const results = await query.go({ cursor, limit: perPage });
2328
- pagesFetched++;
2329
- if (pagesFetched === startPage) {
2330
- items = results.data;
2331
- break;
2332
- }
2333
- cursor = results.cursor;
2334
- if (!cursor && results.data.length > 0 && pagesFetched < startPage) {
2335
- break;
2336
- }
2337
- } while (cursor && pagesFetched < startPage);
2338
- return items;
2339
- } catch (error$1) {
2340
- throw new error.MastraError(
2341
- {
2342
- id: "STORAGE_DYNAMODB_STORE_GET_TRACES_FAILED",
2343
- domain: error.ErrorDomain.STORAGE,
2344
- category: error.ErrorCategory.THIRD_PARTY
2345
- },
2346
- error$1
2347
- );
2348
- }
2349
- }
2350
- async batchTraceInsert({ records }) {
2351
- this.logger.debug("Batch inserting traces", { count: records.length });
2352
- if (!records.length) {
2353
- return;
2354
- }
2355
- try {
2356
- const recordsToSave = records.map((rec) => ({ entity: "trace", ...rec }));
2357
- await this.operations.batchInsert({
2358
- tableName: storage.TABLE_TRACES,
2359
- records: recordsToSave
2360
- // Pass records with 'entity' included
2361
- });
2362
- } catch (error$1) {
2363
- throw new error.MastraError(
2364
- {
2365
- id: "STORAGE_DYNAMODB_STORE_BATCH_TRACE_INSERT_FAILED",
2366
- domain: error.ErrorDomain.STORAGE,
2367
- category: error.ErrorCategory.THIRD_PARTY,
2368
- details: { count: records.length }
2369
- },
2370
- error$1
2371
- );
2372
- }
2373
- }
2374
- async getTracesPaginated(args) {
2375
- const { name, scope, page = 0, perPage = 100, attributes, filters, dateRange } = args;
2376
- this.logger.debug("Getting traces with pagination", { name, scope, page, perPage, attributes, filters, dateRange });
2216
+ async listScoresBySpan({
2217
+ traceId,
2218
+ spanId,
2219
+ pagination
2220
+ }) {
2221
+ this.logger.debug("Getting scores by span", { traceId, spanId, pagination });
2377
2222
  try {
2378
- let query;
2379
- if (name) {
2380
- query = this.service.entities.trace.query.byName({ entity: "trace", name });
2381
- } else if (scope) {
2382
- query = this.service.entities.trace.query.byScope({ entity: "trace", scope });
2383
- } else {
2384
- this.logger.warn("Performing a scan operation on traces - consider using a more specific query");
2385
- query = this.service.entities.trace.scan;
2386
- }
2387
- const results = await query.go({
2388
- order: "desc",
2389
- pages: "all"
2390
- // Get all pages to apply filtering and pagination
2391
- });
2392
- if (!results.data.length) {
2393
- return {
2394
- traces: [],
2395
- total: 0,
2223
+ const query = this.service.entities.score.query.bySpan({ entity: "score", traceId, spanId });
2224
+ const results = await query.go();
2225
+ const allScores = results.data.map((data) => this.parseScoreData(data));
2226
+ allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2227
+ const { page, perPage: perPageInput } = pagination;
2228
+ const perPage = storage.normalizePerPage(perPageInput, Number.MAX_SAFE_INTEGER);
2229
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2230
+ const total = allScores.length;
2231
+ const end = perPageInput === false ? allScores.length : start + perPage;
2232
+ const paginatedScores = allScores.slice(start, end);
2233
+ return {
2234
+ scores: paginatedScores,
2235
+ pagination: {
2236
+ total,
2396
2237
  page,
2397
- perPage,
2398
- hasMore: false
2399
- };
2400
- }
2401
- let filteredData = results.data;
2402
- if (attributes) {
2403
- filteredData = filteredData.filter((item) => {
2404
- try {
2405
- let itemAttributes = {};
2406
- if (item.attributes) {
2407
- if (typeof item.attributes === "string") {
2408
- if (item.attributes === "[object Object]") {
2409
- itemAttributes = {};
2410
- } else {
2411
- try {
2412
- itemAttributes = JSON.parse(item.attributes);
2413
- } catch {
2414
- itemAttributes = {};
2415
- }
2416
- }
2417
- } else if (typeof item.attributes === "object") {
2418
- itemAttributes = item.attributes;
2419
- }
2420
- }
2421
- return Object.entries(attributes).every(([key, value]) => itemAttributes[key] === value);
2422
- } catch (e) {
2423
- this.logger.warn("Failed to parse attributes during filtering", { item, error: e });
2424
- return false;
2425
- }
2426
- });
2427
- }
2428
- if (dateRange?.start) {
2429
- filteredData = filteredData.filter((item) => {
2430
- const itemDate = new Date(item.createdAt);
2431
- return itemDate >= dateRange.start;
2432
- });
2433
- }
2434
- if (dateRange?.end) {
2435
- filteredData = filteredData.filter((item) => {
2436
- const itemDate = new Date(item.createdAt);
2437
- return itemDate <= dateRange.end;
2438
- });
2439
- }
2440
- const total = filteredData.length;
2441
- const start = page * perPage;
2442
- const end = start + perPage;
2443
- const paginatedData = filteredData.slice(start, end);
2444
- const traces = paginatedData.map((item) => {
2445
- let attributes2;
2446
- if (item.attributes) {
2447
- if (typeof item.attributes === "string") {
2448
- if (item.attributes === "[object Object]") {
2449
- attributes2 = void 0;
2450
- } else {
2451
- try {
2452
- attributes2 = JSON.parse(item.attributes);
2453
- } catch {
2454
- attributes2 = void 0;
2455
- }
2456
- }
2457
- } else if (typeof item.attributes === "object") {
2458
- attributes2 = item.attributes;
2459
- }
2238
+ perPage: perPageForResponse,
2239
+ hasMore: end < total
2460
2240
  }
2461
- let status;
2462
- if (item.status) {
2463
- if (typeof item.status === "string") {
2464
- try {
2465
- status = JSON.parse(item.status);
2466
- } catch {
2467
- status = void 0;
2468
- }
2469
- } else if (typeof item.status === "object") {
2470
- status = item.status;
2471
- }
2472
- }
2473
- let events;
2474
- if (item.events) {
2475
- if (typeof item.events === "string") {
2476
- try {
2477
- events = JSON.parse(item.events);
2478
- } catch {
2479
- events = void 0;
2480
- }
2481
- } else if (Array.isArray(item.events)) {
2482
- events = item.events;
2483
- }
2484
- }
2485
- let links;
2486
- if (item.links) {
2487
- if (typeof item.links === "string") {
2488
- try {
2489
- links = JSON.parse(item.links);
2490
- } catch {
2491
- links = void 0;
2492
- }
2493
- } else if (Array.isArray(item.links)) {
2494
- links = item.links;
2495
- }
2496
- }
2497
- return {
2498
- id: item.id,
2499
- parentSpanId: item.parentSpanId,
2500
- name: item.name,
2501
- traceId: item.traceId,
2502
- scope: item.scope,
2503
- kind: item.kind,
2504
- attributes: attributes2,
2505
- status,
2506
- events,
2507
- links,
2508
- other: item.other,
2509
- startTime: item.startTime,
2510
- endTime: item.endTime,
2511
- createdAt: item.createdAt
2512
- };
2513
- });
2514
- return {
2515
- traces,
2516
- total,
2517
- page,
2518
- perPage,
2519
- hasMore: end < total
2520
2241
  };
2521
2242
  } catch (error$1) {
2522
2243
  throw new error.MastraError(
2523
2244
  {
2524
- id: "STORAGE_DYNAMODB_STORE_GET_TRACES_PAGINATED_FAILED",
2245
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_SCORES_BY_SPAN", "FAILED"),
2525
2246
  domain: error.ErrorDomain.STORAGE,
2526
- category: error.ErrorCategory.THIRD_PARTY
2247
+ category: error.ErrorCategory.THIRD_PARTY,
2248
+ details: { traceId, spanId, page: pagination.page, perPage: pagination.perPage }
2527
2249
  },
2528
2250
  error$1
2529
2251
  );
@@ -2546,15 +2268,31 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2546
2268
  super();
2547
2269
  this.service = service;
2548
2270
  }
2271
+ updateWorkflowResults({
2272
+ // workflowName,
2273
+ // runId,
2274
+ // stepId,
2275
+ // result,
2276
+ // requestContext,
2277
+ }) {
2278
+ throw new Error("Method not implemented.");
2279
+ }
2280
+ updateWorkflowState({
2281
+ // workflowName,
2282
+ // runId,
2283
+ // opts,
2284
+ }) {
2285
+ throw new Error("Method not implemented.");
2286
+ }
2549
2287
  // Workflow operations
2550
2288
  async persistWorkflowSnapshot({
2551
2289
  workflowName,
2552
2290
  runId,
2291
+ resourceId,
2553
2292
  snapshot
2554
2293
  }) {
2555
2294
  this.logger.debug("Persisting workflow snapshot", { workflowName, runId });
2556
2295
  try {
2557
- const resourceId = "resourceId" in snapshot ? snapshot.resourceId : void 0;
2558
2296
  const now = (/* @__PURE__ */ new Date()).toISOString();
2559
2297
  const data = {
2560
2298
  entity: "workflow_snapshot",
@@ -2562,7 +2300,6 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2562
2300
  workflow_name: workflowName,
2563
2301
  run_id: runId,
2564
2302
  snapshot: JSON.stringify(snapshot),
2565
- // Stringify the snapshot object
2566
2303
  createdAt: now,
2567
2304
  updatedAt: now,
2568
2305
  resourceId
@@ -2571,7 +2308,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2571
2308
  } catch (error$1) {
2572
2309
  throw new error.MastraError(
2573
2310
  {
2574
- id: "STORAGE_DYNAMODB_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
2311
+ id: storage.createStorageErrorId("DYNAMODB", "PERSIST_WORKFLOW_SNAPSHOT", "FAILED"),
2575
2312
  domain: error.ErrorDomain.STORAGE,
2576
2313
  category: error.ErrorCategory.THIRD_PARTY,
2577
2314
  details: { workflowName, runId }
@@ -2599,7 +2336,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2599
2336
  } catch (error$1) {
2600
2337
  throw new error.MastraError(
2601
2338
  {
2602
- id: "STORAGE_DYNAMODB_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
2339
+ id: storage.createStorageErrorId("DYNAMODB", "LOAD_WORKFLOW_SNAPSHOT", "FAILED"),
2603
2340
  domain: error.ErrorDomain.STORAGE,
2604
2341
  category: error.ErrorCategory.THIRD_PARTY,
2605
2342
  details: { workflowName, runId }
@@ -2608,11 +2345,24 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2608
2345
  );
2609
2346
  }
2610
2347
  }
2611
- async getWorkflowRuns(args) {
2348
+ async listWorkflowRuns(args) {
2612
2349
  this.logger.debug("Getting workflow runs", { args });
2613
2350
  try {
2614
- const limit = args?.limit || 10;
2615
- const offset = args?.offset || 0;
2351
+ const perPage = args?.perPage !== void 0 ? args.perPage : 10;
2352
+ const page = args?.page !== void 0 ? args.page : 0;
2353
+ if (page < 0) {
2354
+ throw new error.MastraError(
2355
+ {
2356
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_WORKFLOW_RUNS", "INVALID_PAGE"),
2357
+ domain: error.ErrorDomain.STORAGE,
2358
+ category: error.ErrorCategory.USER,
2359
+ details: { page }
2360
+ },
2361
+ new Error("page must be >= 0")
2362
+ );
2363
+ }
2364
+ const normalizedPerPage = storage.normalizePerPage(perPage, 10);
2365
+ const offset = page * normalizedPerPage;
2616
2366
  let query;
2617
2367
  if (args?.workflowName) {
2618
2368
  query = this.service.entities.workflow_snapshot.query.primary({
@@ -2634,6 +2384,11 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2634
2384
  });
2635
2385
  if (pageResults.data && pageResults.data.length > 0) {
2636
2386
  let pageFilteredData = pageResults.data;
2387
+ if (args?.status) {
2388
+ pageFilteredData = pageFilteredData.filter((snapshot) => {
2389
+ return snapshot.snapshot.status === args.status;
2390
+ });
2391
+ }
2637
2392
  if (args?.fromDate || args?.toDate) {
2638
2393
  pageFilteredData = pageFilteredData.filter((snapshot) => {
2639
2394
  const createdAt = new Date(snapshot.createdAt);
@@ -2659,7 +2414,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2659
2414
  return { runs: [], total: 0 };
2660
2415
  }
2661
2416
  const total = allMatchingSnapshots.length;
2662
- const paginatedData = allMatchingSnapshots.slice(offset, offset + limit);
2417
+ const paginatedData = allMatchingSnapshots.slice(offset, offset + normalizedPerPage);
2663
2418
  const runs = paginatedData.map((snapshot) => formatWorkflowRun(snapshot));
2664
2419
  return {
2665
2420
  runs,
@@ -2668,7 +2423,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2668
2423
  } catch (error$1) {
2669
2424
  throw new error.MastraError(
2670
2425
  {
2671
- id: "STORAGE_DYNAMODB_STORE_GET_WORKFLOW_RUNS_FAILED",
2426
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_WORKFLOW_RUNS", "FAILED"),
2672
2427
  domain: error.ErrorDomain.STORAGE,
2673
2428
  category: error.ErrorCategory.THIRD_PARTY,
2674
2429
  details: { workflowName: args?.workflowName || "", resourceId: args?.resourceId || "" }
@@ -2680,8 +2435,6 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2680
2435
  async getWorkflowRunById(args) {
2681
2436
  const { runId, workflowName } = args;
2682
2437
  this.logger.debug("Getting workflow run by ID", { runId, workflowName });
2683
- console.log("workflowName", workflowName);
2684
- console.log("runId", runId);
2685
2438
  try {
2686
2439
  if (workflowName) {
2687
2440
  this.logger.debug("WorkflowName provided, using direct GET operation.");
@@ -2691,7 +2444,6 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2691
2444
  workflow_name: workflowName,
2692
2445
  run_id: runId
2693
2446
  }).go();
2694
- console.log("result", result2);
2695
2447
  if (!result2.data) {
2696
2448
  return null;
2697
2449
  }
@@ -2725,7 +2477,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2725
2477
  } catch (error$1) {
2726
2478
  throw new error.MastraError(
2727
2479
  {
2728
- id: "STORAGE_DYNAMODB_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
2480
+ id: storage.createStorageErrorId("DYNAMODB", "GET_WORKFLOW_RUN_BY_ID", "FAILED"),
2729
2481
  domain: error.ErrorDomain.STORAGE,
2730
2482
  category: error.ErrorCategory.THIRD_PARTY,
2731
2483
  details: { runId, workflowName: args?.workflowName || "" }
@@ -2744,7 +2496,7 @@ var DynamoDBStore = class extends storage.MastraStorage {
2744
2496
  hasInitialized = null;
2745
2497
  stores;
2746
2498
  constructor({ name, config }) {
2747
- super({ name });
2499
+ super({ id: config.id, name, disableInit: config.disableInit });
2748
2500
  try {
2749
2501
  if (!config.tableName || typeof config.tableName !== "string" || config.tableName.trim() === "") {
2750
2502
  throw new Error("DynamoDBStore: config.tableName must be provided and cannot be empty.");
@@ -2767,14 +2519,11 @@ var DynamoDBStore = class extends storage.MastraStorage {
2767
2519
  tableName: this.tableName,
2768
2520
  client: this.client
2769
2521
  });
2770
- const traces = new TracesStorageDynamoDB({ service: this.service, operations });
2771
2522
  const workflows = new WorkflowStorageDynamoDB({ service: this.service });
2772
2523
  const memory = new MemoryStorageDynamoDB({ service: this.service });
2773
2524
  const scores = new ScoresStorageDynamoDB({ service: this.service });
2774
2525
  this.stores = {
2775
2526
  operations,
2776
- legacyEvals: new LegacyEvalsDynamoDB({ service: this.service, tableName: this.tableName }),
2777
- traces,
2778
2527
  workflows,
2779
2528
  memory,
2780
2529
  scores
@@ -2782,7 +2531,7 @@ var DynamoDBStore = class extends storage.MastraStorage {
2782
2531
  } catch (error$1) {
2783
2532
  throw new error.MastraError(
2784
2533
  {
2785
- id: "STORAGE_DYNAMODB_STORE_CONSTRUCTOR_FAILED",
2534
+ id: storage.createStorageErrorId("DYNAMODB", "CONSTRUCTOR", "FAILED"),
2786
2535
  domain: error.ErrorDomain.STORAGE,
2787
2536
  category: error.ErrorCategory.USER
2788
2537
  },
@@ -2796,7 +2545,8 @@ var DynamoDBStore = class extends storage.MastraStorage {
2796
2545
  resourceWorkingMemory: true,
2797
2546
  hasColumn: false,
2798
2547
  createTable: false,
2799
- deleteMessages: false
2548
+ deleteMessages: false,
2549
+ listScoresBySpan: true
2800
2550
  };
2801
2551
  }
2802
2552
  /**
@@ -2817,7 +2567,7 @@ var DynamoDBStore = class extends storage.MastraStorage {
2817
2567
  }
2818
2568
  throw new error.MastraError(
2819
2569
  {
2820
- id: "STORAGE_DYNAMODB_STORE_VALIDATE_TABLE_EXISTS_FAILED",
2570
+ id: storage.createStorageErrorId("DYNAMODB", "VALIDATE_TABLE_EXISTS", "FAILED"),
2821
2571
  domain: error.ErrorDomain.STORAGE,
2822
2572
  category: error.ErrorCategory.THIRD_PARTY,
2823
2573
  details: { tableName: this.tableName }
@@ -2840,7 +2590,7 @@ var DynamoDBStore = class extends storage.MastraStorage {
2840
2590
  } catch (error$1) {
2841
2591
  throw new error.MastraError(
2842
2592
  {
2843
- id: "STORAGE_DYNAMODB_STORE_INIT_FAILED",
2593
+ id: storage.createStorageErrorId("DYNAMODB", "INIT", "FAILED"),
2844
2594
  domain: error.ErrorDomain.STORAGE,
2845
2595
  category: error.ErrorCategory.THIRD_PARTY,
2846
2596
  details: { tableName: this.tableName }
@@ -2891,9 +2641,6 @@ var DynamoDBStore = class extends storage.MastraStorage {
2891
2641
  async getThreadById({ threadId }) {
2892
2642
  return this.stores.memory.getThreadById({ threadId });
2893
2643
  }
2894
- async getThreadsByResourceId({ resourceId }) {
2895
- return this.stores.memory.getThreadsByResourceId({ resourceId });
2896
- }
2897
2644
  async saveThread({ thread }) {
2898
2645
  return this.stores.memory.saveThread({ thread });
2899
2646
  }
@@ -2907,43 +2654,39 @@ var DynamoDBStore = class extends storage.MastraStorage {
2907
2654
  async deleteThread({ threadId }) {
2908
2655
  return this.stores.memory.deleteThread({ threadId });
2909
2656
  }
2910
- async getMessages({
2911
- threadId,
2912
- resourceId,
2913
- selectBy,
2914
- format
2915
- }) {
2916
- return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format });
2657
+ async listMessagesById(args) {
2658
+ return this.stores.memory.listMessagesById(args);
2917
2659
  }
2918
2660
  async saveMessages(args) {
2919
2661
  return this.stores.memory.saveMessages(args);
2920
2662
  }
2921
- async getThreadsByResourceIdPaginated(args) {
2922
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
2923
- }
2924
- async getMessagesPaginated(args) {
2925
- return this.stores.memory.getMessagesPaginated(args);
2926
- }
2927
2663
  async updateMessages(_args) {
2928
2664
  return this.stores.memory.updateMessages(_args);
2929
2665
  }
2930
- // Trace operations
2931
- async getTraces(args) {
2932
- return this.stores.traces.getTraces(args);
2933
- }
2934
- async batchTraceInsert({ records }) {
2935
- return this.stores.traces.batchTraceInsert({ records });
2666
+ // Workflow operations
2667
+ async updateWorkflowResults({
2668
+ workflowName,
2669
+ runId,
2670
+ stepId,
2671
+ result,
2672
+ requestContext
2673
+ }) {
2674
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
2936
2675
  }
2937
- async getTracesPaginated(_args) {
2938
- return this.stores.traces.getTracesPaginated(_args);
2676
+ async updateWorkflowState({
2677
+ workflowName,
2678
+ runId,
2679
+ opts
2680
+ }) {
2681
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2939
2682
  }
2940
- // Workflow operations
2941
2683
  async persistWorkflowSnapshot({
2942
2684
  workflowName,
2943
2685
  runId,
2686
+ resourceId,
2944
2687
  snapshot
2945
2688
  }) {
2946
- return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2689
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
2947
2690
  }
2948
2691
  async loadWorkflowSnapshot({
2949
2692
  workflowName,
@@ -2951,8 +2694,8 @@ var DynamoDBStore = class extends storage.MastraStorage {
2951
2694
  }) {
2952
2695
  return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
2953
2696
  }
2954
- async getWorkflowRuns(args) {
2955
- return this.stores.workflows.getWorkflowRuns(args);
2697
+ async listWorkflowRuns(args) {
2698
+ return this.stores.workflows.listWorkflowRuns(args);
2956
2699
  }
2957
2700
  async getWorkflowRunById(args) {
2958
2701
  return this.stores.workflows.getWorkflowRunById(args);
@@ -2970,13 +2713,6 @@ var DynamoDBStore = class extends storage.MastraStorage {
2970
2713
  }) {
2971
2714
  return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
2972
2715
  }
2973
- // Eval operations
2974
- async getEvalsByAgentName(agentName, type) {
2975
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2976
- }
2977
- async getEvals(options) {
2978
- return this.stores.legacyEvals.getEvals(options);
2979
- }
2980
2716
  /**
2981
2717
  * Closes the DynamoDB client connection and cleans up resources.
2982
2718
  * Should be called when the store is no longer needed, e.g., at the end of tests or application shutdown.
@@ -2989,7 +2725,7 @@ var DynamoDBStore = class extends storage.MastraStorage {
2989
2725
  } catch (error$1) {
2990
2726
  throw new error.MastraError(
2991
2727
  {
2992
- id: "STORAGE_DYNAMODB_STORE_CLOSE_FAILED",
2728
+ id: storage.createStorageErrorId("DYNAMODB", "CLOSE", "FAILED"),
2993
2729
  domain: error.ErrorDomain.STORAGE,
2994
2730
  category: error.ErrorCategory.THIRD_PARTY
2995
2731
  },
@@ -3003,31 +2739,41 @@ var DynamoDBStore = class extends storage.MastraStorage {
3003
2739
  async getScoreById({ id: _id }) {
3004
2740
  return this.stores.scores.getScoreById({ id: _id });
3005
2741
  }
3006
- async saveScore(_score) {
3007
- return this.stores.scores.saveScore(_score);
2742
+ async saveScore(score) {
2743
+ return this.stores.scores.saveScore(score);
3008
2744
  }
3009
- async getScoresByRunId({
2745
+ async listScoresByRunId({
3010
2746
  runId: _runId,
3011
2747
  pagination: _pagination
3012
2748
  }) {
3013
- return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
2749
+ return this.stores.scores.listScoresByRunId({ runId: _runId, pagination: _pagination });
3014
2750
  }
3015
- async getScoresByEntityId({
2751
+ async listScoresByEntityId({
3016
2752
  entityId: _entityId,
3017
2753
  entityType: _entityType,
3018
2754
  pagination: _pagination
3019
2755
  }) {
3020
- return this.stores.scores.getScoresByEntityId({
2756
+ return this.stores.scores.listScoresByEntityId({
3021
2757
  entityId: _entityId,
3022
2758
  entityType: _entityType,
3023
2759
  pagination: _pagination
3024
2760
  });
3025
2761
  }
3026
- async getScoresByScorerId({
3027
- scorerId: _scorerId,
3028
- pagination: _pagination
2762
+ async listScoresByScorerId({
2763
+ scorerId,
2764
+ source,
2765
+ entityId,
2766
+ entityType,
2767
+ pagination
2768
+ }) {
2769
+ return this.stores.scores.listScoresByScorerId({ scorerId, source, entityId, entityType, pagination });
2770
+ }
2771
+ async listScoresBySpan({
2772
+ traceId,
2773
+ spanId,
2774
+ pagination
3029
2775
  }) {
3030
- return this.stores.scores.getScoresByScorerId({ scorerId: _scorerId, pagination: _pagination });
2776
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
3031
2777
  }
3032
2778
  };
3033
2779