@mastra/dynamodb 0.0.0-remove-unused-import-20250909212718 → 0.0.0-remove-ai-peer-dep-from-evals-20260105220639

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +1312 -3
  2. package/README.md +0 -4
  3. package/dist/docs/README.md +31 -0
  4. package/dist/docs/SKILL.md +32 -0
  5. package/dist/docs/SOURCE_MAP.json +6 -0
  6. package/dist/docs/storage/01-reference.md +162 -0
  7. package/dist/entities/index.d.ts +20 -1
  8. package/dist/entities/index.d.ts.map +1 -1
  9. package/dist/entities/score.d.ts +20 -1
  10. package/dist/entities/score.d.ts.map +1 -1
  11. package/dist/index.cjs +574 -1222
  12. package/dist/index.cjs.map +1 -1
  13. package/dist/index.js +573 -1224
  14. package/dist/index.js.map +1 -1
  15. package/dist/storage/db/index.d.ts +32 -0
  16. package/dist/storage/db/index.d.ts.map +1 -0
  17. package/dist/storage/domains/memory/index.d.ts +17 -45
  18. package/dist/storage/domains/memory/index.d.ts.map +1 -1
  19. package/dist/storage/domains/scores/index.d.ts +46 -0
  20. package/dist/storage/domains/scores/index.d.ts.map +1 -0
  21. package/dist/storage/domains/utils.d.ts +7 -0
  22. package/dist/storage/domains/utils.d.ts.map +1 -0
  23. package/dist/storage/domains/workflows/index.d.ts +17 -24
  24. package/dist/storage/domains/workflows/index.d.ts.map +1 -1
  25. package/dist/storage/index.d.ts +87 -209
  26. package/dist/storage/index.d.ts.map +1 -1
  27. package/package.json +20 -18
  28. package/dist/storage/domains/legacy-evals/index.d.ts +0 -19
  29. package/dist/storage/domains/legacy-evals/index.d.ts.map +0 -1
  30. package/dist/storage/domains/operations/index.d.ts +0 -69
  31. package/dist/storage/domains/operations/index.d.ts.map +0 -1
  32. package/dist/storage/domains/score/index.d.ts +0 -43
  33. package/dist/storage/domains/score/index.d.ts.map +0 -1
  34. package/dist/storage/domains/traces/index.d.ts +0 -28
  35. package/dist/storage/domains/traces/index.d.ts.map +0 -1
package/dist/index.cjs CHANGED
@@ -6,6 +6,7 @@ var error = require('@mastra/core/error');
6
6
  var storage = require('@mastra/core/storage');
7
7
  var electrodb = require('electrodb');
8
8
  var agent = require('@mastra/core/agent');
9
+ var evals = require('@mastra/core/evals');
9
10
 
10
11
  // src/storage/index.ts
11
12
 
@@ -372,6 +373,10 @@ var scoreEntity = new electrodb.Entity({
372
373
  type: "string",
373
374
  required: false
374
375
  },
376
+ spanId: {
377
+ type: "string",
378
+ required: false
379
+ },
375
380
  runId: {
376
381
  type: "string",
377
382
  required: true
@@ -420,6 +425,10 @@ var scoreEntity = new electrodb.Entity({
420
425
  return value;
421
426
  }
422
427
  },
428
+ preprocessPrompt: {
429
+ type: "string",
430
+ required: false
431
+ },
423
432
  preprocessStepResult: {
424
433
  type: "string",
425
434
  required: false,
@@ -559,7 +568,7 @@ var scoreEntity = new electrodb.Entity({
559
568
  return value;
560
569
  }
561
570
  },
562
- runtimeContext: {
571
+ requestContext: {
563
572
  type: "string",
564
573
  required: false,
565
574
  set: (value) => {
@@ -658,6 +667,11 @@ var scoreEntity = new electrodb.Entity({
658
667
  index: "gsi6",
659
668
  pk: { field: "gsi6pk", composite: ["entity", "threadId"] },
660
669
  sk: { field: "gsi6sk", composite: ["createdAt"] }
670
+ },
671
+ bySpan: {
672
+ index: "gsi7",
673
+ pk: { field: "gsi7pk", composite: ["entity", "traceId", "spanId"] },
674
+ sk: { field: "gsi7sk", composite: ["createdAt"] }
661
675
  }
662
676
  }
663
677
  });
@@ -925,193 +939,114 @@ function getElectroDbService(client, tableName) {
925
939
  }
926
940
  );
927
941
  }
928
- var LegacyEvalsDynamoDB = class extends storage.LegacyEvalsStorage {
942
+ function resolveDynamoDBConfig(config) {
943
+ if ("service" in config) {
944
+ return config.service;
945
+ }
946
+ const dynamoClient = new clientDynamodb.DynamoDBClient({
947
+ region: config.region || "us-east-1",
948
+ endpoint: config.endpoint,
949
+ credentials: config.credentials
950
+ });
951
+ const client = libDynamodb.DynamoDBDocumentClient.from(dynamoClient);
952
+ return getElectroDbService(client, config.tableName);
953
+ }
954
+ var ENTITY_MAP = {
955
+ [storage.TABLE_THREADS]: "thread",
956
+ [storage.TABLE_MESSAGES]: "message",
957
+ [storage.TABLE_RESOURCES]: "resource",
958
+ [storage.TABLE_WORKFLOW_SNAPSHOT]: "workflow_snapshot",
959
+ [storage.TABLE_SCORERS]: "score"
960
+ };
961
+ function getDeleteKey(entityName, item) {
962
+ const key = { entity: entityName };
963
+ switch (entityName) {
964
+ case "thread":
965
+ case "message":
966
+ case "resource":
967
+ case "score":
968
+ key.id = item.id;
969
+ break;
970
+ case "workflow_snapshot":
971
+ key.workflow_name = item.workflow_name;
972
+ key.run_id = item.run_id;
973
+ break;
974
+ default:
975
+ key.id = item.id;
976
+ }
977
+ return key;
978
+ }
979
+ async function deleteTableData(service, tableName) {
980
+ const entityName = ENTITY_MAP[tableName];
981
+ if (!entityName || !service.entities[entityName]) {
982
+ throw new Error(`No entity mapping found for table: ${tableName}`);
983
+ }
984
+ const entity = service.entities[entityName];
985
+ const result = await entity.scan.go({ pages: "all" });
986
+ if (!result.data.length) {
987
+ return;
988
+ }
989
+ const batchSize = 25;
990
+ for (let i = 0; i < result.data.length; i += batchSize) {
991
+ const batch = result.data.slice(i, i + batchSize);
992
+ const keysToDelete = batch.map((item) => getDeleteKey(entityName, item));
993
+ await entity.delete(keysToDelete).go();
994
+ }
995
+ }
996
+
997
+ // src/storage/domains/memory/index.ts
998
+ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
929
999
  service;
930
- tableName;
931
- constructor({ service, tableName }) {
1000
+ constructor(config) {
932
1001
  super();
933
- this.service = service;
934
- this.tableName = tableName;
1002
+ this.service = resolveDynamoDBConfig(config);
935
1003
  }
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
- }
1004
+ async dangerouslyClearAll() {
1005
+ await deleteTableData(this.service, storage.TABLE_THREADS);
1006
+ await deleteTableData(this.service, storage.TABLE_MESSAGES);
1007
+ await deleteTableData(this.service, storage.TABLE_RESOURCES);
999
1008
  }
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 });
1009
+ async deleteMessages(messageIds) {
1010
+ if (!messageIds || messageIds.length === 0) {
1011
+ return;
1012
+ }
1013
+ this.logger.debug("Deleting messages", { count: messageIds.length });
1003
1014
  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;
1015
+ const threadIds = /* @__PURE__ */ new Set();
1016
+ const batchSize = 25;
1017
+ for (let i = 0; i < messageIds.length; i += batchSize) {
1018
+ const batch = messageIds.slice(i, i + batchSize);
1019
+ const messagesToDelete = await Promise.all(
1020
+ batch.map(async (id) => {
1021
+ const result = await this.service.entities.message.get({ entity: "message", id }).go();
1022
+ return result.data;
1023
+ })
1024
+ );
1025
+ for (const message of messagesToDelete) {
1026
+ if (message) {
1027
+ if (message.threadId) {
1028
+ threadIds.add(message.threadId);
1034
1029
  }
1035
- } catch (e) {
1036
- this.logger.warn("Failed to parse test_info during filtering", { record: evalRecord, error: e });
1030
+ await this.service.entities.message.delete({ entity: "message", id: message.id }).go();
1037
1031
  }
1038
- return true;
1039
- });
1032
+ }
1040
1033
  }
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
- });
1034
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1035
+ for (const threadId of threadIds) {
1036
+ await this.service.entities.thread.update({ entity: "thread", id: threadId }).set({ updatedAt: now }).go();
1054
1037
  }
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
1038
  } catch (error$1) {
1092
1039
  throw new error.MastraError(
1093
1040
  {
1094
- id: "STORAGE_DYNAMODB_STORE_GET_EVALS_FAILED",
1041
+ id: storage.createStorageErrorId("DYNAMODB", "DELETE_MESSAGES", "FAILED"),
1095
1042
  domain: error.ErrorDomain.STORAGE,
1096
1043
  category: error.ErrorCategory.THIRD_PARTY,
1097
- details: {
1098
- agentName: agentName || "all",
1099
- type: type || "all",
1100
- page,
1101
- perPage
1102
- }
1044
+ details: { count: messageIds.length }
1103
1045
  },
1104
1046
  error$1
1105
1047
  );
1106
1048
  }
1107
1049
  }
1108
- };
1109
- var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1110
- service;
1111
- constructor({ service }) {
1112
- super();
1113
- this.service = service;
1114
- }
1115
1050
  // Helper function to parse message data (handle JSON fields)
1116
1051
  parseMessageData(data) {
1117
1052
  return {
@@ -1124,17 +1059,17 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1124
1059
  };
1125
1060
  }
1126
1061
  // Helper function to transform and sort threads
