@mastra/mssql 0.0.0-fix-thread-list-20251105222841 → 0.0.0-fix-ai-sdk-dependency-20251124104209

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -156,6 +156,18 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
156
156
  }
157
157
  async listThreadsByResourceId(args) {
158
158
  const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
159
+ if (page < 0) {
160
+ throw new error.MastraError({
161
+ id: "MASTRA_STORAGE_MSSQL_STORE_INVALID_PAGE",
162
+ domain: error.ErrorDomain.STORAGE,
163
+ category: error.ErrorCategory.USER,
164
+ text: "Page number must be non-negative",
165
+ details: {
166
+ resourceId,
167
+ page
168
+ }
169
+ });
170
+ }
159
171
  const perPage = storage.normalizePerPage(perPageInput, 100);
160
172
  const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
161
173
  const { field, direction } = this.parseOrderBy(orderBy);
@@ -511,43 +523,59 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
511
523
  new Error("threadId must be a non-empty string")
512
524
  );
513
525
  }
526
+ if (page < 0) {
527
+ throw new error.MastraError({
528
+ id: "MASTRA_STORAGE_MSSQL_STORE_INVALID_PAGE",
529
+ domain: error.ErrorDomain.STORAGE,
530
+ category: error.ErrorCategory.USER,
531
+ text: "Page number must be non-negative",
532
+ details: {
533
+ threadId,
534
+ page
535
+ }
536
+ });
537
+ }
514
538
  const perPage = storage.normalizePerPage(perPageInput, 40);
515
539
  const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
