@mastra/dynamodb 0.15.10 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -6,7 +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 scores = require('@mastra/core/scores');
9
+ var evals = require('@mastra/core/evals');
10
10
 
11
11
  // src/storage/index.ts
12
12
 
@@ -564,7 +564,7 @@ var scoreEntity = new electrodb.Entity({
564
564
  return value;
565
565
  }
566
566
  },
567
- runtimeContext: {
567
+ requestContext: {
568
568
  type: "string",
569
569
  required: false,
570
570
  set: (value) => {
@@ -935,187 +935,6 @@ function getElectroDbService(client, tableName) {
935
935
  }
936
936
  );
937
937
  }
938
- var LegacyEvalsDynamoDB = class extends storage.LegacyEvalsStorage {
939
- service;
940
- tableName;
941
- constructor({ service, tableName }) {
942
- super();
943
- this.service = service;
944
- this.tableName = tableName;
945
- }
946
- // Eval operations
947
- async getEvalsByAgentName(agentName, type) {
948
- this.logger.debug("Getting evals for agent", { agentName, type });
949
- try {
950
- const query = this.service.entities.eval.query.byAgent({ entity: "eval", agent_name: agentName });
951
- const results = await query.go({ order: "desc", limit: 100 });
952
- if (!results.data.length) {
953
- return [];
954
- }
955
- let filteredData = results.data;
956
- if (type) {
957
- filteredData = filteredData.filter((evalRecord) => {
958
- try {
959
- const testInfo = evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0;
960
- if (type === "test" && !testInfo) {
961
- return false;
962
- }
963
- if (type === "live" && testInfo) {
964
- return false;
965
- }
966
- } catch (e) {
967
- this.logger.warn("Failed to parse test_info during filtering", { record: evalRecord, error: e });
968
- }
969
- return true;
970
- });
971
- }
972
- return filteredData.map((evalRecord) => {
973
- try {
974
- return {
975
- input: evalRecord.input,
976
- output: evalRecord.output,
977
- // Safely parse result and test_info
978
- result: evalRecord.result && typeof evalRecord.result === "string" ? JSON.parse(evalRecord.result) : void 0,
979
- agentName: evalRecord.agent_name,
980
- createdAt: evalRecord.created_at,
981
- // Keep as string from DDB?
982
- metricName: evalRecord.metric_name,
983
- instructions: evalRecord.instructions,
984
- runId: evalRecord.run_id,
985
- globalRunId: evalRecord.global_run_id,
986
- testInfo: evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0
987
- };
988
- } catch (parseError) {
989
- this.logger.error("Failed to parse eval record", { record: evalRecord, error: parseError });
990
- return {
991
- agentName: evalRecord.agent_name,
992
- createdAt: evalRecord.created_at,
993
- runId: evalRecord.run_id,
994
- globalRunId: evalRecord.global_run_id
995
- };
996
- }
997
- });
998
- } catch (error$1) {
999
- throw new error.MastraError(
1000
- {
1001
- id: "STORAGE_DYNAMODB_STORE_GET_EVALS_BY_AGENT_NAME_FAILED",
1002
- domain: error.ErrorDomain.STORAGE,
1003
- category: error.ErrorCategory.THIRD_PARTY,
1004
- details: { agentName }
1005
- },
1006
- error$1
1007
- );
1008
- }
1009
- }
1010
- async getEvals(options = {}) {
1011
- const { agentName, type, page = 0, perPage = 100, dateRange } = options;
1012
- this.logger.debug("Getting evals with pagination", { agentName, type, page, perPage, dateRange });
1013
- try {
1014
- let query;
1015
- if (agentName) {
1016
- query = this.service.entities.eval.query.byAgent({ entity: "eval", agent_name: agentName });
1017
- } else {
1018
- query = this.service.entities.eval.query.byEntity({ entity: "eval" });
1019
- }
1020
- const results = await query.go({
1021
- order: "desc",
1022
- pages: "all"
1023
- // Get all pages to apply filtering and pagination
1024
- });
1025
- if (!results.data.length) {
1026
- return {
1027
- evals: [],
1028
- total: 0,
1029
- page,
1030
- perPage,
1031
- hasMore: false
1032
- };
1033
- }
1034
- let filteredData = results.data;
1035
- if (type) {
1036
- filteredData = filteredData.filter((evalRecord) => {
1037
- try {
1038
- const testInfo = evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0;
1039
- if (type === "test" && !testInfo) {
1040
- return false;
1041
- }
1042
- if (type === "live" && testInfo) {
1043
- return false;
1044
- }
1045
- } catch (e) {
1046
- this.logger.warn("Failed to parse test_info during filtering", { record: evalRecord, error: e });
1047
- }
1048
- return true;
1049
- });
1050
- }
1051
- if (dateRange) {
1052
- const fromDate = dateRange.start;
1053
- const toDate = dateRange.end;
1054
- filteredData = filteredData.filter((evalRecord) => {
1055
- const recordDate = new Date(evalRecord.created_at);
1056
- if (fromDate && recordDate < fromDate) {
1057
- return false;
1058
- }
1059
- if (toDate && recordDate > toDate) {
1060
- return false;
1061
- }
1062
- return true;
1063
- });
1064
- }
1065
- const total = filteredData.length;
1066
- const start = page * perPage;
1067
- const end = start + perPage;
1068
- const paginatedData = filteredData.slice(start, end);
1069
- const evals = paginatedData.map((evalRecord) => {
1070
- try {
1071
- return {
1072
- input: evalRecord.input,
1073
- output: evalRecord.output,
1074
- result: evalRecord.result && typeof evalRecord.result === "string" ? JSON.parse(evalRecord.result) : void 0,
1075
- agentName: evalRecord.agent_name,
1076
- createdAt: evalRecord.created_at,
1077
- metricName: evalRecord.metric_name,
1078
- instructions: evalRecord.instructions,
1079
- runId: evalRecord.run_id,
1080
- globalRunId: evalRecord.global_run_id,
1081
- testInfo: evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0
1082
- };
1083
- } catch (parseError) {
1084
- this.logger.error("Failed to parse eval record", { record: evalRecord, error: parseError });
1085
- return {
1086
- agentName: evalRecord.agent_name,
1087
- createdAt: evalRecord.created_at,
1088
- runId: evalRecord.run_id,
1089
- globalRunId: evalRecord.global_run_id
1090
- };
1091
- }
1092
- });
1093
- const hasMore = end < total;
1094
- return {
1095
- evals,
1096
- total,
1097
- page,
1098
- perPage,
1099
- hasMore
1100
- };
1101
- } catch (error$1) {
1102
- throw new error.MastraError(
1103
- {
1104
- id: "STORAGE_DYNAMODB_STORE_GET_EVALS_FAILED",
1105
- domain: error.ErrorDomain.STORAGE,
1106
- category: error.ErrorCategory.THIRD_PARTY,
1107
- details: {
1108
- agentName: agentName || "all",
1109
- type: type || "all",
1110
- page,
1111
- perPage
1112
- }
1113
- },
1114
- error$1
1115
- );
1116
- }
1117
- }
1118
- };
1119
938
  var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1120
939
  service;
1121
940
  constructor({ service }) {
@@ -1134,17 +953,17 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1134
953
  };
1135
954
  }
