@mastra/libsql 0.16.2 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3,9 +3,9 @@ import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
3
3
  import { parseSqlIdentifier, parseFieldKey } from '@mastra/core/utils';
4
4
  import { MastraVector } from '@mastra/core/vector';
5
5
  import { BaseFilterTranslator } from '@mastra/core/vector/filter';
6
- import { MastraStorage, StoreOperations, TABLE_WORKFLOW_SNAPSHOT, TABLE_AI_SPANS, ScoresStorage, TABLE_SCORERS, safelyParseJSON, TracesStorage, TABLE_TRACES, WorkflowsStorage, MemoryStorage, resolveMessageLimit, TABLE_MESSAGES, TABLE_THREADS, TABLE_RESOURCES, LegacyEvalsStorage, TABLE_EVALS, ObservabilityStorage, TABLE_SCHEMAS, AI_SPAN_SCHEMA } from '@mastra/core/storage';
6
+ import { MastraStorage, StoreOperations, TABLE_WORKFLOW_SNAPSHOT, TABLE_SPANS, ScoresStorage, TABLE_SCORERS, normalizePerPage, calculatePagination, safelyParseJSON, WorkflowsStorage, MemoryStorage, TABLE_MESSAGES, TABLE_THREADS, TABLE_RESOURCES, ObservabilityStorage, TABLE_SCHEMAS, SPAN_SCHEMA } from '@mastra/core/storage';
7
7
  import { MessageList } from '@mastra/core/agent';
8
- import { saveScorePayloadSchema } from '@mastra/core/scores';
8
+ import { saveScorePayloadSchema } from '@mastra/core/evals';
9
9
 
10
10
  // src/vector/index.ts
11
11
  var LibSQLFilterTranslator = class extends BaseFilterTranslator {
@@ -505,9 +505,10 @@ var LibSQLVector = class extends MastraVector {
505
505
  syncUrl,
506
506
  syncInterval,
507
507
  maxRetries = 5,
508
- initialBackoffMs = 100
508
+ initialBackoffMs = 100,
509
+ id
509
510
  }) {
510
- super();
511
+ super({ id });
511
512
  this.turso = createClient({
512
513
  url: connectionUrl,
513
514
  syncUrl,
@@ -918,120 +919,6 @@ var LibSQLVector = class extends MastraVector {
918
919
  });
919
920
  }
920
921
  };
921
- function transformEvalRow(row) {
922
- const resultValue = JSON.parse(row.result);
923
- const testInfoValue = row.test_info ? JSON.parse(row.test_info) : void 0;
924
- if (!resultValue || typeof resultValue !== "object" || !("score" in resultValue)) {
925
- throw new Error(`Invalid MetricResult format: ${JSON.stringify(resultValue)}`);
926
- }
927
- return {
928
- input: row.input,
929
- output: row.output,
930
- result: resultValue,
931
- agentName: row.agent_name,
932
- metricName: row.metric_name,
933
- instructions: row.instructions,
934
- testInfo: testInfoValue,
935
- globalRunId: row.global_run_id,
936
- runId: row.run_id,
937
- createdAt: row.created_at
938
- };
939
- }
940
- var LegacyEvalsLibSQL = class extends LegacyEvalsStorage {
941
- client;
942
- constructor({ client }) {
943
- super();
944
- this.client = client;
945
- }
946
- /** @deprecated use getEvals instead */
947
- async getEvalsByAgentName(agentName, type) {
948
- try {
949
- const baseQuery = `SELECT * FROM ${TABLE_EVALS} WHERE agent_name = ?`;
950
- const typeCondition = type === "test" ? " AND test_info IS NOT NULL AND test_info->>'testPath' IS NOT NULL" : type === "live" ? " AND (test_info IS NULL OR test_info->>'testPath' IS NULL)" : "";
951
- const result = await this.client.execute({
952
- sql: `${baseQuery}${typeCondition} ORDER BY created_at DESC`,
953
- args: [agentName]
954
- });
955
- return result.rows?.map((row) => transformEvalRow(row)) ?? [];
956
- } catch (error) {
957
- if (error instanceof Error && error.message.includes("no such table")) {
958
- return [];
959
- }
960
- throw new MastraError(
961
- {
962
- id: "LIBSQL_STORE_GET_EVALS_BY_AGENT_NAME_FAILED",
963
- domain: ErrorDomain.STORAGE,
964
- category: ErrorCategory.THIRD_PARTY,
965
- details: { agentName }
966
- },
967
- error
968
- );
969
- }
970
- }
971
- async getEvals(options = {}) {
972
- const { agentName, type, page = 0, perPage = 100, dateRange } = options;
973
- const fromDate = dateRange?.start;
974
- const toDate = dateRange?.end;
975
- const conditions = [];
976
- const queryParams = [];
977
- if (agentName) {
978
- conditions.push(`agent_name = ?`);
979
- queryParams.push(agentName);
980
- }
981
- if (type === "test") {
982
- conditions.push(`(test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL)`);
983
- } else if (type === "live") {
984
- conditions.push(`(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)`);
985
- }
986
- if (fromDate) {
987
- conditions.push(`created_at >= ?`);
988
- queryParams.push(fromDate.toISOString());
989
- }
990
- if (toDate) {
991
- conditions.push(`created_at <= ?`);
992
- queryParams.push(toDate.toISOString());
993
- }
994
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
995
- try {
996
- const countResult = await this.client.execute({
997
- sql: `SELECT COUNT(*) as count FROM ${TABLE_EVALS} ${whereClause}`,
998
- args: queryParams
999
- });
1000
- const total = Number(countResult.rows?.[0]?.count ?? 0);
1001
- const currentOffset = page * perPage;
1002
- const hasMore = currentOffset + perPage < total;
1003
- if (total === 0) {
1004
- return {
1005
- evals: [],
1006
- total: 0,
1007
- page,
1008
- perPage,
1009
- hasMore: false
1010
- };
1011
- }
1012
- const dataResult = await this.client.execute({
1013
- sql: `SELECT * FROM ${TABLE_EVALS} ${whereClause} ORDER BY created_at DESC LIMIT ? OFFSET ?`,
1014
- args: [...queryParams, perPage, currentOffset]
1015
- });
1016
- return {
1017
- evals: dataResult.rows?.map((row) => transformEvalRow(row)) ?? [],
1018
- total,
1019
- page,
1020
- perPage,
1021
- hasMore
1022
- };
1023
- } catch (error) {
1024
- throw new MastraError(
1025
- {
1026
- id: "LIBSQL_STORE_GET_EVALS_FAILED",
1027
- domain: ErrorDomain.STORAGE,
1028
- category: ErrorCategory.THIRD_PARTY
1029
- },
1030
- error
1031
- );
1032
- }
1033
- }
1034
- };
1035
922
  var MemoryLibSQL = class extends MemoryStorage {
1036
923
  client;
1037
924
  operations;
@@ -1059,10 +946,9 @@ var MemoryLibSQL = class extends MemoryStorage {
1059
946
  }
1060
947
  async _getIncludedMessages({
1061
948
  threadId,
1062
- selectBy
949
+ include
1063
950
  }) {
1064
951
  if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1065
- const include = selectBy?.include;
1066
952
  if (!include) return null;
1067
953
  const unionQueries = [];
1068
954
  const params = [];
@@ -1105,24 +991,10 @@ var MemoryLibSQL = class extends MemoryStorage {
1105
991
  });
1106
992
  return dedupedRows;
1107
993
  }
