@mastra/dynamodb 0.0.0-pgvector-index-fix-20250905222058 → 0.0.0-playground-studio-again-20251114100107

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -6,6 +6,7 @@ var error = require('@mastra/core/error');
6
6
  var storage = require('@mastra/core/storage');
7
7
  var electrodb = require('electrodb');
8
8
  var agent = require('@mastra/core/agent');
9
+ var evals = require('@mastra/core/evals');
9
10
 
10
11
  // src/storage/index.ts
11
12
 
@@ -372,6 +373,10 @@ var scoreEntity = new electrodb.Entity({
372
373
  type: "string",
373
374
  required: false
374
375
  },
376
+ spanId: {
377
+ type: "string",
378
+ required: false
379
+ },
375
380
  runId: {
376
381
  type: "string",
377
382
  required: true
@@ -559,7 +564,7 @@ var scoreEntity = new electrodb.Entity({
559
564
  return value;
560
565
  }
561
566
  },
562
- runtimeContext: {
567
+ requestContext: {
563
568
  type: "string",
564
569
  required: false,
565
570
  set: (value) => {
@@ -658,6 +663,11 @@ var scoreEntity = new electrodb.Entity({
658
663
  index: "gsi6",
659
664
  pk: { field: "gsi6pk", composite: ["entity", "threadId"] },
660
665
  sk: { field: "gsi6sk", composite: ["createdAt"] }
666
+ },
667
+ bySpan: {
668
+ index: "gsi7",
669
+ pk: { field: "gsi7pk", composite: ["entity", "traceId", "spanId"] },
670
+ sk: { field: "gsi7sk", composite: ["createdAt"] }
661
671
  }
662
672
  }
663
673
  });
@@ -925,187 +935,6 @@ function getElectroDbService(client, tableName) {
925
935
  }
926
936
  );
927
937
  }
928
- var LegacyEvalsDynamoDB = class extends storage.LegacyEvalsStorage {
929
- service;
930
- tableName;
931
- constructor({ service, tableName }) {
932
- super();
933
- this.service = service;
934
- this.tableName = tableName;
935
- }
936
- // Eval operations
937
- async getEvalsByAgentName(agentName, type) {
938
- this.logger.debug("Getting evals for agent", { agentName, type });
939
- try {
940
- const query = this.service.entities.eval.query.byAgent({ entity: "eval", agent_name: agentName });
941
- const results = await query.go({ order: "desc", limit: 100 });
942
- if (!results.data.length) {
943
- return [];
944
- }
945
- let filteredData = results.data;
946
- if (type) {
947
- filteredData = filteredData.filter((evalRecord) => {
948
- try {
949
- const testInfo = evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0;
950
- if (type === "test" && !testInfo) {
951
- return false;
952
- }
953
- if (type === "live" && testInfo) {
954
- return false;
955
- }
956
- } catch (e) {
957
- this.logger.warn("Failed to parse test_info during filtering", { record: evalRecord, error: e });
958
- }
959
- return true;
960
- });
961
- }
962
- return filteredData.map((evalRecord) => {
963
- try {
964
- return {
965
- input: evalRecord.input,
966
- output: evalRecord.output,
967
- // Safely parse result and test_info
968
- result: evalRecord.result && typeof evalRecord.result === "string" ? JSON.parse(evalRecord.result) : void 0,
969
- agentName: evalRecord.agent_name,
970
- createdAt: evalRecord.created_at,
971
- // Keep as string from DDB?
972
- metricName: evalRecord.metric_name,
973
- instructions: evalRecord.instructions,
974
- runId: evalRecord.run_id,
975
- globalRunId: evalRecord.global_run_id,
976
- testInfo: evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0
977
- };
978
- } catch (parseError) {
979
- this.logger.error("Failed to parse eval record", { record: evalRecord, error: parseError });
980
- return {
981
- agentName: evalRecord.agent_name,
982
- createdAt: evalRecord.created_at,
983
- runId: evalRecord.run_id,
984
- globalRunId: evalRecord.global_run_id
985
- };
986
- }
987
- });
988
- } catch (error$1) {
989
- throw new error.MastraError(
990
- {
991
- id: "STORAGE_DYNAMODB_STORE_GET_EVALS_BY_AGENT_NAME_FAILED",
992
- domain: error.ErrorDomain.STORAGE,
993
- category: error.ErrorCategory.THIRD_PARTY,
994
- details: { agentName }
995
- },
996
- error$1
997
- );
998
- }
999
- }
1000
- async getEvals(options = {}) {
1001
- const { agentName, type, page = 0, perPage = 100, dateRange } = options;
1002
- this.logger.debug("Getting evals with pagination", { agentName, type, page, perPage, dateRange });
1003
- try {
1004
- let query;
1005
- if (agentName) {
1006
- query = this.service.entities.eval.query.byAgent({ entity: "eval", agent_name: agentName });
1007
- } else {
1008
- query = this.service.entities.eval.query.byEntity({ entity: "eval" });
1009
- }
1010
- const results = await query.go({
1011
- order: "desc",
1012
- pages: "all"
1013
- // Get all pages to apply filtering and pagination
1014
- });
1015
- if (!results.data.length) {
1016
- return {
1017
- evals: [],
1018
- total: 0,
1019
- page,
1020
- perPage,
1021
- hasMore: false
1022
- };
1023
- }
1024
- let filteredData = results.data;
1025
- if (type) {
1026
- filteredData = filteredData.filter((evalRecord) => {
1027
- try {
1028
- const testInfo = evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0;
1029
- if (type === "test" && !testInfo) {
1030
- return false;
1031
- }
1032
- if (type === "live" && testInfo) {
1033
- return false;
1034
- }
1035
- } catch (e) {
1036
- this.logger.warn("Failed to parse test_info during filtering", { record: evalRecord, error: e });
1037
- }
1038
- return true;
1039
- });
1040
- }
1041
- if (dateRange) {
1042
- const fromDate = dateRange.start;
1043
- const toDate = dateRange.end;
1044
- filteredData = filteredData.filter((evalRecord) => {
1045
- const recordDate = new Date(evalRecord.created_at);
1046
- if (fromDate && recordDate < fromDate) {
1047
- return false;
1048
- }
1049
- if (toDate && recordDate > toDate) {
1050
- return false;
1051
- }
1052
- return true;
1053
- });
1054
- }
1055
- const total = filteredData.length;
1056
- const start = page * perPage;
1057
- const end = start + perPage;
1058
- const paginatedData = filteredData.slice(start, end);
1059
- const evals = paginatedData.map((evalRecord) => {
1060
- try {
1061
- return {
1062
- input: evalRecord.input,
1063
- output: evalRecord.output,
1064
- result: evalRecord.result && typeof evalRecord.result === "string" ? JSON.parse(evalRecord.result) : void 0,
1065
- agentName: evalRecord.agent_name,
1066
- createdAt: evalRecord.created_at,
1067
- metricName: evalRecord.metric_name,
1068
- instructions: evalRecord.instructions,
1069
- runId: evalRecord.run_id,
1070
- globalRunId: evalRecord.global_run_id,
1071
- testInfo: evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0
1072
- };
1073
- } catch (parseError) {
1074
- this.logger.error("Failed to parse eval record", { record: evalRecord, error: parseError });
1075
- return {
1076
- agentName: evalRecord.agent_name,
1077
- createdAt: evalRecord.created_at,
1078
- runId: evalRecord.run_id,
1079
- globalRunId: evalRecord.global_run_id
1080
- };
1081
- }
1082
- });
1083
- const hasMore = end < total;
1084
- return {
1085
- evals,
1086
- total,
1087
- page,
1088
- perPage,
1089
- hasMore
1090
- };
1091
- } catch (error$1) {
1092
- throw new error.MastraError(
1093
- {
1094
- id: "STORAGE_DYNAMODB_STORE_GET_EVALS_FAILED",
1095
- domain: error.ErrorDomain.STORAGE,
1096
- category: error.ErrorCategory.THIRD_PARTY,
1097
- details: {
1098
- agentName: agentName || "all",
1099
- type: type || "all",
1100
- page,
1101
- perPage
1102
- }
1103
- },
1104
- error$1
1105
- );
1106
- }
1107
- }
1108
- };
1109
938
  var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1110
939
  service;
1111
940
  constructor({ service }) {
@@ -1124,17 +953,17 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1124
953
  };
1125
954
  }
