@mastra/dynamodb 0.0.0-toolOptionTypes-20250917085558 → 0.0.0-top-level-fix-20251211111608

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -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 }) {
@@ -1124,17 +957,17 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1124
957
  };
1125
958
  }
1126
959
  // Helper function to transform and sort threads
1127
- transformAndSortThreads(rawThreads, orderBy, sortDirection) {
960
+ transformAndSortThreads(rawThreads, field, direction) {
1128
961
  return rawThreads.map((data) => ({
1129
962
  ...data,
1130
963
  // Convert date strings back to Date objects for consistency
1131
964
  createdAt: typeof data.createdAt === "string" ? new Date(data.createdAt) : data.createdAt,
1132
965
  updatedAt: typeof data.updatedAt === "string" ? new Date(data.updatedAt) : data.updatedAt
1133
966
  })).sort((a, b) => {
1134
- const fieldA = orderBy === "createdAt" ? a.createdAt : a.updatedAt;
1135
- const fieldB = orderBy === "createdAt" ? b.createdAt : b.updatedAt;
967
+ const fieldA = field === "createdAt" ? a.createdAt : a.updatedAt;
968
+ const fieldB = field === "createdAt" ? b.createdAt : b.updatedAt;
1136
969
  const comparison = fieldA.getTime() - fieldB.getTime();
1137
- return sortDirection === "DESC" ? -comparison : comparison;
970
+ return direction === "DESC" ? -comparison : comparison;
1138
971
  });
1139
972
  }
1140
973
  async getThreadById({ threadId }) {
@@ -1156,7 +989,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1156
989
  } catch (error$1) {
1157
990
  throw new error.MastraError(
1158
991
  {
1159
- id: "STORAGE_DYNAMODB_STORE_GET_THREAD_BY_ID_FAILED",
992
+ id: storage.createStorageErrorId("DYNAMODB", "GET_THREAD_BY_ID", "FAILED"),
1160
993
  domain: error.ErrorDomain.STORAGE,
1161
994
  category: error.ErrorCategory.THIRD_PARTY,
1162
995
  details: { threadId }
@@ -1165,32 +998,6 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1165
998
  );
1166
999
  }
1167
1000
  }
1168
- /**
1169
- * @deprecated use getThreadsByResourceIdPaginated instead for paginated results.
1170
- */
1171
- async getThreadsByResourceId(args) {
1172
- const resourceId = args.resourceId;
1173
- const orderBy = this.castThreadOrderBy(args.orderBy);
1174
- const sortDirection = this.castThreadSortDirection(args.sortDirection);
1175
- this.logger.debug("Getting threads by resource ID", { resourceId, orderBy, sortDirection });
1176
- try {
1177
- const result = await this.service.entities.thread.query.byResource({ entity: "thread", resourceId }).go();
1178
- if (!result.data.length) {
1179
- return [];
1180
- }
1181
- return this.transformAndSortThreads(result.data, orderBy, sortDirection);
1182
- } catch (error$1) {
1183
- throw new error.MastraError(
1184
- {
1185
- id: "STORAGE_DYNAMODB_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
1186
- domain: error.ErrorDomain.STORAGE,
1187
- category: error.ErrorCategory.THIRD_PARTY,
1188
- details: { resourceId }
1189
- },
1190
- error$1
1191
- );
1192
- }
1193
- }
1194
1001
  async saveThread({ thread }) {
1195
1002
  this.logger.debug("Saving thread", { threadId: thread.id });
1196
1003
  const now = /* @__PURE__ */ new Date();
@@ -1210,13 +1017,13 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1210
1017
  resourceId: thread.resourceId,
1211
1018
  title: threadData.title,
1212
1019
  createdAt: thread.createdAt || now,
1213
- updatedAt: now,
1020
+ updatedAt: thread.updatedAt || now,
1214
1021
  metadata: thread.metadata
1215
1022
  };
1216
1023
  } catch (error$1) {
1217
1024
  throw new error.MastraError(
1218
1025
  {
1219
- id: "STORAGE_DYNAMODB_STORE_SAVE_THREAD_FAILED",
1026
+ id: storage.createStorageErrorId("DYNAMODB", "SAVE_THREAD", "FAILED"),
1220
1027
  domain: error.ErrorDomain.STORAGE,
1221
1028
  category: error.ErrorCategory.THIRD_PARTY,
1222
1029
  details: { threadId: thread.id }
@@ -1258,7 +1065,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1258
1065
  } catch (error$1) {
1259
1066
  throw new error.MastraError(
1260
1067
  {
1261
- id: "STORAGE_DYNAMODB_STORE_UPDATE_THREAD_FAILED",
1068
+ id: storage.createStorageErrorId("DYNAMODB", "UPDATE_THREAD", "FAILED"),
1262
1069
  domain: error.ErrorDomain.STORAGE,
1263
1070
  category: error.ErrorCategory.THIRD_PARTY,
1264
1071
  details: { threadId: id }
@@ -1270,7 +1077,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1270
1077
  async deleteThread({ threadId }) {
1271
1078
  this.logger.debug("Deleting thread", { threadId });
1272
1079
  try {
1273
- const messages = await this.getMessages({ threadId });
1080
+ const { messages } = await this.listMessages({ threadId, perPage: false });
1274
1081
  if (messages.length > 0) {
1275
1082
  const batchSize = 25;
1276
1083
  for (let i = 0; i < messages.length; i += batchSize) {
@@ -1290,7 +1097,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1290
1097
  } catch (error$1) {
1291
1098
  throw new error.MastraError(
1292
1099
  {
1293
- id: "STORAGE_DYNAMODB_STORE_DELETE_THREAD_FAILED",
1100
+ id: storage.createStorageErrorId("DYNAMODB", "DELETE_THREAD", "FAILED"),
1294
1101
  domain: error.ErrorDomain.STORAGE,
1295
1102
  category: error.ErrorCategory.THIRD_PARTY,
1296
1103
  details: { threadId }
@@ -1299,104 +1106,176 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1299
1106
  );
1300
1107
  }
1301
1108
  }
1302
- async getMessages({
1303
- threadId,
1304
- resourceId,
1305
- selectBy,
1306
- format
1307
- }) {
1308
- 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: [] };
1309
1112
  try {
1310
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1311
- const messages = [];
1312
- const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: Number.MAX_SAFE_INTEGER });
1313
- if (selectBy?.include?.length) {
1314
- const includeMessages = await this._getIncludedMessages(threadId, selectBy);
1315
- if (includeMessages) {
1316
- messages.push(...includeMessages);
1317
- }
1318
- }
1319
- if (limit !== 0) {
1320
- const query = this.service.entities.message.query.byThread({ entity: "message", threadId });
1321
- let results;
1322
- if (limit !== Number.MAX_SAFE_INTEGER && limit > 0) {
1323
- results = await query.go({ limit, order: "desc" });
1324
- results.data = results.data.reverse();
1325
- } else {
1326
- results = await query.go();
1327
- }
1328
- let allThreadMessages = results.data.map((data) => this.parseMessageData(data)).filter((msg) => "content" in msg);
1329
- allThreadMessages.sort((a, b) => {
1330
- const timeA = a.createdAt.getTime();
1331
- const timeB = b.createdAt.getTime();
1332
- if (timeA === timeB) {
1333
- return a.id.localeCompare(b.id);
1334
- }
1335
- return timeA - timeB;
1336
- });
1337
- messages.push(...allThreadMessages);
1338
- }
1339
- messages.sort((a, b) => {
1340
- const timeA = a.createdAt.getTime();
1341
- const timeB = b.createdAt.getTime();
1342
- if (timeA === timeB) {
1343
- return a.id.localeCompare(b.id);
1344
- }
1345
- return timeA - timeB;
1346
- });
1347
- const uniqueMessages = messages.filter(
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(
1348
1119
  (message, index, self) => index === self.findIndex((m) => m.id === message.id)
1349
1120
  );
1350
- const list = new agent.MessageList({ threadId, resourceId }).add(uniqueMessages, "memory");
1351
- if (format === `v2`) return list.get.all.v2();
1352
- return list.get.all.v1();
1121
+ const list = new agent.MessageList().add(uniqueMessages, "memory");
1122
+ return { messages: list.get.all.db() };
1353
1123
  } catch (error$1) {
1354
1124
  throw new error.MastraError(
1355
1125
  {
1356
- id: "STORAGE_DYNAMODB_STORE_GET_MESSAGES_FAILED",
1126
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_MESSAGES_BY_ID", "FAILED"),
1357
1127
  domain: error.ErrorDomain.STORAGE,
1358
1128
  category: error.ErrorCategory.THIRD_PARTY,
1359
- details: { threadId, resourceId: resourceId ?? "" }
1129
+ details: { messageIds: JSON.stringify(messageIds) }
1360
1130
  },
1361
1131
  error$1
1362
1132
  );
1363
1133
  }
1364
1134
  }
1365
- async getMessagesById({
1366
- messageIds,
1367
- format
1368
- }) {
1369
- this.logger.debug("Getting messages by ID", { messageIds });
1370
- if (messageIds.length === 0) return [];
1371
- try {
1372
- const results = await Promise.all(
1373
- messageIds.map((id) => this.service.entities.message.query.primary({ entity: "message", id }).go())
1374
- );
1375
- const data = results.map((result) => result.data).flat(1);
1376
- let parsedMessages = data.map((data2) => this.parseMessageData(data2)).filter((msg) => "content" in msg);
1377
- const uniqueMessages = parsedMessages.filter(
1378
- (message, index, self) => index === self.findIndex((m) => m.id === message.id)
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")
1379
1147
  );
1380
- const list = new agent.MessageList().add(uniqueMessages, "memory");
1381
- if (format === `v1`) return list.get.all.v1();
1382
- return list.get.all.v2();
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
+ );
1162
+ }
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;
1187
+ }
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;
1193
+ });
1194
+ }
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) {
1199
+ return a.id.localeCompare(b.id);
1200
+ }
1201
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
1202
+ });
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
+ };
1383
1250
  } catch (error$1) {
1384
- throw new error.MastraError(
1251
+ const mastraError = new error.MastraError(
1385
1252
  {
1386
- id: "STORAGE_DYNAMODB_STORE_GET_MESSAGES_BY_ID_FAILED",
1253
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_MESSAGES", "FAILED"),
1387
1254
  domain: error.ErrorDomain.STORAGE,
1388
1255
  category: error.ErrorCategory.THIRD_PARTY,
1389
- details: { messageIds: JSON.stringify(messageIds) }
1256
+ details: {
1257
+ threadId: Array.isArray(threadId) ? threadId.join(",") : threadId,
1258
+ resourceId: resourceId ?? ""
1259
+ }
1390
1260
  },
1391
1261
  error$1
1392
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
+ };
1393
1272
  }
1394
1273
  }