1108
- async getMessages({
1109
- threadId,
1110
- resourceId,
1111
- selectBy,
1112
- format
1113
- }) {
994
+ async listMessagesById({ messageIds }) {
995
+ if (messageIds.length === 0) return { messages: [] };
1114
996
  try {
1115
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1116
- const messages = [];
1117
- const limit = resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
1118
- if (selectBy?.include?.length) {
1119
- const includeMessages = await this._getIncludedMessages({ threadId, selectBy });
1120
- if (includeMessages) {
1121
- messages.push(...includeMessages);
1122
- }
1123
- }
1124
- const excludeIds = messages.map((m) => m.id);
1125
- const remainingSql = `
997
+ const sql = `
1126
998
  SELECT
1127
999
  id,
1128
1000
  content,
@@ -1132,105 +1004,71 @@ var MemoryLibSQL = class extends MemoryStorage {
1132
1004
  thread_id,
1133
1005
  "resourceId"
1134
1006
  FROM "${TABLE_MESSAGES}"
1135
- WHERE thread_id = ?
1136
- ${excludeIds.length ? `AND id NOT IN (${excludeIds.map(() => "?").join(", ")})` : ""}
1007
+ WHERE id IN (${messageIds.map(() => "?").join(", ")})
1137
1008
  ORDER BY "createdAt" DESC
1138
- LIMIT ?
1139
1009
  `;
1140
- const remainingArgs = [threadId, ...excludeIds.length ? excludeIds : [], limit];
1141
- const remainingResult = await this.client.execute({ sql: remainingSql, args: remainingArgs });
1142
- if (remainingResult.rows) {
1143
- messages.push(...remainingResult.rows.map((row) => this.parseRow(row)));
1144
- }
1145
- messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
1146
- const list = new MessageList().add(messages, "memory");
1147
- if (format === `v2`) return list.get.all.v2();
1148
- return list.get.all.v1();
1010
+ const result = await this.client.execute({ sql, args: messageIds });
1011
+ if (!result.rows) return { messages: [] };
1012
+ const list = new MessageList().add(result.rows.map(this.parseRow), "memory");
1013
+ return { messages: list.get.all.db() };
1149
1014
  } catch (error) {
1150
1015
  throw new MastraError(
1151
1016
  {
1152
- id: "LIBSQL_STORE_GET_MESSAGES_FAILED",
1017
+ id: "LIBSQL_STORE_LIST_MESSAGES_BY_ID_FAILED",
1153
1018
  domain: ErrorDomain.STORAGE,
1154
1019
  category: ErrorCategory.THIRD_PARTY,
1155
- details: { threadId, resourceId: resourceId ?? "" }
1020
+ details: { messageIds: JSON.stringify(messageIds) }
1156
1021
  },
1157
1022
  error
1158
1023
  );
1159
1024
  }
1160
1025
  }
1161
- async getMessagesById({
1162
- messageIds,
1163
- format
1164
- }) {
1165
- if (messageIds.length === 0) return [];
1166
- try {
1167
- const sql = `
1168
- SELECT
1169
- id,
1170
- content,
1171
- role,
1172
- type,
1173
- "createdAt",
1174
- thread_id,
1175
- "resourceId"
1176
- FROM "${TABLE_MESSAGES}"
1177
- WHERE id IN (${messageIds.map(() => "?").join(", ")})
1178
- ORDER BY "createdAt" DESC
1179
- `;
1180
- const result = await this.client.execute({ sql, args: messageIds });
1181
- if (!result.rows) return [];
1182
- const list = new MessageList().add(result.rows.map(this.parseRow), "memory");
1183
- if (format === `v1`) return list.get.all.v1();
1184
- return list.get.all.v2();
1185
- } catch (error) {
1026
+ async listMessages(args) {
1027
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
1028
+ if (!threadId.trim()) {
1186
1029
  throw new MastraError(
1187
1030
  {
1188
- id: "LIBSQL_STORE_GET_MESSAGES_BY_ID_FAILED",
1031
+ id: "STORAGE_LIBSQL_LIST_MESSAGES_INVALID_THREAD_ID",
1189
1032
  domain: ErrorDomain.STORAGE,
1190
1033
  category: ErrorCategory.THIRD_PARTY,
1191
- details: { messageIds: JSON.stringify(messageIds) }
1034
+ details: { threadId }
1192
1035
  },
1193
- error
1036
+ new Error("threadId must be a non-empty string")
1194
1037
  );
1195
1038
  }
1196
- }
1197
- async getMessagesPaginated(args) {
1198
- const { threadId, format, selectBy } = args;
1199
- const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
1200
- const perPage = perPageInput !== void 0 ? perPageInput : resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
1201
- const fromDate = dateRange?.start;
1202
- const toDate = dateRange?.end;
1203
- const messages = [];
1204
- if (selectBy?.include?.length) {
1205
- try {
1206
- const includeMessages = await this._getIncludedMessages({ threadId, selectBy });
1207
- if (includeMessages) {
1208
- messages.push(...includeMessages);
1209
- }
1210
- } catch (error) {
1211
- throw new MastraError(
1212
- {
1213
- id: "LIBSQL_STORE_GET_MESSAGES_PAGINATED_GET_INCLUDE_MESSAGES_FAILED",
1214
- domain: ErrorDomain.STORAGE,
1215
- category: ErrorCategory.THIRD_PARTY,
1216
- details: { threadId }
1217
- },
1218
- error
1219
- );
1220
- }
1039
+ if (page < 0) {
1040
+ throw new MastraError(
1041
+ {
1042
+ id: "LIBSQL_STORE_LIST_MESSAGES_INVALID_PAGE",
1043
+ domain: ErrorDomain.STORAGE,
1044
+ category: ErrorCategory.USER,
1045
+ details: { page }
1046
+ },
1047
+ new Error("page must be >= 0")
1048
+ );
1221
1049
  }
1050
+ const perPage = normalizePerPage(perPageInput, 40);
1051
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1222
1052
  try {
1223
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1224
- const currentOffset = page * perPage;
1053
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
1054
+ const orderByStatement = `ORDER BY "${field}" ${direction}`;
1225
1055
  const conditions = [`thread_id = ?`];
1226
1056
  const queryParams = [threadId];
1227
- if (fromDate) {
1057
+ if (resourceId) {
1058
+ conditions.push(`"resourceId" = ?`);
1059
+ queryParams.push(resourceId);
1060
+ }
1061
+ if (filter?.dateRange?.start) {
1228
1062
  conditions.push(`"createdAt" >= ?`);
1229
- queryParams.push(fromDate.toISOString());
1063
+ queryParams.push(
1064
+ filter.dateRange.start instanceof Date ? filter.dateRange.start.toISOString() : filter.dateRange.start
1065
+ );
1230
1066
  }
1231
- if (toDate) {
1067
+ if (filter?.dateRange?.end) {
1232
1068
  conditions.push(`"createdAt" <= ?`);
1233
- queryParams.push(toDate.toISOString());
1069
+ queryParams.push(
1070
+ filter.dateRange.end instanceof Date ? filter.dateRange.end.toISOString() : filter.dateRange.end
1071
+ );
1234
1072
  }
1235
1073
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1236
1074
  const countResult = await this.client.execute({
@@ -1238,50 +1076,80 @@ var MemoryLibSQL = class extends MemoryStorage {
1238
1076
  args: queryParams
1239
1077
  });
1240
1078
  const total = Number(countResult.rows?.[0]?.count ?? 0);
1241
- if (total === 0 && messages.length === 0) {
1079
+ const limitValue = perPageInput === false ? total : perPage;
1080
+ const dataResult = await this.client.execute({
1081
+ sql: `SELECT id, content, role, type, "createdAt", "resourceId", "thread_id" FROM ${TABLE_MESSAGES} ${whereClause} ${orderByStatement} LIMIT ? OFFSET ?`,
1082
+ args: [...queryParams, limitValue, offset]
1083
+ });
1084
+ const messages = (dataResult.rows || []).map((row) => this.parseRow(row));
1085
+ if (total === 0 && messages.length === 0 && (!include || include.length === 0)) {
1242
1086
  return {
1243
1087
  messages: [],
1244
1088
  total: 0,
1245
1089
  page,
1246
- perPage,
1090
+ perPage: perPageForResponse,
1247
1091
  hasMore: false
1248
1092
  };
1249
1093
  }
1250
- const excludeIds = messages.map((m) => m.id);
1251
- const excludeIdsParam = excludeIds.map((_, idx) => `$${idx + queryParams.length + 1}`).join(", ");
1252
- const dataResult = await this.client.execute({
1253
- sql: `SELECT id, content, role, type, "createdAt", "resourceId", "thread_id" FROM ${TABLE_MESSAGES} ${whereClause} ${excludeIds.length ? `AND id NOT IN (${excludeIdsParam})` : ""} ORDER BY "createdAt" DESC LIMIT ? OFFSET ?`,
1254
- args: [...queryParams, ...excludeIds, perPage, currentOffset]
1094
+ const messageIds = new Set(messages.map((m) => m.id));
1095
+ if (include && include.length > 0) {
1096
+ const includeMessages = await this._getIncludedMessages({ threadId, include });
1097
+ if (includeMessages) {
1098
+ for (const includeMsg of includeMessages) {
1099
+ if (!messageIds.has(includeMsg.id)) {
1100
+ messages.push(includeMsg);
1101
+ messageIds.add(includeMsg.id);
1102
+ }
1103
+ }
1104
+ }
1105
+ }
1106
+ const list = new MessageList().add(messages, "memory");
1107
+ let finalMessages = list.get.all.db();
1108
+ finalMessages = finalMessages.sort((a, b) => {
1109
+ const isDateField = field === "createdAt" || field === "updatedAt";
1110
+ const aValue = isDateField ? new Date(a[field]).getTime() : a[field];
1111
+ const bValue = isDateField ? new Date(b[field]).getTime() : b[field];
1112
+ if (typeof aValue === "number" && typeof bValue === "number") {
1113
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
1114
+ }
1115
+ return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
1255
1116
  });
1256
- messages.push(...(dataResult.rows || []).map((row) => this.parseRow(row)));
1257
- const messagesToReturn = format === "v1" ? new MessageList().add(messages, "memory").get.all.v1() : new MessageList().add(messages, "memory").get.all.v2();
1117
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
1118
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
1119
+ const hasMore = perPageInput !== false && !allThreadMessagesReturned && offset + perPage < total;
1258
1120
  return {
1259
- messages: messagesToReturn,
1121
+ messages: finalMessages,
1260
1122
  total,
1261
1123
  page,
1262
- perPage,
1263
- hasMore: currentOffset + messages.length < total
1124
+ perPage: perPageForResponse,
1125
+ hasMore
1264
1126
  };
1265
1127
  } catch (error) {
1266
1128
  const mastraError = new MastraError(
1267
1129
  {
1268
- id: "LIBSQL_STORE_GET_MESSAGES_PAGINATED_FAILED",
1130
+ id: "LIBSQL_STORE_LIST_MESSAGES_FAILED",
1269
1131
  domain: ErrorDomain.STORAGE,
1270
1132
  category: ErrorCategory.THIRD_PARTY,
1271
- details: { threadId }
1133
+ details: {
1134
+ threadId,
1135
+ resourceId: resourceId ?? ""
1136
+ }
1272
1137
  },
1273
1138
  error
1274
1139
  );
1275
- this.logger?.trackException?.(mastraError);
1276
1140
  this.logger?.error?.(mastraError.toString());
1277
- return { messages: [], total: 0, page, perPage, hasMore: false };
1141
+ this.logger?.trackException?.(mastraError);
1142
+ return {
1143
+ messages: [],
1144
+ total: 0,
1145
+ page,
1146
+ perPage: perPageForResponse,
1147
+ hasMore: false
1148
+ };
1278
1149
  }
1279
1150
  }
1280
- async saveMessages({
1281
- messages,
1282
- format
1283
- }) {
1284
- if (messages.length === 0) return messages;
1151
+ async saveMessages({ messages }) {
1152
+ if (messages.length === 0) return { messages };
1285
1153
  try {
1286
1154
  const threadId = messages[0]?.threadId;
1287
1155
  if (!threadId) {
@@ -1338,8 +1206,7 @@ var MemoryLibSQL = class extends MemoryStorage {
1338
1206
  await this.client.execute(threadUpdateStatement);
1339
1207
  }
1340
1208
  const list = new MessageList().add(messages, "memory");
1341
- if (format === `v2`) return list.get.all.v2();
1342
- return list.get.all.v1();
1209
+ return { messages: list.get.all.db() };
1343
1210
  } catch (error) {
1344
1211
  throw new MastraError(
1345
1212
  {
@@ -1578,53 +1445,22 @@ var MemoryLibSQL = class extends MemoryStorage {
1578
1445
  );
1579
1446
  }
1580
1447
  }
1581
- /**
1582
- * @deprecated use getThreadsByResourceIdPaginated instead for paginated results.
1583
- */
1584
- async getThreadsByResourceId(args) {
1585
- const resourceId = args.resourceId;
1586
- const orderBy = this.castThreadOrderBy(args.orderBy);
1587
- const sortDirection = this.castThreadSortDirection(args.sortDirection);
1588
- try {
1589
- const baseQuery = `FROM ${TABLE_THREADS} WHERE resourceId = ?`;
1590
- const queryParams = [resourceId];
1591
- const mapRowToStorageThreadType = (row) => ({
1592
- id: row.id,
1593
- resourceId: row.resourceId,
1594
- title: row.title,
1595
- createdAt: new Date(row.createdAt),
1596
- // Convert string to Date
1597
- updatedAt: new Date(row.updatedAt),
1598
- // Convert string to Date
1599
- metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata) : row.metadata
1600
- });
1601
- const result = await this.client.execute({
1602
- sql: `SELECT * ${baseQuery} ORDER BY ${orderBy} ${sortDirection}`,
1603
- args: queryParams
1604
- });
1605
- if (!result.rows) {
1606
- return [];
1607
- }
1608
- return result.rows.map(mapRowToStorageThreadType);
1609
- } catch (error) {
1610
- const mastraError = new MastraError(
1448
+ async listThreadsByResourceId(args) {
1449
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
1450
+ if (page < 0) {
1451
+ throw new MastraError(
1611
1452
  {
1612
- id: "LIBSQL_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
1453
+ id: "LIBSQL_STORE_LIST_THREADS_BY_RESOURCE_ID_INVALID_PAGE",
1613
1454
  domain: ErrorDomain.STORAGE,
1614
- category: ErrorCategory.THIRD_PARTY,
1615
- details: { resourceId }
1455
+ category: ErrorCategory.USER,
1456
+ details: { page }
1616
1457
  },
1617
- error
1458
+ new Error("page must be >= 0")
1618
1459
  );
1619
- this.logger?.trackException?.(mastraError);
1620
- this.logger?.error?.(mastraError.toString());
1621
- return [];
1622
1460
  }
1623
- }
1624
- async getThreadsByResourceIdPaginated(args) {
1625
- const { resourceId, page = 0, perPage = 100 } = args;
1626
- const orderBy = this.castThreadOrderBy(args.orderBy);
1627
- const sortDirection = this.castThreadSortDirection(args.sortDirection);
1461
+ const perPage = normalizePerPage(perPageInput, 100);
1462
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1463
+ const { field, direction } = this.parseOrderBy(orderBy);
1628
1464
  try {
1629
1465
  const baseQuery = `FROM ${TABLE_THREADS} WHERE resourceId = ?`;
1630
1466
  const queryParams = [resourceId];
@@ -1638,7 +1474,6 @@ var MemoryLibSQL = class extends MemoryStorage {
1638
1474
  // Convert string to Date
1639
1475
  metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata) : row.metadata
1640
1476
  });
1641
- const currentOffset = page * perPage;
1642
1477
  const countResult = await this.client.execute({
1643
1478
  sql: `SELECT COUNT(*) as count ${baseQuery}`,
1644
1479
  args: queryParams
@@ -1649,26 +1484,27 @@ var MemoryLibSQL = class extends MemoryStorage {
1649
1484
  threads: [],
1650
1485
  total: 0,
1651
1486
  page,
1652
- perPage,
1487
+ perPage: perPageForResponse,
1653
1488
  hasMore: false
1654
1489
  };
1655
1490
  }
1491
+ const limitValue = perPageInput === false ? total : perPage;
1656
1492
  const dataResult = await this.client.execute({
1657
- sql: `SELECT * ${baseQuery} ORDER BY ${orderBy} ${sortDirection} LIMIT ? OFFSET ?`,
1658
- args: [...queryParams, perPage, currentOffset]
1493
+ sql: `SELECT * ${baseQuery} ORDER BY "${field}" ${direction} LIMIT ? OFFSET ?`,
1494
+ args: [...queryParams, limitValue, offset]
1659
1495
  });
1660
1496
  const threads = (dataResult.rows || []).map(mapRowToStorageThreadType);
1661
1497
  return {
1662
1498
  threads,
1663
1499
  total,
1664
1500
  page,
1665
- perPage,
1666
- hasMore: currentOffset + threads.length < total
1501
+ perPage: perPageForResponse,
1502
+ hasMore: perPageInput === false ? false : offset + perPage < total
1667
1503
  };
1668
1504
  } catch (error) {
1669
1505
  const mastraError = new MastraError(
1670
1506
  {
1671
- id: "LIBSQL_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
1507
+ id: "LIBSQL_STORE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
1672
1508
  domain: ErrorDomain.STORAGE,
1673
1509
  category: ErrorCategory.THIRD_PARTY,
1674
1510
  details: { resourceId }
@@ -1677,7 +1513,13 @@ var MemoryLibSQL = class extends MemoryStorage {
1677
1513
  );
1678
1514
  this.logger?.trackException?.(mastraError);
1679
1515
  this.logger?.error?.(mastraError.toString());
1680
- return { threads: [], total: 0, page, perPage, hasMore: false };
1516
+ return {
1517
+ threads: [],
1518
+ total: 0,
1519
+ page,
1520
+ perPage: perPageForResponse,
1521
+ hasMore: false
1522
+ };
1681
1523
  }
1682
1524
  }
1683
1525
  async saveThread({ thread }) {
@@ -1948,7 +1790,7 @@ var ObservabilityLibSQL = class extends ObservabilityStorage {
1948
1790
  super();
1949
1791
  this.operations = operations;
1950
1792
  }
1951
- async createAISpan(span) {
1793
+ async createSpan(span) {
1952
1794
  try {
1953
1795
  const now = (/* @__PURE__ */ new Date()).toISOString();
1954
1796
  const record = {
@@ -1956,11 +1798,11 @@ var ObservabilityLibSQL = class extends ObservabilityStorage {
1956
1798
  createdAt: now,
1957
1799
  updatedAt: now
1958
1800
  };
1959
- return this.operations.insert({ tableName: TABLE_AI_SPANS, record });
1801
+ return this.operations.insert({ tableName: TABLE_SPANS, record });
1960
1802
  } catch (error) {
1961
1803
  throw new MastraError(
1962
1804
  {
1963
- id: "LIBSQL_STORE_CREATE_AI_SPAN_FAILED",
1805
+ id: "LIBSQL_STORE_CREATE_SPAN_FAILED",
1964
1806
  domain: ErrorDomain.STORAGE,
1965
1807
  category: ErrorCategory.USER,
1966
1808
  details: {
@@ -1974,10 +1816,10 @@ var ObservabilityLibSQL = class extends ObservabilityStorage {
1974
1816
  );
1975
1817
  }
1976
1818
  }
1977
- async getAITrace(traceId) {
1819
+ async getTrace(traceId) {
1978
1820
  try {
1979
1821
  const spans = await this.operations.loadMany({
1980
- tableName: TABLE_AI_SPANS,
1822
+ tableName: TABLE_SPANS,
1981
1823
  whereClause: { sql: " WHERE traceId = ?", args: [traceId] },
1982
1824
  orderBy: "startedAt DESC"
1983
1825
  });
@@ -1986,12 +1828,12 @@ var ObservabilityLibSQL = class extends ObservabilityStorage {
1986
1828
  }
1987
1829
  return {
1988
1830
  traceId,
1989
- spans: spans.map((span) => transformFromSqlRow({ tableName: TABLE_AI_SPANS, sqlRow: span }))
1831
+ spans: spans.map((span) => transformFromSqlRow({ tableName: TABLE_SPANS, sqlRow: span }))
1990
1832
  };
1991
1833
  } catch (error) {
1992
1834
  throw new MastraError(
1993
1835
  {
1994
- id: "LIBSQL_STORE_GET_AI_TRACE_FAILED",
1836
+ id: "LIBSQL_STORE_GET_TRACE_FAILED",
1995
1837
  domain: ErrorDomain.STORAGE,
1996
1838
  category: ErrorCategory.USER,
1997
1839
  details: {
@@ -2002,21 +1844,21 @@ var ObservabilityLibSQL = class extends ObservabilityStorage {
2002
1844
  );
2003
1845
  }
2004
1846
  }
2005
- async updateAISpan({
1847
+ async updateSpan({
2006
1848
  spanId,
2007
1849
  traceId,
2008
1850
  updates
2009
1851
  }) {
2010
1852
  try {
2011
1853
  await this.operations.update({
2012
- tableName: TABLE_AI_SPANS,
1854
+ tableName: TABLE_SPANS,
2013
1855
  keys: { spanId, traceId },
2014
1856
  data: { ...updates, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }
2015
1857
  });
2016
1858
  } catch (error) {
2017
1859
  throw new MastraError(
2018
1860
  {
2019
- id: "LIBSQL_STORE_UPDATE_AI_SPAN_FAILED",
1861
+ id: "LIBSQL_STORE_UPDATE_SPAN_FAILED",
2020
1862
  domain: ErrorDomain.STORAGE,
2021
1863
  category: ErrorCategory.USER,
2022
1864
  details: {
@@ -2028,7 +1870,7 @@ var ObservabilityLibSQL = class extends ObservabilityStorage {
2028
1870
  );
2029
1871
  }
2030
1872
  }
2031
- async getAITracesPaginated({
1873
+ async getTracesPaginated({
2032
1874
  filters,
2033
1875
  pagination
2034
1876
  }) {
@@ -2040,7 +1882,7 @@ var ObservabilityLibSQL = class extends ObservabilityStorage {
2040
1882
  ...buildDateRangeFilter(pagination?.dateRange, "startedAt"),
2041
1883
  parentSpanId: null
2042
1884
  };
2043
- const whereClause = prepareWhereClause(filtersWithDateRange, AI_SPAN_SCHEMA);
1885
+ const whereClause = prepareWhereClause(filtersWithDateRange, SPAN_SCHEMA);
2044
1886
  let actualWhereClause = whereClause.sql || "";
2045
1887
  if (entityId && entityType) {
2046
1888
  const statement = `name = ?`;
@@ -2051,7 +1893,7 @@ var ObservabilityLibSQL = class extends ObservabilityStorage {
2051
1893
  name = `agent run: '${entityId}'`;
2052
1894
  } else {
2053
1895
  const error = new MastraError({
2054
- id: "LIBSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1896
+ id: "LIBSQL_STORE_GET_TRACES_PAGINATED_FAILED",
2055
1897
  domain: ErrorDomain.STORAGE,
2056
1898
  category: ErrorCategory.USER,
2057
1899
  details: {
@@ -2073,13 +1915,13 @@ var ObservabilityLibSQL = class extends ObservabilityStorage {
2073
1915
  let count = 0;
2074
1916
  try {
2075
1917
  count = await this.operations.loadTotalCount({
2076
- tableName: TABLE_AI_SPANS,
1918
+ tableName: TABLE_SPANS,
2077
1919
  whereClause: { sql: actualWhereClause, args: whereClause.args }
2078
1920
  });
2079
1921
  } catch (error) {
2080
1922
  throw new MastraError(
2081
1923
  {
2082
- id: "LIBSQL_STORE_GET_AI_TRACES_PAGINATED_COUNT_FAILED",
1924
+ id: "LIBSQL_STORE_GET_TRACES_PAGINATED_COUNT_FAILED",
2083
1925
  domain: ErrorDomain.STORAGE,
2084
1926
  category: ErrorCategory.USER
2085
1927
  },
@@ -2099,7 +1941,7 @@ var ObservabilityLibSQL = class extends ObservabilityStorage {
2099
1941
  }
2100
1942
  try {
2101
1943
  const spans = await this.operations.loadMany({
2102
- tableName: TABLE_AI_SPANS,
1944
+ tableName: TABLE_SPANS,
2103
1945
  whereClause: {
2104
1946
  sql: actualWhereClause,
2105
1947
  args: whereClause.args
@@ -2115,12 +1957,12 @@ var ObservabilityLibSQL = class extends ObservabilityStorage {
2115
1957
  perPage,
2116
1958
  hasMore: spans.length === perPage
2117
1959
  },
2118
- spans: spans.map((span) => transformFromSqlRow({ tableName: TABLE_AI_SPANS, sqlRow: span }))
1960
+ spans: spans.map((span) => transformFromSqlRow({ tableName: TABLE_SPANS, sqlRow: span }))
2119
1961
  };
2120
1962
  } catch (error) {
2121
1963
  throw new MastraError(
2122
1964
  {
2123
- id: "LIBSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1965
+ id: "LIBSQL_STORE_GET_TRACES_PAGINATED_FAILED",
2124
1966
  domain: ErrorDomain.STORAGE,
2125
1967
  category: ErrorCategory.USER
2126
1968
  },
@@ -2128,11 +1970,11 @@ var ObservabilityLibSQL = class extends ObservabilityStorage {
2128
1970
  );
2129
1971
  }
2130
1972
  }
2131
- async batchCreateAISpans(args) {
1973
+ async batchCreateSpans(args) {
2132
1974
  try {
2133
1975
  const now = (/* @__PURE__ */ new Date()).toISOString();
2134
1976
  return this.operations.batchInsert({
2135
- tableName: TABLE_AI_SPANS,
1977
+ tableName: TABLE_SPANS,
2136
1978
  records: args.records.map((record) => ({
2137
1979
  ...record,
2138
1980
  createdAt: now,
@@ -2142,7 +1984,7 @@ var ObservabilityLibSQL = class extends ObservabilityStorage {
2142
1984
  } catch (error) {
2143
1985
  throw new MastraError(
2144
1986
  {
2145
- id: "LIBSQL_STORE_BATCH_CREATE_AI_SPANS_FAILED",
1987
+ id: "LIBSQL_STORE_BATCH_CREATE_SPANS_FAILED",
2146
1988
  domain: ErrorDomain.STORAGE,
2147
1989
  category: ErrorCategory.USER
2148
1990
  },
@@ -2150,10 +1992,10 @@ var ObservabilityLibSQL = class extends ObservabilityStorage {
2150
1992
  );
2151
1993
  }
2152
1994
  }
2153
- async batchUpdateAISpans(args) {
1995
+ async batchUpdateSpans(args) {
2154
1996
  try {
2155
1997
  return this.operations.batchUpdate({
2156
- tableName: TABLE_AI_SPANS,
1998
+ tableName: TABLE_SPANS,
2157
1999
  updates: args.records.map((record) => ({
2158
2000
  keys: { spanId: record.spanId, traceId: record.traceId },
2159
2001
  data: { ...record.updates, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }
@@ -2162,7 +2004,7 @@ var ObservabilityLibSQL = class extends ObservabilityStorage {
2162
2004
  } catch (error) {
2163
2005
  throw new MastraError(
2164
2006
  {
2165
- id: "LIBSQL_STORE_BATCH_UPDATE_AI_SPANS_FAILED",
2007
+ id: "LIBSQL_STORE_BATCH_UPDATE_SPANS_FAILED",
2166
2008
  domain: ErrorDomain.STORAGE,
2167
2009
  category: ErrorCategory.USER
2168
2010
  },
@@ -2170,17 +2012,17 @@ var ObservabilityLibSQL = class extends ObservabilityStorage {
2170
2012
  );
2171
2013
  }
2172
2014
  }
2173
- async batchDeleteAITraces(args) {
2015
+ async batchDeleteTraces(args) {
2174
2016
  try {
2175
2017
  const keys = args.traceIds.map((traceId) => ({ traceId }));
2176
2018
  return this.operations.batchDelete({
2177
- tableName: TABLE_AI_SPANS,
2019
+ tableName: TABLE_SPANS,
2178
2020
  keys
2179
2021
  });
2180
2022
  } catch (error) {
2181
2023
  throw new MastraError(
2182
2024
  {
2183
- id: "LIBSQL_STORE_BATCH_DELETE_AI_TRACES_FAILED",
2025
+ id: "LIBSQL_STORE_BATCH_DELETE_TRACES_FAILED",
2184
2026
  domain: ErrorDomain.STORAGE,
2185
2027
  category: ErrorCategory.USER
2186
2028
  },
@@ -2236,7 +2078,7 @@ var StoreOperationsLibSQL = class extends StoreOperations {
2236
2078
  )`;
2237
2079
  return stmnt;
2238
2080
  }
2239
- if (tableName === TABLE_AI_SPANS) {
2081
+ if (tableName === TABLE_SPANS) {
2240
2082
  const stmnt = `CREATE TABLE IF NOT EXISTS ${parsedTableName} (
2241
2083
  ${columns.join(",\n")},
2242
2084
  PRIMARY KEY (traceId, spanId)
@@ -2584,22 +2426,44 @@ var ScoresLibSQL = class extends ScoresStorage {
2584
2426
  this.operations = operations;
2585
2427
  this.client = client;
2586
2428
  }
2587
- async getScoresByRunId({
2429
+ async listScoresByRunId({
2588
2430
  runId,
2589
2431
  pagination
2590
2432
  }) {
2591
2433
  try {
2434
+ const { page, perPage: perPageInput } = pagination;
2435
+ const countResult = await this.client.execute({
2436
+ sql: `SELECT COUNT(*) as count FROM ${TABLE_SCORERS} WHERE runId = ?`,
2437
+ args: [runId]
2438
+ });
2439
+ const total = Number(countResult.rows?.[0]?.count ?? 0);
2440
+ if (total === 0) {
2441
+ return {
2442
+ pagination: {
2443
+ total: 0,
2444
+ page,
2445
+ perPage: perPageInput,
2446
+ hasMore: false
2447
+ },
2448
+ scores: []
2449
+ };
2450
+ }
2451
+ const perPage = normalizePerPage(perPageInput, 100);
2452
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2453
+ const limitValue = perPageInput === false ? total : perPage;
2454
+ const end = perPageInput === false ? total : start + perPage;
2592
2455
  const result = await this.client.execute({
2593
2456
  sql: `SELECT * FROM ${TABLE_SCORERS} WHERE runId = ? ORDER BY createdAt DESC LIMIT ? OFFSET ?`,
2594
- args: [runId, pagination.perPage + 1, pagination.page * pagination.perPage]
2457
+ args: [runId, limitValue, start]
2595
2458
  });
2459
+ const scores = result.rows?.map((row) => this.transformScoreRow(row)) ?? [];
2596
2460
  return {
2597
- scores: result.rows?.slice(0, pagination.perPage).map((row) => this.transformScoreRow(row)) ?? [],
2461
+ scores,
2598
2462
  pagination: {
2599
- total: result.rows?.length ?? 0,
2600
- page: pagination.page,
2601
- perPage: pagination.perPage,
2602
- hasMore: result.rows?.length > pagination.perPage
2463
+ total,
2464
+ page,
2465
+ perPage: perPageForResponse,
2466
+ hasMore: end < total
2603
2467
  }
2604
2468
  };
2605
2469
  } catch (error) {
@@ -2613,7 +2477,7 @@ var ScoresLibSQL = class extends ScoresStorage {
2613
2477
  );
2614
2478
  }
2615
2479
  }
2616
- async getScoresByScorerId({
2480
+ async listScoresByScorerId({
2617
2481
  scorerId,
2618
2482
  entityId,
2619
2483
  entityType,
@@ -2621,6 +2485,7 @@ var ScoresLibSQL = class extends ScoresStorage {
2621
2485
  pagination
2622
2486
  }) {
2623
2487
  try {
2488
+ const { page, perPage: perPageInput } = pagination;
2624
2489
  const conditions = [];
2625
2490
  const queryParams = [];
2626
2491
  if (scorerId) {
@@ -2640,17 +2505,38 @@ var ScoresLibSQL = class extends ScoresStorage {
2640
2505
  queryParams.push(source);
2641
2506
  }
2642
2507
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2508
+ const countResult = await this.client.execute({
2509
+ sql: `SELECT COUNT(*) as count FROM ${TABLE_SCORERS} ${whereClause}`,
2510
+ args: queryParams
2511
+ });
2512
+ const total = Number(countResult.rows?.[0]?.count ?? 0);
2513
+ if (total === 0) {
2514
+ return {
2515
+ pagination: {
2516
+ total: 0,
2517
+ page,
2518
+ perPage: perPageInput,
2519
+ hasMore: false
2520
+ },
2521
+ scores: []
2522
+ };
2523
+ }
2524
+ const perPage = normalizePerPage(perPageInput, 100);
2525
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2526
+ const limitValue = perPageInput === false ? total : perPage;
2527
+ const end = perPageInput === false ? total : start + perPage;
2643
2528
  const result = await this.client.execute({
2644
2529
  sql: `SELECT * FROM ${TABLE_SCORERS} ${whereClause} ORDER BY createdAt DESC LIMIT ? OFFSET ?`,
2645
- args: [...queryParams, pagination.perPage + 1, pagination.page * pagination.perPage]
2530
+ args: [...queryParams, limitValue, start]
2646
2531
  });
2532
+ const scores = result.rows?.map((row) => this.transformScoreRow(row)) ?? [];
2647
2533
  return {
2648
- scores: result.rows?.slice(0, pagination.perPage).map((row) => this.transformScoreRow(row)) ?? [],
2534
+ scores,
2649
2535
  pagination: {
2650
- total: result.rows?.length ?? 0,
2651
- page: pagination.page,
2652
- perPage: pagination.perPage,
2653
- hasMore: result.rows?.length > pagination.perPage
2536
+ total,
2537
+ page,
2538
+ perPage: perPageForResponse,
2539
+ hasMore: end < total
2654
2540
  }
2655
2541
  };
2656
2542
  } catch (error) {
@@ -2669,7 +2555,7 @@ var ScoresLibSQL = class extends ScoresStorage {
2669
2555
  const inputValue = safelyParseJSON(row.input ?? "{}");
2670
2556
  const outputValue = safelyParseJSON(row.output ?? "{}");
2671
2557
  const additionalLLMContextValue = row.additionalLLMContext ? safelyParseJSON(row.additionalLLMContext) : null;
2672
- const runtimeContextValue = row.runtimeContext ? safelyParseJSON(row.runtimeContext) : null;
2558
+ const requestContextValue = row.requestContext ? safelyParseJSON(row.requestContext) : null;
2673
2559
  const metadataValue = row.metadata ? safelyParseJSON(row.metadata) : null;
2674
2560
  const entityValue = row.entity ? safelyParseJSON(row.entity) : null;
2675
2561
  const preprocessStepResultValue = row.preprocessStepResult ? safelyParseJSON(row.preprocessStepResult) : null;
@@ -2692,7 +2578,7 @@ var ScoresLibSQL = class extends ScoresStorage {
2692
2578
  input: inputValue,
2693
2579
  output: outputValue,
2694
2580
  additionalContext: additionalLLMContextValue,
2695
- runtimeContext: runtimeContextValue,
2581
+ requestContext: requestContextValue,
2696
2582
  entityType: row.entityType,
2697
2583
  entity: entityValue,
2698
2584
  entityId: row.entityId,
@@ -2722,7 +2608,7 @@ var ScoresLibSQL = class extends ScoresStorage {
2722
2608
  domain: ErrorDomain.STORAGE,
2723
2609
  category: ErrorCategory.USER,
2724
2610
  details: {
2725
- scorer: score.scorer.name,
2611
+ scorer: score.scorer.id,
2726
2612
  entityId: score.entityId,
2727
2613
  entityType: score.entityType,
2728
2614
  traceId: score.traceId || "",
@@ -2756,23 +2642,45 @@ var ScoresLibSQL = class extends ScoresStorage {
2756
2642
  );
2757
2643
  }
2758
2644
  }
2759
- async getScoresByEntityId({
2645
+ async listScoresByEntityId({
2760
2646
  entityId,
2761
2647
  entityType,
2762
2648
  pagination
2763
2649
  }) {
2764
2650
  try {
2651
+ const { page, perPage: perPageInput } = pagination;
2652
+ const countResult = await this.client.execute({
2653
+ sql: `SELECT COUNT(*) as count FROM ${TABLE_SCORERS} WHERE entityId = ? AND entityType = ?`,
2654
+ args: [entityId, entityType]
2655
+ });
2656
+ const total = Number(countResult.rows?.[0]?.count ?? 0);
2657
+ if (total === 0) {
2658
+ return {
2659
+ pagination: {
2660
+ total: 0,
2661
+ page,
2662
+ perPage: perPageInput,
2663
+ hasMore: false
2664
+ },
2665
+ scores: []
2666
+ };
2667
+ }
2668
+ const perPage = normalizePerPage(perPageInput, 100);
2669
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2670
+ const limitValue = perPageInput === false ? total : perPage;
2671
+ const end = perPageInput === false ? total : start + perPage;
2765
2672
  const result = await this.client.execute({
2766
2673
  sql: `SELECT * FROM ${TABLE_SCORERS} WHERE entityId = ? AND entityType = ? ORDER BY createdAt DESC LIMIT ? OFFSET ?`,
2767
- args: [entityId, entityType, pagination.perPage + 1, pagination.page * pagination.perPage]
2674
+ args: [entityId, entityType, limitValue, start]
2768
2675
  });
2676
+ const scores = result.rows?.map((row) => this.transformScoreRow(row)) ?? [];
2769
2677
  return {
2770
- scores: result.rows?.slice(0, pagination.perPage).map((row) => this.transformScoreRow(row)) ?? [],
2678
+ scores,
2771
2679
  pagination: {
2772
- total: result.rows?.length ?? 0,
2773
- page: pagination.page,
2774
- perPage: pagination.perPage,
2775
- hasMore: result.rows?.length > pagination.perPage
2680
+ total,
2681
+ page,
2682
+ perPage: perPageForResponse,
2683
+ hasMore: end < total
2776
2684
  }
2777
2685
  };
2778
2686
  } catch (error) {
@@ -2786,30 +2694,34 @@ var ScoresLibSQL = class extends ScoresStorage {
2786
2694
  );
2787
2695
  }
2788
2696
  }
2789
- async getScoresBySpan({
2697
+ async listScoresBySpan({
2790
2698
  traceId,
2791
2699
  spanId,
2792
2700
  pagination
2793
2701
  }) {
2794
2702
  try {
2703
+ const { page, perPage: perPageInput } = pagination;
2704
+ const perPage = normalizePerPage(perPageInput, 100);
2705
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2795
2706
  const countSQLResult = await this.client.execute({
2796
2707
  sql: `SELECT COUNT(*) as count FROM ${TABLE_SCORERS} WHERE traceId = ? AND spanId = ?`,
2797
2708
  args: [traceId, spanId]
2798
2709
  });
2799
2710
  const total = Number(countSQLResult.rows?.[0]?.count ?? 0);
2711
+ const limitValue = perPageInput === false ? total : perPage;
2712
+ const end = perPageInput === false ? total : start + perPage;
2800
2713
  const result = await this.client.execute({
2801
2714
  sql: `SELECT * FROM ${TABLE_SCORERS} WHERE traceId = ? AND spanId = ? ORDER BY createdAt DESC LIMIT ? OFFSET ?`,
2802
- args: [traceId, spanId, pagination.perPage + 1, pagination.page * pagination.perPage]
2715
+ args: [traceId, spanId, limitValue, start]
2803
2716
  });
2804
- const hasMore = result.rows?.length > pagination.perPage;
2805
- const scores = result.rows?.slice(0, pagination.perPage).map((row) => this.transformScoreRow(row)) ?? [];
2717
+ const scores = result.rows?.map((row) => this.transformScoreRow(row)) ?? [];
2806
2718
  return {
2807
2719
  scores,
2808
2720
  pagination: {
2809
2721
  total,
2810
- page: pagination.page,
2811
- perPage: pagination.perPage,
2812
- hasMore
2722
+ page,
2723
+ perPage: perPageForResponse,
2724
+ hasMore: end < total
2813
2725
  }
2814
2726
  };
2815
2727
  } catch (error) {
@@ -2824,134 +2736,6 @@ var ScoresLibSQL = class extends ScoresStorage {
2824
2736
  }
2825
2737
  }
2826
2738
  };
2827
- var TracesLibSQL = class extends TracesStorage {
2828
- client;
2829
- operations;
2830
- constructor({ client, operations }) {
2831
- super();
2832
- this.client = client;
2833
- this.operations = operations;
2834
- }
2835
- async getTraces(args) {
2836
- if (args.fromDate || args.toDate) {
2837
- args.dateRange = {
2838
- start: args.fromDate,
2839
- end: args.toDate
2840
- };
2841
- }
2842
- try {
2843
- const result = await this.getTracesPaginated(args);
2844
- return result.traces;
2845
- } catch (error) {
2846
- throw new MastraError(
2847
- {
2848
- id: "LIBSQL_STORE_GET_TRACES_FAILED",
2849
- domain: ErrorDomain.STORAGE,
2850
- category: ErrorCategory.THIRD_PARTY
2851
- },
2852
- error
2853
- );
2854
- }
2855
- }
2856
- async getTracesPaginated(args) {
2857
- const { name, scope, page = 0, perPage = 100, attributes, filters, dateRange } = args;
2858
- const fromDate = dateRange?.start;
2859
- const toDate = dateRange?.end;
2860
- const currentOffset = page * perPage;
2861
- const queryArgs = [];
2862
- const conditions = [];
2863
- if (name) {
2864
- conditions.push("name LIKE ?");
2865
- queryArgs.push(`${name}%`);
2866
- }
2867
- if (scope) {
2868
- conditions.push("scope = ?");
2869
- queryArgs.push(scope);
2870
- }
2871
- if (attributes) {
2872
- Object.entries(attributes).forEach(([key, value]) => {
2873
- conditions.push(`json_extract(attributes, '$.${key}') = ?`);
2874
- queryArgs.push(value);
2875
- });
2876
- }
2877
- if (filters) {
2878
- Object.entries(filters).forEach(([key, value]) => {
2879
- conditions.push(`${parseSqlIdentifier(key, "filter key")} = ?`);
2880
- queryArgs.push(value);
2881
- });
2882
- }
2883
- if (fromDate) {
2884
- conditions.push("createdAt >= ?");
2885
- queryArgs.push(fromDate.toISOString());
2886
- }
2887
- if (toDate) {
2888
- conditions.push("createdAt <= ?");
2889
- queryArgs.push(toDate.toISOString());
2890
- }
2891
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2892
- try {
2893
- const countResult = await this.client.execute({
2894
- sql: `SELECT COUNT(*) as count FROM ${TABLE_TRACES} ${whereClause}`,
2895
- args: queryArgs
2896
- });
2897
- const total = Number(countResult.rows?.[0]?.count ?? 0);
2898
- if (total === 0) {
2899
- return {
2900
- traces: [],
2901
- total: 0,
2902
- page,
2903
- perPage,
2904
- hasMore: false
2905
- };
2906
- }
2907
- const dataResult = await this.client.execute({
2908
- sql: `SELECT * FROM ${TABLE_TRACES} ${whereClause} ORDER BY "startTime" DESC LIMIT ? OFFSET ?`,
2909
- args: [...queryArgs, perPage, currentOffset]
2910
- });
2911
- const traces = dataResult.rows?.map(
2912
- (row) => ({
2913
- id: row.id,
2914
- parentSpanId: row.parentSpanId,
2915
- traceId: row.traceId,
2916
- name: row.name,
2917
- scope: row.scope,
2918
- kind: row.kind,
2919
- status: safelyParseJSON(row.status),
2920
- events: safelyParseJSON(row.events),
2921
- links: safelyParseJSON(row.links),
2922
- attributes: safelyParseJSON(row.attributes),
2923
- startTime: row.startTime,
2924
- endTime: row.endTime,
2925
- other: safelyParseJSON(row.other),
2926
- createdAt: row.createdAt
2927
- })
2928
- ) ?? [];
2929
- return {
2930
- traces,
2931
- total,
2932
- page,
2933
- perPage,
2934
- hasMore: currentOffset + traces.length < total
2935
- };
2936
- } catch (error) {
2937
- throw new MastraError(
2938
- {
2939
- id: "LIBSQL_STORE_GET_TRACES_PAGINATED_FAILED",
2940
- domain: ErrorDomain.STORAGE,
2941
- category: ErrorCategory.THIRD_PARTY
2942
- },
2943
- error
2944
- );
2945
- }
2946
- }
2947
- async batchTraceInsert({ records }) {
2948
- this.logger.debug("Batch inserting traces", { count: records.length });
2949
- await this.operations.batchInsert({
2950
- tableName: TABLE_TRACES,
2951
- records
2952
- });
2953
- }
2954
- };
2955
2739
  function parseWorkflowRun(row) {
2956
2740
  let parsedSnapshot = row.snapshot;
2957
2741
  if (typeof parsedSnapshot === "string") {
@@ -3053,7 +2837,7 @@ var WorkflowsLibSQL = class extends WorkflowsStorage {
3053
2837
  runId,
3054
2838
  stepId,
3055
2839
  result,
3056
- runtimeContext
2840
+ requestContext
3057
2841
  }) {
3058
2842
  return this.executeWithRetry(async () => {
3059
2843
  const tx = await this.client.transaction("write");
@@ -3069,20 +2853,21 @@ var WorkflowsLibSQL = class extends WorkflowsStorage {
3069
2853
  activePaths: [],
3070
2854
  timestamp: Date.now(),
3071
2855
  suspendedPaths: {},
2856
+ activeStepsPath: {},
3072
2857
  resumeLabels: {},
3073
2858
  serializedStepGraph: [],
2859
+ status: "pending",
3074
2860
  value: {},
3075
2861
  waitingPaths: {},
3076
- status: "pending",
3077
2862
  runId,
3078
- runtimeContext: {}
2863
+ requestContext: {}
3079
2864
  };
3080
2865
  } else {
3081
2866
  const existingSnapshot = existingSnapshotResult.rows[0].snapshot;
3082
2867
  snapshot = typeof existingSnapshot === "string" ? JSON.parse(existingSnapshot) : existingSnapshot;
3083
2868
  }
3084
2869
  snapshot.context[stepId] = result;
3085
- snapshot.runtimeContext = { ...snapshot.runtimeContext, ...runtimeContext };
2870
+ snapshot.requestContext = { ...snapshot.requestContext, ...requestContext };
3086
2871
  await tx.execute({
3087
2872
  sql: `UPDATE ${TABLE_WORKFLOW_SNAPSHOT} SET snapshot = ? WHERE workflow_name = ? AND run_id = ?`,
3088
2873
  args: [JSON.stringify(snapshot), workflowName, runId]
@@ -3200,13 +2985,14 @@ var WorkflowsLibSQL = class extends WorkflowsStorage {
3200
2985
  );
3201
2986
  }
3202
2987
  }
3203
- async getWorkflowRuns({
2988
+ async listWorkflowRuns({
3204
2989
  workflowName,
3205
2990
  fromDate,
3206
2991
  toDate,
3207
- limit,
3208
- offset,
3209
- resourceId
2992
+ page,
2993
+ perPage,
2994
+ resourceId,
2995
+ status
3210
2996
  } = {}) {
3211
2997
  try {
3212
2998
  const conditions = [];
@@ -3215,6 +3001,10 @@ var WorkflowsLibSQL = class extends WorkflowsStorage {
3215
3001
  conditions.push("workflow_name = ?");
3216
3002
  args.push(workflowName);
3217
3003
  }
3004
+ if (status) {
3005
+ conditions.push("json_extract(snapshot, '$.status') = ?");
3006
+ args.push(status);
3007
+ }
3218
3008
  if (fromDate) {
3219
3009
  conditions.push("createdAt >= ?");
3220
3010
  args.push(fromDate.toISOString());
@@ -3234,23 +3024,26 @@ var WorkflowsLibSQL = class extends WorkflowsStorage {
3234
3024
  }
3235
3025
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
3236
3026
  let total = 0;
3237
- if (limit !== void 0 && offset !== void 0) {
3027
+ const usePagination = typeof perPage === "number" && typeof page === "number";
3028
+ if (usePagination) {
3238
3029
  const countResult = await this.client.execute({
3239
3030
  sql: `SELECT COUNT(*) as count FROM ${TABLE_WORKFLOW_SNAPSHOT} ${whereClause}`,
3240
3031
  args
3241
3032
  });
3242
3033
  total = Number(countResult.rows?.[0]?.count ?? 0);
3243
3034
  }
3035
+ const normalizedPerPage = usePagination ? normalizePerPage(perPage, Number.MAX_SAFE_INTEGER) : 0;
3036
+ const offset = usePagination ? page * normalizedPerPage : 0;
3244
3037
  const result = await this.client.execute({
3245
- sql: `SELECT * FROM ${TABLE_WORKFLOW_SNAPSHOT} ${whereClause} ORDER BY createdAt DESC${limit !== void 0 && offset !== void 0 ? ` LIMIT ? OFFSET ?` : ""}`,
3246
- args: limit !== void 0 && offset !== void 0 ? [...args, limit, offset] : args
3038
+ sql: `SELECT * FROM ${TABLE_WORKFLOW_SNAPSHOT} ${whereClause} ORDER BY createdAt DESC${usePagination ? ` LIMIT ? OFFSET ?` : ""}`,
3039
+ args: usePagination ? [...args, normalizedPerPage, offset] : args
3247
3040
  });
3248
3041
  const runs = (result.rows || []).map((row) => parseWorkflowRun(row));
3249
3042
  return { runs, total: total || runs.length };
3250
3043
  } catch (error) {
3251
3044
  throw new MastraError(
3252
3045
  {
3253
- id: "LIBSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
3046
+ id: "LIBSQL_STORE_LIST_WORKFLOW_RUNS_FAILED",
3254
3047
  domain: ErrorDomain.STORAGE,
3255
3048
  category: ErrorCategory.THIRD_PARTY
3256
3049
  },
@@ -3267,7 +3060,10 @@ var LibSQLStore = class extends MastraStorage {
3267
3060
  initialBackoffMs;
3268
3061
  stores;
3269
3062
  constructor(config) {
3270
- super({ name: `LibSQLStore` });
3063
+ if (!config.id || typeof config.id !== "string" || config.id.trim() === "") {
3064
+ throw new Error("LibSQLStore: id must be provided and cannot be empty.");
3065
+ }
3066
+ super({ id: config.id, name: `LibSQLStore` });
3271
3067
  this.maxRetries = config.maxRetries ?? 5;
3272
3068
  this.initialBackoffMs = config.initialBackoffMs ?? 100;
3273
3069
  if ("url" in config) {
@@ -3291,18 +3087,14 @@ var LibSQLStore = class extends MastraStorage {
3291
3087
  initialBackoffMs: this.initialBackoffMs
3292
3088
  });
3293
3089
  const scores = new ScoresLibSQL({ client: this.client, operations });
3294
- const traces = new TracesLibSQL({ client: this.client, operations });
3295
3090
  const workflows = new WorkflowsLibSQL({ client: this.client, operations });
3296
3091
  const memory = new MemoryLibSQL({ client: this.client, operations });
3297
- const legacyEvals = new LegacyEvalsLibSQL({ client: this.client });
3298
3092
  const observability = new ObservabilityLibSQL({ operations });
3299
3093
  this.stores = {
3300
3094
  operations,
3301
3095
  scores,
3302
- traces,
3303
3096
  workflows,
3304
3097
  memory,
3305
- legacyEvals,
3306
3098
  observability
3307
3099
  };
3308
3100
  }
@@ -3313,8 +3105,8 @@ var LibSQLStore = class extends MastraStorage {
3313
3105
  hasColumn: true,
3314
3106
  createTable: true,
3315
3107
  deleteMessages: true,
3316
- aiTracing: true,
3317
- getScoresBySpan: true
3108
+ observabilityInstance: true,
3109
+ listScoresBySpan: true
3318
3110
  };
3319
3111
  }
3320
3112
  async createTable({
@@ -3354,15 +3146,6 @@ var LibSQLStore = class extends MastraStorage {
3354
3146
  async getThreadById({ threadId }) {
3355
3147
  return this.stores.memory.getThreadById({ threadId });
3356
3148
  }
3357
- /**
3358
- * @deprecated use getThreadsByResourceIdPaginated instead for paginated results.
3359
- */
3360
- async getThreadsByResourceId(args) {
3361
- return this.stores.memory.getThreadsByResourceId(args);
3362
- }
3363
- async getThreadsByResourceIdPaginated(args) {
3364
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
3365
- }
3366
3149
  async saveThread({ thread }) {
3367
3150
  return this.stores.memory.saveThread({ thread });
3368
3151
  }
@@ -3376,24 +3159,12 @@ var LibSQLStore = class extends MastraStorage {
3376
3159
  async deleteThread({ threadId }) {
3377
3160
  return this.stores.memory.deleteThread({ threadId });
3378
3161
  }
3379
- async getMessages({
3380
- threadId,
3381
- selectBy,
3382
- format
3383
- }) {
3384
- return this.stores.memory.getMessages({ threadId, selectBy, format });
3385
- }
3386
- async getMessagesById({
3387
- messageIds,
3388
- format
3389
- }) {
3390
- return this.stores.memory.getMessagesById({ messageIds, format });
3391
- }
3392
- async getMessagesPaginated(args) {
3393
- return this.stores.memory.getMessagesPaginated(args);
3162
+ async listMessagesById({ messageIds }) {
3163
+ return this.stores.memory.listMessagesById({ messageIds });
3394
3164
  }
3395
3165
  async saveMessages(args) {
3396
- return this.stores.memory.saveMessages(args);
3166
+ const result = await this.stores.memory.saveMessages({ messages: args.messages });
3167
+ return { messages: result.messages };
3397
3168
  }
3398
3169
  async updateMessages({
3399
3170
  messages
@@ -3403,55 +3174,33 @@ var LibSQLStore = class extends MastraStorage {
3403
3174
  async deleteMessages(messageIds) {
3404
3175
  return this.stores.memory.deleteMessages(messageIds);
3405
3176
  }
3406
- /** @deprecated use getEvals instead */
3407
- async getEvalsByAgentName(agentName, type) {
3408
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
3409
- }
3410
- async getEvals(options = {}) {
3411
- return this.stores.legacyEvals.getEvals(options);
3412
- }
3413
3177
  async getScoreById({ id }) {
3414
3178
  return this.stores.scores.getScoreById({ id });
3415
3179
  }
3416
3180
  async saveScore(score) {
3417
3181
  return this.stores.scores.saveScore(score);
3418
3182
  }
3419
- async getScoresByScorerId({
3183
+ async listScoresByScorerId({
3420
3184
  scorerId,
3421
3185
  entityId,
3422
3186
  entityType,
3423
3187
  source,
3424
3188
  pagination
3425
3189
  }) {
3426
- return this.stores.scores.getScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
3190
+ return this.stores.scores.listScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
3427
3191
  }
3428
- async getScoresByRunId({
3192
+ async listScoresByRunId({
3429
3193
  runId,
3430
3194
  pagination
3431
3195
  }) {
3432
- return this.stores.scores.getScoresByRunId({ runId, pagination });
3196
+ return this.stores.scores.listScoresByRunId({ runId, pagination });
3433
3197
  }
3434
- async getScoresByEntityId({
3198
+ async listScoresByEntityId({
3435
3199
  entityId,
3436
3200
  entityType,
3437
3201
  pagination
3438
3202
  }) {
3439
- return this.stores.scores.getScoresByEntityId({ entityId, entityType, pagination });
3440
- }
3441
- /**
3442
- * TRACES
3443
- */
3444
- /**
3445
- * @deprecated use getTracesPaginated instead.
3446
- */
3447
- async getTraces(args) {
3448
- return this.stores.traces.getTraces(args);
3449
- }
3450
- async getTracesPaginated(args) {
3451
- return this.stores.traces.getTracesPaginated(args);
3452
- }
3453
- async batchTraceInsert(args) {
3454
- return this.stores.traces.batchTraceInsert(args);
3203
+ return this.stores.scores.listScoresByEntityId({ entityId, entityType, pagination });
3455
3204
  }
3456
3205
  /**
3457
3206
  * WORKFLOWS
@@ -3461,9 +3210,9 @@ var LibSQLStore = class extends MastraStorage {
3461
3210
  runId,
3462
3211
  stepId,
3463
3212
  result,
3464
- runtimeContext
3213
+ requestContext
3465
3214
  }) {
3466
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
3215
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
3467
3216
  }
3468
3217
  async updateWorkflowState({
3469
3218
  workflowName,
@@ -3486,15 +3235,8 @@ var LibSQLStore = class extends MastraStorage {
3486
3235
  }) {
3487
3236
  return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
3488
3237
  }
3489
- async getWorkflowRuns({
3490
- workflowName,
3491
- fromDate,
3492
- toDate,
3493
- limit,
3494
- offset,
3495
- resourceId
3496
- } = {}) {
3497
- return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
3238
+ async listWorkflowRuns(args = {}) {
3239
+ return this.stores.workflows.listWorkflowRuns(args);
3498
3240
  }
3499
3241
  async getWorkflowRunById({
3500
3242
  runId,
@@ -3515,30 +3257,30 @@ var LibSQLStore = class extends MastraStorage {
3515
3257
  }) {
3516
3258
  return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
3517
3259
  }
3518
- async createAISpan(span) {
3519
- return this.stores.observability.createAISpan(span);
3260
+ async createSpan(span) {
3261
+ return this.stores.observability.createSpan(span);
3520
3262
  }
3521
- async updateAISpan(params) {
3522
- return this.stores.observability.updateAISpan(params);
3263
+ async updateSpan(params) {
3264
+ return this.stores.observability.updateSpan(params);
3523
3265
  }
3524
- async getAITrace(traceId) {
3525
- return this.stores.observability.getAITrace(traceId);
3266
+ async getTrace(traceId) {
3267
+ return this.stores.observability.getTrace(traceId);
3526
3268
  }
3527
- async getAITracesPaginated(args) {
3528
- return this.stores.observability.getAITracesPaginated(args);
3269
+ async getTracesPaginated(args) {
3270
+ return this.stores.observability.getTracesPaginated(args);
3529
3271
  }
3530
- async getScoresBySpan({
3272
+ async listScoresBySpan({
3531
3273
  traceId,
3532
3274
  spanId,
3533
3275
  pagination
3534
3276
  }) {
3535
- return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
3277
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
3536
3278
  }
3537
- async batchCreateAISpans(args) {
3538
- return this.stores.observability.batchCreateAISpans(args);
3279
+ async batchCreateSpans(args) {
3280
+ return this.stores.observability.batchCreateSpans(args);
3539
3281
  }
3540
- async batchUpdateAISpans(args) {
3541
- return this.stores.observability.batchUpdateAISpans(args);
3282
+ async batchUpdateSpans(args) {
3283
+ return this.stores.observability.batchUpdateSpans(args);
3542
3284
  }
3543
3285
  };
3544
3286