1126
955
  // Helper function to transform and sort threads
1127
- transformAndSortThreads(rawThreads, orderBy, sortDirection) {
956
+ transformAndSortThreads(rawThreads, field, direction) {
1128
957
  return rawThreads.map((data) => ({
1129
958
  ...data,
1130
959
  // Convert date strings back to Date objects for consistency
1131
960
  createdAt: typeof data.createdAt === "string" ? new Date(data.createdAt) : data.createdAt,
1132
961
  updatedAt: typeof data.updatedAt === "string" ? new Date(data.updatedAt) : data.updatedAt
1133
962
  })).sort((a, b) => {
1134
- const fieldA = orderBy === "createdAt" ? a.createdAt : a.updatedAt;
1135
- 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;
1136
965
  const comparison = fieldA.getTime() - fieldB.getTime();
1137
- return sortDirection === "DESC" ? -comparison : comparison;
966
+ return direction === "DESC" ? -comparison : comparison;
1138
967
  });
1139
968
  }
1140
969
  async getThreadById({ threadId }) {
@@ -1165,32 +994,6 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1165
994
  );
1166
995
  }
1167
996
  }
1168
- /**
1169
- * @deprecated use getThreadsByResourceIdPaginated instead for paginated results.
1170
- */
1171
- async getThreadsByResourceId(args) {
1172
- const resourceId = args.resourceId;
1173
- const orderBy = this.castThreadOrderBy(args.orderBy);
1174
- const sortDirection = this.castThreadSortDirection(args.sortDirection);
1175
- this.logger.debug("Getting threads by resource ID", { resourceId, orderBy, sortDirection });
1176
- try {
1177
- const result = await this.service.entities.thread.query.byResource({ entity: "thread", resourceId }).go();
1178
- if (!result.data.length) {
1179
- return [];
1180
- }
1181
- return this.transformAndSortThreads(result.data, orderBy, sortDirection);
1182
- } catch (error$1) {
1183
- throw new error.MastraError(
1184
- {
1185
- id: "STORAGE_DYNAMODB_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
1186
- domain: error.ErrorDomain.STORAGE,
1187
- category: error.ErrorCategory.THIRD_PARTY,
1188
- details: { resourceId }
1189
- },
1190
- error$1
1191
- );
1192
- }
1193
- }
1194
997
  async saveThread({ thread }) {
1195
998
  this.logger.debug("Saving thread", { threadId: thread.id });
1196
999
  const now = /* @__PURE__ */ new Date();
@@ -1210,7 +1013,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1210
1013
  resourceId: thread.resourceId,
1211
1014
  title: threadData.title,
1212
1015
  createdAt: thread.createdAt || now,
1213
- updatedAt: now,
1016
+ updatedAt: thread.updatedAt || now,
1214
1017
  metadata: thread.metadata
1215
1018
  };
1216
1019
  } catch (error$1) {
@@ -1270,7 +1073,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1270
1073
  async deleteThread({ threadId }) {
1271
1074
  this.logger.debug("Deleting thread", { threadId });
1272
1075
  try {
1273
- const messages = await this.getMessages({ threadId });
1076
+ const { messages } = await this.listMessages({ threadId, perPage: false });
1274
1077
  if (messages.length > 0) {
1275
1078
  const batchSize = 25;
1276
1079
  for (let i = 0; i < messages.length; i += batchSize) {
@@ -1299,104 +1102,175 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1299
1102
  );
1300
1103
  }
1301
1104
  }
1302
- async getMessages({
1303
- threadId,
1304
- resourceId,
1305
- selectBy,
1306
- format
1307
- }) {
1308
- 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: [] };
1309
1108
  try {
1310
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1311
- const messages = [];
1312
- const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: Number.MAX_SAFE_INTEGER });
1313
- if (selectBy?.include?.length) {
1314
- const includeMessages = await this._getIncludedMessages(threadId, selectBy);
1315
- if (includeMessages) {
1316
- messages.push(...includeMessages);
1317
- }
1318
- }
1319
- if (limit !== 0) {
1320
- const query = this.service.entities.message.query.byThread({ entity: "message", threadId });
1321
- let results;
1322
- if (limit !== Number.MAX_SAFE_INTEGER && limit > 0) {
1323
- results = await query.go({ limit, order: "desc" });
1324
- results.data = results.data.reverse();
1325
- } else {
1326
- results = await query.go();
1327
- }
1328
- let allThreadMessages = results.data.map((data) => this.parseMessageData(data)).filter((msg) => "content" in msg);
1329
- allThreadMessages.sort((a, b) => {
1330
- const timeA = a.createdAt.getTime();
1331
- const timeB = b.createdAt.getTime();
1332
- if (timeA === timeB) {
1333
- return a.id.localeCompare(b.id);
1334
- }
1335
- return timeA - timeB;
1336
- });
1337
- messages.push(...allThreadMessages);
1338
- }
1339
- messages.sort((a, b) => {
1340
- const timeA = a.createdAt.getTime();
1341
- const timeB = b.createdAt.getTime();
1342
- if (timeA === timeB) {
1343
- return a.id.localeCompare(b.id);
1344
- }
1345
- return timeA - timeB;
1346
- });
1347
- const uniqueMessages = messages.filter(
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(
1348
1115
  (message, index, self) => index === self.findIndex((m) => m.id === message.id)
1349
1116
  );
1350
- const list = new agent.MessageList({ threadId, resourceId }).add(uniqueMessages, "memory");
1351
- if (format === `v2`) return list.get.all.v2();
1352
- return list.get.all.v1();
1117
+ const list = new agent.MessageList().add(uniqueMessages, "memory");
1118
+ return { messages: list.get.all.db() };
1353
1119
  } catch (error$1) {
1354
1120
  throw new error.MastraError(
1355
1121
  {
1356
- id: "STORAGE_DYNAMODB_STORE_GET_MESSAGES_FAILED",
1122
+ id: "STORAGE_DYNAMODB_STORE_LIST_MESSAGES_BY_ID_FAILED",
1357
1123
  domain: error.ErrorDomain.STORAGE,
1358
1124
  category: error.ErrorCategory.THIRD_PARTY,
1359
- details: { threadId, resourceId: resourceId ?? "" }
1125
+ details: { messageIds: JSON.stringify(messageIds) }
1360
1126
  },
1361
1127
  error$1
1362
1128
  );
1363
1129
  }
1364
1130
  }