1136
955
  // Helper function to transform and sort threads
1137
- transformAndSortThreads(rawThreads, orderBy, sortDirection) {
956
+ transformAndSortThreads(rawThreads, field, direction) {
1138
957
  return rawThreads.map((data) => ({
1139
958
  ...data,
1140
959
  // Convert date strings back to Date objects for consistency
1141
960
  createdAt: typeof data.createdAt === "string" ? new Date(data.createdAt) : data.createdAt,
1142
961
  updatedAt: typeof data.updatedAt === "string" ? new Date(data.updatedAt) : data.updatedAt
1143
962
  })).sort((a, b) => {
1144
- const fieldA = orderBy === "createdAt" ? a.createdAt : a.updatedAt;
1145
- const fieldB = orderBy === "createdAt" ? b.createdAt : b.updatedAt;
963
+ const fieldA = field === "createdAt" ? a.createdAt : a.updatedAt;
964
+ const fieldB = field === "createdAt" ? b.createdAt : b.updatedAt;
1146
965
  const comparison = fieldA.getTime() - fieldB.getTime();
1147
- return sortDirection === "DESC" ? -comparison : comparison;
966
+ return direction === "DESC" ? -comparison : comparison;
1148
967
  });
1149
968
  }
1150
969
  async getThreadById({ threadId }) {
@@ -1175,32 +994,6 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1175
994
  );
1176
995
  }
1177
996
  }
1178
- /**
1179
- * @deprecated use getThreadsByResourceIdPaginated instead for paginated results.
1180
- */
1181
- async getThreadsByResourceId(args) {
1182
- const resourceId = args.resourceId;
1183
- const orderBy = this.castThreadOrderBy(args.orderBy);
1184
- const sortDirection = this.castThreadSortDirection(args.sortDirection);
1185
- this.logger.debug("Getting threads by resource ID", { resourceId, orderBy, sortDirection });
1186
- try {
1187
- const result = await this.service.entities.thread.query.byResource({ entity: "thread", resourceId }).go();
1188
- if (!result.data.length) {
1189
- return [];
1190
- }
1191
- return this.transformAndSortThreads(result.data, orderBy, sortDirection);
1192
- } catch (error$1) {
1193
- throw new error.MastraError(
1194
- {
1195
- id: "STORAGE_DYNAMODB_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
1196
- domain: error.ErrorDomain.STORAGE,
1197
- category: error.ErrorCategory.THIRD_PARTY,
1198
- details: { resourceId }
1199
- },
1200
- error$1
1201
- );
1202
- }
1203
- }
1204
997
  async saveThread({ thread }) {
1205
998
  this.logger.debug("Saving thread", { threadId: thread.id });
1206
999
  const now = /* @__PURE__ */ new Date();
@@ -1220,7 +1013,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1220
1013
  resourceId: thread.resourceId,
1221
1014
  title: threadData.title,
1222
1015
  createdAt: thread.createdAt || now,
1223
- updatedAt: now,
1016
+ updatedAt: thread.updatedAt || now,
1224
1017
  metadata: thread.metadata
1225
1018
  };