1395
1274
  async saveMessages(args) {
1396
- const { messages, format = "v1" } = args;
1275
+ const { messages } = args;
1397
1276
  this.logger.debug("Saving messages", { count: messages.length });
1398
1277
  if (!messages.length) {
1399
- return [];
1278
+ return { messages: [] };
1400
1279
  }
1401
1280
  const threadId = messages[0]?.threadId;
1402
1281
  if (!threadId) {
@@ -1450,12 +1329,11 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1450
1329
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1451
1330
  }).go();
1452
1331
  const list = new agent.MessageList().add(messages, "memory");
1453
- if (format === `v1`) return list.get.all.v1();
1454
- return list.get.all.v2();
1332
+ return { messages: list.get.all.db() };
1455
1333
  } catch (error$1) {
1456
1334
  throw new error.MastraError(
1457
1335
  {
1458
- id: "STORAGE_DYNAMODB_STORE_SAVE_MESSAGES_FAILED",
1336
+ id: storage.createStorageErrorId("DYNAMODB", "SAVE_MESSAGES", "FAILED"),
1459
1337
  domain: error.ErrorDomain.STORAGE,
1460
1338
  category: error.ErrorCategory.THIRD_PARTY,
1461
1339
  details: { count: messages.length }
@@ -1464,37 +1342,48 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1464
1342
  );
1465
1343
  }
1466
1344
  }
1467
- async getThreadsByResourceIdPaginated(args) {
1468
- const { resourceId, page = 0, perPage = 100 } = args;
1469
- const orderBy = this.castThreadOrderBy(args.orderBy);
1470
- const sortDirection = this.castThreadSortDirection(args.sortDirection);
1345
+ async listThreadsByResourceId(args) {
1346
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
1347
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1348
+ if (page < 0) {
1349
+ throw new error.MastraError(
1350
+ {
1351
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_THREADS_BY_RESOURCE_ID", "INVALID_PAGE"),
1352
+ domain: error.ErrorDomain.STORAGE,
1353
+ category: error.ErrorCategory.USER,
1354
+ details: { page }
1355
+ },
1356
+ new Error("page must be >= 0")
1357
+ );
1358
+ }
1359
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1360
+ const { field, direction } = this.parseOrderBy(orderBy);
1471
1361
  this.logger.debug("Getting threads by resource ID with pagination", {
1472
1362
  resourceId,
1473
1363
  page,
1474
1364
  perPage,
1475
- orderBy,
1476
- sortDirection
1365
+ field,
1366
+ direction
1477
1367
  });
1478
1368
  try {
1479
1369
  const query = this.service.entities.thread.query.byResource({ entity: "thread", resourceId });
1480
1370
  const results = await query.go();
1481
- const allThreads = this.transformAndSortThreads(results.data, orderBy, sortDirection);
1482
- const startIndex = page * perPage;
1483
- const endIndex = startIndex + perPage;
1484
- const paginatedThreads = allThreads.slice(startIndex, endIndex);
1371
+ const allThreads = this.transformAndSortThreads(results.data, field, direction);
1372
+ const endIndex = offset + perPage;
1373
+ const paginatedThreads = allThreads.slice(offset, endIndex);
1485
1374
  const total = allThreads.length;
1486
- const hasMore = endIndex < total;
1375
+ const hasMore = offset + perPage < total;
1487
1376
  return {
1488
1377
  threads: paginatedThreads,
1489
1378
  total,
1490
1379
  page,
1491
- perPage,
1380
+ perPage: perPageForResponse,
1492
1381
  hasMore
1493
1382
  };
1494
1383
  } catch (error$1) {
1495
1384
  throw new error.MastraError(
1496
1385
  {
1497
- id: "STORAGE_DYNAMODB_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
1386
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_THREADS_BY_RESOURCE_ID", "FAILED"),
1498
1387
  domain: error.ErrorDomain.STORAGE,
1499
1388
  category: error.ErrorCategory.THIRD_PARTY,
1500
1389
  details: { resourceId, page, perPage }
@@ -1503,98 +1392,24 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1503
1392
  );
1504
1393
  }
1505
1394
  }
1506
- async getMessagesPaginated(args) {
1507
- const { threadId, resourceId, selectBy, format = "v1" } = args;
1508
- const { page = 0, perPage = 40, dateRange } = selectBy?.pagination || {};
1509
- const fromDate = dateRange?.start;
1510
- const toDate = dateRange?.end;
1511
- const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: Number.MAX_SAFE_INTEGER });
1512
- this.logger.debug("Getting messages with pagination", { threadId, page, perPage, fromDate, toDate, limit });
1513
- try {
1514
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1515
- let messages = [];
1516
- if (selectBy?.include?.length) {
1517
- const includeMessages = await this._getIncludedMessages(threadId, selectBy);
1518
- if (includeMessages) {
1519
- messages.push(...includeMessages);
1520
- }
1521
- }
1522
- if (limit !== 0) {
1523
- const query = this.service.entities.message.query.byThread({ entity: "message", threadId });
1524
- let results;
1525
- if (limit !== Number.MAX_SAFE_INTEGER && limit > 0) {
1526
- results = await query.go({ limit, order: "desc" });
1527
- results.data = results.data.reverse();
1528
- } else {
1529
- results = await query.go();
1530
- }
1531
- let allThreadMessages = results.data.map((data) => this.parseMessageData(data)).filter((msg) => "content" in msg);
1532
- allThreadMessages.sort((a, b) => {
1533
- const timeA = a.createdAt.getTime();
1534
- const timeB = b.createdAt.getTime();
1535
- if (timeA === timeB) {
1536
- return a.id.localeCompare(b.id);
1537
- }
1538
- return timeA - timeB;
1539
- });
1540
- const excludeIds = messages.map((m) => m.id);
1541
- if (excludeIds.length > 0) {
1542
- allThreadMessages = allThreadMessages.filter((msg) => !excludeIds.includes(msg.id));
1543
- }
1544
- messages.push(...allThreadMessages);
1545
- }
1546
- messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
1547
- if (fromDate || toDate) {
1548
- messages = messages.filter((msg) => {
1549
- const createdAt = new Date(msg.createdAt).getTime();
1550
- if (fromDate && createdAt < new Date(fromDate).getTime()) return false;
1551
- if (toDate && createdAt > new Date(toDate).getTime()) return false;
1552
- return true;
1553
- });
1554
- }
1555
- const total = messages.length;
1556
- const start = page * perPage;
1557
- const end = start + perPage;
1558
- const paginatedMessages = messages.slice(start, end);
1559
- const hasMore = end < total;
1560
- const list = new agent.MessageList({ threadId, resourceId }).add(paginatedMessages, "memory");
1561
- const finalMessages = format === "v2" ? list.get.all.v2() : list.get.all.v1();
1562
- return {
1563
- messages: finalMessages,
1564
- total,
1565
- page,
1566
- perPage,
1567
- hasMore
1568
- };
1569
- } catch (error$1) {
1570
- const mastraError = new error.MastraError(
1571
- {
1572
- id: "STORAGE_DYNAMODB_STORE_GET_MESSAGES_PAGINATED_FAILED",
1573
- domain: error.ErrorDomain.STORAGE,
1574
- category: error.ErrorCategory.THIRD_PARTY,
1575
- details: { threadId, resourceId: resourceId ?? "" }
1576
- },
1577
- error$1
1578
- );
1579
- this.logger?.trackException?.(mastraError);
1580
- this.logger?.error?.(mastraError.toString());
1581
- return { messages: [], total: 0, page, perPage, hasMore: false };
1582
- }
1583
- }
1584
1395
  // Helper method to get included messages with context