1365
- async getMessagesById({
1366
- messageIds,
1367
- format
1368
- }) {
1369
- this.logger.debug("Getting messages by ID", { messageIds });
1370
- if (messageIds.length === 0) return [];
1371
- try {
1372
- const results = await Promise.all(
1373
- messageIds.map((id) => this.service.entities.message.query.primary({ entity: "message", id }).go())
1374
- );
1375
- const data = results.map((result) => result.data).flat(1);
1376
- let parsedMessages = data.map((data2) => this.parseMessageData(data2)).filter((msg) => "content" in msg);
1377
- const uniqueMessages = parsedMessages.filter(
1378
- (message, index, self) => index === self.findIndex((m) => m.id === message.id)
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")
1379
1142
  );
1380
- const list = new agent.MessageList().add(uniqueMessages, "memory");
1381
- if (format === `v1`) return list.get.all.v1();
1382
- 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
+ };
1383
1245
  } catch (error$1) {
1384
- throw new error.MastraError(
1246
+ const mastraError = new error.MastraError(
1385
1247
  {
1386
- id: "STORAGE_DYNAMODB_STORE_GET_MESSAGES_BY_ID_FAILED",
1248
+ id: "STORAGE_DYNAMODB_STORE_LIST_MESSAGES_FAILED",
1387
1249
  domain: error.ErrorDomain.STORAGE,
1388
1250
  category: error.ErrorCategory.THIRD_PARTY,
1389
- details: { messageIds: JSON.stringify(messageIds) }
1251
+ details: {
1252
+ threadId,
1253
+ resourceId: resourceId ?? ""
1254
+ }
1390
1255
  },
1391
1256
  error$1
1392
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
+ };
1393
1267
  }
1394
1268
  }
1395
1269
  async saveMessages(args) {
1396
- const { messages, format = "v1" } = args;
1270
+ const { messages } = args;
1397
1271
  this.logger.debug("Saving messages", { count: messages.length });
1398
1272
  if (!messages.length) {
1399
- return [];
1273
+ return { messages: [] };
1400
1274
  }
1401
1275
  const threadId = messages[0]?.threadId;
1402
1276
  if (!threadId) {
@@ -1450,8 +1324,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1450
1324
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1451
1325
  }).go();
1452
1326
  const list = new agent.MessageList().add(messages, "memory");
1453
- if (format === `v1`) return list.get.all.v1();
1454
- return list.get.all.v2();
1327
+ return { messages: list.get.all.db() };
1455
1328
  } catch (error$1) {
1456
1329
  throw new error.MastraError(
1457
1330
  {
@@ -1464,37 +1337,48 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1464
1337
  );
1465
1338
  }
1466
1339
  }
1467
- async getThreadsByResourceIdPaginated(args) {
1468
- const { resourceId, page = 0, perPage = 100 } = args;
1469
- const orderBy = this.castThreadOrderBy(args.orderBy);
1470
- const sortDirection = this.castThreadSortDirection(args.sortDirection);
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);
1471
1356
  this.logger.debug("Getting threads by resource ID with pagination", {
1472
1357
  resourceId,
1473
1358
  page,
1474
1359
  perPage,
1475
- orderBy,
1476
- sortDirection
1360
+ field,
1361
+ direction
1477
1362
  });
1478
1363
  try {
1479
1364
  const query = this.service.entities.thread.query.byResource({ entity: "thread", resourceId });
1480
1365
  const results = await query.go();
1481
- const allThreads = this.transformAndSortThreads(results.data, orderBy, sortDirection);
1482
- const startIndex = page * perPage;
1483
- const endIndex = startIndex + perPage;
1484
- const paginatedThreads = allThreads.slice(startIndex, endIndex);
1366
+ const allThreads = this.transformAndSortThreads(results.data, field, direction);
1367
+ const endIndex = offset + perPage;
1368
+ const paginatedThreads = allThreads.slice(offset, endIndex);
1485
1369
  const total = allThreads.length;
1486
- const hasMore = endIndex < total;
1370
+ const hasMore = offset + perPage < total;
1487
1371
  return {
1488
1372
  threads: paginatedThreads,
1489
1373
  total,
1490
1374
  page,
1491
- perPage,
1375
+ perPage: perPageForResponse,
1492
1376
  hasMore
1493
1377
  };
1494
1378
  } catch (error$1) {
1495
1379
  throw new error.MastraError(
1496
1380
  {
1497
- id: "STORAGE_DYNAMODB_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
1381
+ id: "DYNAMODB_STORAGE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
1498
1382
  domain: error.ErrorDomain.STORAGE,
1499
1383
  category: error.ErrorCategory.THIRD_PARTY,
1500
1384
  details: { resourceId, page, perPage }
@@ -1503,84 +1387,6 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1503
1387
  );
1504
1388
  }
1505
1389
  }
