@mastra/dynamodb 0.0.0-remove-unused-import-20250909212718 → 0.0.0-remove-unused-model-providers-api-20251030210744

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { DynamoDBClient, DescribeTableCommand } from '@aws-sdk/client-dynamodb';
2
2
  import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb';
3
3
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
4
- import { MastraStorage, StoreOperations, TracesStorage, TABLE_TRACES, WorkflowsStorage, MemoryStorage, resolveMessageLimit, ScoresStorage, LegacyEvalsStorage, TABLE_AI_SPANS, TABLE_RESOURCES, TABLE_SCORERS, TABLE_EVALS, TABLE_WORKFLOW_SNAPSHOT, TABLE_MESSAGES, TABLE_THREADS } from '@mastra/core/storage';
4
+ import { MastraStorage, StoreOperations, WorkflowsStorage, MemoryStorage, resolveMessageLimit, ScoresStorage, TABLE_AI_SPANS, TABLE_RESOURCES, TABLE_TRACES, TABLE_SCORERS, TABLE_WORKFLOW_SNAPSHOT, TABLE_MESSAGES, TABLE_THREADS } from '@mastra/core/storage';
5
5
  import { Entity, Service } from 'electrodb';
6
6
  import { MessageList } from '@mastra/core/agent';
7
+ import { saveScorePayloadSchema } from '@mastra/core/scores';
7
8
 
8
9
  // src/storage/index.ts
9
10
 