516
540
  try {
517
541
  const { field, direction } = this.parseOrderBy(orderBy, "ASC");
518
- const orderByStatement = `ORDER BY [${field}] ${direction}`;
519
- const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
542
+ const orderByStatement = `ORDER BY [${field}] ${direction}, [seq_id] ${direction}`;
520
543
  const tableName = getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
521
- const conditions = ["[thread_id] = @threadId"];
522
- const request = this.pool.request();
523
- request.input("threadId", threadId);
524
- if (resourceId) {
525
- conditions.push("[resourceId] = @resourceId");
526
- request.input("resourceId", resourceId);
527
- }
528
- if (filter?.dateRange?.start) {
529
- conditions.push("[createdAt] >= @fromDate");
530
- request.input("fromDate", filter.dateRange.start);
531
- }
532
- if (filter?.dateRange?.end) {
533
- conditions.push("[createdAt] <= @toDate");
534
- request.input("toDate", filter.dateRange.end);
535
- }
536
- const whereClause = `WHERE ${conditions.join(" AND ")}`;
537
- const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
538
- const countResult = await request.query(countQuery);
544
+ const baseQuery = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId FROM ${tableName}`;
545
+ const filters = {
546
+ thread_id: threadId,
547
+ ...resourceId ? { resourceId } : {},
548
+ ...buildDateRangeFilter(filter?.dateRange, "createdAt")
549
+ };
550
+ const { sql: actualWhereClause = "", params: whereParams } = prepareWhereClause(
551
+ filters);
552
+ const bindWhereParams = (req) => {
553
+ Object.entries(whereParams).forEach(([paramName, paramValue]) => req.input(paramName, paramValue));
554
+ };
555
+ const countRequest = this.pool.request();
556
+ bindWhereParams(countRequest);
557
+ const countResult = await countRequest.query(`SELECT COUNT(*) as total FROM ${tableName}${actualWhereClause}`);
539
558
  const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
540
- const limitValue = perPageInput === false ? total : perPage;
541
- const dataQuery = `${selectStatement} FROM ${tableName} ${whereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
542
- request.input("offset", offset);
543
- if (limitValue > 2147483647) {
544
- request.input("limit", sql2__default.default.BigInt, limitValue);
545
- } else {
546
- request.input("limit", limitValue);
547
- }
548
- const rowsResult = await request.query(dataQuery);
549
- const rows = rowsResult.recordset || [];
550
- const messages = [...rows];
559
+ const fetchBaseMessages = async () => {
560
+ const request = this.pool.request();
561
+ bindWhereParams(request);
562
+ if (perPageInput === false) {
563
+ const result2 = await request.query(`${baseQuery}${actualWhereClause} ${orderByStatement}`);
564
+ return result2.recordset || [];
565
+ }
566
+ request.input("offset", offset);
567
+ request.input("limit", perPage > 2147483647 ? sql2__default.default.BigInt : sql2__default.default.Int, perPage);
568
+ const result = await request.query(
569
+ `${baseQuery}${actualWhereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`
570
+ );
571
+ return result.recordset || [];
572
+ };
573
+ const baseRows = perPage === 0 ? [] : await fetchBaseMessages();
574
+ const messages = [...baseRows];
575
+ const seqById = /* @__PURE__ */ new Map();
576
+ messages.forEach((msg) => {
577
+ if (typeof msg.seq_id === "number") seqById.set(msg.id, msg.seq_id);
578
+ });
551
579
  if (total === 0 && messages.length === 0 && (!include || include.length === 0)) {
552
580
  return {
553
581
  messages: [],
@@ -557,28 +585,33 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
557
585
  hasMore: false
558
586
  };
559
587
  }
560
- const messageIds = new Set(messages.map((m) => m.id));
561
- if (include && include.length > 0) {
588
+ if (include?.length) {
589
+ const messageIds = new Set(messages.map((m) => m.id));
562
590
  const includeMessages = await this._getIncludedMessages({ threadId, include });
563
- if (includeMessages) {
564
- for (const includeMsg of includeMessages) {
565
- if (!messageIds.has(includeMsg.id)) {
566
- messages.push(includeMsg);
567
- messageIds.add(includeMsg.id);
568
- }
591
+ includeMessages?.forEach((msg) => {
592
+ if (!messageIds.has(msg.id)) {
593
+ messages.push(msg);
594
+ messageIds.add(msg.id);
595
+ if (typeof msg.seq_id === "number") seqById.set(msg.id, msg.seq_id);
569
596
  }
570
- }
597
+ });
571
598
  }
572
599
  const parsed = this._parseAndFormatMessages(messages, "v2");
573
- let finalMessages = parsed;
574
- finalMessages = finalMessages.sort((a, b) => {
575
- const aValue = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
576
- const bValue = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
577
- return direction === "ASC" ? aValue - bValue : bValue - aValue;
600
+ const mult = direction === "ASC" ? 1 : -1;
601
+ const finalMessages = parsed.sort((a, b) => {
602
+ const aVal = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
603
+ const bVal = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
604
+ if (aVal == null || bVal == null) {
605
+ return aVal == null && bVal == null ? a.id.localeCompare(b.id) : aVal == null ? 1 : -1;
606
+ }
607
+ const diff = (typeof aVal === "number" && typeof bVal === "number" ? aVal - bVal : String(aVal).localeCompare(String(bVal))) * mult;
608
+ if (diff !== 0) return diff;
609
+ const seqA = seqById.get(a.id);
610
+ const seqB = seqById.get(b.id);
611
+ return seqA != null && seqB != null ? (seqA - seqB) * mult : a.id.localeCompare(b.id);
578
612
  });
579
- const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
580
- const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
581
- const hasMore = perPageInput !== false && !allThreadMessagesReturned && offset + perPage < total;
613
+ const returnedThreadMessageCount = finalMessages.filter((m) => m.threadId === threadId).length;
614
+ const hasMore = perPageInput !== false && returnedThreadMessageCount < total && offset + perPage < total;
582
615
  return {
583
616
  messages: finalMessages,
584
617
  total,
@@ -988,11 +1021,11 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
988
1021
  endedAt
989
1022
  // Note: createdAt/updatedAt will be set by default values
990
1023
  };
991
- return this.operations.insert({ tableName: storage.TABLE_AI_SPANS, record });
1024
+ return this.operations.insert({ tableName: storage.TABLE_SPANS, record });
992
1025
  } catch (error$1) {
993
1026
  throw new error.MastraError(
994
1027
  {
995
- id: "MSSQL_STORE_CREATE_AI_SPAN_FAILED",
1028
+ id: "MSSQL_STORE_CREATE_SPAN_FAILED",
996
1029
  domain: error.ErrorDomain.STORAGE,
997
1030
  category: error.ErrorCategory.USER,
998
1031
  details: {
@@ -1006,10 +1039,10 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1006
1039
  );
1007
1040
  }
1008
1041
  }
1009
- async getAITrace(traceId) {
1042
+ async getTrace(traceId) {
1010
1043
  try {
1011
1044
  const tableName = getTableName({
1012
- indexName: storage.TABLE_AI_SPANS,
1045
+ indexName: storage.TABLE_SPANS,
1013
1046
  schemaName: getSchemaName(this.schema)
1014
1047
  });
1015
1048
  const request = this.pool.request();
@@ -1030,7 +1063,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1030
1063
  traceId,
1031
1064
  spans: result.recordset.map(
1032
1065
  (span) => transformFromSqlRow({
1033
- tableName: storage.TABLE_AI_SPANS,
1066
+ tableName: storage.TABLE_SPANS,
1034
1067
  sqlRow: span
1035
1068
  })
1036
1069
  )
@@ -1038,7 +1071,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1038
1071
  } catch (error$1) {
1039
1072
  throw new error.MastraError(
1040
1073
  {
1041
- id: "MSSQL_STORE_GET_AI_TRACE_FAILED",
1074
+ id: "MSSQL_STORE_GET_TRACE_FAILED",
1042
1075
  domain: error.ErrorDomain.STORAGE,
1043
1076
  category: error.ErrorCategory.USER,
1044
1077
  details: {
@@ -1063,14 +1096,14 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1063
1096
  data.startedAt = data.startedAt.toISOString();
1064
1097
  }
1065
1098
  await this.operations.update({
1066
- tableName: storage.TABLE_AI_SPANS,
1099
+ tableName: storage.TABLE_SPANS,
1067
1100
  keys: { spanId, traceId },
1068
1101
  data
1069
1102
  });
1070
1103
  } catch (error$1) {
1071
1104
  throw new error.MastraError(
1072
1105
  {
1073
- id: "MSSQL_STORE_UPDATE_AI_SPAN_FAILED",
1106
+ id: "MSSQL_STORE_UPDATE_SPAN_FAILED",
1074
1107
  domain: error.ErrorDomain.STORAGE,
1075
1108
  category: error.ErrorCategory.USER,
1076
1109
  details: {
@@ -1082,7 +1115,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1082
1115
  );
1083
1116
  }
1084
1117
  }
1085
- async getAITracesPaginated({
1118
+ async getTracesPaginated({
1086
1119
  filters,
1087
1120
  pagination
1088
1121
  }) {
@@ -1107,7 +1140,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1107
1140
  name = `agent run: '${entityId}'`;
1108
1141
  } else {
1109
1142
  const error$1 = new error.MastraError({
1110
- id: "MSSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1143
+ id: "MSSQL_STORE_GET_TRACES_PAGINATED_FAILED",
1111
1144
  domain: error.ErrorDomain.STORAGE,
1112
1145
  category: error.ErrorCategory.USER,
1113
1146
  details: {
@@ -1126,7 +1159,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1126
1159
  params[entityParam] = name;
1127
1160
  }
1128
1161
  const tableName = getTableName({
1129
- indexName: storage.TABLE_AI_SPANS,
1162
+ indexName: storage.TABLE_SPANS,
1130
1163
  schemaName: getSchemaName(this.schema)
1131
1164
  });
1132
1165
  try {
@@ -1160,7 +1193,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1160
1193
  );
1161
1194
  const spans = dataResult.recordset.map(
1162
1195
  (row) => transformFromSqlRow({
1163
- tableName: storage.TABLE_AI_SPANS,
1196
+ tableName: storage.TABLE_SPANS,
1164
1197
  sqlRow: row
1165
1198
  })
1166
1199
  );
@@ -1176,7 +1209,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1176
1209
  } catch (error$1) {
1177
1210
  throw new error.MastraError(
1178
1211
  {
1179
- id: "MSSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1212
+ id: "MSSQL_STORE_GET_TRACES_PAGINATED_FAILED",
1180
1213
  domain: error.ErrorDomain.STORAGE,
1181
1214
  category: error.ErrorCategory.USER
1182
1215
  },
@@ -1190,7 +1223,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1190
1223
  }
1191
1224
  try {
1192
1225
  await this.operations.batchInsert({
1193
- tableName: storage.TABLE_AI_SPANS,
1226
+ tableName: storage.TABLE_SPANS,
1194
1227
  records: args.records.map((span) => ({
1195
1228
  ...span,
1196
1229
  startedAt: span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt,
@@ -1200,7 +1233,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1200
1233
  } catch (error$1) {
1201
1234
  throw new error.MastraError(
1202
1235
  {
1203
- id: "MSSQL_STORE_BATCH_CREATE_AI_SPANS_FAILED",
1236
+ id: "MSSQL_STORE_BATCH_CREATE_SPANS_FAILED",
1204
1237
  domain: error.ErrorDomain.STORAGE,
1205
1238
  category: error.ErrorCategory.USER,
1206
1239
  details: {
@@ -1230,13 +1263,13 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1230
1263
  };
1231
1264
  });
1232
1265
  await this.operations.batchUpdate({
1233
- tableName: storage.TABLE_AI_SPANS,
1266
+ tableName: storage.TABLE_SPANS,
1234
1267
  updates
1235
1268
  });
1236
1269
  } catch (error$1) {
1237
1270
  throw new error.MastraError(
1238
1271
  {
1239
- id: "MSSQL_STORE_BATCH_UPDATE_AI_SPANS_FAILED",
1272
+ id: "MSSQL_STORE_BATCH_UPDATE_SPANS_FAILED",
1240
1273
  domain: error.ErrorDomain.STORAGE,
1241
1274
  category: error.ErrorCategory.USER,
1242
1275
  details: {
@@ -1247,20 +1280,20 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1247
1280
  );
1248
1281
  }
1249
1282
  }
1250
- async batchDeleteAITraces(args) {
1283
+ async batchDeleteTraces(args) {
1251
1284
  if (!args.traceIds || args.traceIds.length === 0) {
1252
1285
  return;
1253
1286
  }
1254
1287
  try {
1255
1288
  const keys = args.traceIds.map((traceId) => ({ traceId }));
1256
1289
  await this.operations.batchDelete({
1257
- tableName: storage.TABLE_AI_SPANS,
1290
+ tableName: storage.TABLE_SPANS,
1258
1291
  keys
1259
1292
  });
1260
1293
  } catch (error$1) {
1261
1294
  throw new error.MastraError(
1262
1295
  {
1263
- id: "MSSQL_STORE_BATCH_DELETE_AI_TRACES_FAILED",
1296
+ id: "MSSQL_STORE_BATCH_DELETE_TRACES_FAILED",
1264
1297
  domain: error.ErrorDomain.STORAGE,
1265
1298
  category: error.ErrorCategory.USER,
1266
1299
  details: {
@@ -1685,6 +1718,20 @@ ${columns}
1685
1718
  return value ? 1 : 0;
1686
1719
  }
1687
1720
  if (columnSchema?.type === "jsonb") {
1721
+ if (typeof value === "string") {
1722
+ const trimmed = value.trim();
1723
+ if (trimmed.length > 0) {
1724
+ try {
1725
+ JSON.parse(trimmed);
1726
+ return trimmed;
1727
+ } catch {
1728
+ }
1729
+ }
1730
+ return JSON.stringify(value);
1731
+ }
1732
+ if (typeof value === "bigint") {
1733
+ return value.toString();
1734
+ }
1688
1735
  return JSON.stringify(value);
1689
1736
  }
1690
1737
  if (typeof value === "object") {
@@ -2167,22 +2214,22 @@ ${columns}
2167
2214
  // Spans indexes for optimal trace querying
2168
2215
  {
2169
2216
  name: `${schemaPrefix}mastra_ai_spans_traceid_startedat_idx`,
2170
- table: storage.TABLE_AI_SPANS,
2217
+ table: storage.TABLE_SPANS,
2171
2218
  columns: ["traceId", "startedAt DESC"]
2172
2219
  },
2173
2220
  {
2174
2221
  name: `${schemaPrefix}mastra_ai_spans_parentspanid_startedat_idx`,
2175
- table: storage.TABLE_AI_SPANS,
2222
+ table: storage.TABLE_SPANS,
2176
2223
  columns: ["parentSpanId", "startedAt DESC"]
2177
2224
  },
2178
2225
  {
2179
2226
  name: `${schemaPrefix}mastra_ai_spans_name_idx`,
2180
- table: storage.TABLE_AI_SPANS,
2227
+ table: storage.TABLE_SPANS,
2181
2228
  columns: ["name"]
2182
2229
  },
2183
2230
  {
2184
2231
  name: `${schemaPrefix}mastra_ai_spans_spantype_startedat_idx`,
2185
- table: storage.TABLE_AI_SPANS,
2232
+ table: storage.TABLE_SPANS,
2186
2233
  columns: ["spanType", "startedAt DESC"]
2187
2234
  }
2188
2235
  ];
@@ -2630,13 +2677,14 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2630
2677
  snapshot = {
2631
2678
  context: {},
2632
2679
  activePaths: [],
2680
+ activeStepsPath: {},
2633
2681
  timestamp: Date.now(),
2634
2682
  suspendedPaths: {},
2635
2683
  resumeLabels: {},
2636
2684
  serializedStepGraph: [],
2685
+ status: "pending",
2637
2686
  value: {},
2638
2687
  waitingPaths: {},
2639
- status: "pending",
2640
2688
  runId,
2641
2689
  requestContext: {}
2642
2690
  };
@@ -2866,7 +2914,8 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2866
2914
  toDate,
2867
2915
  page,
2868
2916
  perPage,
2869
- resourceId
2917
+ resourceId,
2918
+ status
2870
2919
  } = {}) {
2871
2920
  try {
2872
2921
  const conditions = [];
@@ -2875,6 +2924,10 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2875
2924
  conditions.push(`[workflow_name] = @workflowName`);
2876
2925
  paramMap["workflowName"] = workflowName;
2877
2926
  }
2927
+ if (status) {
2928
+ conditions.push(`JSON_VALUE([snapshot], '$.status') = @status`);
2929
+ paramMap["status"] = status;
2930
+ }
2878
2931
  if (resourceId) {
2879
2932
  const hasResourceId = await this.operations.hasColumn(storage.TABLE_WORKFLOW_SNAPSHOT, "resourceId");
2880
2933
  if (hasResourceId) {
@@ -2943,7 +2996,10 @@ var MSSQLStore = class extends storage.MastraStorage {
2943
2996
  isConnected = null;
2944
2997
  stores;
2945
2998
  constructor(config) {
2946
- super({ name: "MSSQLStore" });
2999
+ if (!config.id || typeof config.id !== "string" || config.id.trim() === "") {
3000
+ throw new Error("MSSQLStore: id must be provided and cannot be empty.");
3001
+ }
3002
+ super({ id: config.id, name: "MSSQLStore" });
2947
3003
  try {
2948
3004
  if ("connectionString" in config) {
2949
3005
  if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") {
@@ -3140,15 +3196,8 @@ var MSSQLStore = class extends storage.MastraStorage {
3140
3196
  }) {
3141
3197
  return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
3142
3198
  }
3143
- async listWorkflowRuns({
3144
- workflowName,
3145
- fromDate,
3146
- toDate,
3147
- perPage,
3148
- page,
3149
- resourceId
3150
- } = {}) {
3151
- return this.stores.workflows.listWorkflowRuns({ workflowName, fromDate, toDate, perPage, page, resourceId });
3199
+ async listWorkflowRuns(args = {}) {
3200
+ return this.stores.workflows.listWorkflowRuns(args);
3152
3201
  }
3153
3202
  async getWorkflowRunById({
3154
3203
  runId,
@@ -3198,11 +3247,11 @@ var MSSQLStore = class extends storage.MastraStorage {
3198
3247
  }) {
3199
3248
  return this.getObservabilityStore().updateSpan({ spanId, traceId, updates });
3200
3249
  }
3201
- async getAITrace(traceId) {
3202
- return this.getObservabilityStore().getAITrace(traceId);
3250
+ async getTrace(traceId) {
3251
+ return this.getObservabilityStore().getTrace(traceId);
3203
3252
  }
3204
- async getAITracesPaginated(args) {
3205
- return this.getObservabilityStore().getAITracesPaginated(args);
3253
+ async getTracesPaginated(args) {
3254
+ return this.getObservabilityStore().getTracesPaginated(args);
3206
3255
  }
3207
3256
  async batchCreateSpans(args) {
3208
3257
  return this.getObservabilityStore().batchCreateSpans(args);
@@ -3210,8 +3259,8 @@ var MSSQLStore = class extends storage.MastraStorage {
3210
3259
  async batchUpdateSpans(args) {
3211
3260
  return this.getObservabilityStore().batchUpdateSpans(args);
3212
3261
  }
3213
- async batchDeleteAITraces(args) {
3214
- return this.getObservabilityStore().batchDeleteAITraces(args);
3262
+ async batchDeleteTraces(args) {
3263
+ return this.getObservabilityStore().batchDeleteTraces(args);
3215
3264
  }
3216
3265
  /**
3217
3266
  * Scorers