@mastra/mssql 0.0.0-fix-persist-session-cache-option-mcp-server-20251031182703 → 0.0.0-fix-9244-clickhouse-metadata-20251104213434

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -6,7 +6,7 @@ var sql2 = require('mssql');
6
6
  var agent = require('@mastra/core/agent');
7
7
  var utils = require('@mastra/core/utils');
8
8
  var crypto = require('crypto');
9
- var scores = require('@mastra/core/scores');
9
+ var evals = require('@mastra/core/evals');
10
10
 
11
11
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
12
 
@@ -104,7 +104,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
104
104
  });
105
105
  const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
106
106
  const list = new agent.MessageList().add(cleanMessages, "memory");
107
- return format === "v2" ? list.get.all.v2() : list.get.all.v1();
107
+ return format === "v2" ? list.get.all.db() : list.get.all.v1();
108
108
  }
109
109
  constructor({
110
110
  pool,
@@ -154,11 +154,12 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
154
154
  );
155
155
  }
156
156
  }
157
- async getThreadsByResourceIdPaginated(args) {
158
- const { resourceId, page = 0, perPage: perPageInput, orderBy = "createdAt", sortDirection = "DESC" } = args;
157
+ async listThreadsByResourceId(args) {
158
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
159
+ const perPage = storage.normalizePerPage(perPageInput, 100);
160
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
161
+ const { field, direction } = this.parseOrderBy(orderBy);
159
162
  try {
160
- const perPage = perPageInput !== void 0 ? perPageInput : 100;
161
- const currentOffset = page * perPage;
162
163
  const baseQuery = `FROM ${getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
163
164
  const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
164
165
  const countRequest = this.pool.request();
@@ -170,17 +171,22 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
170
171
  threads: [],
171
172
  total: 0,
172
173
  page,
173
- perPage,
174
+ perPage: perPageForResponse,
174
175
  hasMore: false
175
176
  };
176
177
  }
177
- const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
178
- const dir = (sortDirection || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
178
+ const orderByField = field === "createdAt" ? "[createdAt]" : "[updatedAt]";
179
+ const dir = (direction || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
180
+ const limitValue = perPageInput === false ? total : perPage;
179
181
  const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${dir} OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
180
182
  const dataRequest = this.pool.request();
181
183
  dataRequest.input("resourceId", resourceId);
182
- dataRequest.input("perPage", perPage);
183
- dataRequest.input("offset", currentOffset);
184
+ dataRequest.input("offset", offset);
185
+ if (limitValue > 2147483647) {
186
+ dataRequest.input("perPage", sql2__default.default.BigInt, limitValue);
187
+ } else {
188
+ dataRequest.input("perPage", limitValue);
189
+ }
184
190
  const rowsResult = await dataRequest.query(dataQuery);
185
191
  const rows = rowsResult.recordset || [];
186
192
  const threads = rows.map((thread) => ({
@@ -193,13 +199,13 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
193
199
  threads,
194
200
  total,
195
201
  page,
196
- perPage,
197
- hasMore: currentOffset + threads.length < total
202
+ perPage: perPageForResponse,
203
+ hasMore: perPageInput === false ? false : offset + perPage < total
198
204
  };
199
205
  } catch (error$1) {
200
206
  const mastraError = new error.MastraError(
201
207
  {
202
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
208
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
203
209
  domain: error.ErrorDomain.STORAGE,
204
210
  category: error.ErrorCategory.THIRD_PARTY,
205
211
  details: {
@@ -211,7 +217,13 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
211
217
  );
212
218
  this.logger?.error?.(mastraError.toString());
213
219
  this.logger?.trackException?.(mastraError);
214
- return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
220
+ return {
221
+ threads: [],
222
+ total: 0,
223
+ page,
224
+ perPage: perPageForResponse,
225
+ hasMore: false
226
+ };
215
227
  }
216
228
  }
217
229
  async saveThread({ thread }) {
@@ -257,31 +269,6 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
257
269
  );
258
270
  }
259
271
  }
260
- /**
261
- * @deprecated use getThreadsByResourceIdPaginated instead
262
- */
263
- async getThreadsByResourceId(args) {
264
- const { resourceId, orderBy = "createdAt", sortDirection = "DESC" } = args;
265
- try {
266
- const baseQuery = `FROM ${getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
267
- const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
268
- const dir = (sortDirection || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
269
- const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${dir}`;
270
- const request = this.pool.request();
271
- request.input("resourceId", resourceId);
272
- const resultSet = await request.query(dataQuery);
273
- const rows = resultSet.recordset || [];
274
- return rows.map((thread) => ({
275
- ...thread,
276
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
277
- createdAt: thread.createdAt,
278
- updatedAt: thread.updatedAt
279
- }));
280
- } catch (error) {
281
- this.logger?.error?.(`Error getting threads for resource ${resourceId}:`, error);
282
- return [];
283
- }
284
- }
285
272
  /**
286
273
  * Updates a thread's title and metadata, merging with existing metadata. Returns the updated thread.
287
274
  */
@@ -390,8 +377,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
390
377
  }
391
378
  async _getIncludedMessages({
392
379
  threadId,
393
- selectBy,
394
- orderByStatement
380
+ selectBy
395
381
  }) {
396
382
  if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
397
383
  const include = selectBy?.include;
@@ -419,7 +405,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
419
405
  m.[resourceId],
420
406
  m.seq_id
421
407
  FROM (
422
- SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
408
+ SELECT *, ROW_NUMBER() OVER (ORDER BY [createdAt] ASC) as row_num
423
409
  FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
424
410
  WHERE [thread_id] = ${pThreadId}
425
411
  ) AS m
@@ -427,15 +413,17 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
427
413
  OR EXISTS (
428
414
  SELECT 1
429
415
  FROM (
430
- SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
416
+ SELECT *, ROW_NUMBER() OVER (ORDER BY [createdAt] ASC) as row_num
431
417
  FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
432
418
  WHERE [thread_id] = ${pThreadId}
433
419
  ) AS target
434
420
  WHERE target.id = ${pId}
435
421
  AND (
436
- (m.row_num <= target.row_num + ${pPrev} AND m.row_num > target.row_num)
422
+ -- Get previous messages (messages that come BEFORE the target)
423
+ (m.row_num < target.row_num AND m.row_num >= target.row_num - ${pPrev})
437
424
  OR
438
- (m.row_num >= target.row_num - ${pNext} AND m.row_num < target.row_num)
425
+ -- Get next messages (messages that come AFTER the target)
426
+ (m.row_num > target.row_num AND m.row_num <= target.row_num + ${pNext})
439
427
  )
440
428
  )
441
429
  `
@@ -464,8 +452,11 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
464
452
  });
465
453
  return dedupedRows;
466
454
  }
455
+ /**
456
+ * @deprecated use listMessages instead
457
+ */
467
458
  async getMessages(args) {
468
- const { threadId, resourceId, format, selectBy } = args;
459
+ const { threadId, resourceId, selectBy } = args;
469
460
  const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
470
461
  const orderByStatement = `ORDER BY [seq_id] DESC`;
471
462
  const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
@@ -474,7 +465,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
474
465
  let rows = [];
475
466
  const include = selectBy?.include || [];
476
467
  if (include?.length) {
477
- const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
468
+ const includeMessages = await this._getIncludedMessages({ threadId, selectBy });
478
469
  if (includeMessages) {
479
470
  rows.push(...includeMessages);
480
471
  }
@@ -499,8 +490,19 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
499
490
  const timeDiff = a.seq_id - b.seq_id;
500
491
  return timeDiff;
501
492
  });
502
- rows = rows.map(({ seq_id, ...rest }) => rest);
503
- return this._parseAndFormatMessages(rows, format);
493
+ const messagesWithParsedContent = rows.map((row) => {
494
+ if (typeof row.content === "string") {
495
+ try {
496
+ return { ...row, content: JSON.parse(row.content) };
497
+ } catch {
498
+ return row;
499
+ }
500
+ }
501
+ return row;
502
+ });
503
+ const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
504
+ const list = new agent.MessageList().add(cleanMessages, "memory");
505
+ return { messages: list.get.all.db() };
504
506
  } catch (error$1) {
505
507
  const mastraError = new error.MastraError(
506
508
  {
@@ -516,14 +518,11 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
516
518
  );
517
519
  this.logger?.error?.(mastraError.toString());
518
520
  this.logger?.trackException?.(mastraError);
519
- return [];
521
+ return { messages: [] };
520
522
  }
521
523
  }
522
- async getMessagesById({
523
- messageIds,
524
- format
525
- }) {
526
- if (messageIds.length === 0) return [];
524
+ async listMessagesById({ messageIds }) {
525
+ if (messageIds.length === 0) return { messages: [] };
527
526
  const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
528
527
  const orderByStatement = `ORDER BY [seq_id] DESC`;
529
528
  try {
@@ -539,13 +538,23 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
539
538
  const timeDiff = a.seq_id - b.seq_id;
540
539
  return timeDiff;
541
540
  });
542
- rows = rows.map(({ seq_id, ...rest }) => rest);
543
- if (format === `v1`) return this._parseAndFormatMessages(rows, format);
544
- return this._parseAndFormatMessages(rows, `v2`);
541
+ const messagesWithParsedContent = rows.map((row) => {
542
+ if (typeof row.content === "string") {
543
+ try {
544
+ return { ...row, content: JSON.parse(row.content) };
545
+ } catch {
546
+ return row;
547
+ }
548
+ }
549
+ return row;
550
+ });
551
+ const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
552
+ const list = new agent.MessageList().add(cleanMessages, "memory");
553
+ return { messages: list.get.all.db() };
545
554
  } catch (error$1) {
546
555
  const mastraError = new error.MastraError(
547
556
  {
548
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_BY_ID_FAILED",
557
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_MESSAGES_BY_ID_FAILED",
549
558
  domain: error.ErrorDomain.STORAGE,
550
559
  category: error.ErrorCategory.THIRD_PARTY,
551
560
  details: {
@@ -556,110 +565,124 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
556
565
  );
557
566
  this.logger?.error?.(mastraError.toString());
558
567
  this.logger?.trackException?.(mastraError);
559
- return [];
568
+ return { messages: [] };
560
569
  }
561
570
  }
562
- async listMessages(_args) {
563
- throw new Error(
564
- `listMessages is not yet implemented by this storage adapter (${this.constructor.name}). This method is currently being rolled out across all storage adapters. Please use getMessages or getMessagesPaginated as an alternative, or wait for the implementation.`
565
- );
566
- }
567
- async listMessagesById({ messageIds }) {
568
- return this.getMessagesById({ messageIds, format: "v2" });
569
- }
570
- async listThreadsByResourceId(args) {
571
- const { resourceId, limit, offset, orderBy, sortDirection } = args;
572
- const page = Math.floor(offset / limit);
573
- const perPage = limit;
574
- return this.getThreadsByResourceIdPaginated({ resourceId, page, perPage, orderBy, sortDirection });
575
- }
576
- async getMessagesPaginated(args) {
577
- const { threadId, resourceId, format, selectBy } = args;
578
- const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
571
+ async listMessages(args) {
572
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
573
+ if (!threadId.trim()) {
574
+ throw new error.MastraError(
575
+ {
576
+ id: "STORAGE_MSSQL_LIST_MESSAGES_INVALID_THREAD_ID",
577
+ domain: error.ErrorDomain.STORAGE,
578
+ category: error.ErrorCategory.THIRD_PARTY,
579
+ details: { threadId }
580
+ },
581
+ new Error("threadId must be a non-empty string")
582
+ );
583
+ }
584
+ const perPage = storage.normalizePerPage(perPageInput, 40);
585
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
579
586
  try {
580
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
581
- const fromDate = dateRange?.start;
582
- const toDate = dateRange?.end;
587
+ const { field, direction } = this.parseOrderBy(orderBy);
588
+ const orderByStatement = `ORDER BY [${field}] ${direction}`;
583
589
  const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
584
- const orderByStatement = `ORDER BY [seq_id] DESC`;
585
- let messages = [];
586
- if (selectBy?.include?.length) {
587
- const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
588
- if (includeMessages) messages.push(...includeMessages);
589
- }
590
- const perPage = perPageInput !== void 0 ? perPageInput : storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
591
- const currentOffset = page * perPage;
590
+ const tableName = getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
592
591
  const conditions = ["[thread_id] = @threadId"];
593
592
  const request = this.pool.request();
594
593
  request.input("threadId", threadId);
595
- if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
594
+ if (resourceId) {
595
+ conditions.push("[resourceId] = @resourceId");
596
+ request.input("resourceId", resourceId);
597
+ }
598
+ if (filter?.dateRange?.start) {
596
599
  conditions.push("[createdAt] >= @fromDate");
597
- request.input("fromDate", fromDate.toISOString());
600
+ request.input("fromDate", filter.dateRange.start);
598
601
  }
599
- if (toDate instanceof Date && !isNaN(toDate.getTime())) {
602
+ if (filter?.dateRange?.end) {
600
603
  conditions.push("[createdAt] <= @toDate");
601
- request.input("toDate", toDate.toISOString());
604
+ request.input("toDate", filter.dateRange.end);
602
605
  }
603
606
  const whereClause = `WHERE ${conditions.join(" AND ")}`;
604
- const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
607
+ const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
605
608
  const countResult = await request.query(countQuery);
606
609
  const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
607
- if (total === 0 && messages.length > 0) {
608
- const parsedIncluded = this._parseAndFormatMessages(messages, format);
610
+ const limitValue = perPageInput === false ? total : perPage;
611
+ const dataQuery = `${selectStatement} FROM ${tableName} ${whereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
612
+ request.input("offset", offset);
613
+ if (limitValue > 2147483647) {
614
+ request.input("limit", sql2__default.default.BigInt, limitValue);
615
+ } else {
616
+ request.input("limit", limitValue);
617
+ }
618
+ const rowsResult = await request.query(dataQuery);
619
+ const rows = rowsResult.recordset || [];
620
+ const messages = [...rows];
621
+ if (total === 0 && messages.length === 0 && (!include || include.length === 0)) {
609
622
  return {
610
- messages: parsedIncluded,
611
- total: parsedIncluded.length,
623
+ messages: [],
624
+ total: 0,
612
625
  page,
613
- perPage,
626
+ perPage: perPageForResponse,
614
627
  hasMore: false
615
628
  };
616
629
  }
617
- const excludeIds = messages.map((m) => m.id);
618
- if (excludeIds.length > 0) {
619
- const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
620
- conditions.push(`id NOT IN (${excludeParams.join(", ")})`);
621
- excludeIds.forEach((id, idx) => request.input(`id${idx}`, id));
630
+ const messageIds = new Set(messages.map((m) => m.id));
631
+ if (include && include.length > 0) {
632
+ const selectBy = { include };
633
+ const includeMessages = await this._getIncludedMessages({ threadId, selectBy });
634
+ if (includeMessages) {
635
+ for (const includeMsg of includeMessages) {
636
+ if (!messageIds.has(includeMsg.id)) {
637
+ messages.push(includeMsg);
638
+ messageIds.add(includeMsg.id);
639
+ }
640
+ }
641
+ }
622
642
  }
623
- const finalWhereClause = `WHERE ${conditions.join(" AND ")}`;
624
- const dataQuery = `${selectStatement} FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${finalWhereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
625
- request.input("offset", currentOffset);
626
- request.input("limit", perPage);
627
- const rowsResult = await request.query(dataQuery);
628
- const rows = rowsResult.recordset || [];
629
- rows.sort((a, b) => a.seq_id - b.seq_id);
630
- messages.push(...rows);
631
- const parsed = this._parseAndFormatMessages(messages, format);
643
+ const parsed = this._parseAndFormatMessages(messages, "v2");
644
+ let finalMessages = parsed;
645
+ finalMessages = finalMessages.sort((a, b) => {
646
+ const aValue = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
647
+ const bValue = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
648
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
649
+ });
650
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
651
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
652
+ const hasMore = perPageInput !== false && !allThreadMessagesReturned && offset + perPage < total;
632
653
  return {
633
- messages: parsed,
654
+ messages: finalMessages,
634
655
  total,
635
656
  page,
636
- perPage,
637
- hasMore: currentOffset + rows.length < total
657
+ perPage: perPageForResponse,
658
+ hasMore
638
659
  };
639
660
  } catch (error$1) {
640
661
  const mastraError = new error.MastraError(
641
662
  {
642
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_PAGINATED_FAILED",
663
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_MESSAGES_FAILED",
643
664
  domain: error.ErrorDomain.STORAGE,
644
665
  category: error.ErrorCategory.THIRD_PARTY,
645
666
  details: {
646
667
  threadId,
647
- resourceId: resourceId ?? "",
648
- page
668
+ resourceId: resourceId ?? ""
649
669
  }
650
670
  },
651
671
  error$1
652
672
  );
653
673
  this.logger?.error?.(mastraError.toString());
654
674
  this.logger?.trackException?.(mastraError);
655
- return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
675
+ return {
676
+ messages: [],
677
+ total: 0,
678
+ page,
679
+ perPage: perPageForResponse,
680
+ hasMore: false
681
+ };
656
682
  }
657
683
  }
658
- async saveMessages({
659
- messages,
660
- format
661
- }) {
662
- if (messages.length === 0) return messages;
684
+ async saveMessages({ messages }) {
685
+ if (messages.length === 0) return { messages: [] };
663
686
  const threadId = messages[0]?.threadId;
664
687
  if (!threadId) {
665
688
  throw new error.MastraError({
@@ -741,8 +764,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
741
764
  return message;
742
765
  });
743
766
  const list = new agent.MessageList().add(messagesWithParsedContent, "memory");
744
- if (format === "v2") return list.get.all.v2();
745
- return list.get.all.v1();
767
+ return { messages: list.get.all.db() };
746
768
  } catch (error$1) {
747
769
  throw new error.MastraError(
748
770
  {
@@ -2318,7 +2340,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2318
2340
  async saveScore(score) {
2319
2341
  let validatedScore;
2320
2342
  try {
2321
- validatedScore = scores.saveScorePayloadSchema.parse(score);
2343
+ validatedScore = evals.saveScorePayloadSchema.parse(score);
2322
2344
  } catch (error$1) {
2323
2345
  throw new error.MastraError(
2324
2346
  {
@@ -2374,7 +2396,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2374
2396
  );
2375
2397
  }
2376
2398
  }
2377
- async getScoresByScorerId({
2399
+ async listScoresByScorerId({
2378
2400
  scorerId,
2379
2401
  pagination,
2380
2402
  entityId,
@@ -2408,31 +2430,36 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2408
2430
  });
2409
2431
  const totalResult = await countRequest.query(`SELECT COUNT(*) as count FROM ${tableName} WHERE ${whereClause}`);
2410
2432
  const total = totalResult.recordset[0]?.count || 0;
2433
+ const { page, perPage: perPageInput } = pagination;
2411
2434
  if (total === 0) {
2412
2435
  return {
2413
2436
  pagination: {
2414
2437
  total: 0,
2415
- page: pagination.page,
2416
- perPage: pagination.perPage,
2438
+ page,
2439
+ perPage: perPageInput,
2417
2440
  hasMore: false
2418
2441
  },
2419
2442
  scores: []
2420
2443
  };
2421
2444
  }
2445
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2446
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2447
+ const limitValue = perPageInput === false ? total : perPage;
2448
+ const end = perPageInput === false ? total : start + perPage;
2422
2449
  const dataRequest = this.pool.request();
2423
2450
  Object.entries(params).forEach(([key, value]) => {
2424
2451
  dataRequest.input(key, value);
2425
2452
  });
2426
- dataRequest.input("perPage", pagination.perPage);
2427
- dataRequest.input("offset", pagination.page * pagination.perPage);
2453
+ dataRequest.input("perPage", limitValue);
2454
+ dataRequest.input("offset", start);
2428
2455
  const dataQuery = `SELECT * FROM ${tableName} WHERE ${whereClause} ORDER BY [createdAt] DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
2429
2456
  const result = await dataRequest.query(dataQuery);
2430
2457
  return {
2431
2458
  pagination: {
2432
2459
  total: Number(total),
2433
- page: pagination.page,
2434
- perPage: pagination.perPage,
2435
- hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2460
+ page,
2461
+ perPage: perPageForResponse,
2462
+ hasMore: end < total
2436
2463
  },
2437
2464
  scores: result.recordset.map((row) => transformScoreRow(row))
2438
2465
  };
@@ -2448,7 +2475,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2448
2475
  );
2449
2476
  }
2450
2477
  }
2451
- async getScoresByRunId({
2478
+ async listScoresByRunId({
2452
2479
  runId,
2453
2480
  pagination
2454
2481
  }) {
@@ -2459,30 +2486,35 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2459
2486
  `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [runId] = @p1`
2460
2487
  );
2461
2488
  const total = totalResult.recordset[0]?.count || 0;
2489
+ const { page, perPage: perPageInput } = pagination;
2462
2490
  if (total === 0) {
2463
2491
  return {
2464
2492
  pagination: {
2465
2493
  total: 0,
2466
- page: pagination.page,
2467
- perPage: pagination.perPage,
2494
+ page,
2495
+ perPage: perPageInput,
2468
2496
  hasMore: false
2469
2497
  },
2470
2498
  scores: []
2471
2499
  };
2472
2500
  }
2501
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2502
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2503
+ const limitValue = perPageInput === false ? total : perPage;
2504
+ const end = perPageInput === false ? total : start + perPage;
2473
2505
  const dataRequest = this.pool.request();
2474
2506
  dataRequest.input("p1", runId);
2475
- dataRequest.input("p2", pagination.perPage);
2476
- dataRequest.input("p3", pagination.page * pagination.perPage);
2507
+ dataRequest.input("p2", limitValue);
2508
+ dataRequest.input("p3", start);
2477
2509
  const result = await dataRequest.query(
2478
2510
  `SELECT * FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [runId] = @p1 ORDER BY [createdAt] DESC OFFSET @p3 ROWS FETCH NEXT @p2 ROWS ONLY`
2479
2511
  );
2480
2512
  return {
2481
2513
  pagination: {
2482
2514
  total: Number(total),
2483
- page: pagination.page,
2484
- perPage: pagination.perPage,
2485
- hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2515
+ page,
2516
+ perPage: perPageForResponse,
2517
+ hasMore: end < total
2486
2518
  },
2487
2519
  scores: result.recordset.map((row) => transformScoreRow(row))
2488
2520
  };
@@ -2498,7 +2530,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2498
2530
  );
2499
2531
  }
2500
2532
  }
2501
- async getScoresByEntityId({
2533
+ async listScoresByEntityId({
2502
2534
  entityId,
2503
2535
  entityType,
2504
2536
  pagination
@@ -2511,31 +2543,36 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2511
2543
  `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [entityId] = @p1 AND [entityType] = @p2`
2512
2544
  );
2513
2545
  const total = totalResult.recordset[0]?.count || 0;
2546
+ const { page, perPage: perPageInput } = pagination;
2547
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2548
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2514
2549
  if (total === 0) {
2515
2550
  return {
2516
2551
  pagination: {
2517
2552
  total: 0,
2518
- page: pagination.page,
2519
- perPage: pagination.perPage,
2553
+ page,
2554
+ perPage: perPageForResponse,
2520
2555
  hasMore: false
2521
2556
  },
2522
2557
  scores: []
2523
2558
  };
2524
2559
  }
2560
+ const limitValue = perPageInput === false ? total : perPage;
2561
+ const end = perPageInput === false ? total : start + perPage;
2525
2562
  const dataRequest = this.pool.request();
2526
2563
  dataRequest.input("p1", entityId);
2527
2564
  dataRequest.input("p2", entityType);
2528
- dataRequest.input("p3", pagination.perPage);
2529
- dataRequest.input("p4", pagination.page * pagination.perPage);
2565
+ dataRequest.input("p3", limitValue);
2566
+ dataRequest.input("p4", start);
2530
2567
  const result = await dataRequest.query(
2531
2568
  `SELECT * FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [entityId] = @p1 AND [entityType] = @p2 ORDER BY [createdAt] DESC OFFSET @p4 ROWS FETCH NEXT @p3 ROWS ONLY`
2532
2569
  );
2533
2570
  return {
2534
2571
  pagination: {
2535
2572
  total: Number(total),
2536
- page: pagination.page,
2537
- perPage: pagination.perPage,
2538
- hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2573
+ page,
2574
+ perPage: perPageForResponse,
2575
+ hasMore: end < total
2539
2576
  },
2540
2577
  scores: result.recordset.map((row) => transformScoreRow(row))
2541
2578
  };
@@ -2551,7 +2588,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2551
2588
  );
2552
2589
  }
2553
2590
  }
2554
- async getScoresBySpan({
2591
+ async listScoresBySpan({
2555
2592
  traceId,
2556
2593
  spanId,
2557
2594
  pagination
@@ -2564,34 +2601,38 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2564
2601
  `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [traceId] = @p1 AND [spanId] = @p2`
2565
2602
  );
2566
2603
  const total = totalResult.recordset[0]?.count || 0;
2604
+ const { page, perPage: perPageInput } = pagination;
2605
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2606
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2567
2607
  if (total === 0) {
2568
2608
  return {
2569
2609
  pagination: {
2570
2610
  total: 0,
2571
- page: pagination.page,
2572
- perPage: pagination.perPage,
2611
+ page,
2612
+ perPage: perPageForResponse,
2573
2613
  hasMore: false
2574
2614
  },
2575
2615
  scores: []
2576
2616
  };
2577
2617
  }
2578
- const limit = pagination.perPage + 1;
2618
+ const limitValue = perPageInput === false ? total : perPage;
2619
+ const end = perPageInput === false ? total : start + perPage;
2579
2620
  const dataRequest = this.pool.request();
2580
2621
  dataRequest.input("p1", traceId);
2581
2622
  dataRequest.input("p2", spanId);
2582
- dataRequest.input("p3", limit);
2583
- dataRequest.input("p4", pagination.page * pagination.perPage);
2623
+ dataRequest.input("p3", limitValue);
2624
+ dataRequest.input("p4", start);
2584
2625
  const result = await dataRequest.query(
2585
2626
  `SELECT * FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [traceId] = @p1 AND [spanId] = @p2 ORDER BY [createdAt] DESC OFFSET @p4 ROWS FETCH NEXT @p3 ROWS ONLY`
2586
2627
  );
2587
2628
  return {
2588
2629
  pagination: {
2589
2630
  total: Number(total),
2590
- page: pagination.page,
2591
- perPage: pagination.perPage,
2592
- hasMore: result.recordset.length > pagination.perPage
2631
+ page,
2632
+ perPage: perPageForResponse,
2633
+ hasMore: end < total
2593
2634
  },
2594
- scores: result.recordset.slice(0, pagination.perPage).map((row) => transformScoreRow(row))
2635
+ scores: result.recordset.map((row) => transformScoreRow(row))
2595
2636
  };
2596
2637
  } catch (error$1) {
2597
2638
  throw new error.MastraError(
@@ -2890,12 +2931,12 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2890
2931
  );
2891
2932
  }
2892
2933
  }
2893
- async getWorkflowRuns({
2934
+ async listWorkflowRuns({
2894
2935
  workflowName,
2895
2936
  fromDate,
2896
2937
  toDate,
2897
- limit,
2898
- offset,
2938
+ page,
2939
+ perPage,
2899
2940
  resourceId
2900
2941
  } = {}) {
2901
2942
  try {
@@ -2933,15 +2974,18 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2933
2974
  request.input(key, value);
2934
2975
  }
2935
2976
  });
2936
- if (limit !== void 0 && offset !== void 0) {
2977
+ const usePagination = typeof perPage === "number" && typeof page === "number";
2978
+ if (usePagination) {
2937
2979
  const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
2938
2980
  const countResult = await request.query(countQuery);
2939
2981
  total = Number(countResult.recordset[0]?.count || 0);
2940
2982
  }
2941
2983
  let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
2942
- if (limit !== void 0 && offset !== void 0) {
2943
- query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
2944
- request.input("limit", limit);
2984
+ if (usePagination) {
2985
+ const normalizedPerPage = storage.normalizePerPage(perPage, Number.MAX_SAFE_INTEGER);
2986
+ const offset = page * normalizedPerPage;
2987
+ query += ` OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
2988
+ request.input("perPage", normalizedPerPage);
2945
2989
  request.input("offset", offset);
2946
2990
  }
2947
2991
  const result = await request.query(query);
@@ -2950,7 +2994,7 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2950
2994
  } catch (error$1) {
2951
2995
  throw new error.MastraError(
2952
2996
  {
2953
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
2997
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_WORKFLOW_RUNS_FAILED",
2954
2998
  domain: error.ErrorDomain.STORAGE,
2955
2999
  category: error.ErrorCategory.THIRD_PARTY,
2956
3000
  details: {
@@ -2961,9 +3005,6 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2961
3005
  );
2962
3006
  }
2963
3007
  }
2964
- async listWorkflowRuns(args) {
2965
- return this.getWorkflowRuns(args);
2966
- }
2967
3008
  };
2968
3009
 
2969
3010
  // src/storage/index.ts
@@ -3058,7 +3099,7 @@ var MSSQLStore = class extends storage.MastraStorage {
3058
3099
  hasColumn: true,
3059
3100
  createTable: true,
3060
3101
  deleteMessages: true,
3061
- getScoresBySpan: true,
3102
+ listScoresBySpan: true,
3062
3103
  aiTracing: true,
3063
3104
  indexManagement: true
3064
3105
  };
@@ -3097,15 +3138,6 @@ var MSSQLStore = class extends storage.MastraStorage {
3097
3138
  async getThreadById({ threadId }) {
3098
3139
  return this.stores.memory.getThreadById({ threadId });
3099
3140
  }
3100
- /**
3101
- * @deprecated use getThreadsByResourceIdPaginated instead
3102
- */
3103
- async getThreadsByResourceId(args) {
3104
- return this.stores.memory.getThreadsByResourceId(args);
3105
- }
3106
- async getThreadsByResourceIdPaginated(args) {
3107
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
3108
- }
3109
3141
  async saveThread({ thread }) {
3110
3142
  return this.stores.memory.saveThread({ thread });
3111
3143
  }
@@ -3119,17 +3151,14 @@ var MSSQLStore = class extends storage.MastraStorage {
3119
3151
  async deleteThread({ threadId }) {
3120
3152
  return this.stores.memory.deleteThread({ threadId });
3121
3153
  }
3154
+ /**
3155
+ * @deprecated use listMessages instead
3156
+ */
3122
3157
  async getMessages(args) {
3123
3158
  return this.stores.memory.getMessages(args);
3124
3159
  }
3125
- async getMessagesById({
3126
- messageIds,
3127
- format
3128
- }) {
3129
- return this.stores.memory.getMessagesById({ messageIds, format });
3130
- }
3131
- async getMessagesPaginated(args) {
3132
- return this.stores.memory.getMessagesPaginated(args);
3160
+ async listMessagesById({ messageIds }) {
3161
+ return this.stores.memory.listMessagesById({ messageIds });
3133
3162
  }
3134
3163
  async saveMessages(args) {
3135
3164
  return this.stores.memory.saveMessages(args);
@@ -3188,15 +3217,15 @@ var MSSQLStore = class extends storage.MastraStorage {
3188
3217
  }) {
3189
3218
  return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
3190
3219
  }
3191
- async getWorkflowRuns({
3220
+ async listWorkflowRuns({
3192
3221
  workflowName,
3193
3222
  fromDate,
3194
3223
  toDate,
3195
- limit,
3196
- offset,
3224
+ perPage,
3225
+ page,
3197
3226
  resourceId
3198
3227
  } = {}) {
3199
- return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
3228
+ return this.stores.workflows.listWorkflowRuns({ workflowName, fromDate, toDate, perPage, page, resourceId });
3200
3229
  }
3201
3230
  async getWorkflowRunById({
3202
3231
  runId,
@@ -3267,14 +3296,14 @@ var MSSQLStore = class extends storage.MastraStorage {
3267
3296
  async getScoreById({ id: _id }) {
3268
3297
  return this.stores.scores.getScoreById({ id: _id });
3269
3298
  }
3270
- async getScoresByScorerId({
3299
+ async listScoresByScorerId({
3271
3300
  scorerId: _scorerId,
3272
3301
  pagination: _pagination,
3273
3302
  entityId: _entityId,
3274
3303
  entityType: _entityType,
3275
3304
  source: _source
3276
3305
  }) {
3277
- return this.stores.scores.getScoresByScorerId({
3306
+ return this.stores.scores.listScoresByScorerId({
3278
3307
  scorerId: _scorerId,
3279
3308
  pagination: _pagination,
3280
3309
  entityId: _entityId,
@@ -3285,29 +3314,29 @@ var MSSQLStore = class extends storage.MastraStorage {
3285
3314
  async saveScore(_score) {
3286
3315
  return this.stores.scores.saveScore(_score);
3287
3316
  }
3288
- async getScoresByRunId({
3317
+ async listScoresByRunId({
3289
3318
  runId: _runId,
3290
3319
  pagination: _pagination
3291
3320
  }) {
3292
- return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
3321
+ return this.stores.scores.listScoresByRunId({ runId: _runId, pagination: _pagination });
3293
3322
  }
3294
- async getScoresByEntityId({
3323
+ async listScoresByEntityId({
3295
3324
  entityId: _entityId,
3296
3325
  entityType: _entityType,
3297
3326
  pagination: _pagination
3298
3327
  }) {
3299
- return this.stores.scores.getScoresByEntityId({
3328
+ return this.stores.scores.listScoresByEntityId({
3300
3329
  entityId: _entityId,
3301
3330
  entityType: _entityType,
3302
3331
  pagination: _pagination
3303
3332
  });
3304
3333
  }
3305
- async getScoresBySpan({
3334
+ async listScoresBySpan({
3306
3335
  traceId,
3307
3336
  spanId,
3308
3337
  pagination: _pagination
3309
3338
  }) {
3310
- return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination: _pagination });
3339
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination: _pagination });
3311
3340
  }
3312
3341
  };
3313
3342