1226
1019
  } catch (error$1) {
@@ -1280,7 +1073,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1280
1073
  async deleteThread({ threadId }) {
1281
1074
  this.logger.debug("Deleting thread", { threadId });
1282
1075
  try {
1283
- const messages = await this.getMessages({ threadId });
1076
+ const { messages } = await this.listMessages({ threadId, perPage: false });
1284
1077
  if (messages.length > 0) {
1285
1078
  const batchSize = 25;
1286
1079
  for (let i = 0; i < messages.length; i += batchSize) {
@@ -1309,104 +1102,175 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1309
1102
  );
1310
1103
  }
1311
1104
  }
1312
- async getMessages({
1313
- threadId,
1314
- resourceId,
1315
- selectBy,
1316
- format
1317
- }) {
1318
- this.logger.debug("Getting messages", { threadId, selectBy });
1105
+ async listMessagesById({ messageIds }) {
1106
+ this.logger.debug("Getting messages by ID", { messageIds });
1107
+ if (messageIds.length === 0) return { messages: [] };
1319
1108
  try {
1320
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1321
- const messages = [];
1322
- const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: Number.MAX_SAFE_INTEGER });
1323
- if (selectBy?.include?.length) {
1324
- const includeMessages = await this._getIncludedMessages(threadId, selectBy);
1325
- if (includeMessages) {
1326
- messages.push(...includeMessages);
1327
- }
1328
- }
1329
- if (limit !== 0) {
1330
- const query = this.service.entities.message.query.byThread({ entity: "message", threadId });
1331
- let results;
1332
- if (limit !== Number.MAX_SAFE_INTEGER && limit > 0) {
1333
- results = await query.go({ limit, order: "desc" });
1334
- results.data = results.data.reverse();
1335
- } else {
1336
- results = await query.go();
1337
- }
1338
- let allThreadMessages = results.data.map((data) => this.parseMessageData(data)).filter((msg) => "content" in msg);
1339
- allThreadMessages.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
- messages.push(...allThreadMessages);
1348
- }
1349
- messages.sort((a, b) => {
1350
- const timeA = a.createdAt.getTime();
1351
- const timeB = b.createdAt.getTime();
1352
- if (timeA === timeB) {
1353
- return a.id.localeCompare(b.id);
1354
- }
1355
- return timeA - timeB;
1356
- });
1357
- const uniqueMessages = messages.filter(
1109
+ const results = await Promise.all(
1110
+ messageIds.map((id) => this.service.entities.message.query.primary({ entity: "message", id }).go())
1111
+ );
1112
+ const data = results.map((result) => result.data).flat(1);
1113
+ let parsedMessages = data.map((data2) => this.parseMessageData(data2)).filter((msg) => "content" in msg);
1114
+ const uniqueMessages = parsedMessages.filter(
1358
1115
  (message, index, self) => index === self.findIndex((m) => m.id === message.id)
1359
1116
  );
1360
- const list = new agent.MessageList({ threadId, resourceId }).add(uniqueMessages, "memory");
1361
- if (format === `v2`) return list.get.all.v2();
1362
- return list.get.all.v1();
1117
+ const list = new agent.MessageList().add(uniqueMessages, "memory");
1118
+ return { messages: list.get.all.db() };
1363
1119
  } catch (error$1) {
1364
1120
  throw new error.MastraError(
1365
1121
  {
1366
- id: "STORAGE_DYNAMODB_STORE_GET_MESSAGES_FAILED",
1122
+ id: "STORAGE_DYNAMODB_STORE_LIST_MESSAGES_BY_ID_FAILED",
1367
1123
  domain: error.ErrorDomain.STORAGE,
1368
1124
  category: error.ErrorCategory.THIRD_PARTY,
1369
- details: { threadId, resourceId: resourceId ?? "" }
1125
+ details: { messageIds: JSON.stringify(messageIds) }
1370
1126
  },
1371
1127
  error$1
1372
1128
  );
1373
1129
  }
1374
1130
  }
1375
- async getMessagesById({
1376
- messageIds,
1377
- format
1378
- }) {
1379
- this.logger.debug("Getting messages by ID", { messageIds });
1380
- if (messageIds.length === 0) return [];
1381
- try {
1382
- const results = await Promise.all(
1383
- messageIds.map((id) => this.service.entities.message.query.primary({ entity: "message", id }).go())
1384
- );
1385
- const data = results.map((result) => result.data).flat(1);
1386
- let parsedMessages = data.map((data2) => this.parseMessageData(data2)).filter((msg) => "content" in msg);
1387
- const uniqueMessages = parsedMessages.filter(
1388
- (message, index, self) => index === self.findIndex((m) => m.id === message.id)
1131
+ async listMessages(args) {
1132
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
1133
+ if (!threadId.trim()) {
1134
+ throw new error.MastraError(
1135
+ {
1136
+ id: "STORAGE_DYNAMODB_LIST_MESSAGES_INVALID_THREAD_ID",
1137
+ domain: error.ErrorDomain.STORAGE,
1138
+ category: error.ErrorCategory.THIRD_PARTY,
1139
+ details: { threadId }
1140
+ },
1141
+ new Error("threadId must be a non-empty string")
1389
1142
  );
1390
- const list = new agent.MessageList().add(uniqueMessages, "memory");
1391
- if (format === `v1`) return list.get.all.v1();
1392
- return list.get.all.v2();
1143
+ }
1144
+ const perPage = storage.normalizePerPage(perPageInput, 40);
1145
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1146
+ try {
1147
+ if (page < 0) {
1148
+ throw new error.MastraError(
1149
+ {
1150
+ id: "STORAGE_DYNAMODB_LIST_MESSAGES_INVALID_PAGE",
1151
+ domain: error.ErrorDomain.STORAGE,
1152
+ category: error.ErrorCategory.USER,
1153
+ details: { page }
1154
+ },
1155
+ new Error("page must be >= 0")
1156
+ );
1157
+ }
1158
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
1159
+ this.logger.debug("Getting messages with listMessages", {
1160
+ threadId,
1161
+ resourceId,
1162
+ perPageInput,
1163
+ offset,
1164
+ perPage,
1165
+ page,
1166
+ field,
1167
+ direction
1168
+ });
1169
+ const query = this.service.entities.message.query.byThread({ entity: "message", threadId });
1170
+ const results = await query.go();
1171
+ let allThreadMessages = results.data.map((data) => this.parseMessageData(data)).filter((msg) => "content" in msg && typeof msg.content === "object");
1172
+ if (resourceId) {
1173
+ allThreadMessages = allThreadMessages.filter((msg) => msg.resourceId === resourceId);
1174
+ }
1175
+ if (filter?.dateRange) {
1176
+ const dateRange = filter.dateRange;
1177
+ allThreadMessages = allThreadMessages.filter((msg) => {
1178
+ const createdAt = new Date(msg.createdAt).getTime();
1179
+ if (dateRange.start) {
1180
+ const startTime = dateRange.start instanceof Date ? dateRange.start.getTime() : new Date(dateRange.start).getTime();
1181
+ if (createdAt < startTime) return false;
1182
+ }
1183
+ if (dateRange.end) {
1184
+ const endTime = dateRange.end instanceof Date ? dateRange.end.getTime() : new Date(dateRange.end).getTime();
1185
+ if (createdAt > endTime) return false;
1186
+ }
1187
+ return true;
1188
+ });
1189
+ }
1190
+ allThreadMessages.sort((a, b) => {
1191
+ const aValue = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
1192
+ const bValue = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
1193
+ if (aValue === bValue) {
1194
+ return a.id.localeCompare(b.id);
1195
+ }
1196
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
1197
+ });
1198
+ const total = allThreadMessages.length;
1199
+ const paginatedMessages = allThreadMessages.slice(offset, offset + perPage);
1200
+ const paginatedCount = paginatedMessages.length;
1201
+ if (total === 0 && paginatedCount === 0 && (!include || include.length === 0)) {
1202
+ return {
1203
+ messages: [],
1204
+ total: 0,
1205
+ page,
1206
+ perPage: perPageForResponse,
1207
+ hasMore: false
1208
+ };
1209
+ }
1210
+ const messageIds = new Set(paginatedMessages.map((m) => m.id));
1211
+ let includeMessages = [];
1212
+ if (include && include.length > 0) {
1213
+ const selectBy = { include };
1214
+ includeMessages = await this._getIncludedMessages(threadId, selectBy);
1215
+ for (const includeMsg of includeMessages) {
1216
+ if (!messageIds.has(includeMsg.id)) {
1217
+ paginatedMessages.push(includeMsg);
1218
+ messageIds.add(includeMsg.id);
1219
+ }
1220
+ }
1221
+ }
1222
+ const list = new agent.MessageList().add(paginatedMessages, "memory");
1223
+ let finalMessages = list.get.all.db();
1224
+ finalMessages = finalMessages.sort((a, b) => {
1225
+ const aValue = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
1226
+ const bValue = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
1227
+ if (aValue === bValue) {
1228
+ return a.id.localeCompare(b.id);
1229
+ }
1230
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
1231
+ });
1232
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
1233
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
1234
+ let hasMore = false;
1235
+ if (perPageInput !== false && !allThreadMessagesReturned) {
1236
+ hasMore = offset + paginatedCount < total;
1237
+ }
1238
+ return {
1239
+ messages: finalMessages,
1240
+ total,
1241
+ page,
1242
+ perPage: perPageForResponse,
1243
+ hasMore
1244
+ };
1393
1245
  } catch (error$1) {
1394
- throw new error.MastraError(
1246
+ const mastraError = new error.MastraError(
1395
1247
  {
1396
- id: "STORAGE_DYNAMODB_STORE_GET_MESSAGES_BY_ID_FAILED",
1248
+ id: "STORAGE_DYNAMODB_STORE_LIST_MESSAGES_FAILED",
1397
1249
  domain: error.ErrorDomain.STORAGE,
1398
1250
  category: error.ErrorCategory.THIRD_PARTY,
1399
- details: { messageIds: JSON.stringify(messageIds) }
1251
+ details: {
1252
+ threadId,
1253
+ resourceId: resourceId ?? ""
1254
+ }
1400
1255
  },
1401
1256
  error$1
1402
1257
  );
1258
+ this.logger?.error?.(mastraError.toString());
1259
+ this.logger?.trackException?.(mastraError);
1260
+ return {
1261
+ messages: [],
1262
+ total: 0,
1263
+ page,
1264
+ perPage: perPageForResponse,
1265
+ hasMore: false
1266
+ };
1403
1267
  }
1404
1268
  }
1405
1269
  async saveMessages(args) {
1406
- const { messages, format = "v1" } = args;
1270
+ const { messages } = args;
1407
1271
  this.logger.debug("Saving messages", { count: messages.length });
1408
1272
  if (!messages.length) {
1409
- return [];
1273
+ return { messages: [] };
1410
1274
  }
1411
1275
  const threadId = messages[0]?.threadId;
1412
1276
  if (!threadId) {
@@ -1460,8 +1324,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1460
1324
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1461
1325
  }).go();
1462
1326
  const list = new agent.MessageList().add(messages, "memory");
1463
- if (format === `v1`) return list.get.all.v1();
1464
- return list.get.all.v2();
1327
+ return { messages: list.get.all.db() };
1465
1328
  } catch (error$1) {
1466
1329
  throw new error.MastraError(
1467
1330
  {
@@ -1474,37 +1337,48 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1474
1337
  );
1475
1338
  }
1476
1339
  }
1477
- async getThreadsByResourceIdPaginated(args) {
1478
- const { resourceId, page = 0, perPage = 100 } = args;
1479
- const orderBy = this.castThreadOrderBy(args.orderBy);
1480
- const sortDirection = this.castThreadSortDirection(args.sortDirection);
1340
+ async listThreadsByResourceId(args) {
1341
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
1342
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1343
+ if (page < 0) {
1344
+ throw new error.MastraError(
1345
+ {
1346
+ id: "STORAGE_DYNAMODB_LIST_THREADS_BY_RESOURCE_ID_INVALID_PAGE",
1347
+ domain: error.ErrorDomain.STORAGE,
1348
+ category: error.ErrorCategory.USER,
1349
+ details: { page }
1350
+ },
1351
+ new Error("page must be >= 0")
1352
+ );
1353
+ }
1354
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1355
+ const { field, direction } = this.parseOrderBy(orderBy);
1481
1356
  this.logger.debug("Getting threads by resource ID with pagination", {
1482
1357
  resourceId,
1483
1358
  page,
1484
1359
  perPage,
1485
- orderBy,
1486
- sortDirection
1360
+ field,
1361
+ direction
1487
1362
  });
1488
1363
  try {
1489
1364
  const query = this.service.entities.thread.query.byResource({ entity: "thread", resourceId });
1490
1365
  const results = await query.go();
1491
- const allThreads = this.transformAndSortThreads(results.data, orderBy, sortDirection);
1492
- const startIndex = page * perPage;
1493
- const endIndex = startIndex + perPage;
1494
- const paginatedThreads = allThreads.slice(startIndex, endIndex);
1366
+ const allThreads = this.transformAndSortThreads(results.data, field, direction);
1367
+ const endIndex = offset + perPage;
1368
+ const paginatedThreads = allThreads.slice(offset, endIndex);
1495
1369
  const total = allThreads.length;
1496
- const hasMore = endIndex < total;
1370
+ const hasMore = offset + perPage < total;
1497
1371
  return {
1498
1372
  threads: paginatedThreads,
1499
1373
  total,
1500
1374
  page,
1501
- perPage,
1375
+ perPage: perPageForResponse,
1502
1376
  hasMore
1503
1377
  };
1504
1378
  } catch (error$1) {
1505
1379
  throw new error.MastraError(
1506
1380
  {
1507
- id: "STORAGE_DYNAMODB_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
1381
+ id: "DYNAMODB_STORAGE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
1508
1382
  domain: error.ErrorDomain.STORAGE,
1509
1383
  category: error.ErrorCategory.THIRD_PARTY,
1510
1384
  details: { resourceId, page, perPage }
@@ -1513,84 +1387,6 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1513
1387
  );
1514
1388
  }
1515
1389
  }
1516
- async getMessagesPaginated(args) {
1517
- const { threadId, resourceId, selectBy, format = "v1" } = args;
1518
- const { page = 0, perPage = 40, dateRange } = selectBy?.pagination || {};
1519
- const fromDate = dateRange?.start;
1520
- const toDate = dateRange?.end;
1521
- const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: Number.MAX_SAFE_INTEGER });
1522
- this.logger.debug("Getting messages with pagination", { threadId, page, perPage, fromDate, toDate, limit });
1523
- try {
1524
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1525
- let messages = [];
1526
- if (selectBy?.include?.length) {
1527
- const includeMessages = await this._getIncludedMessages(threadId, selectBy);
1528
- if (includeMessages) {
1529
- messages.push(...includeMessages);
1530
- }
1531
- }
1532
- if (limit !== 0) {
1533
- const query = this.service.entities.message.query.byThread({ entity: "message", threadId });
1534
- let results;
1535
- if (limit !== Number.MAX_SAFE_INTEGER && limit > 0) {
1536
- results = await query.go({ limit, order: "desc" });
1537
- results.data = results.data.reverse();
1538
- } else {
1539
- results = await query.go();
1540
- }
1541
- let allThreadMessages = results.data.map((data) => this.parseMessageData(data)).filter((msg) => "content" in msg);
1542
- allThreadMessages.sort((a, b) => {
1543
- const timeA = a.createdAt.getTime();
1544
- const timeB = b.createdAt.getTime();
1545
- if (timeA === timeB) {
1546
- return a.id.localeCompare(b.id);
1547
- }
1548
- return timeA - timeB;
1549
- });
1550
- const excludeIds = messages.map((m) => m.id);
1551
- if (excludeIds.length > 0) {
1552
- allThreadMessages = allThreadMessages.filter((msg) => !excludeIds.includes(msg.id));
1553
- }
1554
- messages.push(...allThreadMessages);
1555
- }
1556
- messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
1557
- if (fromDate || toDate) {
1558
- messages = messages.filter((msg) => {
1559
- const createdAt = new Date(msg.createdAt).getTime();
1560
- if (fromDate && createdAt < new Date(fromDate).getTime()) return false;
1561
- if (toDate && createdAt > new Date(toDate).getTime()) return false;
1562
- return true;
1563
- });
1564
- }
1565
- const total = messages.length;
1566
- const start = page * perPage;
1567
- const end = start + perPage;
1568
- const paginatedMessages = messages.slice(start, end);
1569
- const hasMore = end < total;
1570
- const list = new agent.MessageList({ threadId, resourceId }).add(paginatedMessages, "memory");
1571
- const finalMessages = format === "v2" ? list.get.all.v2() : list.get.all.v1();
1572
- return {
1573
- messages: finalMessages,
1574
- total,
1575
- page,
1576
- perPage,
1577
- hasMore
1578
- };
1579
- } catch (error$1) {
1580
- const mastraError = new error.MastraError(
1581
- {
1582
- id: "STORAGE_DYNAMODB_STORE_GET_MESSAGES_PAGINATED_FAILED",
1583
- domain: error.ErrorDomain.STORAGE,
1584
- category: error.ErrorCategory.THIRD_PARTY,
1585
- details: { threadId, resourceId: resourceId ?? "" }
1586
- },
1587
- error$1
1588
- );
1589
- this.logger?.trackException?.(mastraError);
1590
- this.logger?.error?.(mastraError.toString());
1591
- return { messages: [], total: 0, page, perPage, hasMore: false };
1592
- }
1593
- }
1594
1390
  // Helper method to get included messages with context
1595
1391
  async _getIncludedMessages(threadId, selectBy) {
1596
1392
  if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
@@ -1857,11 +1653,10 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
1857
1653
  [storage.TABLE_THREADS]: "thread",
1858
1654
  [storage.TABLE_MESSAGES]: "message",
1859
1655
  [storage.TABLE_WORKFLOW_SNAPSHOT]: "workflow_snapshot",
1860
- [storage.TABLE_EVALS]: "eval",
1861
1656
  [storage.TABLE_SCORERS]: "score",
1862
1657
  [storage.TABLE_TRACES]: "trace",
1863
1658
  [storage.TABLE_RESOURCES]: "resource",
1864
- [storage.TABLE_AI_SPANS]: "ai_span"
1659
+ [storage.TABLE_SPANS]: "ai_span"
1865
1660
  };
1866
1661
  return mapping[tableName] || null;
1867
1662
  }
@@ -2046,6 +1841,10 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
2046
1841
  if (!item.id) throw new Error(`Missing required key 'id' for entity 'score'`);
2047
1842
  key.id = item.id;
2048
1843
  break;
1844
+ case "resource":
1845
+ if (!item.id) throw new Error(`Missing required key 'id' for entity 'resource'`);
1846
+ key.id = item.id;
1847
+ break;
2049
1848
  default:
2050
1849
  this.logger.warn(`Unknown entity type encountered during clearTable: ${entityName}`);
2051
1850
  throw new Error(`Cannot construct delete key for unknown entity type: ${entityName}`);
@@ -2190,7 +1989,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2190
1989
  async saveScore(score) {
2191
1990
  let validatedScore;
2192
1991
  try {
2193
- validatedScore = scores.saveScorePayloadSchema.parse(score);
1992
+ validatedScore = evals.saveScorePayloadSchema.parse(score);
2194
1993
  } catch (error$1) {
2195
1994
  throw new error.MastraError(
2196
1995
  {
@@ -2222,7 +2021,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2222
2021
  input: typeof validatedScore.input === "string" ? validatedScore.input : JSON.stringify(validatedScore.input),
2223
2022
  output: typeof validatedScore.output === "string" ? validatedScore.output : JSON.stringify(validatedScore.output),
2224
2023
  additionalContext: typeof validatedScore.additionalContext === "string" ? validatedScore.additionalContext : JSON.stringify(validatedScore.additionalContext),
2225
- runtimeContext: typeof validatedScore.runtimeContext === "string" ? validatedScore.runtimeContext : JSON.stringify(validatedScore.runtimeContext),
2024
+ requestContext: typeof validatedScore.requestContext === "string" ? validatedScore.requestContext : JSON.stringify(validatedScore.requestContext),
2226
2025
  entityType: validatedScore.entityType,
2227
2026
  entityData: typeof validatedScore.entity === "string" ? validatedScore.entity : JSON.stringify(validatedScore.entity),
2228
2027
  entityId: validatedScore.entityId,
@@ -2253,7 +2052,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2253
2052
  );
2254
2053
  }
2255
2054
  }
2256
- async getScoresByScorerId({
2055
+ async listScoresByScorerId({
2257
2056
  scorerId,
2258
2057
  pagination,
2259
2058
  entityId,
@@ -2274,18 +2073,19 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2274
2073
  allScores = allScores.filter((score) => score.source === source);
2275
2074
  }
2276
2075
  allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2277
- const startIndex = pagination.page * pagination.perPage;
2278
- const endIndex = startIndex + pagination.perPage;
2279
- const paginatedScores = allScores.slice(startIndex, endIndex);
2076
+ const { page, perPage: perPageInput } = pagination;
2077
+ const perPage = storage.normalizePerPage(perPageInput, Number.MAX_SAFE_INTEGER);
2078
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2280
2079
  const total = allScores.length;
2281
- const hasMore = endIndex < total;
2080
+ const end = perPageInput === false ? allScores.length : start + perPage;
2081
+ const paginatedScores = allScores.slice(start, end);
2282
2082
  return {
2283
2083
  scores: paginatedScores,
2284
2084
  pagination: {
2285
2085
  total,
2286
- page: pagination.page,
2287
- perPage: pagination.perPage,
2288
- hasMore
2086
+ page,
2087
+ perPage: perPageForResponse,
2088
+ hasMore: end < total
2289
2089
  }
2290
2090
  };
2291
2091
  } catch (error$1) {
@@ -2307,7 +2107,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2307
2107
  );
2308
2108
  }
2309
2109
  }
2310
- async getScoresByRunId({
2110
+ async listScoresByRunId({
2311
2111
  runId,
2312
2112
  pagination
2313
2113
  }) {
@@ -2317,18 +2117,19 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2317
2117
  const results = await query.go();
2318
2118
  const allScores = results.data.map((data) => this.parseScoreData(data));
2319
2119
  allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2320
- const startIndex = pagination.page * pagination.perPage;
2321
- const endIndex = startIndex + pagination.perPage;
2322
- const paginatedScores = allScores.slice(startIndex, endIndex);
2120
+ const { page, perPage: perPageInput } = pagination;
2121
+ const perPage = storage.normalizePerPage(perPageInput, Number.MAX_SAFE_INTEGER);
2122
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2323
2123
  const total = allScores.length;
2324
- const hasMore = endIndex < total;
2124
+ const end = perPageInput === false ? allScores.length : start + perPage;
2125
+ const paginatedScores = allScores.slice(start, end);
2325
2126
  return {
2326
2127
  scores: paginatedScores,
2327
2128
  pagination: {
2328
2129
  total,
2329
- page: pagination.page,
2330
- perPage: pagination.perPage,
2331
- hasMore
2130
+ page,
2131
+ perPage: perPageForResponse,
2132
+ hasMore: end < total
2332
2133
  }
2333
2134
  };
2334
2135
  } catch (error$1) {
@@ -2343,7 +2144,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2343
2144
  );
2344
2145
  }
2345
2146
  }
2346
- async getScoresByEntityId({
2147
+ async listScoresByEntityId({
2347
2148
  entityId,
2348
2149
  entityType,
2349
2150
  pagination
@@ -2355,18 +2156,19 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2355
2156
  let allScores = results.data.map((data) => this.parseScoreData(data));
2356
2157
  allScores = allScores.filter((score) => score.entityType === entityType);
2357
2158
  allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2358
- const startIndex = pagination.page * pagination.perPage;
2359
- const endIndex = startIndex + pagination.perPage;
2360
- const paginatedScores = allScores.slice(startIndex, endIndex);
2159
+ const { page, perPage: perPageInput } = pagination;
2160
+ const perPage = storage.normalizePerPage(perPageInput, Number.MAX_SAFE_INTEGER);
2161
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2361
2162
  const total = allScores.length;
2362
- const hasMore = endIndex < total;
2163
+ const end = perPageInput === false ? allScores.length : start + perPage;
2164
+ const paginatedScores = allScores.slice(start, end);
2363
2165
  return {
2364
2166
  scores: paginatedScores,
2365
2167
  pagination: {
2366
2168
  total,
2367
- page: pagination.page,
2368
- perPage: pagination.perPage,
2369
- hasMore
2169
+ page,
2170
+ perPage: perPageForResponse,
2171
+ hasMore: end < total
2370
2172
  }
2371
2173
  };
2372
2174
  } catch (error$1) {
@@ -2381,7 +2183,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2381
2183
  );
2382
2184
  }
2383
2185
  }
2384
- async getScoresBySpan({
2186
+ async listScoresBySpan({
2385
2187
  traceId,
2386
2188
  spanId,
2387
2189
  pagination
@@ -2392,18 +2194,19 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2392
2194
  const results = await query.go();
2393
2195
  const allScores = results.data.map((data) => this.parseScoreData(data));
2394
2196
  allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2395
- const startIndex = pagination.page * pagination.perPage;
2396
- const endIndex = startIndex + pagination.perPage;
2397
- const paginatedScores = allScores.slice(startIndex, endIndex);
2197
+ const { page, perPage: perPageInput } = pagination;
2198
+ const perPage = storage.normalizePerPage(perPageInput, Number.MAX_SAFE_INTEGER);
2199
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2398
2200
  const total = allScores.length;
2399
- const hasMore = endIndex < total;
2201
+ const end = perPageInput === false ? allScores.length : start + perPage;
2202
+ const paginatedScores = allScores.slice(start, end);
2400
2203
  return {
2401
2204
  scores: paginatedScores,
2402
2205
  pagination: {
2403
2206
  total,
2404
- page: pagination.page,
2405
- perPage: pagination.perPage,
2406
- hasMore
2207
+ page,
2208
+ perPage: perPageForResponse,
2209
+ hasMore: end < total
2407
2210
  }
2408
2211
  };
2409
2212
  } catch (error$1) {
@@ -2419,239 +2222,6 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2419
2222
  }
2420
2223
  }
2421
2224
  };
2422
- var TracesStorageDynamoDB = class extends storage.TracesStorage {
2423
- service;
2424
- operations;
2425
- constructor({ service, operations }) {
2426
- super();
2427
- this.service = service;
2428
- this.operations = operations;
2429
- }
2430
- // Trace operations
2431
- async getTraces(args) {
2432
- const { name, scope, page, perPage } = args;
2433
- this.logger.debug("Getting traces", { name, scope, page, perPage });
2434
- try {
2435
- let query;
2436
- if (name) {
2437
- query = this.service.entities.trace.query.byName({ entity: "trace", name });
2438
- } else if (scope) {
2439
- query = this.service.entities.trace.query.byScope({ entity: "trace", scope });
2440
- } else {
2441
- this.logger.warn("Performing a scan operation on traces - consider using a more specific query");
2442
- query = this.service.entities.trace.scan;
2443
- }
2444
- let items = [];
2445
- let cursor = null;
2446
- let pagesFetched = 0;
2447
- const startPage = page > 0 ? page : 1;
2448
- do {
2449
- const results = await query.go({ cursor, limit: perPage });
2450
- pagesFetched++;
2451
- if (pagesFetched === startPage) {
2452
- items = results.data;
2453
- break;
2454
- }
2455
- cursor = results.cursor;
2456
- if (!cursor && results.data.length > 0 && pagesFetched < startPage) {
2457
- break;
2458
- }
2459
- } while (cursor && pagesFetched < startPage);
2460
- return items;
2461
- } catch (error$1) {
2462
- throw new error.MastraError(
2463
- {
2464
- id: "STORAGE_DYNAMODB_STORE_GET_TRACES_FAILED",
2465
- domain: error.ErrorDomain.STORAGE,
2466
- category: error.ErrorCategory.THIRD_PARTY
2467
- },
2468
- error$1
2469
- );
2470
- }
2471
- }
2472
- async batchTraceInsert({ records }) {
2473
- this.logger.debug("Batch inserting traces", { count: records.length });
2474
- if (!records.length) {
2475
- return;
2476
- }
2477
- try {
2478
- const recordsToSave = records.map((rec) => ({ entity: "trace", ...rec }));
2479
- await this.operations.batchInsert({
2480
- tableName: storage.TABLE_TRACES,
2481
- records: recordsToSave
2482
- // Pass records with 'entity' included
2483
- });
2484
- } catch (error$1) {
2485
- throw new error.MastraError(
2486
- {
2487
- id: "STORAGE_DYNAMODB_STORE_BATCH_TRACE_INSERT_FAILED",
2488
- domain: error.ErrorDomain.STORAGE,
2489
- category: error.ErrorCategory.THIRD_PARTY,
2490
- details: { count: records.length }
2491
- },
2492
- error$1
2493
- );
2494
- }
2495
- }
2496
- async getTracesPaginated(args) {
2497
- const { name, scope, page = 0, perPage = 100, attributes, filters, dateRange } = args;
2498
- this.logger.debug("Getting traces with pagination", { name, scope, page, perPage, attributes, filters, dateRange });
2499
- try {
2500
- let query;
2501
- if (name) {
2502
- query = this.service.entities.trace.query.byName({ entity: "trace", name });
2503
- } else if (scope) {
2504
- query = this.service.entities.trace.query.byScope({ entity: "trace", scope });
2505
- } else {
2506
- this.logger.warn("Performing a scan operation on traces - consider using a more specific query");
2507
- query = this.service.entities.trace.scan;
2508
- }
2509
- const results = await query.go({
2510
- order: "desc",
2511
- pages: "all"
2512
- // Get all pages to apply filtering and pagination
2513
- });
2514
- if (!results.data.length) {
2515
- return {
2516
- traces: [],
2517
- total: 0,
2518
- page,
2519
- perPage,
2520
- hasMore: false
2521
- };
2522
- }
2523
- let filteredData = results.data;
2524
- if (attributes) {
2525
- filteredData = filteredData.filter((item) => {
2526
- try {
2527
- let itemAttributes = {};
2528
- if (item.attributes) {
2529
- if (typeof item.attributes === "string") {
2530
- if (item.attributes === "[object Object]") {
2531
- itemAttributes = {};
2532
- } else {
2533
- try {
2534
- itemAttributes = JSON.parse(item.attributes);
2535
- } catch {
2536
- itemAttributes = {};
2537
- }
2538
- }
2539
- } else if (typeof item.attributes === "object") {
2540
- itemAttributes = item.attributes;
2541
- }
2542
- }
2543
- return Object.entries(attributes).every(([key, value]) => itemAttributes[key] === value);
2544
- } catch (e) {
2545
- this.logger.warn("Failed to parse attributes during filtering", { item, error: e });
2546
- return false;
2547
- }
2548
- });
2549
- }
2550
- if (dateRange?.start) {
2551
- filteredData = filteredData.filter((item) => {
2552
- const itemDate = new Date(item.createdAt);
2553
- return itemDate >= dateRange.start;
2554
- });
2555
- }
2556
- if (dateRange?.end) {
2557
- filteredData = filteredData.filter((item) => {
2558
- const itemDate = new Date(item.createdAt);
2559
- return itemDate <= dateRange.end;
2560
- });
2561
- }
2562
- const total = filteredData.length;
2563
- const start = page * perPage;
2564
- const end = start + perPage;
2565
- const paginatedData = filteredData.slice(start, end);
2566
- const traces = paginatedData.map((item) => {
2567
- let attributes2;
2568
- if (item.attributes) {
2569
- if (typeof item.attributes === "string") {
2570
- if (item.attributes === "[object Object]") {
2571
- attributes2 = void 0;
2572
- } else {
2573
- try {
2574
- attributes2 = JSON.parse(item.attributes);
2575
- } catch {
2576
- attributes2 = void 0;
2577
- }
2578
- }
2579
- } else if (typeof item.attributes === "object") {
2580
- attributes2 = item.attributes;
2581
- }
2582
- }
2583
- let status;
2584
- if (item.status) {
2585
- if (typeof item.status === "string") {
2586
- try {
2587
- status = JSON.parse(item.status);
2588
- } catch {
2589
- status = void 0;
2590
- }
2591
- } else if (typeof item.status === "object") {
2592
- status = item.status;
2593
- }
2594
- }
2595
- let events;
2596
- if (item.events) {
2597
- if (typeof item.events === "string") {
2598
- try {
2599
- events = JSON.parse(item.events);
2600
- } catch {
2601
- events = void 0;
2602
- }
2603
- } else if (Array.isArray(item.events)) {
2604
- events = item.events;
2605
- }
2606
- }
2607
- let links;
2608
- if (item.links) {
2609
- if (typeof item.links === "string") {
2610
- try {
2611
- links = JSON.parse(item.links);
2612
- } catch {
2613
- links = void 0;
2614
- }
2615
- } else if (Array.isArray(item.links)) {
2616
- links = item.links;
2617
- }
2618
- }
2619
- return {
2620
- id: item.id,
2621
- parentSpanId: item.parentSpanId,
2622
- name: item.name,
2623
- traceId: item.traceId,
2624
- scope: item.scope,
2625
- kind: item.kind,
2626
- attributes: attributes2,
2627
- status,
2628
- events,
2629
- links,
2630
- other: item.other,
2631
- startTime: item.startTime,
2632
- endTime: item.endTime,
2633
- createdAt: item.createdAt
2634
- };
2635
- });
2636
- return {
2637
- traces,
2638
- total,
2639
- page,
2640
- perPage,
2641
- hasMore: end < total
2642
- };
2643
- } catch (error$1) {
2644
- throw new error.MastraError(
2645
- {
2646
- id: "STORAGE_DYNAMODB_STORE_GET_TRACES_PAGINATED_FAILED",
2647
- domain: error.ErrorDomain.STORAGE,
2648
- category: error.ErrorCategory.THIRD_PARTY
2649
- },
2650
- error$1
2651
- );
2652
- }
2653
- }
2654
- };
2655
2225
  function formatWorkflowRun(snapshotData) {
2656
2226
  return {
2657
2227
  workflowName: snapshotData.workflow_name,
@@ -2673,7 +2243,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2673
2243
  // runId,
2674
2244
  // stepId,
2675
2245
  // result,
2676
- // runtimeContext,
2246
+ // requestContext,
2677
2247
  }) {
2678
2248
  throw new Error("Method not implemented.");
2679
2249
  }
@@ -2700,7 +2270,6 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2700
2270
  workflow_name: workflowName,
2701
2271
  run_id: runId,
2702
2272
  snapshot: JSON.stringify(snapshot),
2703
- // Stringify the snapshot object
2704
2273
  createdAt: now,
2705
2274
  updatedAt: now,
2706
2275
  resourceId
@@ -2746,11 +2315,24 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2746
2315
  );
2747
2316
  }
2748
2317
  }
2749
- async getWorkflowRuns(args) {
2318
+ async listWorkflowRuns(args) {
2750
2319
  this.logger.debug("Getting workflow runs", { args });
2751
2320
  try {
2752
- const limit = args?.limit || 10;
2753
- const offset = args?.offset || 0;
2321
+ const perPage = args?.perPage !== void 0 ? args.perPage : 10;
2322
+ const page = args?.page !== void 0 ? args.page : 0;
2323
+ if (page < 0) {
2324
+ throw new error.MastraError(
2325
+ {
2326
+ id: "DYNAMODB_STORE_INVALID_PAGE",
2327
+ domain: error.ErrorDomain.STORAGE,
2328
+ category: error.ErrorCategory.USER,
2329
+ details: { page }
2330
+ },
2331
+ new Error("page must be >= 0")
2332
+ );
2333
+ }
2334
+ const normalizedPerPage = storage.normalizePerPage(perPage, 10);
2335
+ const offset = page * normalizedPerPage;
2754
2336
  let query;
2755
2337
  if (args?.workflowName) {
2756
2338
  query = this.service.entities.workflow_snapshot.query.primary({
@@ -2772,6 +2354,11 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2772
2354
  });
2773
2355
  if (pageResults.data && pageResults.data.length > 0) {
2774
2356
  let pageFilteredData = pageResults.data;
2357
+ if (args?.status) {
2358
+ pageFilteredData = pageFilteredData.filter((snapshot) => {
2359
+ return snapshot.snapshot.status === args.status;
2360
+ });
2361
+ }
2775
2362
  if (args?.fromDate || args?.toDate) {
2776
2363
  pageFilteredData = pageFilteredData.filter((snapshot) => {
2777
2364
  const createdAt = new Date(snapshot.createdAt);
@@ -2797,7 +2384,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2797
2384
  return { runs: [], total: 0 };
2798
2385
  }
2799
2386
  const total = allMatchingSnapshots.length;
2800
- const paginatedData = allMatchingSnapshots.slice(offset, offset + limit);
2387
+ const paginatedData = allMatchingSnapshots.slice(offset, offset + normalizedPerPage);
2801
2388
  const runs = paginatedData.map((snapshot) => formatWorkflowRun(snapshot));
2802
2389
  return {
2803
2390
  runs,
@@ -2806,7 +2393,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2806
2393
  } catch (error$1) {
2807
2394
  throw new error.MastraError(
2808
2395
  {
2809
- id: "STORAGE_DYNAMODB_STORE_GET_WORKFLOW_RUNS_FAILED",
2396
+ id: "STORAGE_DYNAMODB_STORE_LIST_WORKFLOW_RUNS_FAILED",
2810
2397
  domain: error.ErrorDomain.STORAGE,
2811
2398
  category: error.ErrorCategory.THIRD_PARTY,
2812
2399
  details: { workflowName: args?.workflowName || "", resourceId: args?.resourceId || "" }
@@ -2879,7 +2466,7 @@ var DynamoDBStore = class extends storage.MastraStorage {
2879
2466
  hasInitialized = null;
2880
2467
  stores;
2881
2468
  constructor({ name, config }) {
2882
- super({ name });
2469
+ super({ id: config.id, name });
2883
2470
  try {
2884
2471
  if (!config.tableName || typeof config.tableName !== "string" || config.tableName.trim() === "") {
2885
2472
  throw new Error("DynamoDBStore: config.tableName must be provided and cannot be empty.");
@@ -2902,14 +2489,11 @@ var DynamoDBStore = class extends storage.MastraStorage {
2902
2489
  tableName: this.tableName,
2903
2490
  client: this.client
2904
2491
  });
2905
- const traces = new TracesStorageDynamoDB({ service: this.service, operations });
2906
2492
  const workflows = new WorkflowStorageDynamoDB({ service: this.service });
2907
2493
  const memory = new MemoryStorageDynamoDB({ service: this.service });
2908
2494
  const scores = new ScoresStorageDynamoDB({ service: this.service });
2909
2495
  this.stores = {
2910
2496
  operations,
2911
- legacyEvals: new LegacyEvalsDynamoDB({ service: this.service, tableName: this.tableName }),
2912
- traces,
2913
2497
  workflows,
2914
2498
  memory,
2915
2499
  scores
@@ -2932,7 +2516,7 @@ var DynamoDBStore = class extends storage.MastraStorage {
2932
2516
  hasColumn: false,
2933
2517
  createTable: false,
2934
2518
  deleteMessages: false,
2935
- getScoresBySpan: true
2519
+ listScoresBySpan: true
2936
2520
  };
2937
2521
  }
2938
2522
  /**
@@ -3027,9 +2611,6 @@ var DynamoDBStore = class extends storage.MastraStorage {
3027
2611
  async getThreadById({ threadId }) {
3028
2612
  return this.stores.memory.getThreadById({ threadId });
3029
2613
  }
3030
- async getThreadsByResourceId(args) {
3031
- return this.stores.memory.getThreadsByResourceId(args);
3032
- }
3033
2614
  async saveThread({ thread }) {
3034
2615
  return this.stores.memory.saveThread({ thread });
3035
2616
  }
@@ -3043,51 +2624,24 @@ var DynamoDBStore = class extends storage.MastraStorage {
3043
2624
  async deleteThread({ threadId }) {
3044
2625
  return this.stores.memory.deleteThread({ threadId });
3045
2626
  }
3046
- async getMessages({
3047
- threadId,
3048
- resourceId,
3049
- selectBy,
3050
- format
3051
- }) {
3052
- return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format });
3053
- }
3054
- async getMessagesById({
3055
- messageIds,
3056
- format
3057
- }) {
3058
- return this.stores.memory.getMessagesById({ messageIds, format });
2627
+ async listMessagesById(args) {
2628
+ return this.stores.memory.listMessagesById(args);
3059
2629
  }
3060
2630
  async saveMessages(args) {
3061
2631
  return this.stores.memory.saveMessages(args);
3062
2632
  }
3063
- async getThreadsByResourceIdPaginated(args) {
3064
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
3065
- }
3066
- async getMessagesPaginated(args) {
3067
- return this.stores.memory.getMessagesPaginated(args);
3068
- }
3069
2633
  async updateMessages(_args) {
3070
2634
  return this.stores.memory.updateMessages(_args);
3071
2635
  }
3072
- // Trace operations
3073
- async getTraces(args) {
3074
- return this.stores.traces.getTraces(args);
3075
- }
3076
- async batchTraceInsert({ records }) {
3077
- return this.stores.traces.batchTraceInsert({ records });
3078
- }
3079
- async getTracesPaginated(_args) {
3080
- return this.stores.traces.getTracesPaginated(_args);
3081
- }
3082
2636
  // Workflow operations
3083
2637
  async updateWorkflowResults({
3084
2638
  workflowName,
3085
2639
  runId,
3086
2640
  stepId,
3087
2641
  result,
3088
- runtimeContext
2642
+ requestContext
3089
2643
  }) {
3090
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2644
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
3091
2645
  }
3092
2646
  async updateWorkflowState({
3093
2647
  workflowName,
@@ -3110,8 +2664,8 @@ var DynamoDBStore = class extends storage.MastraStorage {
3110
2664
  }) {
3111
2665
  return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
3112
2666
  }
3113
- async getWorkflowRuns(args) {
3114
- return this.stores.workflows.getWorkflowRuns(args);
2667
+ async listWorkflowRuns(args) {
2668
+ return this.stores.workflows.listWorkflowRuns(args);
3115
2669
  }
3116
2670
  async getWorkflowRunById(args) {
3117
2671
  return this.stores.workflows.getWorkflowRunById(args);
@@ -3129,13 +2683,6 @@ var DynamoDBStore = class extends storage.MastraStorage {
3129
2683
  }) {
3130
2684
  return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
3131
2685
  }
3132
- // Eval operations
3133
- async getEvalsByAgentName(agentName, type) {
3134
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
3135
- }
3136
- async getEvals(options) {
3137
- return this.stores.legacyEvals.getEvals(options);
3138
- }
3139
2686
  /**
3140
2687
  * Closes the DynamoDB client connection and cleans up resources.
3141
2688
  * Should be called when the store is no longer needed, e.g., at the end of tests or application shutdown.
@@ -3165,38 +2712,38 @@ var DynamoDBStore = class extends storage.MastraStorage {
3165
2712
  async saveScore(_score) {
3166
2713
  return this.stores.scores.saveScore(_score);
3167
2714
  }
3168
- async getScoresByRunId({
2715
+ async listScoresByRunId({
3169
2716
  runId: _runId,
3170
2717
  pagination: _pagination
3171
2718
  }) {
3172
- return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
2719
+ return this.stores.scores.listScoresByRunId({ runId: _runId, pagination: _pagination });
3173
2720
  }
3174
- async getScoresByEntityId({
2721
+ async listScoresByEntityId({
3175
2722
  entityId: _entityId,
3176
2723
  entityType: _entityType,
3177
2724
  pagination: _pagination
3178
2725
  }) {
3179
- return this.stores.scores.getScoresByEntityId({
2726
+ return this.stores.scores.listScoresByEntityId({
3180
2727
  entityId: _entityId,
3181
2728
  entityType: _entityType,
3182
2729
  pagination: _pagination
3183
2730
  });
3184
2731
  }
3185
- async getScoresByScorerId({
2732
+ async listScoresByScorerId({
3186
2733
  scorerId,
3187
2734
  source,
3188
2735
  entityId,
3189
2736
  entityType,
3190
2737
  pagination
3191
2738
  }) {
3192
- return this.stores.scores.getScoresByScorerId({ scorerId, source, entityId, entityType, pagination });
2739
+ return this.stores.scores.listScoresByScorerId({ scorerId, source, entityId, entityType, pagination });
3193
2740
  }
3194
- async getScoresBySpan({
2741
+ async listScoresBySpan({
3195
2742
  traceId,
3196
2743
  spanId,
3197
2744
  pagination
3198
2745
  }) {
3199
- return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
2746
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
3200
2747
  }
3201
2748
  };
3202
2749