1127
- transformAndSortThreads(rawThreads, orderBy, sortDirection) {
1062
+ transformAndSortThreads(rawThreads, field, direction) {
1128
1063
  return rawThreads.map((data) => ({
1129
1064
  ...data,
1130
1065
  // Convert date strings back to Date objects for consistency
1131
1066
  createdAt: typeof data.createdAt === "string" ? new Date(data.createdAt) : data.createdAt,
1132
1067
  updatedAt: typeof data.updatedAt === "string" ? new Date(data.updatedAt) : data.updatedAt
1133
1068
  })).sort((a, b) => {
1134
- const fieldA = orderBy === "createdAt" ? a.createdAt : a.updatedAt;
1135
- const fieldB = orderBy === "createdAt" ? b.createdAt : b.updatedAt;
1069
+ const fieldA = field === "createdAt" ? a.createdAt : a.updatedAt;
1070
+ const fieldB = field === "createdAt" ? b.createdAt : b.updatedAt;
1136
1071
  const comparison = fieldA.getTime() - fieldB.getTime();
1137
- return sortDirection === "DESC" ? -comparison : comparison;
1072
+ return direction === "DESC" ? -comparison : comparison;
1138
1073
  });
1139
1074
  }
1140
1075
  async getThreadById({ threadId }) {
@@ -1156,7 +1091,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1156
1091
  } catch (error$1) {
1157
1092
  throw new error.MastraError(
1158
1093
  {
1159
- id: "STORAGE_DYNAMODB_STORE_GET_THREAD_BY_ID_FAILED",
1094
+ id: storage.createStorageErrorId("DYNAMODB", "GET_THREAD_BY_ID", "FAILED"),
1160
1095
  domain: error.ErrorDomain.STORAGE,
1161
1096
  category: error.ErrorCategory.THIRD_PARTY,
1162
1097
  details: { threadId }
@@ -1165,32 +1100,6 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1165
1100
  );
1166
1101
  }
1167
1102
  }
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
1103
  async saveThread({ thread }) {
1195
1104
  this.logger.debug("Saving thread", { threadId: thread.id });
1196
1105
  const now = /* @__PURE__ */ new Date();
@@ -1210,13 +1119,13 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1210
1119
  resourceId: thread.resourceId,
1211
1120
  title: threadData.title,
1212
1121
  createdAt: thread.createdAt || now,
1213
- updatedAt: now,
1122
+ updatedAt: thread.updatedAt || now,
1214
1123
  metadata: thread.metadata
1215
1124
  };
1216
1125
  } catch (error$1) {
1217
1126
  throw new error.MastraError(
1218
1127
  {
1219
- id: "STORAGE_DYNAMODB_STORE_SAVE_THREAD_FAILED",
1128
+ id: storage.createStorageErrorId("DYNAMODB", "SAVE_THREAD", "FAILED"),
1220
1129
  domain: error.ErrorDomain.STORAGE,
1221
1130
  category: error.ErrorCategory.THIRD_PARTY,
1222
1131
  details: { threadId: thread.id }
@@ -1258,7 +1167,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1258
1167
  } catch (error$1) {
1259
1168
  throw new error.MastraError(
1260
1169
  {
1261
- id: "STORAGE_DYNAMODB_STORE_UPDATE_THREAD_FAILED",
1170
+ id: storage.createStorageErrorId("DYNAMODB", "UPDATE_THREAD", "FAILED"),
1262
1171
  domain: error.ErrorDomain.STORAGE,
1263
1172
  category: error.ErrorCategory.THIRD_PARTY,
1264
1173
  details: { threadId: id }
@@ -1270,7 +1179,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1270
1179
  async deleteThread({ threadId }) {
1271
1180
  this.logger.debug("Deleting thread", { threadId });
1272
1181
  try {
1273
- const messages = await this.getMessages({ threadId });
1182
+ const { messages } = await this.listMessages({ threadId, perPage: false });
1274
1183
  if (messages.length > 0) {
1275
1184
  const batchSize = 25;
1276
1185
  for (let i = 0; i < messages.length; i += batchSize) {
@@ -1290,7 +1199,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1290
1199
  } catch (error$1) {
1291
1200
  throw new error.MastraError(
1292
1201
  {
1293
- id: "STORAGE_DYNAMODB_STORE_DELETE_THREAD_FAILED",
1202
+ id: storage.createStorageErrorId("DYNAMODB", "DELETE_THREAD", "FAILED"),
1294
1203
  domain: error.ErrorDomain.STORAGE,
1295
1204
  category: error.ErrorCategory.THIRD_PARTY,
1296
1205
  details: { threadId }
@@ -1299,104 +1208,166 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1299
1208
  );
1300
1209
  }
1301
1210
  }
1302
- async getMessages({
1303
- threadId,
1304
- resourceId,
1305
- selectBy,
1306
- format
1307
- }) {
1308
- this.logger.debug("Getting messages", { threadId, selectBy });
1211
+ async listMessagesById({ messageIds }) {
1212
+ this.logger.debug("Getting messages by ID", { messageIds });
1213
+ if (messageIds.length === 0) return { messages: [] };
1309
1214
  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(
1215
+ const results = await Promise.all(
1216
+ messageIds.map((id) => this.service.entities.message.query.primary({ entity: "message", id }).go())
1217
+ );
1218
+ const data = results.map((result) => result.data).flat(1);
1219
+ let parsedMessages = data.map((data2) => this.parseMessageData(data2)).filter((msg) => "content" in msg);
1220
+ const uniqueMessages = parsedMessages.filter(
1348
1221
  (message, index, self) => index === self.findIndex((m) => m.id === message.id)
1349
1222
  );
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();
1223
+ const list = new agent.MessageList().add(uniqueMessages, "memory");
1224
+ return { messages: list.get.all.db() };
1353
1225
  } catch (error$1) {
1354
1226
  throw new error.MastraError(
1355
1227
  {
1356
- id: "STORAGE_DYNAMODB_STORE_GET_MESSAGES_FAILED",
1228
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_MESSAGES_BY_ID", "FAILED"),
1357
1229
  domain: error.ErrorDomain.STORAGE,
1358
1230
  category: error.ErrorCategory.THIRD_PARTY,
1359
- details: { threadId, resourceId: resourceId ?? "" }
1231
+ details: { messageIds: JSON.stringify(messageIds) }
1360
1232
  },
1361
1233
  error$1
1362
1234
  );
1363
1235
  }
1364
1236
  }
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())
1237
+ async listMessages(args) {
1238
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
1239
+ const threadIds = Array.isArray(threadId) ? threadId : [threadId];
1240
+ if (threadIds.length === 0 || threadIds.some((id) => !id.trim())) {
1241
+ throw new error.MastraError(
1242
+ {
1243
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_MESSAGES", "INVALID_THREAD_ID"),
1244
+ domain: error.ErrorDomain.STORAGE,
1245
+ category: error.ErrorCategory.THIRD_PARTY,
1246
+ details: { threadId: Array.isArray(threadId) ? threadId.join(",") : threadId }
1247
+ },
1248
+ new Error("threadId must be a non-empty string or array of non-empty strings")
1374
1249
  );
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)
1250
+ }
1251
+ const perPage = storage.normalizePerPage(perPageInput, 40);
1252
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1253
+ try {
1254
+ if (page < 0) {
1255
+ throw new error.MastraError(
1256
+ {
1257
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_MESSAGES", "INVALID_PAGE"),
1258
+ domain: error.ErrorDomain.STORAGE,
1259
+ category: error.ErrorCategory.USER,
1260
+ details: { page }
1261
+ },
1262
+ new Error("page must be >= 0")
1263
+ );
1264
+ }
1265
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
1266
+ this.logger.debug("Getting messages with listMessages", {
1267
+ threadId,
1268
+ resourceId,
1269
+ perPageInput,
1270
+ offset,
1271
+ perPage,
1272
+ page,
1273
+ field,
1274
+ direction
1275
+ });
1276
+ const query = this.service.entities.message.query.byThread({ entity: "message", threadId });
1277
+ const results = await query.go();
1278
+ let allThreadMessages = results.data.map((data) => this.parseMessageData(data)).filter((msg) => "content" in msg && typeof msg.content === "object");
1279
+ if (resourceId) {
1280
+ allThreadMessages = allThreadMessages.filter((msg) => msg.resourceId === resourceId);
1281
+ }
1282
+ allThreadMessages = storage.filterByDateRange(
1283
+ allThreadMessages,
1284
+ (msg) => new Date(msg.createdAt),
1285
+ filter?.dateRange
1379
1286
  );
1380
- const list = new agent.MessageList().add(uniqueMessages, "memory");
1381
- if (format === `v1`) return list.get.all.v1();
1382
- return list.get.all.v2();
1287
+ allThreadMessages.sort((a, b) => {
1288
+ const aValue = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
1289
+ const bValue = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
1290
+ if (aValue === bValue) {
1291
+ return a.id.localeCompare(b.id);
1292
+ }
1293
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
1294
+ });
1295
+ const total = allThreadMessages.length;
1296
+ const paginatedMessages = allThreadMessages.slice(offset, offset + perPage);
1297
+ const paginatedCount = paginatedMessages.length;
1298
+ if (total === 0 && paginatedCount === 0 && (!include || include.length === 0)) {
1299
+ return {
1300
+ messages: [],
1301
+ total: 0,
1302
+ page,
1303
+ perPage: perPageForResponse,
1304
+ hasMore: false
1305
+ };
1306
+ }
1307
+ const messageIds = new Set(paginatedMessages.map((m) => m.id));
1308
+ let includeMessages = [];
1309
+ if (include && include.length > 0) {
1310
+ const selectBy = { include };
1311
+ includeMessages = await this._getIncludedMessages(selectBy);
1312
+ for (const includeMsg of includeMessages) {
1313
+ if (!messageIds.has(includeMsg.id)) {
1314
+ paginatedMessages.push(includeMsg);
1315
+ messageIds.add(includeMsg.id);
1316
+ }
1317
+ }
1318
+ }
1319
+ const list = new agent.MessageList().add(paginatedMessages, "memory");
1320
+ let finalMessages = list.get.all.db();
1321
+ finalMessages = finalMessages.sort((a, b) => {
1322
+ const aValue = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
1323
+ const bValue = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
1324
+ if (aValue === bValue) {
1325
+ return a.id.localeCompare(b.id);
1326
+ }
1327
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
1328
+ });
1329
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
1330
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
1331
+ let hasMore = false;
1332
+ if (perPageInput !== false && !allThreadMessagesReturned) {
1333
+ hasMore = offset + paginatedCount < total;
1334
+ }
1335
+ return {
1336
+ messages: finalMessages,
1337
+ total,
1338
+ page,
1339
+ perPage: perPageForResponse,
1340
+ hasMore
1341
+ };
1383
1342
  } catch (error$1) {
1384
- throw new error.MastraError(
1343
+ const mastraError = new error.MastraError(
1385
1344
  {
1386
- id: "STORAGE_DYNAMODB_STORE_GET_MESSAGES_BY_ID_FAILED",
1345
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_MESSAGES", "FAILED"),
1387
1346
  domain: error.ErrorDomain.STORAGE,
1388
1347
  category: error.ErrorCategory.THIRD_PARTY,
1389
- details: { messageIds: JSON.stringify(messageIds) }
1348
+ details: {
1349
+ threadId: Array.isArray(threadId) ? threadId.join(",") : threadId,
1350
+ resourceId: resourceId ?? ""
1351
+ }
1390
1352
  },
1391
1353
  error$1
1392
1354
  );
1355
+ this.logger?.error?.(mastraError.toString());
1356
+ this.logger?.trackException?.(mastraError);
1357
+ return {
1358
+ messages: [],
1359
+ total: 0,
1360
+ page,
1361
+ perPage: perPageForResponse,
1362
+ hasMore: false
1363
+ };
1393
1364
  }
1394
1365
  }
1395
1366
  async saveMessages(args) {
1396
- const { messages, format = "v1" } = args;
1367
+ const { messages } = args;
1397
1368
  this.logger.debug("Saving messages", { count: messages.length });
1398
1369
  if (!messages.length) {
1399
- return [];
1370
+ return { messages: [] };
1400
1371
  }
1401
1372
  const threadId = messages[0]?.threadId;
1402
1373
  if (!threadId) {
@@ -1450,12 +1421,11 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1450
1421
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1451
1422
  }).go();
1452
1423
  const list = new agent.MessageList().add(messages, "memory");
1453
- if (format === `v1`) return list.get.all.v1();
1454
- return list.get.all.v2();
1424
+ return { messages: list.get.all.db() };
1455
1425
  } catch (error$1) {
1456
1426
  throw new error.MastraError(
1457
1427
  {
1458
- id: "STORAGE_DYNAMODB_STORE_SAVE_MESSAGES_FAILED",
1428
+ id: storage.createStorageErrorId("DYNAMODB", "SAVE_MESSAGES", "FAILED"),
1459
1429
  domain: error.ErrorDomain.STORAGE,
1460
1430
  category: error.ErrorCategory.THIRD_PARTY,
1461
1431
  details: { count: messages.length }
@@ -1464,37 +1434,48 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1464
1434
  );
1465
1435
  }
1466
1436
  }
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);
1437
+ async listThreadsByResourceId(args) {
1438
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
1439
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1440
+ if (page < 0) {
1441
+ throw new error.MastraError(
1442
+ {
1443
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_THREADS_BY_RESOURCE_ID", "INVALID_PAGE"),
1444
+ domain: error.ErrorDomain.STORAGE,
1445
+ category: error.ErrorCategory.USER,
1446
+ details: { page }
1447
+ },
1448
+ new Error("page must be >= 0")
1449
+ );
1450
+ }
1451
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1452
+ const { field, direction } = this.parseOrderBy(orderBy);
1471
1453
  this.logger.debug("Getting threads by resource ID with pagination", {
1472
1454
  resourceId,
1473
1455
  page,
1474
1456
  perPage,
1475
- orderBy,
1476
- sortDirection
1457
+ field,
1458
+ direction
1477
1459
  });
1478
1460
  try {
1479
1461
  const query = this.service.entities.thread.query.byResource({ entity: "thread", resourceId });
1480
1462
  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);
1463
+ const allThreads = this.transformAndSortThreads(results.data, field, direction);
1464
+ const endIndex = offset + perPage;
1465
+ const paginatedThreads = allThreads.slice(offset, endIndex);
1485
1466
  const total = allThreads.length;
1486
- const hasMore = endIndex < total;
1467
+ const hasMore = offset + perPage < total;
1487
1468
  return {
1488
1469
  threads: paginatedThreads,
1489
1470
  total,
1490
1471
  page,
1491
- perPage,
1472
+ perPage: perPageForResponse,
1492
1473
  hasMore
1493
1474
  };
1494
1475
  } catch (error$1) {
1495
1476
  throw new error.MastraError(
1496
1477
  {
1497
- id: "STORAGE_DYNAMODB_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
1478
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_THREADS_BY_RESOURCE_ID", "FAILED"),
1498
1479
  domain: error.ErrorDomain.STORAGE,
1499
1480
  category: error.ErrorCategory.THIRD_PARTY,
1500
1481
  details: { resourceId, page, perPage }
@@ -1503,98 +1484,24 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1503
1484
  );
1504
1485
  }
1505
1486
  }
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
1487
  // Helper method to get included messages with context
1585
- async _getIncludedMessages(threadId, selectBy) {
1586
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1488
+ async _getIncludedMessages(selectBy) {
1587
1489
  if (!selectBy?.include?.length) {
1588
1490
  return [];
1589
1491
  }
1590
1492
  const includeMessages = [];
1591
1493
  for (const includeItem of selectBy.include) {
1592
1494
  try {
1593
- const { id, threadId: targetThreadId, withPreviousMessages = 0, withNextMessages = 0 } = includeItem;
1594
- const searchThreadId = targetThreadId || threadId;
1495
+ const { id, withPreviousMessages = 0, withNextMessages = 0 } = includeItem;
1496
+ const targetResult = await this.service.entities.message.get({ entity: "message", id }).go();
1497
+ if (!targetResult.data) {
1498
+ this.logger.warn("Target message not found", { id });
1499
+ continue;
1500
+ }
1501
+ const targetMessageData = targetResult.data;
1502
+ const searchThreadId = targetMessageData.threadId;
1595
1503
  this.logger.debug("Getting included messages for", {
1596
1504
  id,
1597
- targetThreadId,
1598
1505
  searchThreadId,
1599
1506
  withPreviousMessages,
1600
1507
  withNextMessages
@@ -1617,7 +1524,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1617
1524
  });
1618
1525
  const targetIndex = allMessages.findIndex((msg) => msg.id === id);
1619
1526
  if (targetIndex === -1) {
1620
- this.logger.warn("Target message not found", { id, threadId: searchThreadId });
1527
+ this.logger.warn("Target message not found in thread", { id, threadId: searchThreadId });
1621
1528
  continue;
1622
1529
  }
1623
1530
  this.logger.debug("Found target message at index", { id, targetIndex, totalMessages: allMessages.length });
@@ -1702,7 +1609,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1702
1609
  } catch (error$1) {
1703
1610
  throw new error.MastraError(
1704
1611
  {
1705
- id: "STORAGE_DYNAMODB_STORE_UPDATE_MESSAGES_FAILED",
1612
+ id: storage.createStorageErrorId("DYNAMODB", "UPDATE_MESSAGES", "FAILED"),
1706
1613
  domain: error.ErrorDomain.STORAGE,
1707
1614
  category: error.ErrorCategory.THIRD_PARTY,
1708
1615
  details: { count: messages.length }
@@ -1731,7 +1638,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1731
1638
  } catch (error$1) {
1732
1639
  throw new error.MastraError(
1733
1640
  {
1734
- id: "STORAGE_DYNAMODB_STORE_GET_RESOURCE_BY_ID_FAILED",
1641
+ id: storage.createStorageErrorId("DYNAMODB", "GET_RESOURCE_BY_ID", "FAILED"),
1735
1642
  domain: error.ErrorDomain.STORAGE,
1736
1643
  category: error.ErrorCategory.THIRD_PARTY,
1737
1644
  details: { resourceId }
@@ -1763,7 +1670,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1763
1670
  } catch (error$1) {
1764
1671
  throw new error.MastraError(
1765
1672
  {
1766
- id: "STORAGE_DYNAMODB_STORE_SAVE_RESOURCE_FAILED",
1673
+ id: storage.createStorageErrorId("DYNAMODB", "SAVE_RESOURCE", "FAILED"),
1767
1674
  domain: error.ErrorDomain.STORAGE,
1768
1675
  category: error.ErrorCategory.THIRD_PARTY,
1769
1676
  details: { resourceId: resource.id }
@@ -1812,7 +1719,7 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1812
1719
  } catch (error$1) {
1813
1720
  throw new error.MastraError(
1814
1721
  {
1815
- id: "STORAGE_DYNAMODB_STORE_UPDATE_RESOURCE_FAILED",
1722
+ id: storage.createStorageErrorId("DYNAMODB", "UPDATE_RESOURCE", "FAILED"),
1816
1723
  domain: error.ErrorDomain.STORAGE,
1817
1724
  category: error.ErrorCategory.THIRD_PARTY,
1818
1725
  details: { resourceId }
@@ -1822,406 +1729,123 @@ var MemoryStorageDynamoDB = class extends storage.MemoryStorage {
1822
1729
  }
1823
1730
  }
1824
1731
  };
1825
- var StoreOperationsDynamoDB = class extends storage.StoreOperations {
1826
- client;
1827
- tableName;
1732
+ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
1828
1733
  service;
1829
- constructor({
1830
- service,
1831
- tableName,
1832
- client
1833
- }) {
1734
+ constructor(config) {
1834
1735
  super();
1835
- this.service = service;
1836
- this.client = client;
1837
- this.tableName = tableName;
1838
- }
1839
- async hasColumn() {
1840
- return true;
1736
+ this.service = resolveDynamoDBConfig(config);
1841
1737
  }
1842
- async dropTable() {
1843
- }
1844
- // Helper methods for entity/table mapping
1845
- getEntityNameForTable(tableName) {
1846
- const mapping = {
1847
- [storage.TABLE_THREADS]: "thread",
1848
- [storage.TABLE_MESSAGES]: "message",
1849
- [storage.TABLE_WORKFLOW_SNAPSHOT]: "workflow_snapshot",
1850
- [storage.TABLE_EVALS]: "eval",
1851
- [storage.TABLE_SCORERS]: "score",
1852
- [storage.TABLE_TRACES]: "trace",
1853
- [storage.TABLE_RESOURCES]: "resource",
1854
- [storage.TABLE_AI_SPANS]: "ai_span"
1855
- };
1856
- return mapping[tableName] || null;
1738
+ async dangerouslyClearAll() {
1739
+ await deleteTableData(this.service, storage.TABLE_SCORERS);
1857
1740
  }
1858
1741
  /**
1859
- * Pre-processes a record to ensure Date objects are converted to ISO strings
1860
- * This is necessary because ElectroDB validation happens before setters are applied
1742
+ * DynamoDB-specific score row transformation.
1743
+ *
1744
+ * Note: This implementation does NOT use coreTransformScoreRow because:
1745
+ * 1. ElectroDB already parses JSON fields via its entity getters
1746
+ * 2. DynamoDB stores empty strings for null values (which need special handling)
1747
+ * 3. 'entity' is a reserved ElectroDB key, so we use 'entityData' column
1861
1748
  */
1862
- preprocessRecord(record) {
1863
- const processed = { ...record };
1864
- if (processed.createdAt instanceof Date) {
1865
- processed.createdAt = processed.createdAt.toISOString();
1866
- }
1867
- if (processed.updatedAt instanceof Date) {
1868
- processed.updatedAt = processed.updatedAt.toISOString();
1869
- }
1870
- if (processed.created_at instanceof Date) {
1871
- processed.created_at = processed.created_at.toISOString();
1872
- }
1873
- if (processed.result && typeof processed.result === "object") {
1874
- processed.result = JSON.stringify(processed.result);
1875
- }
1876
- if (processed.test_info && typeof processed.test_info === "object") {
1877
- processed.test_info = JSON.stringify(processed.test_info);
1878
- } else if (processed.test_info === void 0 || processed.test_info === null) {
1879
- delete processed.test_info;
1880
- }
1881
- if (processed.snapshot && typeof processed.snapshot === "object") {
1882
- processed.snapshot = JSON.stringify(processed.snapshot);
1883
- }
1884
- if (processed.attributes && typeof processed.attributes === "object") {
1885
- processed.attributes = JSON.stringify(processed.attributes);
1886
- }
1887
- if (processed.status && typeof processed.status === "object") {
1888
- processed.status = JSON.stringify(processed.status);
1889
- }
1890
- if (processed.events && typeof processed.events === "object") {
1891
- processed.events = JSON.stringify(processed.events);
1892
- }
1893
- if (processed.links && typeof processed.links === "object") {
1894
- processed.links = JSON.stringify(processed.links);
1749
+ parseScoreData(data) {
1750
+ const result = {};
1751
+ for (const key of Object.keys(storage.SCORERS_SCHEMA)) {
1752
+ if (["traceId", "resourceId", "threadId", "spanId"].includes(key)) {
1753
+ result[key] = data[key] === "" ? null : data[key];
1754
+ continue;
1755
+ }
1756
+ result[key] = data[key];
1895
1757
  }
1896
- return processed;
1758
+ result.entity = data.entityData ?? null;
1759
+ return {
1760
+ ...result,
1761
+ createdAt: data.createdAt ? new Date(data.createdAt) : /* @__PURE__ */ new Date(),
1762
+ updatedAt: data.updatedAt ? new Date(data.updatedAt) : /* @__PURE__ */ new Date()
1763
+ };
1897
1764
  }
1898
- /**
1899
- * Validates that the required DynamoDB table exists and is accessible.
1900
- * This does not check the table structure - it assumes the table
1901
- * was created with the correct structure via CDK/CloudFormation.
1902
- */
1903
- async validateTableExists() {
1765
+ async getScoreById({ id }) {
1766
+ this.logger.debug("Getting score by ID", { id });
1904
1767
  try {
1905
- const command = new clientDynamodb.DescribeTableCommand({
1906
- TableName: this.tableName
1907
- });
1908
- await this.client.send(command);
1909
- return true;
1910
- } catch (error$1) {
1911
- if (error$1.name === "ResourceNotFoundException") {
1912
- return false;
1768
+ const result = await this.service.entities.score.get({ entity: "score", id }).go();
1769
+ if (!result.data) {
1770
+ return null;
1913
1771
  }
1772
+ return this.parseScoreData(result.data);
1773
+ } catch (error$1) {
1914
1774
  throw new error.MastraError(
1915
1775
  {
1916
- id: "STORAGE_DYNAMODB_STORE_VALIDATE_TABLE_EXISTS_FAILED",
1776
+ id: storage.createStorageErrorId("DYNAMODB", "GET_SCORE_BY_ID", "FAILED"),
1917
1777
  domain: error.ErrorDomain.STORAGE,
1918
1778
  category: error.ErrorCategory.THIRD_PARTY,
1919
- details: { tableName: this.tableName }
1920
- },
1921
- error$1
1922
- );
1923
- }
1924
- }
1925
- /**
1926
- * This method is modified for DynamoDB with ElectroDB single-table design.
1927
- * It assumes the table is created and managed externally via CDK/CloudFormation.
1928
- *
1929
- * This implementation only validates that the required table exists and is accessible.
1930
- * No table creation is attempted - we simply check if we can access the table.
1931
- */
1932
- async createTable({ tableName }) {
1933
- this.logger.debug("Validating access to externally managed table", { tableName, physicalTable: this.tableName });
1934
- try {
1935
- const tableExists = await this.validateTableExists();
1936
- if (!tableExists) {
1937
- this.logger.error(
1938
- `Table ${this.tableName} does not exist or is not accessible. It should be created via CDK/CloudFormation.`
1939
- );
1940
- throw new Error(
1941
- `Table ${this.tableName} does not exist or is not accessible. Ensure it's created via CDK/CloudFormation before using this store.`
1942
- );
1943
- }
1944
- this.logger.debug(`Table ${this.tableName} exists and is accessible`);
1945
- } catch (error$1) {
1946
- this.logger.error("Error validating table access", { tableName: this.tableName, error: error$1 });
1947
- throw new error.MastraError(
1948
- {
1949
- id: "STORAGE_DYNAMODB_STORE_VALIDATE_TABLE_ACCESS_FAILED",
1950
- domain: error.ErrorDomain.STORAGE,
1951
- category: error.ErrorCategory.THIRD_PARTY,
1952
- details: { tableName: this.tableName }
1953
- },
1954
- error$1
1955
- );
1956
- }
1957
- }
1958
- async insert({ tableName, record }) {
1959
- this.logger.debug("DynamoDB insert called", { tableName });
1960
- const entityName = this.getEntityNameForTable(tableName);
1961
- if (!entityName || !this.service.entities[entityName]) {
1962
- throw new error.MastraError({
1963
- id: "STORAGE_DYNAMODB_STORE_INSERT_INVALID_ARGS",
1964
- domain: error.ErrorDomain.STORAGE,
1965
- category: error.ErrorCategory.USER,
1966
- text: "No entity defined for tableName",
1967
- details: { tableName }
1968
- });
1969
- }
1970
- try {
1971
- const dataToSave = { entity: entityName, ...this.preprocessRecord(record) };
1972
- await this.service.entities[entityName].create(dataToSave).go();
1973
- } catch (error$1) {
1974
- throw new error.MastraError(
1975
- {
1976
- id: "STORAGE_DYNAMODB_STORE_INSERT_FAILED",
1977
- domain: error.ErrorDomain.STORAGE,
1978
- category: error.ErrorCategory.THIRD_PARTY,
1979
- details: { tableName }
1779
+ details: { id }
1980
1780
  },
1981
1781
  error$1
1982
1782
  );
1983
1783
  }
1984
1784
  }
1985
- async alterTable(_args) {
1986
- }
1987
- /**
1988
- * Clear all items from a logical "table" (entity type)
1989
- */
1990
- async clearTable({ tableName }) {
1991
- this.logger.debug("DynamoDB clearTable called", { tableName });
1992
- const entityName = this.getEntityNameForTable(tableName);
1993
- if (!entityName || !this.service.entities[entityName]) {
1994
- throw new error.MastraError({
1995
- id: "STORAGE_DYNAMODB_STORE_CLEAR_TABLE_INVALID_ARGS",
1996
- domain: error.ErrorDomain.STORAGE,
1997
- category: error.ErrorCategory.USER,
1998
- text: "No entity defined for tableName",
1999
- details: { tableName }
2000
- });
2001
- }
1785
+ async saveScore(score) {
1786
+ let validatedScore;
2002
1787
  try {
2003
- const result = await this.service.entities[entityName].scan.go({ pages: "all" });
2004
- if (!result.data.length) {
2005
- this.logger.debug(`No records found to clear for ${tableName}`);
2006
- return;
2007
- }
2008
- this.logger.debug(`Found ${result.data.length} records to delete for ${tableName}`);
2009
- const keysToDelete = result.data.map((item) => {
2010
- const key = { entity: entityName };
2011
- switch (entityName) {
2012
- case "thread":
2013
- if (!item.id) throw new Error(`Missing required key 'id' for entity 'thread'`);
2014
- key.id = item.id;
2015
- break;
2016
- case "message":
2017
- if (!item.id) throw new Error(`Missing required key 'id' for entity 'message'`);
2018
- key.id = item.id;
2019
- break;
2020
- case "workflow_snapshot":
2021
- if (!item.workflow_name)
2022
- throw new Error(`Missing required key 'workflow_name' for entity 'workflow_snapshot'`);
2023
- if (!item.run_id) throw new Error(`Missing required key 'run_id' for entity 'workflow_snapshot'`);
2024
- key.workflow_name = item.workflow_name;
2025
- key.run_id = item.run_id;
2026
- break;
2027
- case "eval":
2028
- if (!item.run_id) throw new Error(`Missing required key 'run_id' for entity 'eval'`);
2029
- key.run_id = item.run_id;
2030
- break;
2031
- case "trace":
2032
- if (!item.id) throw new Error(`Missing required key 'id' for entity 'trace'`);
2033
- key.id = item.id;
2034
- break;
2035
- case "score":
2036
- if (!item.id) throw new Error(`Missing required key 'id' for entity 'score'`);
2037
- key.id = item.id;
2038
- break;
2039
- default:
2040
- this.logger.warn(`Unknown entity type encountered during clearTable: ${entityName}`);
2041
- throw new Error(`Cannot construct delete key for unknown entity type: ${entityName}`);
2042
- }
2043
- return key;
2044
- });
2045
- const batchSize = 25;
2046
- for (let i = 0; i < keysToDelete.length; i += batchSize) {
2047
- const batchKeys = keysToDelete.slice(i, i + batchSize);
2048
- await this.service.entities[entityName].delete(batchKeys).go();
2049
- }
2050
- this.logger.debug(`Successfully cleared all records for ${tableName}`);
1788
+ validatedScore = evals.saveScorePayloadSchema.parse(score);
2051
1789
  } catch (error$1) {
2052
1790
  throw new error.MastraError(
2053
1791
  {
2054
- id: "STORAGE_DYNAMODB_STORE_CLEAR_TABLE_FAILED",
1792
+ id: storage.createStorageErrorId("DYNAMODB", "SAVE_SCORE", "VALIDATION_FAILED"),
2055
1793
  domain: error.ErrorDomain.STORAGE,
2056
- category: error.ErrorCategory.THIRD_PARTY,
2057
- details: { tableName }
2058
- },
2059
- error$1
2060
- );
2061
- }
2062
- }
2063
- /**
2064
- * Insert multiple records as a batch
2065
- */
2066
- async batchInsert({ tableName, records }) {
2067
- this.logger.debug("DynamoDB batchInsert called", { tableName, count: records.length });
2068
- const entityName = this.getEntityNameForTable(tableName);
2069
- if (!entityName || !this.service.entities[entityName]) {
2070
- throw new error.MastraError({
2071
- id: "STORAGE_DYNAMODB_STORE_BATCH_INSERT_INVALID_ARGS",
2072
- domain: error.ErrorDomain.STORAGE,
2073
- category: error.ErrorCategory.USER,
2074
- text: "No entity defined for tableName",
2075
- details: { tableName }
2076
- });
2077
- }
2078
- const recordsToSave = records.map((rec) => ({ entity: entityName, ...this.preprocessRecord(rec) }));
2079
- const batchSize = 25;
2080
- const batches = [];
2081
- for (let i = 0; i < recordsToSave.length; i += batchSize) {
2082
- const batch = recordsToSave.slice(i, i + batchSize);
2083
- batches.push(batch);
2084
- }
2085
- try {
2086
- for (const batch of batches) {
2087
- for (const recordData of batch) {
2088
- if (!recordData.entity) {
2089
- this.logger.error("Missing entity property in record data for batchInsert", { recordData, tableName });
2090
- throw new Error(`Internal error: Missing entity property during batchInsert for ${tableName}`);
1794
+ category: error.ErrorCategory.USER,
1795
+ details: {
1796
+ scorer: typeof score.scorer?.id === "string" ? score.scorer.id : String(score.scorer?.id ?? "unknown"),
1797
+ entityId: score.entityId ?? "unknown",
1798
+ entityType: score.entityType ?? "unknown",
1799
+ traceId: score.traceId ?? "",
1800
+ spanId: score.spanId ?? ""
2091
1801
  }
2092
- this.logger.debug("Attempting to create record in batchInsert:", { entityName, recordData });
2093
- await this.service.entities[entityName].create(recordData).go();
2094
- }
2095
- }
2096
- } catch (error$1) {
2097
- throw new error.MastraError(
2098
- {
2099
- id: "STORAGE_DYNAMODB_STORE_BATCH_INSERT_FAILED",
2100
- domain: error.ErrorDomain.STORAGE,
2101
- category: error.ErrorCategory.THIRD_PARTY,
2102
- details: { tableName }
2103
- },
2104
- error$1
2105
- );
2106
- }
2107
- }
2108
- /**
2109
- * Load a record by its keys
2110
- */
2111
- async load({ tableName, keys }) {
2112
- this.logger.debug("DynamoDB load called", { tableName, keys });
2113
- const entityName = this.getEntityNameForTable(tableName);
2114
- if (!entityName || !this.service.entities[entityName]) {
2115
- throw new error.MastraError({
2116
- id: "STORAGE_DYNAMODB_STORE_LOAD_INVALID_ARGS",
2117
- domain: error.ErrorDomain.STORAGE,
2118
- category: error.ErrorCategory.USER,
2119
- text: "No entity defined for tableName",
2120
- details: { tableName }
2121
- });
2122
- }
2123
- try {
2124
- const keyObject = { entity: entityName, ...keys };
2125
- const result = await this.service.entities[entityName].get(keyObject).go();
2126
- if (!result.data) {
2127
- return null;
2128
- }
2129
- let data = result.data;
2130
- return data;
2131
- } catch (error$1) {
2132
- throw new error.MastraError(
2133
- {
2134
- id: "STORAGE_DYNAMODB_STORE_LOAD_FAILED",
2135
- domain: error.ErrorDomain.STORAGE,
2136
- category: error.ErrorCategory.THIRD_PARTY,
2137
- details: { tableName }
2138
1802
  },
2139
1803
  error$1
2140
1804
  );
2141
1805
  }
2142
- }
2143
- };
2144
- var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2145
- service;
2146
- constructor({ service }) {
2147
- super();
2148
- this.service = service;
2149
- }
2150
- // Helper function to parse score data (handle JSON fields)
2151
- parseScoreData(data) {
2152
- return {
2153
- ...data,
2154
- // Convert date strings back to Date objects for consistency
2155
- createdAt: data.createdAt ? new Date(data.createdAt) : /* @__PURE__ */ new Date(),
2156
- updatedAt: data.updatedAt ? new Date(data.updatedAt) : /* @__PURE__ */ new Date()
2157
- // JSON fields are already transformed by the entity's getters
2158
- };
2159
- }
2160
- async getScoreById({ id }) {
2161
- this.logger.debug("Getting score by ID", { id });
2162
- try {
2163
- const result = await this.service.entities.score.get({ entity: "score", id }).go();
2164
- if (!result.data) {
2165
- return null;
2166
- }
2167
- return this.parseScoreData(result.data);
2168
- } catch (error$1) {
2169
- throw new error.MastraError(
2170
- {
2171
- id: "STORAGE_DYNAMODB_STORE_GET_SCORE_BY_ID_FAILED",
2172
- domain: error.ErrorDomain.STORAGE,
2173
- category: error.ErrorCategory.THIRD_PARTY,
2174
- details: { id }
2175
- },
2176
- error$1
2177
- );
2178
- }
2179
- }
2180
- async saveScore(score) {
2181
- this.logger.debug("Saving score", { scorerId: score.scorerId, runId: score.runId });
2182
1806
  const now = /* @__PURE__ */ new Date();
2183
- const scoreId = `score-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
2184
- const scoreData = {
2185
- entity: "score",
2186
- id: scoreId,
2187
- scorerId: score.scorerId,
2188
- traceId: score.traceId || "",
2189
- runId: score.runId,
2190
- scorer: typeof score.scorer === "string" ? score.scorer : JSON.stringify(score.scorer),
2191
- preprocessStepResult: typeof score.preprocessStepResult === "string" ? score.preprocessStepResult : JSON.stringify(score.preprocessStepResult),
2192
- analyzeStepResult: typeof score.analyzeStepResult === "string" ? score.analyzeStepResult : JSON.stringify(score.analyzeStepResult),
2193
- score: score.score,
2194
- reason: score.reason,
2195
- preprocessPrompt: score.preprocessPrompt,
2196
- generateScorePrompt: score.generateScorePrompt,
2197
- analyzePrompt: score.analyzePrompt,
2198
- reasonPrompt: score.reasonPrompt,
2199
- input: typeof score.input === "string" ? score.input : JSON.stringify(score.input),
2200
- output: typeof score.output === "string" ? score.output : JSON.stringify(score.output),
2201
- additionalContext: typeof score.additionalContext === "string" ? score.additionalContext : JSON.stringify(score.additionalContext),
2202
- runtimeContext: typeof score.runtimeContext === "string" ? score.runtimeContext : JSON.stringify(score.runtimeContext),
2203
- entityType: score.entityType,
2204
- entityData: typeof score.entity === "string" ? score.entity : JSON.stringify(score.entity),
2205
- entityId: score.entityId,
2206
- source: score.source,
2207
- resourceId: score.resourceId || "",
2208
- threadId: score.threadId || "",
2209
- createdAt: now.toISOString(),
2210
- updatedAt: now.toISOString()
2211
- };
1807
+ const scoreId = crypto.randomUUID();
1808
+ const scorer = typeof validatedScore.scorer === "string" ? validatedScore.scorer : JSON.stringify(validatedScore.scorer);
1809
+ const preprocessStepResult = typeof validatedScore.preprocessStepResult === "string" ? validatedScore.preprocessStepResult : JSON.stringify(validatedScore.preprocessStepResult);
1810
+ const analyzeStepResult = typeof validatedScore.analyzeStepResult === "string" ? validatedScore.analyzeStepResult : JSON.stringify(validatedScore.analyzeStepResult);
1811
+ const input = typeof validatedScore.input === "string" ? validatedScore.input : JSON.stringify(validatedScore.input);
1812
+ const output = typeof validatedScore.output === "string" ? validatedScore.output : JSON.stringify(validatedScore.output);
1813
+ const requestContext = typeof validatedScore.requestContext === "string" ? validatedScore.requestContext : JSON.stringify(validatedScore.requestContext);
1814
+ const entity = typeof validatedScore.entity === "string" ? validatedScore.entity : JSON.stringify(validatedScore.entity);
1815
+ const scoreData = Object.fromEntries(
1816
+ Object.entries({
1817
+ ...validatedScore,
1818
+ entity: "score",
1819
+ id: scoreId,
1820
+ scorer,
1821
+ preprocessStepResult,
1822
+ analyzeStepResult,
1823
+ input,
1824
+ output,
1825
+ requestContext,
1826
+ entityData: entity,
1827
+ traceId: validatedScore.traceId || "",
1828
+ resourceId: validatedScore.resourceId || "",
1829
+ threadId: validatedScore.threadId || "",
1830
+ spanId: validatedScore.spanId || "",
1831
+ createdAt: now.toISOString(),
1832
+ updatedAt: now.toISOString()
1833
+ }).filter(([_, value]) => value !== void 0 && value !== null)
1834
+ );
2212
1835
  try {
2213
1836
  await this.service.entities.score.upsert(scoreData).go();
2214
- const savedScore = {
2215
- ...score,
2216
- id: scoreId,
2217
- createdAt: now,
2218
- updatedAt: now
1837
+ return {
1838
+ score: {
1839
+ ...validatedScore,
1840
+ id: scoreId,
1841
+ createdAt: now,
1842
+ updatedAt: now
1843
+ }
2219
1844
  };
2220
- return { score: savedScore };
2221
1845
  } catch (error$1) {
2222
1846
  throw new error.MastraError(
2223
1847
  {
2224
- id: "STORAGE_DYNAMODB_STORE_SAVE_SCORE_FAILED",
1848
+ id: storage.createStorageErrorId("DYNAMODB", "SAVE_SCORE", "FAILED"),
2225
1849
  domain: error.ErrorDomain.STORAGE,
2226
1850
  category: error.ErrorCategory.THIRD_PARTY,
2227
1851
  details: { scorerId: score.scorerId, runId: score.runId }
@@ -2230,7 +1854,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2230
1854
  );
2231
1855
  }
2232
1856
  }
2233
- async getScoresByScorerId({
1857
+ async listScoresByScorerId({
2234
1858
  scorerId,
2235
1859
  pagination,
2236
1860
  entityId,
@@ -2251,24 +1875,25 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2251
1875
  allScores = allScores.filter((score) => score.source === source);
2252
1876
  }
2253
1877
  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);
1878
+ const { page, perPage: perPageInput } = pagination;
1879
+ const perPage = storage.normalizePerPage(perPageInput, Number.MAX_SAFE_INTEGER);
1880
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2257
1881
  const total = allScores.length;
2258
- const hasMore = endIndex < total;
1882
+ const end = perPageInput === false ? allScores.length : start + perPage;
1883
+ const paginatedScores = allScores.slice(start, end);
2259
1884
  return {
2260
1885
  scores: paginatedScores,
2261
1886
  pagination: {
2262
1887
  total,
2263
- page: pagination.page,
2264
- perPage: pagination.perPage,
2265
- hasMore
1888
+ page,
1889
+ perPage: perPageForResponse,
1890
+ hasMore: end < total
2266
1891
  }
2267
1892
  };
2268
1893
  } catch (error$1) {
2269
1894
  throw new error.MastraError(
2270
1895
  {
2271
- id: "STORAGE_DYNAMODB_STORE_GET_SCORES_BY_SCORER_ID_FAILED",
1896
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_SCORES_BY_SCORER_ID", "FAILED"),
2272
1897
  domain: error.ErrorDomain.STORAGE,
2273
1898
  category: error.ErrorCategory.THIRD_PARTY,
2274
1899
  details: {
@@ -2284,7 +1909,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2284
1909
  );
2285
1910
  }
2286
1911
  }
2287
- async getScoresByRunId({
1912
+ async listScoresByRunId({
2288
1913
  runId,
2289
1914
  pagination
2290
1915
  }) {
@@ -2294,24 +1919,25 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2294
1919
  const results = await query.go();
2295
1920
  const allScores = results.data.map((data) => this.parseScoreData(data));
2296
1921
  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);
1922
+ const { page, perPage: perPageInput } = pagination;
1923
+ const perPage = storage.normalizePerPage(perPageInput, Number.MAX_SAFE_INTEGER);
1924
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2300
1925
  const total = allScores.length;
2301
- const hasMore = endIndex < total;
1926
+ const end = perPageInput === false ? allScores.length : start + perPage;
1927
+ const paginatedScores = allScores.slice(start, end);
2302
1928
  return {
2303
1929
  scores: paginatedScores,
2304
1930
  pagination: {
2305
1931
  total,
2306
- page: pagination.page,
2307
- perPage: pagination.perPage,
2308
- hasMore
1932
+ page,
1933
+ perPage: perPageForResponse,
1934
+ hasMore: end < total
2309
1935
  }
2310
1936
  };
2311
1937
  } catch (error$1) {
2312
1938
  throw new error.MastraError(
2313
1939
  {
2314
- id: "STORAGE_DYNAMODB_STORE_GET_SCORES_BY_RUN_ID_FAILED",
1940
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_SCORES_BY_RUN_ID", "FAILED"),
2315
1941
  domain: error.ErrorDomain.STORAGE,
2316
1942
  category: error.ErrorCategory.THIRD_PARTY,
2317
1943
  details: { runId, page: pagination.page, perPage: pagination.perPage }
@@ -2320,7 +1946,7 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2320
1946
  );
2321
1947
  }
2322
1948
  }
2323
- async getScoresByEntityId({
1949
+ async listScoresByEntityId({
2324
1950
  entityId,
2325
1951
  entityType,
2326
1952
  pagination
@@ -2332,24 +1958,25 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2332
1958
  let allScores = results.data.map((data) => this.parseScoreData(data));
2333
1959
  allScores = allScores.filter((score) => score.entityType === entityType);
2334
1960
  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);
1961
+ const { page, perPage: perPageInput } = pagination;
1962
+ const perPage = storage.normalizePerPage(perPageInput, Number.MAX_SAFE_INTEGER);
1963
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2338
1964
  const total = allScores.length;
2339
- const hasMore = endIndex < total;
1965
+ const end = perPageInput === false ? allScores.length : start + perPage;
1966
+ const paginatedScores = allScores.slice(start, end);
2340
1967
  return {
2341
1968
  scores: paginatedScores,
2342
1969
  pagination: {
2343
1970
  total,
2344
- page: pagination.page,
2345
- perPage: pagination.perPage,
2346
- hasMore
1971
+ page,
1972
+ perPage: perPageForResponse,
1973
+ hasMore: end < total
2347
1974
  }
2348
1975
  };
2349
1976
  } catch (error$1) {
2350
1977
  throw new error.MastraError(
2351
1978
  {
2352
- id: "STORAGE_DYNAMODB_STORE_GET_SCORES_BY_ENTITY_ID_FAILED",
1979
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_SCORES_BY_ENTITY_ID", "FAILED"),
2353
1980
  domain: error.ErrorDomain.STORAGE,
2354
1981
  category: error.ErrorCategory.THIRD_PARTY,
2355
1982
  details: { entityId, entityType, page: pagination.page, perPage: pagination.perPage }
@@ -2358,298 +1985,162 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2358
1985
  );
2359
1986
  }
2360
1987
  }
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 });
1988
+ async listScoresBySpan({
1989
+ traceId,
1990
+ spanId,
1991
+ pagination
1992
+ }) {
1993
+ this.logger.debug("Getting scores by span", { traceId, spanId, pagination });
2374
1994
  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;
1995
+ const query = this.service.entities.score.query.bySpan({ entity: "score", traceId, spanId });
1996
+ const results = await query.go();
1997
+ const allScores = results.data.map((data) => this.parseScoreData(data));
1998
+ allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
1999
+ const { page, perPage: perPageInput } = pagination;
2000
+ const perPage = storage.normalizePerPage(perPageInput, Number.MAX_SAFE_INTEGER);
2001
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2002
+ const total = allScores.length;
2003
+ const end = perPageInput === false ? allScores.length : start + perPage;
2004
+ const paginatedScores = allScores.slice(start, end);
2005
+ return {
2006
+ scores: paginatedScores,
2007
+ pagination: {
2008
+ total,
2009
+ page,
2010
+ perPage: perPageForResponse,
2011
+ hasMore: end < total
2398
2012
  }
2399
- } while (cursor && pagesFetched < startPage);
2400
- return items;
2013
+ };
2401
2014
  } catch (error$1) {
2402
2015
  throw new error.MastraError(
2403
2016
  {
2404
- id: "STORAGE_DYNAMODB_STORE_GET_TRACES_FAILED",
2017
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_SCORES_BY_SPAN", "FAILED"),
2405
2018
  domain: error.ErrorDomain.STORAGE,
2406
- category: error.ErrorCategory.THIRD_PARTY
2019
+ category: error.ErrorCategory.THIRD_PARTY,
2020
+ details: { traceId, spanId, page: pagination.page, perPage: pagination.perPage }
2407
2021
  },
2408
2022
  error$1
2409
2023
  );
2410
2024
  }
2411
2025
  }
2412
- async batchTraceInsert({ records }) {
2413
- this.logger.debug("Batch inserting traces", { count: records.length });
2414
- if (!records.length) {
2415
- return;
2416
- }
2026
+ };
2027
+ function formatWorkflowRun(snapshotData) {
2028
+ return {
2029
+ workflowName: snapshotData.workflow_name,
2030
+ runId: snapshotData.run_id,
2031
+ snapshot: snapshotData.snapshot,
2032
+ createdAt: new Date(snapshotData.createdAt),
2033
+ updatedAt: new Date(snapshotData.updatedAt),
2034
+ resourceId: snapshotData.resourceId
2035
+ };
2036
+ }
2037
+ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2038
+ service;
2039
+ constructor(config) {
2040
+ super();
2041
+ this.service = resolveDynamoDBConfig(config);
2042
+ }
2043
+ async dangerouslyClearAll() {
2044
+ await deleteTableData(this.service, storage.TABLE_WORKFLOW_SNAPSHOT);
2045
+ }
2046
+ async updateWorkflowResults({
2047
+ workflowName,
2048
+ runId,
2049
+ stepId,
2050
+ result,
2051
+ requestContext
2052
+ }) {
2417
2053
  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
- });
2054
+ const existingSnapshot = await this.loadWorkflowSnapshot({ workflowName, runId });
2055
+ let snapshot;
2056
+ if (!existingSnapshot) {
2057
+ snapshot = {
2058
+ context: {},
2059
+ activePaths: [],
2060
+ timestamp: Date.now(),
2061
+ suspendedPaths: {},
2062
+ activeStepsPath: {},
2063
+ resumeLabels: {},
2064
+ serializedStepGraph: [],
2065
+ status: "pending",
2066
+ value: {},
2067
+ waitingPaths: {},
2068
+ runId,
2069
+ requestContext: {}
2070
+ };
2071
+ } else {
2072
+ snapshot = existingSnapshot;
2073
+ }
2074
+ snapshot.context[stepId] = result;
2075
+ snapshot.requestContext = { ...snapshot.requestContext, ...requestContext };
2076
+ await this.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2077
+ return snapshot.context;
2424
2078
  } catch (error$1) {
2079
+ if (error$1 instanceof error.MastraError) throw error$1;
2425
2080
  throw new error.MastraError(
2426
2081
  {
2427
- id: "STORAGE_DYNAMODB_STORE_BATCH_TRACE_INSERT_FAILED",
2082
+ id: storage.createStorageErrorId("DYNAMODB", "UPDATE_WORKFLOW_RESULTS", "FAILED"),
2428
2083
  domain: error.ErrorDomain.STORAGE,
2429
2084
  category: error.ErrorCategory.THIRD_PARTY,
2430
- details: { count: records.length }
2085
+ details: { workflowName, runId, stepId }
2431
2086
  },
2432
2087
  error$1
2433
2088
  );
2434
2089
  }
2435
2090
  }
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 });
2091
+ async updateWorkflowState({
2092
+ workflowName,
2093
+ runId,
2094
+ opts
2095
+ }) {
2439
2096
  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,
2458
- page,
2459
- perPage,
2460
- hasMore: false
2461
- };
2097
+ const existingSnapshot = await this.loadWorkflowSnapshot({ workflowName, runId });
2098
+ if (!existingSnapshot || !existingSnapshot.context) {
2099
+ return void 0;
2462
2100
  }
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
- }
2558
- }
2559
- return {
2560
- id: item.id,
2561
- parentSpanId: item.parentSpanId,
2562
- name: item.name,
2563
- traceId: item.traceId,
2564
- scope: item.scope,
2565
- kind: item.kind,
2566
- attributes: attributes2,
2567
- status,
2568
- events,
2569
- links,
2570
- other: item.other,
2571
- startTime: item.startTime,
2572
- endTime: item.endTime,
2573
- createdAt: item.createdAt
2574
- };
2575
- });
2576
- return {
2577
- traces,
2578
- total,
2579
- page,
2580
- perPage,
2581
- hasMore: end < total
2582
- };
2101
+ const updatedSnapshot = { ...existingSnapshot, ...opts };
2102
+ await this.persistWorkflowSnapshot({ workflowName, runId, snapshot: updatedSnapshot });
2103
+ return updatedSnapshot;
2583
2104
  } catch (error$1) {
2105
+ if (error$1 instanceof error.MastraError) throw error$1;
2584
2106
  throw new error.MastraError(
2585
2107
  {
2586
- id: "STORAGE_DYNAMODB_STORE_GET_TRACES_PAGINATED_FAILED",
2108
+ id: storage.createStorageErrorId("DYNAMODB", "UPDATE_WORKFLOW_STATE", "FAILED"),
2587
2109
  domain: error.ErrorDomain.STORAGE,
2588
- category: error.ErrorCategory.THIRD_PARTY
2110
+ category: error.ErrorCategory.THIRD_PARTY,
2111
+ details: { workflowName, runId }
2589
2112
  },
2590
2113
  error$1
2591
2114
  );
2592
2115
  }
2593
2116
  }
2594
- };
2595
- function formatWorkflowRun(snapshotData) {
2596
- return {
2597
- workflowName: snapshotData.workflow_name,
2598
- runId: snapshotData.run_id,
2599
- snapshot: snapshotData.snapshot,
2600
- createdAt: new Date(snapshotData.createdAt),
2601
- updatedAt: new Date(snapshotData.updatedAt),
2602
- resourceId: snapshotData.resourceId
2603
- };
2604
- }
2605
- var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2606
- service;
2607
- constructor({ service }) {
2608
- super();
2609
- this.service = service;
2610
- }
2611
- updateWorkflowResults({
2612
- // workflowName,
2613
- // runId,
2614
- // stepId,
2615
- // result,
2616
- // runtimeContext,
2617
- }) {
2618
- throw new Error("Method not implemented.");
2619
- }
2620
- updateWorkflowState({
2621
- // workflowName,
2622
- // runId,
2623
- // opts,
2624
- }) {
2625
- throw new Error("Method not implemented.");
2626
- }
2627
2117
  // Workflow operations
2628
2118
  async persistWorkflowSnapshot({
2629
2119
  workflowName,
2630
2120
  runId,
2631
- snapshot
2121
+ resourceId,
2122
+ snapshot,
2123
+ createdAt,
2124
+ updatedAt
2632
2125
  }) {
2633
2126
  this.logger.debug("Persisting workflow snapshot", { workflowName, runId });
2634
2127
  try {
2635
- const resourceId = "resourceId" in snapshot ? snapshot.resourceId : void 0;
2636
- const now = (/* @__PURE__ */ new Date()).toISOString();
2128
+ const now = /* @__PURE__ */ new Date();
2637
2129
  const data = {
2638
2130
  entity: "workflow_snapshot",
2639
2131
  // Add entity type
2640
2132
  workflow_name: workflowName,
2641
2133
  run_id: runId,
2642
2134
  snapshot: JSON.stringify(snapshot),
2643
- // Stringify the snapshot object
2644
- createdAt: now,
2645
- updatedAt: now,
2135
+ createdAt: (createdAt ?? now).toISOString(),
2136
+ updatedAt: (updatedAt ?? now).toISOString(),
2646
2137
  resourceId
2647
2138
  };
2648
2139
  await this.service.entities.workflow_snapshot.upsert(data).go();
2649
2140
  } catch (error$1) {
2650
2141
  throw new error.MastraError(
2651
2142
  {
2652
- id: "STORAGE_DYNAMODB_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
2143
+ id: storage.createStorageErrorId("DYNAMODB", "PERSIST_WORKFLOW_SNAPSHOT", "FAILED"),
2653
2144
  domain: error.ErrorDomain.STORAGE,
2654
2145
  category: error.ErrorCategory.THIRD_PARTY,
2655
2146
  details: { workflowName, runId }
@@ -2677,7 +2168,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2677
2168
  } catch (error$1) {
2678
2169
  throw new error.MastraError(
2679
2170
  {
2680
- id: "STORAGE_DYNAMODB_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
2171
+ id: storage.createStorageErrorId("DYNAMODB", "LOAD_WORKFLOW_SNAPSHOT", "FAILED"),
2681
2172
  domain: error.ErrorDomain.STORAGE,
2682
2173
  category: error.ErrorCategory.THIRD_PARTY,
2683
2174
  details: { workflowName, runId }
@@ -2686,11 +2177,24 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2686
2177
  );
2687
2178
  }
2688
2179
  }
2689
- async getWorkflowRuns(args) {
2180
+ async listWorkflowRuns(args) {
2690
2181
  this.logger.debug("Getting workflow runs", { args });
2691
2182
  try {
2692
- const limit = args?.limit || 10;
2693
- const offset = args?.offset || 0;
2183
+ const perPage = args?.perPage !== void 0 ? args.perPage : 10;
2184
+ const page = args?.page !== void 0 ? args.page : 0;
2185
+ if (page < 0) {
2186
+ throw new error.MastraError(
2187
+ {
2188
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_WORKFLOW_RUNS", "INVALID_PAGE"),
2189
+ domain: error.ErrorDomain.STORAGE,
2190
+ category: error.ErrorCategory.USER,
2191
+ details: { page }
2192
+ },
2193
+ new Error("page must be >= 0")
2194
+ );
2195
+ }
2196
+ const normalizedPerPage = storage.normalizePerPage(perPage, 10);
2197
+ const offset = page * normalizedPerPage;
2694
2198
  let query;
2695
2199
  if (args?.workflowName) {
2696
2200
  query = this.service.entities.workflow_snapshot.query.primary({
@@ -2712,6 +2216,11 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2712
2216
  });
2713
2217
  if (pageResults.data && pageResults.data.length > 0) {
2714
2218
  let pageFilteredData = pageResults.data;
2219
+ if (args?.status) {
2220
+ pageFilteredData = pageFilteredData.filter((snapshot) => {
2221
+ return snapshot.snapshot.status === args.status;
2222
+ });
2223
+ }
2715
2224
  if (args?.fromDate || args?.toDate) {
2716
2225
  pageFilteredData = pageFilteredData.filter((snapshot) => {
2717
2226
  const createdAt = new Date(snapshot.createdAt);
@@ -2737,7 +2246,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2737
2246
  return { runs: [], total: 0 };
2738
2247
  }
2739
2248
  const total = allMatchingSnapshots.length;
2740
- const paginatedData = allMatchingSnapshots.slice(offset, offset + limit);
2249
+ const paginatedData = allMatchingSnapshots.slice(offset, offset + normalizedPerPage);
2741
2250
  const runs = paginatedData.map((snapshot) => formatWorkflowRun(snapshot));
2742
2251
  return {
2743
2252
  runs,
@@ -2746,7 +2255,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2746
2255
  } catch (error$1) {
2747
2256
  throw new error.MastraError(
2748
2257
  {
2749
- id: "STORAGE_DYNAMODB_STORE_GET_WORKFLOW_RUNS_FAILED",
2258
+ id: storage.createStorageErrorId("DYNAMODB", "LIST_WORKFLOW_RUNS", "FAILED"),
2750
2259
  domain: error.ErrorDomain.STORAGE,
2751
2260
  category: error.ErrorCategory.THIRD_PARTY,
2752
2261
  details: { workflowName: args?.workflowName || "", resourceId: args?.resourceId || "" }
@@ -2758,8 +2267,6 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2758
2267
  async getWorkflowRunById(args) {
2759
2268
  const { runId, workflowName } = args;
2760
2269
  this.logger.debug("Getting workflow run by ID", { runId, workflowName });
2761
- console.log("workflowName", workflowName);
2762
- console.log("runId", runId);
2763
2270
  try {
2764
2271
  if (workflowName) {
2765
2272
  this.logger.debug("WorkflowName provided, using direct GET operation.");
@@ -2769,7 +2276,6 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2769
2276
  workflow_name: workflowName,
2770
2277
  run_id: runId
2771
2278
  }).go();
2772
- console.log("result", result2);
2773
2279
  if (!result2.data) {
2774
2280
  return null;
2775
2281
  }
@@ -2803,7 +2309,7 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2803
2309
  } catch (error$1) {
2804
2310
  throw new error.MastraError(
2805
2311
  {
2806
- id: "STORAGE_DYNAMODB_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
2312
+ id: storage.createStorageErrorId("DYNAMODB", "GET_WORKFLOW_RUN_BY_ID", "FAILED"),
2807
2313
  domain: error.ErrorDomain.STORAGE,
2808
2314
  category: error.ErrorCategory.THIRD_PARTY,
2809
2315
  details: { runId, workflowName: args?.workflowName || "" }
@@ -2812,9 +2318,32 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2812
2318
  );
2813
2319
  }
2814
2320
  }
2321
+ async deleteWorkflowRunById({ runId, workflowName }) {
2322
+ this.logger.debug("Deleting workflow run by ID", { runId, workflowName });
2323
+ try {
2324
+ await this.service.entities.workflow_snapshot.delete({
2325
+ entity: "workflow_snapshot",
2326
+ workflow_name: workflowName,
2327
+ run_id: runId
2328
+ }).go();
2329
+ } catch (error$1) {
2330
+ throw new error.MastraError(
2331
+ {
2332
+ id: storage.createStorageErrorId("DYNAMODB", "DELETE_WORKFLOW_RUN_BY_ID", "FAILED"),
2333
+ domain: error.ErrorDomain.STORAGE,
2334
+ category: error.ErrorCategory.THIRD_PARTY,
2335
+ details: { runId, workflowName }
2336
+ },
2337
+ error$1
2338
+ );
2339
+ }
2340
+ }
2815
2341
  };
2816
2342
 
2817
2343
  // src/storage/index.ts
2344
+ var isClientConfig = (config) => {
2345
+ return "client" in config;
2346
+ };
2818
2347
  var DynamoDBStore = class extends storage.MastraStorage {
2819
2348
  tableName;
2820
2349
  client;
@@ -2822,7 +2351,7 @@ var DynamoDBStore = class extends storage.MastraStorage {
2822
2351
  hasInitialized = null;
2823
2352
  stores;
2824
2353
  constructor({ name, config }) {
2825
- super({ name });
2354
+ super({ id: config.id, name, disableInit: config.disableInit });
2826
2355
  try {
2827
2356
  if (!config.tableName || typeof config.tableName !== "string" || config.tableName.trim() === "") {
2828
2357
  throw new Error("DynamoDBStore: config.tableName must be provided and cannot be empty.");
@@ -2832,27 +2361,23 @@ var DynamoDBStore = class extends storage.MastraStorage {
2832
2361
  `DynamoDBStore: config.tableName "${config.tableName}" contains invalid characters or is not between 3 and 255 characters long.`
2833
2362
  );
2834
2363
  }
2835
- const dynamoClient = new clientDynamodb.DynamoDBClient({
2836
- region: config.region || "us-east-1",
2837
- endpoint: config.endpoint,
2838
- credentials: config.credentials
2839
- });
2840
2364
  this.tableName = config.tableName;
2841
- this.client = libDynamodb.DynamoDBDocumentClient.from(dynamoClient);
2365
+ if (isClientConfig(config)) {
2366
+ this.client = config.client;
2367
+ } else {
2368
+ const dynamoClient = new clientDynamodb.DynamoDBClient({
2369
+ region: config.region || "us-east-1",
2370
+ endpoint: config.endpoint,
2371
+ credentials: config.credentials
2372
+ });
2373
+ this.client = libDynamodb.DynamoDBDocumentClient.from(dynamoClient);
2374
+ }
2842
2375
  this.service = getElectroDbService(this.client, this.tableName);
2843
- const operations = new StoreOperationsDynamoDB({
2844
- service: this.service,
2845
- tableName: this.tableName,
2846
- client: this.client
2847
- });
2848
- const traces = new TracesStorageDynamoDB({ service: this.service, operations });
2849
- const workflows = new WorkflowStorageDynamoDB({ service: this.service });
2850
- const memory = new MemoryStorageDynamoDB({ service: this.service });
2851
- const scores = new ScoresStorageDynamoDB({ service: this.service });
2376
+ const domainConfig = { service: this.service };
2377
+ const workflows = new WorkflowStorageDynamoDB(domainConfig);
2378
+ const memory = new MemoryStorageDynamoDB(domainConfig);
2379
+ const scores = new ScoresStorageDynamoDB(domainConfig);
2852
2380
  this.stores = {
2853
- operations,
2854
- legacyEvals: new LegacyEvalsDynamoDB({ service: this.service, tableName: this.tableName }),
2855
- traces,
2856
2381
  workflows,
2857
2382
  memory,
2858
2383
  scores
@@ -2860,7 +2385,7 @@ var DynamoDBStore = class extends storage.MastraStorage {
2860
2385
  } catch (error$1) {
2861
2386
  throw new error.MastraError(
2862
2387
  {
2863
- id: "STORAGE_DYNAMODB_STORE_CONSTRUCTOR_FAILED",
2388
+ id: storage.createStorageErrorId("DYNAMODB", "CONSTRUCTOR", "FAILED"),
2864
2389
  domain: error.ErrorDomain.STORAGE,
2865
2390
  category: error.ErrorCategory.USER
2866
2391
  },
@@ -2868,15 +2393,6 @@ var DynamoDBStore = class extends storage.MastraStorage {
2868
2393
  );
2869
2394
  }
2870
2395
  }
2871
- get supports() {
2872
- return {
2873
- selectByIncludeResourceScope: true,
2874
- resourceWorkingMemory: true,
2875
- hasColumn: false,
2876
- createTable: false,
2877
- deleteMessages: false
2878
- };
2879
- }
2880
2396
  /**
2881
2397
  * Validates that the required DynamoDB table exists and is accessible.
2882
2398
  * This does not check the table structure - it assumes the table
@@ -2895,7 +2411,7 @@ var DynamoDBStore = class extends storage.MastraStorage {
2895
2411
  }
2896
2412
  throw new error.MastraError(
2897
2413
  {
2898
- id: "STORAGE_DYNAMODB_STORE_VALIDATE_TABLE_EXISTS_FAILED",
2414
+ id: storage.createStorageErrorId("DYNAMODB", "VALIDATE_TABLE_EXISTS", "FAILED"),
2899
2415
  domain: error.ErrorDomain.STORAGE,
2900
2416
  category: error.ErrorCategory.THIRD_PARTY,
2901
2417
  details: { tableName: this.tableName }
@@ -2918,7 +2434,7 @@ var DynamoDBStore = class extends storage.MastraStorage {
2918
2434
  } catch (error$1) {
2919
2435
  throw new error.MastraError(
2920
2436
  {
2921
- id: "STORAGE_DYNAMODB_STORE_INIT_FAILED",
2437
+ id: storage.createStorageErrorId("DYNAMODB", "INIT", "FAILED"),
2922
2438
  domain: error.ErrorDomain.STORAGE,
2923
2439
  category: error.ErrorCategory.THIRD_PARTY,
2924
2440
  details: { tableName: this.tableName }
@@ -2944,142 +2460,10 @@ var DynamoDBStore = class extends storage.MastraStorage {
2944
2460
  throw err;
2945
2461
  });
2946
2462
  }
2947
- async createTable({ tableName, schema }) {
2948
- return this.stores.operations.createTable({ tableName, schema });
2949
- }
2950
- async alterTable(_args) {
2951
- return this.stores.operations.alterTable(_args);
2952
- }
2953
- async clearTable({ tableName }) {
2954
- return this.stores.operations.clearTable({ tableName });
2955
- }
2956
- async dropTable({ tableName }) {
2957
- return this.stores.operations.dropTable({ tableName });
2958
- }
2959
- async insert({ tableName, record }) {
2960
- return this.stores.operations.insert({ tableName, record });
2961
- }
2962
- async batchInsert({ tableName, records }) {
2963
- return this.stores.operations.batchInsert({ tableName, records });
2964
- }
2965
- async load({ tableName, keys }) {
2966
- return this.stores.operations.load({ tableName, keys });
2967
- }
2968
- // Thread operations
2969
- async getThreadById({ threadId }) {
2970
- return this.stores.memory.getThreadById({ threadId });
2971
- }
2972
- async getThreadsByResourceId(args) {
2973
- return this.stores.memory.getThreadsByResourceId(args);
2974
- }
2975
- async saveThread({ thread }) {
2976
- return this.stores.memory.saveThread({ thread });
2977
- }
2978
- async updateThread({
2979
- id,
2980
- title,
2981
- metadata
2982
- }) {
2983
- return this.stores.memory.updateThread({ id, title, metadata });
2984
- }
2985
- async deleteThread({ threadId }) {
2986
- return this.stores.memory.deleteThread({ threadId });
2987
- }
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 });
3001
- }
3002
- async saveMessages(args) {
3003
- return this.stores.memory.saveMessages(args);
3004
- }
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
- async updateMessages(_args) {
3012
- return this.stores.memory.updateMessages(_args);
3013
- }
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
- // Workflow operations
3025
- async updateWorkflowResults({
3026
- workflowName,
3027
- runId,
3028
- stepId,
3029
- result,
3030
- runtimeContext
3031
- }) {
3032
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
3033
- }
3034
- async updateWorkflowState({
3035
- workflowName,
3036
- runId,
3037
- opts
3038
- }) {
3039
- return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
3040
- }
3041
- async persistWorkflowSnapshot({
3042
- workflowName,
3043
- runId,
3044
- snapshot
3045
- }) {
3046
- return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
3047
- }
3048
- async loadWorkflowSnapshot({
3049
- workflowName,
3050
- runId
3051
- }) {
3052
- return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
3053
- }
3054
- async getWorkflowRuns(args) {
3055
- return this.stores.workflows.getWorkflowRuns(args);
3056
- }
3057
- async getWorkflowRunById(args) {
3058
- return this.stores.workflows.getWorkflowRunById(args);
3059
- }
3060
- async getResourceById({ resourceId }) {
3061
- return this.stores.memory.getResourceById({ resourceId });
3062
- }
3063
- async saveResource({ resource }) {
3064
- return this.stores.memory.saveResource({ resource });
3065
- }
3066
- async updateResource({
3067
- resourceId,
3068
- workingMemory,
3069
- metadata
3070
- }) {
3071
- return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
3072
- }
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
2463
  /**
3081
2464
  * Closes the DynamoDB client connection and cleans up resources.
3082
- * Should be called when the store is no longer needed, e.g., at the end of tests or application shutdown.
2465
+ *
2466
+ * This will close the DynamoDB client, including pre-configured clients.
3083
2467
  */
3084
2468
  async close() {
3085
2469
  this.logger.debug("Closing DynamoDB client for store:", { name: this.name });
@@ -3089,7 +2473,7 @@ var DynamoDBStore = class extends storage.MastraStorage {
3089
2473
  } catch (error$1) {
3090
2474
  throw new error.MastraError(
3091
2475
  {
3092
- id: "STORAGE_DYNAMODB_STORE_CLOSE_FAILED",
2476
+ id: storage.createStorageErrorId("DYNAMODB", "CLOSE", "FAILED"),
3093
2477
  domain: error.ErrorDomain.STORAGE,
3094
2478
  category: error.ErrorCategory.THIRD_PARTY
3095
2479
  },
@@ -3097,43 +2481,11 @@ var DynamoDBStore = class extends storage.MastraStorage {
3097
2481
  );
3098
2482
  }
3099
2483
  }
3100
- /**
3101
- * SCORERS - Not implemented
3102
- */
3103
- async getScoreById({ id: _id }) {
3104
- return this.stores.scores.getScoreById({ id: _id });
3105
- }
3106
- async saveScore(_score) {
3107
- return this.stores.scores.saveScore(_score);
3108
- }
3109
- async getScoresByRunId({
3110
- runId: _runId,
3111
- pagination: _pagination
3112
- }) {
3113
- return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
3114
- }
3115
- async getScoresByEntityId({
3116
- entityId: _entityId,
3117
- entityType: _entityType,
3118
- pagination: _pagination
3119
- }) {
3120
- return this.stores.scores.getScoresByEntityId({
3121
- entityId: _entityId,
3122
- entityType: _entityType,
3123
- pagination: _pagination
3124
- });
3125
- }
3126
- async getScoresByScorerId({
3127
- scorerId,
3128
- source,
3129
- entityId,
3130
- entityType,
3131
- pagination
3132
- }) {
3133
- return this.stores.scores.getScoresByScorerId({ scorerId, source, entityId, entityType, pagination });
3134
- }
3135
2484
  };
3136
2485
 
3137
2486
  exports.DynamoDBStore = DynamoDBStore;
2487
+ exports.MemoryStorageDynamoDB = MemoryStorageDynamoDB;
2488
+ exports.ScoresStorageDynamoDB = ScoresStorageDynamoDB;
2489
+ exports.WorkflowStorageDynamoDB = WorkflowStorageDynamoDB;
3138
2490
  //# sourceMappingURL=index.cjs.map
3139
2491
  //# sourceMappingURL=index.cjs.map