1585
- async _getIncludedMessages(threadId, selectBy) {
1586
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1396
+ async _getIncludedMessages(selectBy) {
1587
1397
  if (!selectBy?.include?.length) {
1588
1398
  return [];
1589
1399
  }
1590
1400
  const includeMessages = [];
1591
1401
  for (const includeItem of selectBy.include) {
1592
1402
  try {
1593
- const { id, threadId: targetThreadId, withPreviousMessages = 0, withNextMessages = 0 } = includeItem;
1594
- 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;
1595
1411
  this.logger.debug("Getting included messages for", {
1596
1412
  id,
1597
- targetThreadId,
1598
1413
  searchThreadId,
1599
1414
  withPreviousMessages,
1600
1415
  withNextMessages
@@ -1617,7 +1432,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1617
1432
  });
1618
1433
  const targetIndex = allMessages.findIndex((msg) => msg.id === id);
1619
1434
  if (targetIndex === -1) {
1620
- this.logger.warn("Target message not found", { id, threadId: searchThreadId });
1435
+ this.logger.warn("Target message not found in thread", { id, threadId: searchThreadId });
1621
1436
  continue;
1622
1437
  }
1623
1438
  this.logger.debug("Found target message at index", { id, targetIndex, totalMessages: allMessages.length });
@@ -1702,7 +1517,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1702
1517
  } catch (error$1) {
1703
1518
  throw new error.MastraError(
1704
1519
  {
1705
- id: "STORAGE_DYNAMODB_STORE_UPDATE_MESSAGES_FAILED",
1520
+ id: storage.createStorageErrorId("DYNAMODB", "UPDATE_MESSAGES", "FAILED"),
1706
1521
  domain: error.ErrorDomain.STORAGE,
1707
1522
  category: error.ErrorCategory.THIRD_PARTY,
1708
1523
  details: { count: messages.length }
@@ -1731,7 +1546,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1731
1546
  } catch (error$1) {
1732
1547
  throw new error.MastraError(
1733
1548
  {
1734
- id: "STORAGE_DYNAMODB_STORE_GET_RESOURCE_BY_ID_FAILED",
1549
+ id: storage.createStorageErrorId("DYNAMODB", "GET_RESOURCE_BY_ID", "FAILED"),
1735
1550
  domain: error.ErrorDomain.STORAGE,
1736
1551
  category: error.ErrorCategory.THIRD_PARTY,
1737
1552
  details: { resourceId }
@@ -1763,7 +1578,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1763
1578
  } catch (error$1) {
1764
1579
  throw new error.MastraError(
1765
1580
  {
1766
- id: "STORAGE_DYNAMODB_STORE_SAVE_RESOURCE_FAILED",
1581
+ id: storage.createStorageErrorId("DYNAMODB", "SAVE_RESOURCE", "FAILED"),
1767
1582
  domain: error.ErrorDomain.STORAGE,
1768
1583
  category: error.ErrorCategory.THIRD_PARTY,
1769
1584
  details: { resourceId: resource.id }
@@ -1812,7 +1627,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1812
1627
  } catch (error$1) {
1813
1628
  throw new error.MastraError(
1814
1629
  {
1815
- id: "STORAGE_DYNAMODB_STORE_UPDATE_RESOURCE_FAILED",
1630
+ id: storage.createStorageErrorId("DYNAMODB", "UPDATE_RESOURCE", "FAILED"),
1816
1631
  domain: error.ErrorDomain.STORAGE,
1817
1632
  category: error.ErrorCategory.THIRD_PARTY,
1818
1633
  details: { resourceId }
@@ -1847,11 +1662,11 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
1847
1662
  [storage.TABLE_THREADS]: "thread",
1848
1663
  [storage.TABLE_MESSAGES]: "message",
1849
1664
  [storage.TABLE_WORKFLOW_SNAPSHOT]: "workflow_snapshot",
1850
- [storage.TABLE_EVALS]: "eval",
1851
1665
  [storage.TABLE_SCORERS]: "score",
1852
1666
  [storage.TABLE_TRACES]: "trace",
1853
1667
  [storage.TABLE_RESOURCES]: "resource",
1854
- [storage.TABLE_AI_SPANS]: "ai_span"
1668
+ [storage.TABLE_SPANS]: "ai_span",
1669
+ mastra_agents: "agent"
1855
1670
  };
1856
1671
  return mapping[tableName] || null;
1857
1672
  }
@@ -1913,7 +1728,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
1913
1728
  }
1914
1729
  throw new error.MastraError(
1915
1730
  {
1916
- id: "STORAGE_DYNAMODB_STORE_VALIDATE_TABLE_EXISTS_FAILED",
1731
+ id: storage.createStorageErrorId("DYNAMODB", "VALIDATE_TABLE_EXISTS", "FAILED"),
1917
1732
  domain: error.ErrorDomain.STORAGE,
1918
1733
  category: error.ErrorCategory.THIRD_PARTY,
1919
1734
  details: { tableName: this.tableName }
@@ -1946,7 +1761,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
1946
1761
  this.logger.error("Error validating table access", { tableName: this.tableName, error: error$1 });
1947
1762
  throw new error.MastraError(
1948
1763
  {
1949
- id: "STORAGE_DYNAMODB_STORE_VALIDATE_TABLE_ACCESS_FAILED",
1764
+ id: storage.createStorageErrorId("DYNAMODB", "VALIDATE_TABLE_ACCESS", "FAILED"),
1950
1765
  domain: error.ErrorDomain.STORAGE,
1951
1766
  category: error.ErrorCategory.THIRD_PARTY,
1952
1767
  details: { tableName: this.tableName }
@@ -1960,7 +1775,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
1960
1775
  const entityName = this.getEntityNameForTable(tableName);
1961
1776
  if (!entityName || !this.service.entities[entityName]) {
1962
1777
  throw new error.MastraError({
1963
- id: "STORAGE_DYNAMODB_STORE_INSERT_INVALID_ARGS",
1778
+ id: storage.createStorageErrorId("DYNAMODB", "INSERT", "INVALID_ARGS"),
1964
1779
  domain: error.ErrorDomain.STORAGE,
1965
1780
  category: error.ErrorCategory.USER,
1966
1781
  text: "No entity defined for tableName",
@@ -1973,7 +1788,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
1973
1788
  } catch (error$1) {
1974
1789
  throw new error.MastraError(
1975
1790
  {
1976
- id: "STORAGE_DYNAMODB_STORE_INSERT_FAILED",
1791
+ id: storage.createStorageErrorId("DYNAMODB", "INSERT", "FAILED"),
1977
1792
  domain: error.ErrorDomain.STORAGE,
1978
1793
  category: error.ErrorCategory.THIRD_PARTY,
1979
1794
  details: { tableName }
@@ -1992,7 +1807,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
1992
1807
  const entityName = this.getEntityNameForTable(tableName);
1993
1808
  if (!entityName || !this.service.entities[entityName]) {
1994
1809
  throw new error.MastraError({
1995
- id: "STORAGE_DYNAMODB_STORE_CLEAR_TABLE_INVALID_ARGS",
1810
+ id: storage.createStorageErrorId("DYNAMODB", "CLEAR_TABLE", "INVALID_ARGS"),
1996
1811
  domain: error.ErrorDomain.STORAGE,
1997
1812
  category: error.ErrorCategory.USER,
1998
1813
  text: "No entity defined for tableName",
@@ -2036,6 +1851,10 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
2036
1851
  if (!item.id) throw new Error(`Missing required key 'id' for entity 'score'`);
2037
1852
  key.id = item.id;
2038
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;
2039
1858
  default:
2040
1859
  this.logger.warn(`Unknown entity type encountered during clearTable: ${entityName}`);
2041
1860
  throw new Error(`Cannot construct delete key for unknown entity type: ${entityName}`);
@@ -2051,7 +1870,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
2051
1870
  } catch (error$1) {
2052
1871
  throw new error.MastraError(
2053
1872
  {
2054
- id: "STORAGE_DYNAMODB_STORE_CLEAR_TABLE_FAILED",
1873
+ id: storage.createStorageErrorId("DYNAMODB", "CLEAR_TABLE", "FAILED"),
2055
1874
  domain: error.ErrorDomain.STORAGE,
2056
1875
  category: error.ErrorCategory.THIRD_PARTY,
2057
1876
  details: { tableName }
@@ -2068,7 +1887,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
2068
1887
  const entityName = this.getEntityNameForTable(tableName);
2069
1888
  if (!entityName || !this.service.entities[entityName]) {
2070
1889
  throw new error.MastraError({
2071
- id: "STORAGE_DYNAMODB_STORE_BATCH_INSERT_INVALID_ARGS",
1890
+ id: storage.createStorageErrorId("DYNAMODB", "BATCH_INSERT", "INVALID_ARGS"),
2072
1891
  domain: error.ErrorDomain.STORAGE,
2073
1892
  category: error.ErrorCategory.USER,
2074
1893
  text: "No entity defined for tableName",
@@ -2096,7 +1915,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
2096
1915
  } catch (error$1) {
2097
1916
  throw new error.MastraError(
2098
1917
  {
2099
- id: "STORAGE_DYNAMODB_STORE_BATCH_INSERT_FAILED",
1918
+ id: storage.createStorageErrorId("DYNAMODB", "BATCH_INSERT", "FAILED"),
2100
1919
  domain: error.ErrorDomain.STORAGE,
2101
1920
  category: error.ErrorCategory.THIRD_PARTY,
2102
1921
  details: { tableName }
@@ -2113,7 +1932,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
2113
1932
  const entityName = this.getEntityNameForTable(tableName);
2114
1933
  if (!entityName || !this.service.entities[entityName]) {
2115
1934
  throw new error.MastraError({
2116
- id: "STORAGE_DYNAMODB_STORE_LOAD_INVALID_ARGS",
1935
+ id: storage.createStorageErrorId("DYNAMODB", "LOAD", "INVALID_ARGS"),
2117
1936
  domain: error.ErrorDomain.STORAGE,
2118
1937
  category: error.ErrorCategory.USER,
2119
1938
  text: "No entity defined for tableName",
@@ -2131,7 +1950,7 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
2131
1950
  } catch (error$1) {
2132
1951
  throw new error.MastraError(
2133
1952
  {
2134
- id: "STORAGE_DYNAMODB_STORE_LOAD_FAILED",
1953
+ id: storage.createStorageErrorId("DYNAMODB", "LOAD", "FAILED"),
2135
1954
  domain: error.ErrorDomain.STORAGE,
2136
1955
  category: error.ErrorCategory.THIRD_PARTY,
2137
1956
  details: { tableName }
@@ -2147,14 +1966,28 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2147
1966
  super();
2148
1967
  this.service = service;
2149
1968
  }
2150
- // 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
+ */
2151
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;
2152
1987
  return {
2153
- ...data,
2154
- // Convert date strings back to Date objects for consistency
1988
+ ...result,
2155
1989
  createdAt: data.createdAt ? new Date(data.createdAt) : /* @__PURE__ */ new Date(),
2156
1990
  updatedAt: data.updatedAt ? new Date(data.updatedAt) : /* @__PURE__ */ new Date()
2157
- // JSON fields are already transformed by the entity's getters
2158
1991
  };
2159
1992
  }
2160
1993
  async getScoreById({ id }) {
@@ -2168,7 +2001,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2168
2001
  } catch (error$1) {
2169
2002
  throw new error.MastraError(
2170
2003
  {
2171
- id: "STORAGE_DYNAMODB_STORE_GET_SCORE_BY_ID_FAILED",
2004
+ id: storage.createStorageErrorId("DYNAMODB", "GET_SCORE_BY_ID", "FAILED"),
2172
2005
  domain: error.ErrorDomain.STORAGE,
2173
2006
  category: error.ErrorCategory.THIRD_PARTY,
2174
2007
  details: { id }
@@ -2178,50 +2011,69 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2178
2011
  }
2179
2012
  }
2180
2013
  async saveScore(score) {
2181
- 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
+ }
2182
2034
  const now = /* @__PURE__ */ new Date();
2183
- const scoreId = `score-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
2184
- const scoreData = {
2185
- entity: "score",
2186
- id: scoreId,
2187
- scorerId: score.scorerId,
2188
- traceId: score.traceId || "",
2189
- runId: score.runId,
2190
- scorer: typeof score.scorer === "string" ? score.scorer : JSON.stringify(score.scorer),
2191
- preprocessStepResult: typeof score.preprocessStepResult === "string" ? score.preprocessStepResult : JSON.stringify(score.preprocessStepResult),
2192
- analyzeStepResult: typeof score.analyzeStepResult === "string" ? score.analyzeStepResult : JSON.stringify(score.analyzeStepResult),
2193
- score: score.score,
2194
- reason: score.reason,
2195
- preprocessPrompt: score.preprocessPrompt,
2196
- generateScorePrompt: score.generateScorePrompt,
2197
- analyzePrompt: score.analyzePrompt,
2198
- reasonPrompt: score.reasonPrompt,
2199
- input: typeof score.input === "string" ? score.input : JSON.stringify(score.input),
2200
- output: typeof score.output === "string" ? score.output : JSON.stringify(score.output),
2201
- additionalContext: typeof score.additionalContext === "string" ? score.additionalContext : JSON.stringify(score.additionalContext),
2202
- runtimeContext: typeof score.runtimeContext === "string" ? score.runtimeContext : JSON.stringify(score.runtimeContext),
2203
- entityType: score.entityType,
2204
- entityData: typeof score.entity === "string" ? score.entity : JSON.stringify(score.entity),
2205
- entityId: score.entityId,
2206
- source: score.source,
2207
- resourceId: score.resourceId || "",
2208
- threadId: score.threadId || "",
2209
- createdAt: now.toISOString(),
2210
- updatedAt: now.toISOString()
2211
- };
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
+ );
2212
2063
  try {
2213
2064
  await this.service.entities.score.upsert(scoreData).go();
2214
- const savedScore = {
2215
- ...score,
2216
- id: scoreId,
2217
- createdAt: now,
2218
- updatedAt: now
2065
+ return {
2066
+ score: {
2067
+ ...validatedScore,
2068
+ id: scoreId,
2069
+ createdAt: now,
2070
+ updatedAt: now
2071
+ }
2219
2072
  };
2220
- return { score: savedScore };
2221
2073
  } catch (error$1) {
2222
2074
  throw new error.MastraError(
2223
2075
  {
2224
- id: "STORAGE_DYNAMODB_STORE_SAVE_SCORE_FAILED",
2076
+ id: storage.createStorageErrorId("DYNAMODB", "SAVE_SCORE", "FAILED"),
2225
2077
  domain: error.ErrorDomain.STORAGE,
2226
2078
  category: error.ErrorCategory.THIRD_PARTY,
2227
2079
  details: { scorerId: score.scorerId, runId: score.runId }
@@ -2230,7 +2082,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2230
2082
  );
2231
2083
  }
2232
2084
  }
2233
- async getScoresByScorerId({
2085
+ async listScoresByScorerId({
2234
2086
  scorerId,
2235
2087
  pagination,
2236
2088
  entityId,
@@ -2251,24 +2103,25 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2251
2103
  allScores = allScores.filter((score) => score.source === source);
2252
2104
  }
2253
2105
  allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2254
- const startIndex = pagination.page * pagination.perPage;
2255
- const endIndex = startIndex + pagination.perPage;
2256
- 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);
2257
2109
  const total = allScores.length;
2258
- const hasMore = endIndex < total;
2110
+ const end = perPageInput === false ? allScores.length : start + perPage;
2111
+ const paginatedScores = allScores.slice(start, end);
2259
2112
  return {
2260
2113
  scores: paginatedScores,
2261
2114
  pagination: {
2262
2115
  total,
2263
- page: pagination.page,
2264
- perPage: pagination.perPage,
2265
- hasMore
2116
+ page,
2117
+ perPage: perPageForResponse,
2118
+ hasMore: end < total
2266
2119
  }
2267
2120
  };
2268
2121
  } catch (error$1) {
2269
2122
  throw new error.MastraError(
2270
2123
  {
2271
- id: "STORAGE_DYNAMODB_STORE_GET_SCORES_BY_SCORER_ID_FAILED",
2124
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_SCORES_BY_SCORER_ID", "FAILED"),
2272
2125
  domain: error.ErrorDomain.STORAGE,
2273
2126
  category: error.ErrorCategory.THIRD_PARTY,
2274
2127
  details: {
@@ -2284,7 +2137,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2284
2137
  );
2285
2138
  }
2286
2139
  }
2287
- async getScoresByRunId({
2140
+ async listScoresByRunId({
2288
2141
  runId,
2289
2142
  pagination
2290
2143
  }) {
@@ -2294,24 +2147,25 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2294
2147
  const results = await query.go();
2295
2148
  const allScores = results.data.map((data) => this.parseScoreData(data));
2296
2149
  allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2297
- const startIndex = pagination.page * pagination.perPage;
2298
- const endIndex = startIndex + pagination.perPage;
2299
- 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);
2300
2153
  const total = allScores.length;
2301
- const hasMore = endIndex < total;
2154
+ const end = perPageInput === false ? allScores.length : start + perPage;
2155
+ const paginatedScores = allScores.slice(start, end);
2302
2156
  return {
2303
2157
  scores: paginatedScores,
2304
2158
  pagination: {
2305
2159
  total,
2306
- page: pagination.page,
2307
- perPage: pagination.perPage,
2308
- hasMore
2160
+ page,
2161
+ perPage: perPageForResponse,
2162
+ hasMore: end < total
2309
2163
  }
2310
2164
  };
2311
2165
  } catch (error$1) {
2312
2166
  throw new error.MastraError(
2313
2167
  {
2314
- id: "STORAGE_DYNAMODB_STORE_GET_SCORES_BY_RUN_ID_FAILED",
2168
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_SCORES_BY_RUN_ID", "FAILED"),
2315
2169
  domain: error.ErrorDomain.STORAGE,
2316
2170
  category: error.ErrorCategory.THIRD_PARTY,
2317
2171
  details: { runId, page: pagination.page, perPage: pagination.perPage }
@@ -2320,7 +2174,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2320
2174
  );
2321
2175
  }
2322
2176
  }
2323
- async getScoresByEntityId({
2177
+ async listScoresByEntityId({
2324
2178
  entityId,
2325
2179
  entityType,
2326
2180
  pagination
@@ -2332,24 +2186,25 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2332
2186
  let allScores = results.data.map((data) => this.parseScoreData(data));
2333
2187
  allScores = allScores.filter((score) => score.entityType === entityType);
2334
2188
  allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2335
- const startIndex = pagination.page * pagination.perPage;
2336
- const endIndex = startIndex + pagination.perPage;
2337
- 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);
2338
2192
  const total = allScores.length;
2339
- const hasMore = endIndex < total;
2193
+ const end = perPageInput === false ? allScores.length : start + perPage;
2194
+ const paginatedScores = allScores.slice(start, end);
2340
2195
  return {
2341
2196
  scores: paginatedScores,
2342
2197
  pagination: {
2343
2198
  total,
2344
- page: pagination.page,
2345
- perPage: pagination.perPage,
2346
- hasMore
2199
+ page,
2200
+ perPage: perPageForResponse,
2201
+ hasMore: end < total
2347
2202
  }
2348
2203
  };
2349
2204
  } catch (error$1) {
2350
2205
  throw new error.MastraError(
2351
2206
  {
2352
- id: "STORAGE_DYNAMODB_STORE_GET_SCORES_BY_ENTITY_ID_FAILED",
2207
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_SCORES_BY_ENTITY_ID", "FAILED"),
2353
2208
  domain: error.ErrorDomain.STORAGE,
2354
2209
  category: error.ErrorCategory.THIRD_PARTY,
2355
2210
  details: { entityId, entityType, page: pagination.page, perPage: pagination.perPage }
@@ -2358,234 +2213,39 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2358
2213
  );
2359
2214
  }
2360
2215
  }
2361
- };
2362
- var TracesStorageDynamoDB = class extends storage.TracesStorage {
2363
- service;
2364
- operations;
2365
- constructor({ service, operations }) {
2366
- super();
2367
- this.service = service;
2368
- this.operations = operations;
2369
- }
2370
- // Trace operations
2371
- async getTraces(args) {
2372
- const { name, scope, page, perPage } = args;
2373
- this.logger.debug("Getting traces", { name, scope, page, perPage });
2374
- try {
2375
- let query;
2376
- if (name) {
2377
- query = this.service.entities.trace.query.byName({ entity: "trace", name });
2378
- } else if (scope) {
2379
- query = this.service.entities.trace.query.byScope({ entity: "trace", scope });
2380
- } else {
2381
- this.logger.warn("Performing a scan operation on traces - consider using a more specific query");
2382
- query = this.service.entities.trace.scan;
2383
- }
2384
- let items = [];
2385
- let cursor = null;
2386
- let pagesFetched = 0;
2387
- const startPage = page > 0 ? page : 1;
2388
- do {
2389
- const results = await query.go({ cursor, limit: perPage });
2390
- pagesFetched++;
2391
- if (pagesFetched === startPage) {
2392
- items = results.data;
2393
- break;
2394
- }
2395
- cursor = results.cursor;
2396
- if (!cursor && results.data.length > 0 && pagesFetched < startPage) {
2397
- break;
2398
- }
2399
- } while (cursor && pagesFetched < startPage);
2400
- return items;
2401
- } catch (error$1) {
2402
- throw new error.MastraError(
2403
- {
2404
- id: "STORAGE_DYNAMODB_STORE_GET_TRACES_FAILED",
2405
- domain: error.ErrorDomain.STORAGE,
2406
- category: error.ErrorCategory.THIRD_PARTY
2407
- },
2408
- error$1
2409
- );
2410
- }
2411
- }
2412
- async batchTraceInsert({ records }) {
2413
- this.logger.debug("Batch inserting traces", { count: records.length });
2414
- if (!records.length) {
2415
- return;
2416
- }
2417
- try {
2418
- const recordsToSave = records.map((rec) => ({ entity: "trace", ...rec }));
2419
- await this.operations.batchInsert({
2420
- tableName: storage.TABLE_TRACES,
2421
- records: recordsToSave
2422
- // Pass records with 'entity' included
2423
- });
2424
- } catch (error$1) {
2425
- throw new error.MastraError(
2426
- {
2427
- id: "STORAGE_DYNAMODB_STORE_BATCH_TRACE_INSERT_FAILED",
2428
- domain: error.ErrorDomain.STORAGE,
2429
- category: error.ErrorCategory.THIRD_PARTY,
2430
- details: { count: records.length }
2431
- },
2432
- error$1
2433
- );
2434
- }
2435
- }
2436
- async getTracesPaginated(args) {
2437
- const { name, scope, page = 0, perPage = 100, attributes, filters, dateRange } = args;
2438
- 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 });
2439
2222
  try {
2440
- let query;
2441
- if (name) {
2442
- query = this.service.entities.trace.query.byName({ entity: "trace", name });
2443
- } else if (scope) {
2444
- query = this.service.entities.trace.query.byScope({ entity: "trace", scope });
2445
- } else {
2446
- this.logger.warn("Performing a scan operation on traces - consider using a more specific query");
2447
- query = this.service.entities.trace.scan;
2448
- }
2449
- const results = await query.go({
2450
- order: "desc",
2451
- pages: "all"
2452
- // Get all pages to apply filtering and pagination
2453
- });
2454
- if (!results.data.length) {
2455
- return {
2456
- traces: [],
2457
- 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,
2458
2237
  page,
2459
- perPage,
2460
- hasMore: false
2461
- };
2462
- }
2463
- let filteredData = results.data;
2464
- if (attributes) {
2465
- filteredData = filteredData.filter((item) => {
2466
- try {
2467
- let itemAttributes = {};
2468
- if (item.attributes) {
2469
- if (typeof item.attributes === "string") {
2470
- if (item.attributes === "[object Object]") {
2471
- itemAttributes = {};
2472
- } else {
2473
- try {
2474
- itemAttributes = JSON.parse(item.attributes);
2475
- } catch {
2476
- itemAttributes = {};
2477
- }
2478
- }
2479
- } else if (typeof item.attributes === "object") {
2480
- itemAttributes = item.attributes;
2481
- }
2482
- }
2483
- return Object.entries(attributes).every(([key, value]) => itemAttributes[key] === value);
2484
- } catch (e) {
2485
- this.logger.warn("Failed to parse attributes during filtering", { item, error: e });
2486
- return false;
2487
- }
2488
- });
2489
- }
2490
- if (dateRange?.start) {
2491
- filteredData = filteredData.filter((item) => {
2492
- const itemDate = new Date(item.createdAt);
2493
- return itemDate >= dateRange.start;
2494
- });
2495
- }
2496
- if (dateRange?.end) {
2497
- filteredData = filteredData.filter((item) => {
2498
- const itemDate = new Date(item.createdAt);
2499
- return itemDate <= dateRange.end;
2500
- });
2501
- }
2502
- const total = filteredData.length;
2503
- const start = page * perPage;
2504
- const end = start + perPage;
2505
- const paginatedData = filteredData.slice(start, end);
2506
- const traces = paginatedData.map((item) => {
2507
- let attributes2;
2508
- if (item.attributes) {
2509
- if (typeof item.attributes === "string") {
2510
- if (item.attributes === "[object Object]") {
2511
- attributes2 = void 0;
2512
- } else {
2513
- try {
2514
- attributes2 = JSON.parse(item.attributes);
2515
- } catch {
2516
- attributes2 = void 0;
2517
- }
2518
- }
2519
- } else if (typeof item.attributes === "object") {
2520
- attributes2 = item.attributes;
2521
- }
2522
- }
2523
- let status;
2524
- if (item.status) {
2525
- if (typeof item.status === "string") {
2526
- try {
2527
- status = JSON.parse(item.status);
2528
- } catch {
2529
- status = void 0;
2530
- }
2531
- } else if (typeof item.status === "object") {
2532
- status = item.status;
2533
- }
2238
+ perPage: perPageForResponse,
2239
+ hasMore: end < total
2534
2240
  }
2535
- let events;
2536
- if (item.events) {
2537
- if (typeof item.events === "string") {
2538
- try {
2539
- events = JSON.parse(item.events);
2540
- } catch {
2541
- events = void 0;
2542
- }
2543
- } else if (Array.isArray(item.events)) {
2544
- events = item.events;
2545
- }
2546
- }
2547
- let links;
2548
- if (item.links) {
2549
- if (typeof item.links === "string") {
2550
- try {
2551
- links = JSON.parse(item.links);
2552
- } catch {
2553
- links = void 0;
2554
- }
2555
- } else if (Array.isArray(item.links)) {
2556
- links = item.links;
2557
- }
2558
- }
2559
- return {
2560
- id: item.id,
2561
- parentSpanId: item.parentSpanId,
2562
- name: item.name,
2563
- traceId: item.traceId,
2564
- scope: item.scope,
2565
- kind: item.kind,
2566
- attributes: attributes2,
2567
- status,
2568
- events,
2569
- links,
2570
- other: item.other,
2571
- startTime: item.startTime,
2572
- endTime: item.endTime,
2573
- createdAt: item.createdAt
2574
- };
2575
- });
2576
- return {
2577
- traces,
2578
- total,
2579
- page,
2580
- perPage,
2581
- hasMore: end < total
2582
2241
  };
2583
2242
  } catch (error$1) {
2584
2243
  throw new error.MastraError(
2585
2244
  {
2586
- id: "STORAGE_DYNAMODB_STORE_GET_TRACES_PAGINATED_FAILED",
2245
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_SCORES_BY_SPAN", "FAILED"),
2587
2246
  domain: error.ErrorDomain.STORAGE,
2588
- category: error.ErrorCategory.THIRD_PARTY
2247
+ category: error.ErrorCategory.THIRD_PARTY,
2248
+ details: { traceId, spanId, page: pagination.page, perPage: pagination.perPage }
2589
2249
  },
2590
2250
  error$1
2591
2251
  );
@@ -2613,7 +2273,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2613
2273
  // runId,
2614
2274
  // stepId,
2615
2275
  // result,
2616
- // runtimeContext,
2276
+ // requestContext,
2617
2277
  }) {
2618
2278
  throw new Error("Method not implemented.");
2619
2279
  }
@@ -2640,7 +2300,6 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2640
2300
  workflow_name: workflowName,
2641
2301
  run_id: runId,
2642
2302
  snapshot: JSON.stringify(snapshot),
2643
- // Stringify the snapshot object
2644
2303
  createdAt: now,
2645
2304
  updatedAt: now,
2646
2305
  resourceId
@@ -2649,7 +2308,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2649
2308
  } catch (error$1) {
2650
2309
  throw new error.MastraError(
2651
2310
  {
2652
- id: "STORAGE_DYNAMODB_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
2311
+ id: storage.createStorageErrorId("DYNAMODB", "PERSIST_WORKFLOW_SNAPSHOT", "FAILED"),
2653
2312
  domain: error.ErrorDomain.STORAGE,
2654
2313
  category: error.ErrorCategory.THIRD_PARTY,
2655
2314
  details: { workflowName, runId }
@@ -2677,7 +2336,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2677
2336
  } catch (error$1) {
2678
2337
  throw new error.MastraError(
2679
2338
  {
2680
- id: "STORAGE_DYNAMODB_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
2339
+ id: storage.createStorageErrorId("DYNAMODB", "LOAD_WORKFLOW_SNAPSHOT", "FAILED"),
2681
2340
  domain: error.ErrorDomain.STORAGE,
2682
2341
  category: error.ErrorCategory.THIRD_PARTY,
2683
2342
  details: { workflowName, runId }
@@ -2686,11 +2345,24 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2686
2345
  );
2687
2346
  }
2688
2347
  }
2689
- async getWorkflowRuns(args) {
2348
+ async listWorkflowRuns(args) {
2690
2349
  this.logger.debug("Getting workflow runs", { args });
2691
2350
  try {
2692
- const limit = args?.limit || 10;
2693
- 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;
2694
2366
  let query;
2695
2367
  if (args?.workflowName) {
2696
2368
  query = this.service.entities.workflow_snapshot.query.primary({
@@ -2712,6 +2384,11 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2712
2384
  });
2713
2385
  if (pageResults.data && pageResults.data.length > 0) {
2714
2386
  let pageFilteredData = pageResults.data;
2387
+ if (args?.status) {
2388
+ pageFilteredData = pageFilteredData.filter((snapshot) => {
2389
+ return snapshot.snapshot.status === args.status;
2390
+ });
2391
+ }
2715
2392
  if (args?.fromDate || args?.toDate) {
2716
2393
  pageFilteredData = pageFilteredData.filter((snapshot) => {
2717
2394
  const createdAt = new Date(snapshot.createdAt);
@@ -2737,7 +2414,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2737
2414
  return { runs: [], total: 0 };
2738
2415
  }
2739
2416
  const total = allMatchingSnapshots.length;
2740
- const paginatedData = allMatchingSnapshots.slice(offset, offset + limit);
2417
+ const paginatedData = allMatchingSnapshots.slice(offset, offset + normalizedPerPage);
2741
2418
  const runs = paginatedData.map((snapshot) => formatWorkflowRun(snapshot));
2742
2419
  return {
2743
2420
  runs,
@@ -2746,7 +2423,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2746
2423
  } catch (error$1) {
2747
2424
  throw new error.MastraError(
2748
2425
  {
2749
- id: "STORAGE_DYNAMODB_STORE_GET_WORKFLOW_RUNS_FAILED",
2426
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_WORKFLOW_RUNS", "FAILED"),
2750
2427
  domain: error.ErrorDomain.STORAGE,
2751
2428
  category: error.ErrorCategory.THIRD_PARTY,
2752
2429
  details: { workflowName: args?.workflowName || "", resourceId: args?.resourceId || "" }
@@ -2758,8 +2435,6 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2758
2435
  async getWorkflowRunById(args) {
2759
2436
  const { runId, workflowName } = args;
2760
2437
  this.logger.debug("Getting workflow run by ID", { runId, workflowName });
2761
- console.log("workflowName", workflowName);
2762
- console.log("runId", runId);
2763
2438
  try {
2764
2439
  if (workflowName) {
2765
2440
  this.logger.debug("WorkflowName provided, using direct GET operation.");
@@ -2769,7 +2444,6 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2769
2444
  workflow_name: workflowName,
2770
2445
  run_id: runId
2771
2446
  }).go();
2772
- console.log("result", result2);
2773
2447
  if (!result2.data) {
2774
2448
  return null;
2775
2449
  }
@@ -2803,7 +2477,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2803
2477
  } catch (error$1) {
2804
2478
  throw new error.MastraError(
2805
2479
  {
2806
- id: "STORAGE_DYNAMODB_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
2480
+ id: storage.createStorageErrorId("DYNAMODB", "GET_WORKFLOW_RUN_BY_ID", "FAILED"),
2807
2481
  domain: error.ErrorDomain.STORAGE,
2808
2482
  category: error.ErrorCategory.THIRD_PARTY,
2809
2483
  details: { runId, workflowName: args?.workflowName || "" }
@@ -2812,6 +2486,26 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2812
2486
  );
2813
2487
  }
2814
2488
  }
2489
+ async deleteWorkflowRunById({ runId, workflowName }) {
2490
+ this.logger.debug("Deleting workflow run by ID", { runId, workflowName });
2491
+ try {
2492
+ await this.service.entities.workflow_snapshot.delete({
2493
+ entity: "workflow_snapshot",
2494
+ workflow_name: workflowName,
2495
+ run_id: runId
2496
+ }).go();
2497
+ } catch (error$1) {
2498
+ throw new error.MastraError(
2499
+ {
2500
+ id: storage.createStorageErrorId("DYNAMODB", "DELETE_WORKFLOW_RUN_BY_ID", "FAILED"),
2501
+ domain: error.ErrorDomain.STORAGE,
2502
+ category: error.ErrorCategory.THIRD_PARTY,
2503
+ details: { runId, workflowName }
2504
+ },
2505
+ error$1
2506
+ );
2507
+ }
2508
+ }
2815
2509
  };
2816
2510
 
2817
2511
  // src/storage/index.ts
@@ -2822,7 +2516,7 @@ var DynamoDBStore = class extends storage.MastraStorage {
2822
2516
  hasInitialized = null;
2823
2517
  stores;
2824
2518
  constructor({ name, config }) {
2825
- super({ name });
2519
+ super({ id: config.id, name, disableInit: config.disableInit });
2826
2520
  try {
2827
2521
  if (!config.tableName || typeof config.tableName !== "string" || config.tableName.trim() === "") {
2828
2522
  throw new Error("DynamoDBStore: config.tableName must be provided and cannot be empty.");
@@ -2845,14 +2539,11 @@ var DynamoDBStore = class extends storage.MastraStorage {
2845
2539
  tableName: this.tableName,
2846
2540
  client: this.client
2847
2541
  });
2848
- const traces = new TracesStorageDynamoDB({ service: this.service, operations });
2849
2542
  const workflows = new WorkflowStorageDynamoDB({ service: this.service });
2850
2543
  const memory = new MemoryStorageDynamoDB({ service: this.service });
2851
2544
  const scores = new ScoresStorageDynamoDB({ service: this.service });
2852
2545
  this.stores = {
2853
2546
  operations,
2854
- legacyEvals: new LegacyEvalsDynamoDB({ service: this.service, tableName: this.tableName }),
2855
- traces,
2856
2547
  workflows,
2857
2548
  memory,
2858
2549
  scores
@@ -2860,7 +2551,7 @@ var DynamoDBStore = class extends storage.MastraStorage {
2860
2551
  } catch (error$1) {
2861
2552
  throw new error.MastraError(
2862
2553
  {
2863
- id: "STORAGE_DYNAMODB_STORE_CONSTRUCTOR_FAILED",
2554
+ id: storage.createStorageErrorId("DYNAMODB", "CONSTRUCTOR", "FAILED"),
2864
2555
  domain: error.ErrorDomain.STORAGE,
2865
2556
  category: error.ErrorCategory.USER
2866
2557
  },
@@ -2874,7 +2565,8 @@ var DynamoDBStore = class extends storage.MastraStorage {
2874
2565
  resourceWorkingMemory: true,
2875
2566
  hasColumn: false,
2876
2567
  createTable: false,
2877
- deleteMessages: false
2568
+ deleteMessages: false,
2569
+ listScoresBySpan: true
2878
2570
  };
2879
2571
  }
2880
2572
  /**
@@ -2895,7 +2587,7 @@ var DynamoDBStore = class extends storage.MastraStorage {
2895
2587
  }
2896
2588
  throw new error.MastraError(
2897
2589
  {
2898
- id: "STORAGE_DYNAMODB_STORE_VALIDATE_TABLE_EXISTS_FAILED",
2590
+ id: storage.createStorageErrorId("DYNAMODB", "VALIDATE_TABLE_EXISTS", "FAILED"),
2899
2591
  domain: error.ErrorDomain.STORAGE,
2900
2592
  category: error.ErrorCategory.THIRD_PARTY,
2901
2593
  details: { tableName: this.tableName }
@@ -2918,7 +2610,7 @@ var DynamoDBStore = class extends storage.MastraStorage {
2918
2610
  } catch (error$1) {
2919
2611
  throw new error.MastraError(
2920
2612
  {
2921
- id: "STORAGE_DYNAMODB_STORE_INIT_FAILED",
2613
+ id: storage.createStorageErrorId("DYNAMODB", "INIT", "FAILED"),
2922
2614
  domain: error.ErrorDomain.STORAGE,
2923
2615
  category: error.ErrorCategory.THIRD_PARTY,
2924
2616
  details: { tableName: this.tableName }
@@ -2969,9 +2661,6 @@ var DynamoDBStore = class extends storage.MastraStorage {
2969
2661
  async getThreadById({ threadId }) {
2970
2662
  return this.stores.memory.getThreadById({ threadId });
2971
2663
  }
2972
- async getThreadsByResourceId(args) {
2973
- return this.stores.memory.getThreadsByResourceId(args);
2974
- }
2975
2664
  async saveThread({ thread }) {
2976
2665
  return this.stores.memory.saveThread({ thread });
2977
2666
  }
@@ -2985,51 +2674,24 @@ var DynamoDBStore = class extends storage.MastraStorage {
2985
2674
  async deleteThread({ threadId }) {
2986
2675
  return this.stores.memory.deleteThread({ threadId });
2987
2676
  }
2988
- async getMessages({
2989
- threadId,
2990
- resourceId,
2991
- selectBy,
2992
- format
2993
- }) {
2994
- return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format });
2995
- }
2996
- async getMessagesById({
2997
- messageIds,
2998
- format
2999
- }) {
3000
- return this.stores.memory.getMessagesById({ messageIds, format });
2677
+ async listMessagesById(args) {
2678
+ return this.stores.memory.listMessagesById(args);
3001
2679
  }
3002
2680
  async saveMessages(args) {
3003
2681
  return this.stores.memory.saveMessages(args);
3004
2682
  }
3005
- async getThreadsByResourceIdPaginated(args) {
3006
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
3007
- }
3008
- async getMessagesPaginated(args) {
3009
- return this.stores.memory.getMessagesPaginated(args);
3010
- }
3011
2683
  async updateMessages(_args) {
3012
2684
  return this.stores.memory.updateMessages(_args);
3013
2685
  }
3014
- // Trace operations
3015
- async getTraces(args) {
3016
- return this.stores.traces.getTraces(args);
3017
- }
3018
- async batchTraceInsert({ records }) {
3019
- return this.stores.traces.batchTraceInsert({ records });
3020
- }
3021
- async getTracesPaginated(_args) {
3022
- return this.stores.traces.getTracesPaginated(_args);
3023
- }
3024
2686
  // Workflow operations
3025
2687
  async updateWorkflowResults({
3026
2688
  workflowName,
3027
2689
  runId,
3028
2690
  stepId,
3029
2691
  result,
3030
- runtimeContext
2692
+ requestContext
3031
2693
  }) {
3032
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2694
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
3033
2695
  }
3034
2696
  async updateWorkflowState({
3035
2697
  workflowName,
@@ -3052,12 +2714,15 @@ var DynamoDBStore = class extends storage.MastraStorage {
3052
2714
  }) {
3053
2715
  return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
3054
2716
  }
3055
- async getWorkflowRuns(args) {
3056
- return this.stores.workflows.getWorkflowRuns(args);
2717
+ async listWorkflowRuns(args) {
2718
+ return this.stores.workflows.listWorkflowRuns(args);
3057
2719
  }
3058
2720
  async getWorkflowRunById(args) {
3059
2721
  return this.stores.workflows.getWorkflowRunById(args);
3060
2722
  }
2723
+ async deleteWorkflowRunById({ runId, workflowName }) {
2724
+ return this.stores.workflows.deleteWorkflowRunById({ runId, workflowName });
2725
+ }
3061
2726
  async getResourceById({ resourceId }) {
3062
2727
  return this.stores.memory.getResourceById({ resourceId });
3063
2728
  }
@@ -3071,13 +2736,6 @@ var DynamoDBStore = class extends storage.MastraStorage {
3071
2736
  }) {
3072
2737
  return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
3073
2738
  }
3074
- // Eval operations
3075
- async getEvalsByAgentName(agentName, type) {
3076
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
3077
- }
3078
- async getEvals(options) {
3079
- return this.stores.legacyEvals.getEvals(options);
3080
- }
3081
2739
  /**
3082
2740
  * Closes the DynamoDB client connection and cleans up resources.
3083
2741
  * Should be called when the store is no longer needed, e.g., at the end of tests or application shutdown.
@@ -3090,7 +2748,7 @@ var DynamoDBStore = class extends storage.MastraStorage {
3090
2748
  } catch (error$1) {
3091
2749
  throw new error.MastraError(
3092
2750
  {
3093
- id: "STORAGE_DYNAMODB_STORE_CLOSE_FAILED",
2751
+ id: storage.createStorageErrorId("DYNAMODB", "CLOSE", "FAILED"),
3094
2752
  domain: error.ErrorDomain.STORAGE,
3095
2753
  category: error.ErrorCategory.THIRD_PARTY
3096
2754
  },
@@ -3104,34 +2762,41 @@ var DynamoDBStore = class extends storage.MastraStorage {
3104
2762
  async getScoreById({ id: _id }) {
3105
2763
  return this.stores.scores.getScoreById({ id: _id });
3106
2764
  }
3107
- async saveScore(_score) {
3108
- return this.stores.scores.saveScore(_score);
2765
+ async saveScore(score) {
2766
+ return this.stores.scores.saveScore(score);
3109
2767
  }
3110
- async getScoresByRunId({
2768
+ async listScoresByRunId({
3111
2769
  runId: _runId,
3112
2770
  pagination: _pagination
3113
2771
  }) {
3114
- return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
2772
+ return this.stores.scores.listScoresByRunId({ runId: _runId, pagination: _pagination });
3115
2773
  }
3116
- async getScoresByEntityId({
2774
+ async listScoresByEntityId({
3117
2775
  entityId: _entityId,
3118
2776
  entityType: _entityType,
3119
2777
  pagination: _pagination
3120
2778
  }) {
3121
- return this.stores.scores.getScoresByEntityId({
2779
+ return this.stores.scores.listScoresByEntityId({
3122
2780
  entityId: _entityId,
3123
2781
  entityType: _entityType,
3124
2782
  pagination: _pagination
3125
2783
  });
3126
2784
  }
3127
- async getScoresByScorerId({
2785
+ async listScoresByScorerId({
3128
2786
  scorerId,
3129
2787
  source,
3130
2788
  entityId,
3131
2789
  entityType,
3132
2790
  pagination
3133
2791
  }) {
3134
- return this.stores.scores.getScoresByScorerId({ scorerId, source, entityId, entityType, pagination });
2792
+ return this.stores.scores.listScoresByScorerId({ scorerId, source, entityId, entityType, pagination });
2793
+ }
2794
+ async listScoresBySpan({
2795
+ traceId,
2796
+ spanId,
2797
+ pagination
2798
+ }) {
2799
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
3135
2800
  }
3136
2801
  };
3137
2802