1506
- async getMessagesPaginated(args) {
1507
- const { threadId, resourceId, selectBy, format = "v1" } = args;
1508
- const { page = 0, perPage = 40, dateRange } = selectBy?.pagination || {};
1509
- const fromDate = dateRange?.start;
1510
- const toDate = dateRange?.end;
1511
- const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: Number.MAX_SAFE_INTEGER });
1512
- this.logger.debug("Getting messages with pagination", { threadId, page, perPage, fromDate, toDate, limit });
1513
- try {
1514
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1515
- let messages = [];
1516
- if (selectBy?.include?.length) {
1517
- const includeMessages = await this._getIncludedMessages(threadId, selectBy);
1518
- if (includeMessages) {
1519
- messages.push(...includeMessages);
1520
- }
1521
- }
1522
- if (limit !== 0) {
1523
- const query = this.service.entities.message.query.byThread({ entity: "message", threadId });
1524
- let results;
1525
- if (limit !== Number.MAX_SAFE_INTEGER && limit > 0) {
1526
- results = await query.go({ limit, order: "desc" });
1527
- results.data = results.data.reverse();
1528
- } else {
1529
- results = await query.go();
1530
- }
1531
- let allThreadMessages = results.data.map((data) => this.parseMessageData(data)).filter((msg) => "content" in msg);
1532
- allThreadMessages.sort((a, b) => {
1533
- const timeA = a.createdAt.getTime();
1534
- const timeB = b.createdAt.getTime();
1535
- if (timeA === timeB) {
1536
- return a.id.localeCompare(b.id);
1537
- }
1538
- return timeA - timeB;
1539
- });
1540
- const excludeIds = messages.map((m) => m.id);
1541
- if (excludeIds.length > 0) {
1542
- allThreadMessages = allThreadMessages.filter((msg) => !excludeIds.includes(msg.id));
1543
- }
1544
- messages.push(...allThreadMessages);
1545
- }
1546
- messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
1547
- if (fromDate || toDate) {
1548
- messages = messages.filter((msg) => {
1549
- const createdAt = new Date(msg.createdAt).getTime();
1550
- if (fromDate && createdAt < new Date(fromDate).getTime()) return false;
1551
- if (toDate && createdAt > new Date(toDate).getTime()) return false;
1552
- return true;
1553
- });
1554
- }
1555
- const total = messages.length;
1556
- const start = page * perPage;
1557
- const end = start + perPage;
1558
- const paginatedMessages = messages.slice(start, end);
1559
- const hasMore = end < total;
1560
- const list = new agent.MessageList({ threadId, resourceId }).add(paginatedMessages, "memory");
1561
- const finalMessages = format === "v2" ? list.get.all.v2() : list.get.all.v1();
1562
- return {
1563
- messages: finalMessages,
1564
- total,
1565
- page,
1566
- perPage,
1567
- hasMore
1568
- };
1569
- } catch (error$1) {
1570
- const mastraError = new error.MastraError(
1571
- {
1572
- id: "STORAGE_DYNAMODB_STORE_GET_MESSAGES_PAGINATED_FAILED",
1573
- domain: error.ErrorDomain.STORAGE,
1574
- category: error.ErrorCategory.THIRD_PARTY,
1575
- details: { threadId, resourceId: resourceId ?? "" }
1576
- },
1577
- error$1
1578
- );
1579
- this.logger?.trackException?.(mastraError);
1580
- this.logger?.error?.(mastraError.toString());
1581
- return { messages: [], total: 0, page, perPage, hasMore: false };
1582
- }
1583
- }
1584
1390
  // Helper method to get included messages with context
1585
1391
  async _getIncludedMessages(threadId, selectBy) {
1586
1392
  if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
@@ -1847,11 +1653,10 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
1847
1653
  [storage.TABLE_THREADS]: "thread",
1848
1654
  [storage.TABLE_MESSAGES]: "message",
1849
1655
  [storage.TABLE_WORKFLOW_SNAPSHOT]: "workflow_snapshot",
1850
- [storage.TABLE_EVALS]: "eval",
1851
1656
  [storage.TABLE_SCORERS]: "score",
1852
1657
  [storage.TABLE_TRACES]: "trace",
1853
1658
  [storage.TABLE_RESOURCES]: "resource",
1854
- [storage.TABLE_AI_SPANS]: "ai_span"
1659
+ [storage.TABLE_SPANS]: "ai_span"
1855
1660
  };
1856
1661
  return mapping[tableName] || null;
1857
1662
  }
@@ -2036,6 +1841,10 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
2036
1841
  if (!item.id) throw new Error(`Missing required key 'id' for entity 'score'`);
2037
1842
  key.id = item.id;
2038
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;
2039
1848
  default:
2040
1849
  this.logger.warn(`Unknown entity type encountered during clearTable: ${entityName}`);
2041
1850
  throw new Error(`Cannot construct delete key for unknown entity type: ${entityName}`);
@@ -2178,34 +1987,47 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2178
1987
  }
2179
1988
  }
