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