@@ -370,6 +371,10 @@ var scoreEntity = new Entity({
370
371
  type: "string",
371
372
  required: false
372
373
  },
374
+ spanId: {
375
+ type: "string",
376
+ required: false
377
+ },
373
378
  runId: {
374
379
  type: "string",
375
380
  required: true
@@ -557,7 +562,7 @@ var scoreEntity = new Entity({
557
562
  return value;
558
563
  }
559
564
  },
560
- runtimeContext: {
565
+ requestContext: {
561
566
  type: "string",
562
567
  required: false,
563
568
  set: (value) => {
@@ -656,6 +661,11 @@ var scoreEntity = new Entity({
656
661
  index: "gsi6",
657
662
  pk: { field: "gsi6pk", composite: ["entity", "threadId"] },
658
663
  sk: { field: "gsi6sk", composite: ["createdAt"] }
664
+ },
665
+ bySpan: {
666
+ index: "gsi7",
667
+ pk: { field: "gsi7pk", composite: ["entity", "traceId", "spanId"] },
668
+ sk: { field: "gsi7sk", composite: ["createdAt"] }
659
669
  }
660
670
  }
661
671
  });
@@ -923,187 +933,6 @@ function getElectroDbService(client, tableName) {
923
933
  }
924
934
  );
925
935
  }
926
- var LegacyEvalsDynamoDB = class extends LegacyEvalsStorage {
927
- service;
928
- tableName;
929
- constructor({ service, tableName }) {
930
- super();
931
- this.service = service;
932
- this.tableName = tableName;
933
- }
934
- // Eval operations
935
- async getEvalsByAgentName(agentName, type) {
936
- this.logger.debug("Getting evals for agent", { agentName, type });
937
- try {
938
- const query = this.service.entities.eval.query.byAgent({ entity: "eval", agent_name: agentName });
939
- const results = await query.go({ order: "desc", limit: 100 });
940
- if (!results.data.length) {
941
- return [];
942
- }
943
- let filteredData = results.data;
944
- if (type) {
945
- filteredData = filteredData.filter((evalRecord) => {
946
- try {
947
- const testInfo = evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0;
948
- if (type === "test" && !testInfo) {
949
- return false;
950
- }
951
- if (type === "live" && testInfo) {
952
- return false;
953
- }
954
- } catch (e) {
955
- this.logger.warn("Failed to parse test_info during filtering", { record: evalRecord, error: e });
956
- }
957
- return true;
958
- });
959
- }
960
- return filteredData.map((evalRecord) => {
961
- try {
962
- return {
963
- input: evalRecord.input,
964
- output: evalRecord.output,
965
- // Safely parse result and test_info
966
- result: evalRecord.result && typeof evalRecord.result === "string" ? JSON.parse(evalRecord.result) : void 0,
967
- agentName: evalRecord.agent_name,
968
- createdAt: evalRecord.created_at,
969
- // Keep as string from DDB?
970
- metricName: evalRecord.metric_name,
971
- instructions: evalRecord.instructions,
972
- runId: evalRecord.run_id,
973
- globalRunId: evalRecord.global_run_id,
974
- testInfo: evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0
975
- };
976
- } catch (parseError) {
977
- this.logger.error("Failed to parse eval record", { record: evalRecord, error: parseError });
978
- return {
979
- agentName: evalRecord.agent_name,
980
- createdAt: evalRecord.created_at,
981
- runId: evalRecord.run_id,
982
- globalRunId: evalRecord.global_run_id
983
- };
984
- }
985
- });
986
- } catch (error) {
987
- throw new MastraError(
988
- {
989
- id: "STORAGE_DYNAMODB_STORE_GET_EVALS_BY_AGENT_NAME_FAILED",
990
- domain: ErrorDomain.STORAGE,
991
- category: ErrorCategory.THIRD_PARTY,
992
- details: { agentName }
993
- },
994
- error
995
- );
996
- }
997
- }
998
- async getEvals(options = {}) {
999
- const { agentName, type, page = 0, perPage = 100, dateRange } = options;
1000
- this.logger.debug("Getting evals with pagination", { agentName, type, page, perPage, dateRange });
1001
- try {
1002
- let query;
1003
- if (agentName) {
1004
- query = this.service.entities.eval.query.byAgent({ entity: "eval", agent_name: agentName });
1005
- } else {
1006
- query = this.service.entities.eval.query.byEntity({ entity: "eval" });
1007
- }
1008
- const results = await query.go({
1009
- order: "desc",
1010
- pages: "all"
1011
- // Get all pages to apply filtering and pagination
1012
- });
1013
- if (!results.data.length) {
1014
- return {
1015
- evals: [],
1016
- total: 0,
1017
- page,
1018
- perPage,
1019
- hasMore: false
1020
- };
1021
- }
1022
- let filteredData = results.data;
1023
- if (type) {
1024
- filteredData = filteredData.filter((evalRecord) => {
1025
- try {
1026
- const testInfo = evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0;
1027
- if (type === "test" && !testInfo) {
1028
- return false;
1029
- }
1030
- if (type === "live" && testInfo) {
1031
- return false;
1032
- }
1033
- } catch (e) {
1034
- this.logger.warn("Failed to parse test_info during filtering", { record: evalRecord, error: e });
1035
- }
1036
- return true;
1037
- });
1038
- }
1039
- if (dateRange) {
1040
- const fromDate = dateRange.start;
1041
- const toDate = dateRange.end;
1042
- filteredData = filteredData.filter((evalRecord) => {
1043
- const recordDate = new Date(evalRecord.created_at);
1044
- if (fromDate && recordDate < fromDate) {
1045
- return false;
1046
- }
1047
- if (toDate && recordDate > toDate) {
1048
- return false;
1049
- }
1050
- return true;
1051
- });
1052
- }
1053
- const total = filteredData.length;
1054
- const start = page * perPage;
1055
- const end = start + perPage;
1056
- const paginatedData = filteredData.slice(start, end);
1057
- const evals = paginatedData.map((evalRecord) => {
1058
- try {
1059
- return {
1060
- input: evalRecord.input,
1061
- output: evalRecord.output,
1062
- result: evalRecord.result && typeof evalRecord.result === "string" ? JSON.parse(evalRecord.result) : void 0,
1063
- agentName: evalRecord.agent_name,
1064
- createdAt: evalRecord.created_at,
1065
- metricName: evalRecord.metric_name,
1066
- instructions: evalRecord.instructions,
1067
- runId: evalRecord.run_id,
1068
- globalRunId: evalRecord.global_run_id,
1069
- testInfo: evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0
1070
- };
1071
- } catch (parseError) {
1072
- this.logger.error("Failed to parse eval record", { record: evalRecord, error: parseError });
1073
- return {
1074
- agentName: evalRecord.agent_name,
1075
- createdAt: evalRecord.created_at,
1076
- runId: evalRecord.run_id,
1077
- globalRunId: evalRecord.global_run_id
1078
- };
1079
- }
1080
- });
1081
- const hasMore = end < total;
1082
- return {
1083
- evals,
1084
- total,
1085
- page,
1086
- perPage,
1087
- hasMore
1088
- };
1089
- } catch (error) {
1090
- throw new MastraError(
1091
- {
1092
- id: "STORAGE_DYNAMODB_STORE_GET_EVALS_FAILED",
1093
- domain: ErrorDomain.STORAGE,
1094
- category: ErrorCategory.THIRD_PARTY,
1095
- details: {
1096
- agentName: agentName || "all",
1097
- type: type || "all",
1098
- page,
1099
- perPage
1100
- }
1101
- },
1102
- error
1103
- );
1104
- }
1105
- }
1106
- };
1107
936
  var MemoryStorageDynamoDB = class extends MemoryStorage {
1108
937
  service;
1109
938
  constructor({ service }) {
@@ -1208,7 +1037,7 @@ var MemoryStorageDynamoDB = class extends MemoryStorage {
1208
1037
  resourceId: thread.resourceId,
1209
1038
  title: threadData.title,
1210
1039
  createdAt: thread.createdAt || now,
1211
- updatedAt: now,
1040
+ updatedAt: thread.updatedAt || now,
1212
1041
  metadata: thread.metadata
1213
1042
  };
1214
1043
  } catch (error) {
@@ -1360,10 +1189,7 @@ var MemoryStorageDynamoDB = class extends MemoryStorage {
1360
1189
  );
1361
1190
  }
1362
1191
  }
1363
- async getMessagesById({
1364
- messageIds,
1365
- format
1366
- }) {
1192
+ async listMessagesById({ messageIds }) {
1367
1193
  this.logger.debug("Getting messages by ID", { messageIds });
1368
1194
  if (messageIds.length === 0) return [];
1369
1195
  try {
@@ -1376,7 +1202,6 @@ var MemoryStorageDynamoDB = class extends MemoryStorage {
1376
1202
  (message, index, self) => index === self.findIndex((m) => m.id === message.id)
1377
1203
  );
1378
1204
  const list = new MessageList().add(uniqueMessages, "memory");
1379
- if (format === `v1`) return list.get.all.v1();
1380
1205
  return list.get.all.v2();
1381
1206
  } catch (error) {
1382
1207
  throw new MastraError(
@@ -1390,6 +1215,150 @@ var MemoryStorageDynamoDB = class extends MemoryStorage {
1390
1215
  );
1391
1216
  }
1392
1217
  }
1218
+ async listMessages(args) {
1219
+ const { threadId, resourceId, include, filter, limit, offset = 0, orderBy } = args;
1220
+ if (!threadId.trim()) {
1221
+ throw new MastraError(
1222
+ {
1223
+ id: "STORAGE_DYNAMODB_LIST_MESSAGES_INVALID_THREAD_ID",
1224
+ domain: ErrorDomain.STORAGE,
1225
+ category: ErrorCategory.THIRD_PARTY,
1226
+ details: { threadId }
1227
+ },
1228
+ new Error("threadId must be a non-empty string")
1229
+ );
1230
+ }
1231
+ try {
1232
+ let perPage = 40;
1233
+ if (limit !== void 0) {
1234
+ if (limit === false) {
1235
+ perPage = Number.MAX_SAFE_INTEGER;
1236
+ } else if (limit === 0) {
1237
+ perPage = 0;
1238
+ } else if (typeof limit === "number" && limit > 0) {
1239
+ perPage = limit;
1240
+ }
1241
+ }
1242
+ const page = perPage === 0 ? 0 : Math.floor(offset / perPage);
1243
+ const sortField = orderBy?.field || "createdAt";
1244
+ const sortDirection = orderBy?.direction || "DESC";
1245
+ this.logger.debug("Getting messages with listMessages", {
1246
+ threadId,
1247
+ resourceId,
1248
+ limit,
1249
+ offset,
1250
+ perPage,
1251
+ page,
1252
+ sortField,
1253
+ sortDirection
1254
+ });
1255
+ const query = this.service.entities.message.query.byThread({ entity: "message", threadId });
1256
+ const results = await query.go();
1257
+ let allThreadMessages = results.data.map((data) => this.parseMessageData(data)).filter((msg) => "content" in msg && typeof msg.content === "object");
1258
+ if (resourceId) {
1259
+ allThreadMessages = allThreadMessages.filter((msg) => msg.resourceId === resourceId);
1260
+ }
1261
+ if (filter?.dateRange) {
1262
+ const dateRange = filter.dateRange;
1263
+ allThreadMessages = allThreadMessages.filter((msg) => {
1264
+ const createdAt = new Date(msg.createdAt).getTime();
1265
+ if (dateRange.start) {
1266
+ const startTime = dateRange.start instanceof Date ? dateRange.start.getTime() : new Date(dateRange.start).getTime();
1267
+ if (createdAt < startTime) return false;
1268
+ }
1269
+ if (dateRange.end) {
1270
+ const endTime = dateRange.end instanceof Date ? dateRange.end.getTime() : new Date(dateRange.end).getTime();
1271
+ if (createdAt > endTime) return false;
1272
+ }
1273
+ return true;
1274
+ });
1275
+ }
1276
+ allThreadMessages.sort((a, b) => {
1277
+ const aValue = sortField === "createdAt" ? new Date(a.createdAt).getTime() : a[sortField];
1278
+ const bValue = sortField === "createdAt" ? new Date(b.createdAt).getTime() : b[sortField];
1279
+ if (aValue === bValue) {
1280
+ return a.id.localeCompare(b.id);
1281
+ }
1282
+ return sortDirection === "ASC" ? aValue - bValue : bValue - aValue;
1283
+ });
1284
+ const total = allThreadMessages.length;
1285
+ const paginatedMessages = allThreadMessages.slice(offset, offset + perPage);
1286
+ const paginatedCount = paginatedMessages.length;
1287
+ if (total === 0 && paginatedCount === 0) {
1288
+ return {
1289
+ messages: [],
1290
+ total: 0,
1291
+ page,
1292
+ perPage,
1293
+ hasMore: false
1294
+ };
1295
+ }
1296
+ const messageIds = new Set(paginatedMessages.map((m) => m.id));
1297
+ let includeMessages = [];
1298
+ if (include && include.length > 0) {
1299
+ const selectBy = { include };
1300
+ includeMessages = await this._getIncludedMessages(threadId, selectBy);
1301
+ for (const includeMsg of includeMessages) {
1302
+ if (!messageIds.has(includeMsg.id)) {
1303
+ paginatedMessages.push(includeMsg);
1304
+ messageIds.add(includeMsg.id);
1305
+ }
1306
+ }
1307
+ }
1308
+ const list = new MessageList().add(paginatedMessages, "memory");
1309
+ let finalMessages = list.get.all.v2();
1310
+ finalMessages = finalMessages.sort((a, b) => {
1311
+ const aValue = sortField === "createdAt" ? new Date(a.createdAt).getTime() : a[sortField];
1312
+ const bValue = sortField === "createdAt" ? new Date(b.createdAt).getTime() : b[sortField];
1313
+ if (aValue === bValue) {
1314
+ return a.id.localeCompare(b.id);
1315
+ }
1316
+ return sortDirection === "ASC" ? aValue - bValue : bValue - aValue;
1317
+ });
1318
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
1319
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
1320
+ const hasMore = limit === false ? false : allThreadMessagesReturned ? false : offset + paginatedCount < total;
1321
+ return {
1322
+ messages: finalMessages,
1323
+ total,
1324
+ page,
1325
+ perPage,
1326
+ hasMore
1327
+ };
1328
+ } catch (error) {
1329
+ const mastraError = new MastraError(
1330
+ {
1331
+ id: "STORAGE_DYNAMODB_STORE_LIST_MESSAGES_FAILED",
1332
+ domain: ErrorDomain.STORAGE,
1333
+ category: ErrorCategory.THIRD_PARTY,
1334
+ details: {
1335
+ threadId,
1336
+ resourceId: resourceId ?? ""
1337
+ }
1338
+ },
1339
+ error
1340
+ );
1341
+ this.logger?.error?.(mastraError.toString());
1342
+ this.logger?.trackException?.(mastraError);
1343
+ return {
1344
+ messages: [],
1345
+ total: 0,
1346
+ page: Math.floor(offset / (limit === false ? Number.MAX_SAFE_INTEGER : limit || 40)),
1347
+ perPage: limit === false ? Number.MAX_SAFE_INTEGER : limit || 40,
1348
+ hasMore: false
1349
+ };
1350
+ }
1351
+ }
1352
+ /**
1353
+ * @todo When migrating from getThreadsByResourceIdPaginated to this method,
1354
+ * implement orderBy and sortDirection support for full sorting capabilities
1355
+ */
1356
+ async listThreadsByResourceId(args) {
1357
+ const { resourceId, limit, offset } = args;
1358
+ const page = Math.floor(offset / limit);
1359
+ const perPage = limit;
1360
+ return this.getThreadsByResourceIdPaginated({ resourceId, page, perPage });
1361
+ }
1393
1362
  async saveMessages(args) {
1394
1363
  const { messages, format = "v1" } = args;
1395
1364
  this.logger.debug("Saving messages", { count: messages.length });
@@ -1845,7 +1814,6 @@ var StoreOperationsDynamoDB = class extends StoreOperations {
1845
1814
  [TABLE_THREADS]: "thread",
1846
1815
  [TABLE_MESSAGES]: "message",
1847
1816
  [TABLE_WORKFLOW_SNAPSHOT]: "workflow_snapshot",
1848
- [TABLE_EVALS]: "eval",
1849
1817
  [TABLE_SCORERS]: "score",
1850
1818
  [TABLE_TRACES]: "trace",
1851
1819
  [TABLE_RESOURCES]: "resource",
@@ -2034,6 +2002,10 @@ var StoreOperationsDynamoDB = class extends StoreOperations {
2034
2002
  if (!item.id) throw new Error(`Missing required key 'id' for entity 'score'`);
2035
2003
  key.id = item.id;
2036
2004
  break;
2005
+ case "resource":
2006
+ if (!item.id) throw new Error(`Missing required key 'id' for entity 'resource'`);
2007
+ key.id = item.id;
2008
+ break;
2037
2009
  default:
2038
2010
  this.logger.warn(`Unknown entity type encountered during clearTable: ${entityName}`);
2039
2011
  throw new Error(`Cannot construct delete key for unknown entity type: ${entityName}`);
@@ -2176,34 +2148,47 @@ var ScoresStorageDynamoDB = class extends ScoresStorage {
2176
2148
  }
2177
2149
  }
2178
2150
  async saveScore(score) {
2179
- this.logger.debug("Saving score", { scorerId: score.scorerId, runId: score.runId });
2151
+ let validatedScore;
2152
+ try {
2153
+ validatedScore = saveScorePayloadSchema.parse(score);
2154
+ } catch (error) {
2155
+ throw new MastraError(
2156
+ {
2157
+ id: "STORAGE_DYNAMODB_STORE_SAVE_SCORE_FAILED",
2158
+ domain: ErrorDomain.STORAGE,
2159
+ category: ErrorCategory.THIRD_PARTY
2160
+ },
2161
+ error
2162
+ );
2163
+ }
2180
2164
  const now = /* @__PURE__ */ new Date();
2181
2165
  const scoreId = `score-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
2182
2166
  const scoreData = {
2183
2167
  entity: "score",
2184
2168
  id: scoreId,
2185
- scorerId: score.scorerId,
2186
- traceId: score.traceId || "",
2187
- runId: score.runId,
2188
- scorer: typeof score.scorer === "string" ? score.scorer : JSON.stringify(score.scorer),
2189
- preprocessStepResult: typeof score.preprocessStepResult === "string" ? score.preprocessStepResult : JSON.stringify(score.preprocessStepResult),
2190
- analyzeStepResult: typeof score.analyzeStepResult === "string" ? score.analyzeStepResult : JSON.stringify(score.analyzeStepResult),
2191
- score: score.score,
2192
- reason: score.reason,
2193
- preprocessPrompt: score.preprocessPrompt,
2194
- generateScorePrompt: score.generateScorePrompt,
2195
- analyzePrompt: score.analyzePrompt,
2196
- reasonPrompt: score.reasonPrompt,
2197
- input: typeof score.input === "string" ? score.input : JSON.stringify(score.input),
2198
- output: typeof score.output === "string" ? score.output : JSON.stringify(score.output),
2199
- additionalContext: typeof score.additionalContext === "string" ? score.additionalContext : JSON.stringify(score.additionalContext),
2200
- runtimeContext: typeof score.runtimeContext === "string" ? score.runtimeContext : JSON.stringify(score.runtimeContext),
2201
- entityType: score.entityType,
2202
- entityData: typeof score.entity === "string" ? score.entity : JSON.stringify(score.entity),
2203
- entityId: score.entityId,
2204
- source: score.source,
2205
- resourceId: score.resourceId || "",
2206
- threadId: score.threadId || "",
2169
+ scorerId: validatedScore.scorerId,
2170
+ traceId: validatedScore.traceId || "",
2171
+ spanId: validatedScore.spanId || "",
2172
+ runId: validatedScore.runId,
2173
+ scorer: typeof validatedScore.scorer === "string" ? validatedScore.scorer : JSON.stringify(validatedScore.scorer),
2174
+ preprocessStepResult: typeof validatedScore.preprocessStepResult === "string" ? validatedScore.preprocessStepResult : JSON.stringify(validatedScore.preprocessStepResult),
2175
+ analyzeStepResult: typeof validatedScore.analyzeStepResult === "string" ? validatedScore.analyzeStepResult : JSON.stringify(validatedScore.analyzeStepResult),
2176
+ score: validatedScore.score,
2177
+ reason: validatedScore.reason,
2178
+ preprocessPrompt: validatedScore.preprocessPrompt,
2179
+ generateScorePrompt: validatedScore.generateScorePrompt,
2180
+ generateReasonPrompt: validatedScore.generateReasonPrompt,
2181
+ analyzePrompt: validatedScore.analyzePrompt,
2182
+ input: typeof validatedScore.input === "string" ? validatedScore.input : JSON.stringify(validatedScore.input),
2183
+ output: typeof validatedScore.output === "string" ? validatedScore.output : JSON.stringify(validatedScore.output),
2184
+ additionalContext: typeof validatedScore.additionalContext === "string" ? validatedScore.additionalContext : JSON.stringify(validatedScore.additionalContext),
2185
+ requestContext: typeof validatedScore.requestContext === "string" ? validatedScore.requestContext : JSON.stringify(validatedScore.requestContext),
2186
+ entityType: validatedScore.entityType,
2187
+ entityData: typeof validatedScore.entity === "string" ? validatedScore.entity : JSON.stringify(validatedScore.entity),
2188
+ entityId: validatedScore.entityId,
2189
+ source: validatedScore.source,
2190
+ resourceId: validatedScore.resourceId || "",
2191
+ threadId: validatedScore.threadId || "",
2207
2192
  createdAt: now.toISOString(),
2208
2193
  updatedAt: now.toISOString()
2209
2194
  };
@@ -2356,234 +2341,38 @@ var ScoresStorageDynamoDB = class extends ScoresStorage {
2356
2341
  );
2357
2342
  }
2358
2343
  }
2359
- };
2360
- var TracesStorageDynamoDB = class extends TracesStorage {
2361
- service;
2362
- operations;
2363
- constructor({ service, operations }) {
2364
- super();
2365
- this.service = service;
2366
- this.operations = operations;
2367
- }
2368
- // Trace operations
2369
- async getTraces(args) {
2370
- const { name, scope, page, perPage } = args;
2371
- this.logger.debug("Getting traces", { name, scope, page, perPage });
2372
- try {
2373
- let query;
2374
- if (name) {
2375
- query = this.service.entities.trace.query.byName({ entity: "trace", name });
2376
- } else if (scope) {
2377
- query = this.service.entities.trace.query.byScope({ entity: "trace", scope });
2378
- } else {
2379
- this.logger.warn("Performing a scan operation on traces - consider using a more specific query");
2380
- query = this.service.entities.trace.scan;
2381
- }
2382
- let items = [];
2383
- let cursor = null;
2384
- let pagesFetched = 0;
2385
- const startPage = page > 0 ? page : 1;
2386
- do {
2387
- const results = await query.go({ cursor, limit: perPage });
2388
- pagesFetched++;
2389
- if (pagesFetched === startPage) {
2390
- items = results.data;
2391
- break;
2392
- }
2393
- cursor = results.cursor;
2394
- if (!cursor && results.data.length > 0 && pagesFetched < startPage) {
2395
- break;
2396
- }
2397
- } while (cursor && pagesFetched < startPage);
2398
- return items;
2399
- } catch (error) {
2400
- throw new MastraError(
2401
- {
2402
- id: "STORAGE_DYNAMODB_STORE_GET_TRACES_FAILED",
2403
- domain: ErrorDomain.STORAGE,
2404
- category: ErrorCategory.THIRD_PARTY
2405
- },
2406
- error
2407
- );
2408
- }
2409
- }
2410
- async batchTraceInsert({ records }) {
2411
- this.logger.debug("Batch inserting traces", { count: records.length });
2412
- if (!records.length) {
2413
- return;
2414
- }
2415
- try {
2416
- const recordsToSave = records.map((rec) => ({ entity: "trace", ...rec }));
2417
- await this.operations.batchInsert({
2418
- tableName: TABLE_TRACES,
2419
- records: recordsToSave
2420
- // Pass records with 'entity' included
2421
- });
2422
- } catch (error) {
2423
- throw new MastraError(
2424
- {
2425
- id: "STORAGE_DYNAMODB_STORE_BATCH_TRACE_INSERT_FAILED",
2426
- domain: ErrorDomain.STORAGE,
2427
- category: ErrorCategory.THIRD_PARTY,
2428
- details: { count: records.length }
2429
- },
2430
- error
2431
- );
2432
- }
2433
- }
2434
- async getTracesPaginated(args) {
2435
- const { name, scope, page = 0, perPage = 100, attributes, filters, dateRange } = args;
2436
- this.logger.debug("Getting traces with pagination", { name, scope, page, perPage, attributes, filters, dateRange });
2344
+ async getScoresBySpan({
2345
+ traceId,
2346
+ spanId,
2347
+ pagination
2348
+ }) {
2349
+ this.logger.debug("Getting scores by span", { traceId, spanId, pagination });
2437
2350
  try {
2438
- let query;
2439
- if (name) {
2440
- query = this.service.entities.trace.query.byName({ entity: "trace", name });
2441
- } else if (scope) {
2442
- query = this.service.entities.trace.query.byScope({ entity: "trace", scope });
2443
- } else {
2444
- this.logger.warn("Performing a scan operation on traces - consider using a more specific query");
2445
- query = this.service.entities.trace.scan;
2446
- }
2447
- const results = await query.go({
2448
- order: "desc",
2449
- pages: "all"
2450
- // Get all pages to apply filtering and pagination
2451
- });
2452
- if (!results.data.length) {
2453
- return {
2454
- traces: [],
2455
- total: 0,
2456
- page,
2457
- perPage,
2458
- hasMore: false
2459
- };
2460
- }
2461
- let filteredData = results.data;
2462
- if (attributes) {
2463
- filteredData = filteredData.filter((item) => {
2464
- try {
2465
- let itemAttributes = {};
2466
- if (item.attributes) {
2467
- if (typeof item.attributes === "string") {
2468
- if (item.attributes === "[object Object]") {
2469
- itemAttributes = {};
2470
- } else {
2471
- try {
2472
- itemAttributes = JSON.parse(item.attributes);
2473
- } catch {
2474
- itemAttributes = {};
2475
- }
2476
- }
2477
- } else if (typeof item.attributes === "object") {
2478
- itemAttributes = item.attributes;
2479
- }
2480
- }
2481
- return Object.entries(attributes).every(([key, value]) => itemAttributes[key] === value);
2482
- } catch (e) {
2483
- this.logger.warn("Failed to parse attributes during filtering", { item, error: e });
2484
- return false;
2485
- }
2486
- });
2487
- }
2488
- if (dateRange?.start) {
2489
- filteredData = filteredData.filter((item) => {
2490
- const itemDate = new Date(item.createdAt);
2491
- return itemDate >= dateRange.start;
2492
- });
2493
- }
2494
- if (dateRange?.end) {
2495
- filteredData = filteredData.filter((item) => {
2496
- const itemDate = new Date(item.createdAt);
2497
- return itemDate <= dateRange.end;
2498
- });
2499
- }
2500
- const total = filteredData.length;
2501
- const start = page * perPage;
2502
- const end = start + perPage;
2503
- const paginatedData = filteredData.slice(start, end);
2504
- const traces = paginatedData.map((item) => {
2505
- let attributes2;
2506
- if (item.attributes) {
2507
- if (typeof item.attributes === "string") {
2508
- if (item.attributes === "[object Object]") {
2509
- attributes2 = void 0;
2510
- } else {
2511
- try {
2512
- attributes2 = JSON.parse(item.attributes);
2513
- } catch {
2514
- attributes2 = void 0;
2515
- }
2516
- }
2517
- } else if (typeof item.attributes === "object") {
2518
- attributes2 = item.attributes;
2519
- }
2520
- }
2521
- let status;
2522
- if (item.status) {
2523
- if (typeof item.status === "string") {
2524
- try {
2525
- status = JSON.parse(item.status);
2526
- } catch {
2527
- status = void 0;
2528
- }
2529
- } else if (typeof item.status === "object") {
2530
- status = item.status;
2531
- }
2532
- }
2533
- let events;
2534
- if (item.events) {
2535
- if (typeof item.events === "string") {
2536
- try {
2537
- events = JSON.parse(item.events);
2538
- } catch {
2539
- events = void 0;
2540
- }
2541
- } else if (Array.isArray(item.events)) {
2542
- events = item.events;
2543
- }
2544
- }
2545
- let links;
2546
- if (item.links) {
2547
- if (typeof item.links === "string") {
2548
- try {
2549
- links = JSON.parse(item.links);
2550
- } catch {
2551
- links = void 0;
2552
- }
2553
- } else if (Array.isArray(item.links)) {
2554
- links = item.links;
2555
- }
2556
- }
2557
- return {
2558
- id: item.id,
2559
- parentSpanId: item.parentSpanId,
2560
- name: item.name,
2561
- traceId: item.traceId,
2562
- scope: item.scope,
2563
- kind: item.kind,
2564
- attributes: attributes2,
2565
- status,
2566
- events,
2567
- links,
2568
- other: item.other,
2569
- startTime: item.startTime,
2570
- endTime: item.endTime,
2571
- createdAt: item.createdAt
2572
- };
2573
- });
2351
+ const query = this.service.entities.score.query.bySpan({ entity: "score", traceId, spanId });
2352
+ const results = await query.go();
2353
+ const allScores = results.data.map((data) => this.parseScoreData(data));
2354
+ allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2355
+ const startIndex = pagination.page * pagination.perPage;
2356
+ const endIndex = startIndex + pagination.perPage;
2357
+ const paginatedScores = allScores.slice(startIndex, endIndex);
2358
+ const total = allScores.length;
2359
+ const hasMore = endIndex < total;
2574
2360
  return {
2575
- traces,
2576
- total,
2577
- page,
2578
- perPage,
2579
- hasMore: end < total
2361
+ scores: paginatedScores,
2362
+ pagination: {
2363
+ total,
2364
+ page: pagination.page,
2365
+ perPage: pagination.perPage,
2366
+ hasMore
2367
+ }
2580
2368
  };
2581
2369
  } catch (error) {
2582
2370
  throw new MastraError(
2583
2371
  {
2584
- id: "STORAGE_DYNAMODB_STORE_GET_TRACES_PAGINATED_FAILED",
2372
+ id: "STORAGE_DYNAMODB_STORE_GET_SCORES_BY_SPAN_FAILED",
2585
2373
  domain: ErrorDomain.STORAGE,
2586
- category: ErrorCategory.THIRD_PARTY
2374
+ category: ErrorCategory.THIRD_PARTY,
2375
+ details: { traceId, spanId, page: pagination.page, perPage: pagination.perPage }
2587
2376
  },
2588
2377
  error
2589
2378
  );
@@ -2611,7 +2400,7 @@ var WorkflowStorageDynamoDB = class extends WorkflowsStorage {
2611
2400
  // runId,
2612
2401
  // stepId,
2613
2402
  // result,
2614
- // runtimeContext,
2403
+ // requestContext,
2615
2404
  }) {
2616
2405
  throw new Error("Method not implemented.");
2617
2406
  }
@@ -2626,11 +2415,11 @@ var WorkflowStorageDynamoDB = class extends WorkflowsStorage {
2626
2415
  async persistWorkflowSnapshot({
2627
2416
  workflowName,
2628
2417
  runId,
2418
+ resourceId,
2629
2419
  snapshot
2630
2420
  }) {
2631
2421
  this.logger.debug("Persisting workflow snapshot", { workflowName, runId });
2632
2422
  try {
2633
- const resourceId = "resourceId" in snapshot ? snapshot.resourceId : void 0;
2634
2423
  const now = (/* @__PURE__ */ new Date()).toISOString();
2635
2424
  const data = {
2636
2425
  entity: "workflow_snapshot",
@@ -2684,7 +2473,7 @@ var WorkflowStorageDynamoDB = class extends WorkflowsStorage {
2684
2473
  );
2685
2474
  }
2686
2475
  }
2687
- async getWorkflowRuns(args) {
2476
+ async listWorkflowRuns(args) {
2688
2477
  this.logger.debug("Getting workflow runs", { args });
2689
2478
  try {
2690
2479
  const limit = args?.limit || 10;
@@ -2756,8 +2545,6 @@ var WorkflowStorageDynamoDB = class extends WorkflowsStorage {
2756
2545
  async getWorkflowRunById(args) {
2757
2546
  const { runId, workflowName } = args;
2758
2547
  this.logger.debug("Getting workflow run by ID", { runId, workflowName });
2759
- console.log("workflowName", workflowName);
2760
- console.log("runId", runId);
2761
2548
  try {
2762
2549
  if (workflowName) {
2763
2550
  this.logger.debug("WorkflowName provided, using direct GET operation.");
@@ -2767,7 +2554,6 @@ var WorkflowStorageDynamoDB = class extends WorkflowsStorage {
2767
2554
  workflow_name: workflowName,
2768
2555
  run_id: runId
2769
2556
  }).go();
2770
- console.log("result", result2);
2771
2557
  if (!result2.data) {
2772
2558
  return null;
2773
2559
  }
@@ -2843,14 +2629,11 @@ var DynamoDBStore = class extends MastraStorage {
2843
2629
  tableName: this.tableName,
2844
2630
  client: this.client
2845
2631
  });
2846
- const traces = new TracesStorageDynamoDB({ service: this.service, operations });
2847
2632
  const workflows = new WorkflowStorageDynamoDB({ service: this.service });
2848
2633
  const memory = new MemoryStorageDynamoDB({ service: this.service });
2849
2634
  const scores = new ScoresStorageDynamoDB({ service: this.service });
2850
2635
  this.stores = {
2851
2636
  operations,
2852
- legacyEvals: new LegacyEvalsDynamoDB({ service: this.service, tableName: this.tableName }),
2853
- traces,
2854
2637
  workflows,
2855
2638
  memory,
2856
2639
  scores
@@ -2872,7 +2655,8 @@ var DynamoDBStore = class extends MastraStorage {
2872
2655
  resourceWorkingMemory: true,
2873
2656
  hasColumn: false,
2874
2657
  createTable: false,
2875
- deleteMessages: false
2658
+ deleteMessages: false,
2659
+ getScoresBySpan: true
2876
2660
  };
2877
2661
  }
2878
2662
  /**
@@ -2991,12 +2775,6 @@ var DynamoDBStore = class extends MastraStorage {
2991
2775
  }) {
2992
2776
  return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format });
2993
2777
  }
2994
- async getMessagesById({
2995
- messageIds,
2996
- format
2997
- }) {
2998
- return this.stores.memory.getMessagesById({ messageIds, format });
2999
- }
3000
2778
  async saveMessages(args) {
3001
2779
  return this.stores.memory.saveMessages(args);
3002
2780
  }
@@ -3009,25 +2787,15 @@ var DynamoDBStore = class extends MastraStorage {
3009
2787
  async updateMessages(_args) {
3010
2788
  return this.stores.memory.updateMessages(_args);
3011
2789
  }
3012
- // Trace operations
3013
- async getTraces(args) {
3014
- return this.stores.traces.getTraces(args);
3015
- }
3016
- async batchTraceInsert({ records }) {
3017
- return this.stores.traces.batchTraceInsert({ records });
3018
- }
3019
- async getTracesPaginated(_args) {
3020
- return this.stores.traces.getTracesPaginated(_args);
3021
- }
3022
2790
  // Workflow operations
3023
2791
  async updateWorkflowResults({
3024
2792
  workflowName,
3025
2793
  runId,
3026
2794
  stepId,
3027
2795
  result,
3028
- runtimeContext
2796
+ requestContext
3029
2797
  }) {
3030
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2798
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
3031
2799
  }
3032
2800
  async updateWorkflowState({
3033
2801
  workflowName,
@@ -3039,9 +2807,10 @@ var DynamoDBStore = class extends MastraStorage {
3039
2807
  async persistWorkflowSnapshot({
3040
2808
  workflowName,
3041
2809
  runId,
2810
+ resourceId,
3042
2811
  snapshot
3043
2812
  }) {
3044
- return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2813
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
3045
2814
  }
3046
2815
  async loadWorkflowSnapshot({
3047
2816
  workflowName,
@@ -3049,8 +2818,8 @@ var DynamoDBStore = class extends MastraStorage {
3049
2818
  }) {
3050
2819
  return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
3051
2820
  }
3052
- async getWorkflowRuns(args) {
3053
- return this.stores.workflows.getWorkflowRuns(args);
2821
+ async listWorkflowRuns(args) {
2822
+ return this.stores.workflows.listWorkflowRuns(args);
3054
2823
  }
3055
2824
  async getWorkflowRunById(args) {
3056
2825
  return this.stores.workflows.getWorkflowRunById(args);
@@ -3068,13 +2837,6 @@ var DynamoDBStore = class extends MastraStorage {
3068
2837
  }) {
3069
2838
  return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
3070
2839
  }
3071
- // Eval operations
3072
- async getEvalsByAgentName(agentName, type) {
3073
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
3074
- }
3075
- async getEvals(options) {
3076
- return this.stores.legacyEvals.getEvals(options);
3077
- }
3078
2840
  /**
3079
2841
  * Closes the DynamoDB client connection and cleans up resources.
3080
2842
  * Should be called when the store is no longer needed, e.g., at the end of tests or application shutdown.
@@ -3130,6 +2892,13 @@ var DynamoDBStore = class extends MastraStorage {
3130
2892
  }) {
3131
2893
  return this.stores.scores.getScoresByScorerId({ scorerId, source, entityId, entityType, pagination });
3132
2894
  }
2895
+ async getScoresBySpan({
2896
+ traceId,
2897
+ spanId,
2898
+ pagination
2899
+ }) {
2900
+ return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
2901
+ }
3133
2902
  };
3134
2903
 
3135
2904
  export { DynamoDBStore };