2180
1989
  async saveScore(score) {
2181
- this.logger.debug("Saving score", { scorerId: score.scorerId, runId: score.runId });
1990
+ let validatedScore;
1991
+ try {
1992
+ validatedScore = evals.saveScorePayloadSchema.parse(score);
1993
+ } catch (error$1) {
1994
+ throw new error.MastraError(
1995
+ {
1996
+ id: "STORAGE_DYNAMODB_STORE_SAVE_SCORE_FAILED",
1997
+ domain: error.ErrorDomain.STORAGE,
1998
+ category: error.ErrorCategory.THIRD_PARTY
1999
+ },
2000
+ error$1
2001
+ );
2002
+ }
2182
2003
  const now = /* @__PURE__ */ new Date();
2183
2004
  const scoreId = `score-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
2184
2005
  const scoreData = {
2185
2006
  entity: "score",
2186
2007
  id: scoreId,
2187
- scorerId: score.scorerId,
2188
- traceId: score.traceId || "",
2189
- runId: score.runId,
2190
- scorer: typeof score.scorer === "string" ? score.scorer : JSON.stringify(score.scorer),
2191
- preprocessStepResult: typeof score.preprocessStepResult === "string" ? score.preprocessStepResult : JSON.stringify(score.preprocessStepResult),
2192
- analyzeStepResult: typeof score.analyzeStepResult === "string" ? score.analyzeStepResult : JSON.stringify(score.analyzeStepResult),
2193
- score: score.score,
2194
- reason: score.reason,
2195
- preprocessPrompt: score.preprocessPrompt,
2196
- generateScorePrompt: score.generateScorePrompt,
2197
- analyzePrompt: score.analyzePrompt,
2198
- reasonPrompt: score.reasonPrompt,
2199
- input: typeof score.input === "string" ? score.input : JSON.stringify(score.input),
2200
- output: typeof score.output === "string" ? score.output : JSON.stringify(score.output),
2201
- additionalContext: typeof score.additionalContext === "string" ? score.additionalContext : JSON.stringify(score.additionalContext),
2202
- runtimeContext: typeof score.runtimeContext === "string" ? score.runtimeContext : JSON.stringify(score.runtimeContext),
2203
- entityType: score.entityType,
2204
- entityData: typeof score.entity === "string" ? score.entity : JSON.stringify(score.entity),
2205
- entityId: score.entityId,
2206
- source: score.source,
2207
- resourceId: score.resourceId || "",
2208
- threadId: score.threadId || "",
2008
+ scorerId: validatedScore.scorerId,
2009
+ traceId: validatedScore.traceId || "",
2010
+ spanId: validatedScore.spanId || "",
2011
+ runId: validatedScore.runId,
2012
+ scorer: typeof validatedScore.scorer === "string" ? validatedScore.scorer : JSON.stringify(validatedScore.scorer),
2013
+ preprocessStepResult: typeof validatedScore.preprocessStepResult === "string" ? validatedScore.preprocessStepResult : JSON.stringify(validatedScore.preprocessStepResult),
2014
+ analyzeStepResult: typeof validatedScore.analyzeStepResult === "string" ? validatedScore.analyzeStepResult : JSON.stringify(validatedScore.analyzeStepResult),
2015
+ score: validatedScore.score,
2016
+ reason: validatedScore.reason,
2017
+ preprocessPrompt: validatedScore.preprocessPrompt,
2018
+ generateScorePrompt: validatedScore.generateScorePrompt,
2019
+ generateReasonPrompt: validatedScore.generateReasonPrompt,
2020
+ analyzePrompt: validatedScore.analyzePrompt,
2021
+ input: typeof validatedScore.input === "string" ? validatedScore.input : JSON.stringify(validatedScore.input),
2022
+ output: typeof validatedScore.output === "string" ? validatedScore.output : JSON.stringify(validatedScore.output),
2023
+ additionalContext: typeof validatedScore.additionalContext === "string" ? validatedScore.additionalContext : JSON.stringify(validatedScore.additionalContext),
2024
+ requestContext: typeof validatedScore.requestContext === "string" ? validatedScore.requestContext : JSON.stringify(validatedScore.requestContext),
2025
+ entityType: validatedScore.entityType,
2026
+ entityData: typeof validatedScore.entity === "string" ? validatedScore.entity : JSON.stringify(validatedScore.entity),
2027
+ entityId: validatedScore.entityId,
2028
+ source: validatedScore.source,
2029
+ resourceId: validatedScore.resourceId || "",
2030
+ threadId: validatedScore.threadId || "",
2209
2031
  createdAt: now.toISOString(),
2210
2032
  updatedAt: now.toISOString()
2211
2033
  };
@@ -2230,7 +2052,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2230
2052
  );
2231
2053
  }
2232
2054
  }
2233
- async getScoresByScorerId({
2055
+ async listScoresByScorerId({
2234
2056
  scorerId,
2235
2057
  pagination,
2236
2058
  entityId,
@@ -2251,18 +2073,19 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2251
2073
  allScores = allScores.filter((score) => score.source === source);
2252
2074
  }
2253
2075
  allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2254
- const startIndex = pagination.page * pagination.perPage;
2255
- const endIndex = startIndex + pagination.perPage;
2256
- const paginatedScores = allScores.slice(startIndex, endIndex);
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);
2257
2079
  const total = allScores.length;
2258
- const hasMore = endIndex < total;
2080
+ const end = perPageInput === false ? allScores.length : start + perPage;
2081
+ const paginatedScores = allScores.slice(start, end);
2259
2082
  return {
2260
2083
  scores: paginatedScores,
2261
2084
  pagination: {
2262
2085
  total,
2263
- page: pagination.page,
2264
- perPage: pagination.perPage,
2265
- hasMore
2086
+ page,
2087
+ perPage: perPageForResponse,
2088
+ hasMore: end < total
2266
2089
  }
2267
2090
  };
2268
2091
  } catch (error$1) {
@@ -2284,7 +2107,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2284
2107
  );
2285
2108
  }
2286
2109
  }
2287
- async getScoresByRunId({
2110
+ async listScoresByRunId({
2288
2111
  runId,
2289
2112
  pagination
2290
2113
  }) {
@@ -2294,18 +2117,19 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2294
2117
  const results = await query.go();
2295
2118
  const allScores = results.data.map((data) => this.parseScoreData(data));
2296
2119
  allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2297
- const startIndex = pagination.page * pagination.perPage;
2298
- const endIndex = startIndex + pagination.perPage;
2299
- const paginatedScores = allScores.slice(startIndex, endIndex);
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);
2300
2123
  const total = allScores.length;
2301
- const hasMore = endIndex < total;
2124
+ const end = perPageInput === false ? allScores.length : start + perPage;
2125
+ const paginatedScores = allScores.slice(start, end);
2302
2126
  return {
2303
2127
  scores: paginatedScores,
2304
2128
  pagination: {
2305
2129
  total,
2306
- page: pagination.page,
2307
- perPage: pagination.perPage,
2308
- hasMore
2130
+ page,
2131
+ perPage: perPageForResponse,
2132
+ hasMore: end < total
2309
2133
  }
2310
2134
  };
2311
2135
  } catch (error$1) {
@@ -2320,7 +2144,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2320
2144
  );
2321
2145
  }
2322
2146
  }
2323
- async getScoresByEntityId({
2147
+ async listScoresByEntityId({
2324
2148
  entityId,
2325
2149
  entityType,
2326
2150
  pagination
@@ -2332,18 +2156,19 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2332
2156
  let allScores = results.data.map((data) => this.parseScoreData(data));
2333
2157
  allScores = allScores.filter((score) => score.entityType === entityType);
2334
2158
  allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2335
- const startIndex = pagination.page * pagination.perPage;
2336
- const endIndex = startIndex + pagination.perPage;
2337
- const paginatedScores = allScores.slice(startIndex, endIndex);
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);
2338
2162
  const total = allScores.length;
2339
- const hasMore = endIndex < total;
2163
+ const end = perPageInput === false ? allScores.length : start + perPage;
2164
+ const paginatedScores = allScores.slice(start, end);
2340
2165
  return {
2341
2166
  scores: paginatedScores,
2342
2167
  pagination: {
2343
2168
  total,
2344
- page: pagination.page,
2345
- perPage: pagination.perPage,
2346
- hasMore
2169
+ page,
2170
+ perPage: perPageForResponse,
2171
+ hasMore: end < total
2347
2172
  }
2348
2173
  };
2349
2174
  } catch (error$1) {
@@ -2358,234 +2183,39 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2358
2183
  );
2359
2184
  }
2360
2185
  }
2361
- };
2362
- var TracesStorageDynamoDB = class extends storage.TracesStorage {
2363
- service;
2364
- operations;
2365
- constructor({ service, operations }) {
2366
- super();
2367
- this.service = service;
2368
- this.operations = operations;
2369
- }
2370
- // Trace operations
2371
- async getTraces(args) {
2372
- const { name, scope, page, perPage } = args;
2373
- this.logger.debug("Getting traces", { name, scope, page, perPage });
2374
- try {
2375
- let query;
2376
- if (name) {
2377
- query = this.service.entities.trace.query.byName({ entity: "trace", name });
2378
- } else if (scope) {
2379
- query = this.service.entities.trace.query.byScope({ entity: "trace", scope });
2380
- } else {
2381
- this.logger.warn("Performing a scan operation on traces - consider using a more specific query");
2382
- query = this.service.entities.trace.scan;
2383
- }
2384
- let items = [];
2385
- let cursor = null;
2386
- let pagesFetched = 0;
2387
- const startPage = page > 0 ? page : 1;
2388
- do {
2389
- const results = await query.go({ cursor, limit: perPage });
2390
- pagesFetched++;
2391
- if (pagesFetched === startPage) {
2392
- items = results.data;
2393
- break;
2394
- }
2395
- cursor = results.cursor;
2396
- if (!cursor && results.data.length > 0 && pagesFetched < startPage) {
2397
- break;
2398
- }
2399
- } while (cursor && pagesFetched < startPage);
2400
- return items;
2401
- } catch (error$1) {
2402
- throw new error.MastraError(
2403
- {
2404
- id: "STORAGE_DYNAMODB_STORE_GET_TRACES_FAILED",
2405
- domain: error.ErrorDomain.STORAGE,
2406
- category: error.ErrorCategory.THIRD_PARTY
2407
- },
2408
- error$1
2409
- );
2410
- }
2411
- }
2412
- async batchTraceInsert({ records }) {
2413
- this.logger.debug("Batch inserting traces", { count: records.length });
2414
- if (!records.length) {
2415
- return;
2416
- }
2417
- try {
2418
- const recordsToSave = records.map((rec) => ({ entity: "trace", ...rec }));
2419
- await this.operations.batchInsert({
2420
- tableName: storage.TABLE_TRACES,
2421
- records: recordsToSave
2422
- // Pass records with 'entity' included
2423
- });
2424
- } catch (error$1) {
2425
- throw new error.MastraError(
2426
- {
2427
- id: "STORAGE_DYNAMODB_STORE_BATCH_TRACE_INSERT_FAILED",
2428
- domain: error.ErrorDomain.STORAGE,
2429
- category: error.ErrorCategory.THIRD_PARTY,
2430
- details: { count: records.length }
2431
- },
2432
- error$1
2433
- );
2434
- }
2435
- }
2436
- async getTracesPaginated(args) {
2437
- const { name, scope, page = 0, perPage = 100, attributes, filters, dateRange } = args;
2438
- this.logger.debug("Getting traces with pagination", { name, scope, page, perPage, attributes, filters, dateRange });
2186
+ async listScoresBySpan({
2187
+ traceId,
2188
+ spanId,
2189
+ pagination
2190
+ }) {
2191
+ this.logger.debug("Getting scores by span", { traceId, spanId, pagination });
2439
2192
  try {
2440
- let query;
2441
- if (name) {
2442
- query = this.service.entities.trace.query.byName({ entity: "trace", name });
2443
- } else if (scope) {
2444
- query = this.service.entities.trace.query.byScope({ entity: "trace", scope });
2445
- } else {
2446
- this.logger.warn("Performing a scan operation on traces - consider using a more specific query");
2447
- query = this.service.entities.trace.scan;
2448
- }
2449
- const results = await query.go({
2450
- order: "desc",
2451
- pages: "all"
2452
- // Get all pages to apply filtering and pagination
2453
- });
2454
- if (!results.data.length) {
2455
- return {
2456
- traces: [],
2457
- total: 0,
2193
+ const query = this.service.entities.score.query.bySpan({ entity: "score", traceId, spanId });
2194
+ const results = await query.go();
2195
+ const allScores = results.data.map((data) => this.parseScoreData(data));
2196
+ allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
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);
2200
+ const total = allScores.length;
2201
+ const end = perPageInput === false ? allScores.length : start + perPage;
2202
+ const paginatedScores = allScores.slice(start, end);
2203
+ return {
2204
+ scores: paginatedScores,
2205
+ pagination: {
2206
+ total,
2458
2207
  page,
2459
- perPage,
2460
- hasMore: false
2461
- };
2462
- }
2463
- let filteredData = results.data;
2464
- if (attributes) {
2465
- filteredData = filteredData.filter((item) => {
2466
- try {
2467
- let itemAttributes = {};
2468
- if (item.attributes) {
2469
- if (typeof item.attributes === "string") {
2470
- if (item.attributes === "[object Object]") {
2471
- itemAttributes = {};
2472
- } else {
2473
- try {
2474
- itemAttributes = JSON.parse(item.attributes);
2475
- } catch {
2476
- itemAttributes = {};
2477
- }
2478
- }
2479
- } else if (typeof item.attributes === "object") {
2480
- itemAttributes = item.attributes;
2481
- }
2482
- }
2483
- return Object.entries(attributes).every(([key, value]) => itemAttributes[key] === value);
2484
- } catch (e) {
2485
- this.logger.warn("Failed to parse attributes during filtering", { item, error: e });
2486
- return false;
2487
- }
2488
- });
2489
- }
2490
- if (dateRange?.start) {
2491
- filteredData = filteredData.filter((item) => {
2492
- const itemDate = new Date(item.createdAt);
2493
- return itemDate >= dateRange.start;
2494
- });
2495
- }
2496
- if (dateRange?.end) {
2497
- filteredData = filteredData.filter((item) => {
2498
- const itemDate = new Date(item.createdAt);
2499
- return itemDate <= dateRange.end;
2500
- });
2501
- }
2502
- const total = filteredData.length;
2503
- const start = page * perPage;
2504
- const end = start + perPage;
2505
- const paginatedData = filteredData.slice(start, end);
2506
- const traces = paginatedData.map((item) => {
2507
- let attributes2;
2508
- if (item.attributes) {
2509
- if (typeof item.attributes === "string") {
2510
- if (item.attributes === "[object Object]") {
2511
- attributes2 = void 0;
2512
- } else {
2513
- try {
2514
- attributes2 = JSON.parse(item.attributes);
2515
- } catch {
2516
- attributes2 = void 0;
2517
- }
2518
- }
2519
- } else if (typeof item.attributes === "object") {
2520
- attributes2 = item.attributes;
2521
- }
2522
- }
2523
- let status;
2524
- if (item.status) {
2525
- if (typeof item.status === "string") {
2526
- try {
2527
- status = JSON.parse(item.status);
2528
- } catch {
2529
- status = void 0;
2530
- }
2531
- } else if (typeof item.status === "object") {
2532
- status = item.status;
2533
- }
2534
- }
2535
- let events;
2536
- if (item.events) {
2537
- if (typeof item.events === "string") {
2538
- try {
2539
- events = JSON.parse(item.events);
2540
- } catch {
2541
- events = void 0;
2542
- }
2543
- } else if (Array.isArray(item.events)) {
2544
- events = item.events;
2545
- }
2546
- }
2547
- let links;
2548
- if (item.links) {
2549
- if (typeof item.links === "string") {
2550
- try {
2551
- links = JSON.parse(item.links);
2552
- } catch {
2553
- links = void 0;
2554
- }
2555
- } else if (Array.isArray(item.links)) {
2556
- links = item.links;
2557
- }
2208
+ perPage: perPageForResponse,
2209
+ hasMore: end < total
2558
2210
  }
2559
- return {
2560
- id: item.id,
2561
- parentSpanId: item.parentSpanId,
2562
- name: item.name,
2563
- traceId: item.traceId,
2564
- scope: item.scope,
2565
- kind: item.kind,
2566
- attributes: attributes2,
2567
- status,
2568
- events,
2569
- links,
2570
- other: item.other,
2571
- startTime: item.startTime,
2572
- endTime: item.endTime,
2573
- createdAt: item.createdAt
2574
- };
2575
- });
2576
- return {
2577
- traces,
2578
- total,
2579
- page,
2580
- perPage,
2581
- hasMore: end < total
2582
2211
  };
2583
2212
  } catch (error$1) {
2584
2213
  throw new error.MastraError(
2585
2214
  {
2586
- id: "STORAGE_DYNAMODB_STORE_GET_TRACES_PAGINATED_FAILED",
2215
+ id: "STORAGE_DYNAMODB_STORE_GET_SCORES_BY_SPAN_FAILED",
2587
2216
  domain: error.ErrorDomain.STORAGE,
2588
- category: error.ErrorCategory.THIRD_PARTY
2217
+ category: error.ErrorCategory.THIRD_PARTY,
2218
+ details: { traceId, spanId, page: pagination.page, perPage: pagination.perPage }
2589
2219
  },
2590
2220
  error$1
2591
2221
  );
@@ -2613,7 +2243,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2613
2243
  // runId,
2614
2244
  // stepId,
2615
2245
  // result,
2616
- // runtimeContext,
2246
+ // requestContext,
2617
2247
  }) {
2618
2248
  throw new Error("Method not implemented.");
2619
2249
  }
@@ -2628,11 +2258,11 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2628
2258
  async persistWorkflowSnapshot({
2629
2259
  workflowName,
2630
2260
  runId,
2261
+ resourceId,
2631
2262
  snapshot
2632
2263
  }) {
2633
2264
  this.logger.debug("Persisting workflow snapshot", { workflowName, runId });
2634
2265
  try {
2635
- const resourceId = "resourceId" in snapshot ? snapshot.resourceId : void 0;
2636
2266
  const now = (/* @__PURE__ */ new Date()).toISOString();
2637
2267
  const data = {
2638
2268
  entity: "workflow_snapshot",
@@ -2640,7 +2270,6 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2640
2270
  workflow_name: workflowName,
2641
2271
  run_id: runId,
2642
2272
  snapshot: JSON.stringify(snapshot),
2643
- // Stringify the snapshot object
2644
2273
  createdAt: now,
2645
2274
  updatedAt: now,
2646
2275
  resourceId
@@ -2686,11 +2315,24 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2686
2315
  );
2687
2316
  }
2688
2317
  }
2689
- async getWorkflowRuns(args) {
2318
+ async listWorkflowRuns(args) {
2690
2319
  this.logger.debug("Getting workflow runs", { args });
2691
2320
  try {
2692
- const limit = args?.limit || 10;
2693
- 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;
2694
2336
  let query;
2695
2337
  if (args?.workflowName) {
2696
2338
  query = this.service.entities.workflow_snapshot.query.primary({
@@ -2712,6 +2354,11 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2712
2354
  });
2713
2355
  if (pageResults.data && pageResults.data.length > 0) {
2714
2356
  let pageFilteredData = pageResults.data;
2357
+ if (args?.status) {
2358
+ pageFilteredData = pageFilteredData.filter((snapshot) => {
2359
+ return snapshot.snapshot.status === args.status;
2360
+ });
2361
+ }
2715
2362
  if (args?.fromDate || args?.toDate) {
2716
2363
  pageFilteredData = pageFilteredData.filter((snapshot) => {
2717
2364
  const createdAt = new Date(snapshot.createdAt);
@@ -2737,7 +2384,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2737
2384
  return { runs: [], total: 0 };
2738
2385
  }
2739
2386
  const total = allMatchingSnapshots.length;
2740
- const paginatedData = allMatchingSnapshots.slice(offset, offset + limit);
2387
+ const paginatedData = allMatchingSnapshots.slice(offset, offset + normalizedPerPage);
2741
2388
  const runs = paginatedData.map((snapshot) => formatWorkflowRun(snapshot));
2742
2389
  return {
2743
2390
  runs,
@@ -2746,7 +2393,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2746
2393
  } catch (error$1) {
2747
2394
  throw new error.MastraError(
2748
2395
  {
2749
- id: "STORAGE_DYNAMODB_STORE_GET_WORKFLOW_RUNS_FAILED",
2396
+ id: "STORAGE_DYNAMODB_STORE_LIST_WORKFLOW_RUNS_FAILED",
2750
2397
  domain: error.ErrorDomain.STORAGE,
2751
2398
  category: error.ErrorCategory.THIRD_PARTY,
2752
2399
  details: { workflowName: args?.workflowName || "", resourceId: args?.resourceId || "" }
@@ -2758,8 +2405,6 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2758
2405
  async getWorkflowRunById(args) {
2759
2406
  const { runId, workflowName } = args;
2760
2407
  this.logger.debug("Getting workflow run by ID", { runId, workflowName });
2761
- console.log("workflowName", workflowName);
2762
- console.log("runId", runId);
2763
2408
  try {
2764
2409
  if (workflowName) {
2765
2410
  this.logger.debug("WorkflowName provided, using direct GET operation.");
@@ -2769,7 +2414,6 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2769
2414
  workflow_name: workflowName,
2770
2415
  run_id: runId
2771
2416
  }).go();
2772
- console.log("result", result2);
2773
2417
  if (!result2.data) {
2774
2418
  return null;
2775
2419
  }
@@ -2822,7 +2466,7 @@ var DynamoDBStore = class extends storage.MastraStorage {
2822
2466
  hasInitialized = null;
2823
2467
  stores;
2824
2468
  constructor({ name, config }) {
2825
- super({ name });
2469
+ super({ id: config.id, name });
2826
2470
  try {
2827
2471
  if (!config.tableName || typeof config.tableName !== "string" || config.tableName.trim() === "") {
2828
2472
  throw new Error("DynamoDBStore: config.tableName must be provided and cannot be empty.");
@@ -2845,14 +2489,11 @@ var DynamoDBStore = class extends storage.MastraStorage {
2845
2489
  tableName: this.tableName,
2846
2490
  client: this.client
2847
2491
  });
2848
- const traces = new TracesStorageDynamoDB({ service: this.service, operations });
2849
2492
  const workflows = new WorkflowStorageDynamoDB({ service: this.service });
2850
2493
  const memory = new MemoryStorageDynamoDB({ service: this.service });
2851
2494
  const scores = new ScoresStorageDynamoDB({ service: this.service });
2852
2495
  this.stores = {
2853
2496
  operations,
2854
- legacyEvals: new LegacyEvalsDynamoDB({ service: this.service, tableName: this.tableName }),
2855
- traces,
2856
2497
  workflows,
2857
2498
  memory,
2858
2499
  scores
@@ -2874,7 +2515,8 @@ var DynamoDBStore = class extends storage.MastraStorage {
2874
2515
  resourceWorkingMemory: true,
2875
2516
  hasColumn: false,
2876
2517
  createTable: false,
2877
- deleteMessages: false
2518
+ deleteMessages: false,
2519
+ listScoresBySpan: true
2878
2520
  };
2879
2521
  }
2880
2522
  /**
@@ -2969,9 +2611,6 @@ var DynamoDBStore = class extends storage.MastraStorage {
2969
2611
  async getThreadById({ threadId }) {
2970
2612
  return this.stores.memory.getThreadById({ threadId });
2971
2613
  }
2972
- async getThreadsByResourceId(args) {
2973
- return this.stores.memory.getThreadsByResourceId(args);
2974
- }
2975
2614
  async saveThread({ thread }) {
2976
2615
  return this.stores.memory.saveThread({ thread });
2977
2616
  }
@@ -2985,51 +2624,24 @@ var DynamoDBStore = class extends storage.MastraStorage {
2985
2624
  async deleteThread({ threadId }) {
2986
2625
  return this.stores.memory.deleteThread({ threadId });
2987
2626
  }
2988
- async getMessages({
2989
- threadId,
2990
- resourceId,
2991
- selectBy,
2992
- format
2993
- }) {
2994
- return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format });
2995
- }
2996
- async getMessagesById({
2997
- messageIds,
2998
- format
2999
- }) {
3000
- return this.stores.memory.getMessagesById({ messageIds, format });
2627
+ async listMessagesById(args) {
2628
+ return this.stores.memory.listMessagesById(args);
3001
2629
  }
3002
2630
  async saveMessages(args) {
3003
2631
  return this.stores.memory.saveMessages(args);
3004
2632
  }
3005
- async getThreadsByResourceIdPaginated(args) {
3006
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
3007
- }
3008
- async getMessagesPaginated(args) {
3009
- return this.stores.memory.getMessagesPaginated(args);
3010
- }
3011
2633
  async updateMessages(_args) {
3012
2634
  return this.stores.memory.updateMessages(_args);
3013
2635
  }
3014
- // Trace operations
3015
- async getTraces(args) {
3016
- return this.stores.traces.getTraces(args);
3017
- }
3018
- async batchTraceInsert({ records }) {
3019
- return this.stores.traces.batchTraceInsert({ records });
3020
- }
3021
- async getTracesPaginated(_args) {
3022
- return this.stores.traces.getTracesPaginated(_args);
3023
- }
3024
2636
  // Workflow operations
3025
2637
  async updateWorkflowResults({
3026
2638
  workflowName,
3027
2639
  runId,
3028
2640
  stepId,
3029
2641
  result,
3030
- runtimeContext
2642
+ requestContext
3031
2643
  }) {
3032
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2644
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
3033
2645
  }
3034
2646
  async updateWorkflowState({
3035
2647
  workflowName,
@@ -3041,9 +2653,10 @@ var DynamoDBStore = class extends storage.MastraStorage {
3041
2653
  async persistWorkflowSnapshot({
3042
2654
  workflowName,
3043
2655
  runId,
2656
+ resourceId,
3044
2657
  snapshot
3045
2658
  }) {
3046
- return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2659
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
3047
2660
  }
3048
2661
  async loadWorkflowSnapshot({
3049
2662
  workflowName,
@@ -3051,8 +2664,8 @@ var DynamoDBStore = class extends storage.MastraStorage {
3051
2664
  }) {
3052
2665
  return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
3053
2666
  }
3054
- async getWorkflowRuns(args) {
3055
- return this.stores.workflows.getWorkflowRuns(args);
2667
+ async listWorkflowRuns(args) {
2668
+ return this.stores.workflows.listWorkflowRuns(args);
3056
2669
  }
3057
2670
  async getWorkflowRunById(args) {
3058
2671
  return this.stores.workflows.getWorkflowRunById(args);
@@ -3070,13 +2683,6 @@ var DynamoDBStore = class extends storage.MastraStorage {
3070
2683
  }) {
3071
2684
  return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
3072
2685
  }
3073
- // Eval operations
3074
- async getEvalsByAgentName(agentName, type) {
3075
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
3076
- }
3077
- async getEvals(options) {
3078
- return this.stores.legacyEvals.getEvals(options);
3079
- }
3080
2686
  /**
3081
2687
  * Closes the DynamoDB client connection and cleans up resources.
3082
2688
  * Should be called when the store is no longer needed, e.g., at the end of tests or application shutdown.
@@ -3106,31 +2712,38 @@ var DynamoDBStore = class extends storage.MastraStorage {
3106
2712
  async saveScore(_score) {
3107
2713
  return this.stores.scores.saveScore(_score);
3108
2714
  }
3109
- async getScoresByRunId({
2715
+ async listScoresByRunId({
3110
2716
  runId: _runId,
3111
2717
  pagination: _pagination
3112
2718
  }) {
3113
- return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
2719
+ return this.stores.scores.listScoresByRunId({ runId: _runId, pagination: _pagination });
3114
2720
  }
3115
- async getScoresByEntityId({
2721
+ async listScoresByEntityId({
3116
2722
  entityId: _entityId,
3117
2723
  entityType: _entityType,
3118
2724
  pagination: _pagination
3119
2725
  }) {
3120
- return this.stores.scores.getScoresByEntityId({
2726
+ return this.stores.scores.listScoresByEntityId({
3121
2727
  entityId: _entityId,
3122
2728
  entityType: _entityType,
3123
2729
  pagination: _pagination
3124
2730
  });
3125
2731
  }
3126
- async getScoresByScorerId({
2732
+ async listScoresByScorerId({
3127
2733
  scorerId,
3128
2734
  source,
3129
2735
  entityId,
3130
2736
  entityType,
3131
2737
  pagination
3132
2738
  }) {
3133
- return this.stores.scores.getScoresByScorerId({ scorerId, source, entityId, entityType, pagination });
2739
+ return this.stores.scores.listScoresByScorerId({ scorerId, source, entityId, entityType, pagination });
2740
+ }
2741
+ async listScoresBySpan({
2742
+ traceId,
2743
+ spanId,
2744
+ pagination
2745
+ }) {
2746
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
3134
2747
  }
3135
2748
  };
3136
2749