@mastra/mssql 0.0.0-sidebar-window-undefined-fix-20251029233656 → 0.0.0-span-scorring-test-20251124132129

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
@@ -2,15 +2,15 @@
2
2
 
3
3
  var error = require('@mastra/core/error');
4
4
  var storage = require('@mastra/core/storage');
5
- var sql3 = require('mssql');
6
- var utils = require('@mastra/core/utils');
5
+ var sql2 = require('mssql');
7
6
  var agent = require('@mastra/core/agent');
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
 
13
- var sql3__default = /*#__PURE__*/_interopDefault(sql3);
13
+ var sql2__default = /*#__PURE__*/_interopDefault(sql2);
14
14
 
15
15
  // src/storage/index.ts
16
16
  function getSchemaName(schema) {
@@ -86,153 +86,7 @@ function transformFromSqlRow({
86
86
  return result;
87
87
  }
88
88
 
89
- // src/storage/domains/legacy-evals/index.ts
90
- function transformEvalRow(row) {
91
- let testInfoValue = null, resultValue = null;
92
- if (row.test_info) {
93
- try {
94
- testInfoValue = typeof row.test_info === "string" ? JSON.parse(row.test_info) : row.test_info;
95
- } catch {
96
- }
97
- }
98
- if (row.result) {
99
- try {
100
- resultValue = typeof row.result === "string" ? JSON.parse(row.result) : row.result;
101
- } catch {
102
- }
103
- }
104
- return {
105
- agentName: row.agent_name,
106
- input: row.input,
107
- output: row.output,
108
- result: resultValue,
109
- metricName: row.metric_name,
110
- instructions: row.instructions,
111
- testInfo: testInfoValue,
112
- globalRunId: row.global_run_id,
113
- runId: row.run_id,
114
- createdAt: row.created_at
115
- };
116
- }
117
- var LegacyEvalsMSSQL = class extends storage.LegacyEvalsStorage {
118
- pool;
119
- schema;
120
- constructor({ pool, schema }) {
121
- super();
122
- this.pool = pool;
123
- this.schema = schema;
124
- }
125
- /** @deprecated use getEvals instead */
126
- async getEvalsByAgentName(agentName, type) {
127
- try {
128
- let query = `SELECT * FROM ${getTableName({ indexName: storage.TABLE_EVALS, schemaName: getSchemaName(this.schema) })} WHERE agent_name = @p1`;
129
- if (type === "test") {
130
- query += " AND test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL";
131
- } else if (type === "live") {
132
- query += " AND (test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)";
133
- }
134
- query += " ORDER BY created_at DESC";
135
- const request = this.pool.request();
136
- request.input("p1", agentName);
137
- const result = await request.query(query);
138
- const rows = result.recordset;
139
- return typeof transformEvalRow === "function" ? rows?.map((row) => transformEvalRow(row)) ?? [] : rows ?? [];
140
- } catch (error) {
141
- if (error && error.number === 208 && error.message && error.message.includes("Invalid object name")) {
142
- return [];
143
- }
144
- this.logger?.error?.("Failed to get evals for the specified agent:", error);
145
- throw error;
146
- }
147
- }
148
- async getEvals(options = {}) {
149
- const { agentName, type, page = 0, perPage = 100, dateRange } = options;
150
- const fromDate = dateRange?.start;
151
- const toDate = dateRange?.end;
152
- const where = [];
153
- const params = {};
154
- if (agentName) {
155
- where.push("agent_name = @agentName");
156
- params["agentName"] = agentName;
157
- }
158
- if (type === "test") {
159
- where.push("test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL");
160
- } else if (type === "live") {
161
- where.push("(test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)");
162
- }
163
- if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
164
- where.push(`[created_at] >= @fromDate`);
165
- params[`fromDate`] = fromDate.toISOString();
166
- }
167
- if (toDate instanceof Date && !isNaN(toDate.getTime())) {
168
- where.push(`[created_at] <= @toDate`);
169
- params[`toDate`] = toDate.toISOString();
170
- }
171
- const whereClause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
172
- const tableName = getTableName({ indexName: storage.TABLE_EVALS, schemaName: getSchemaName(this.schema) });
173
- const offset = page * perPage;
174
- const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
175
- const dataQuery = `SELECT * FROM ${tableName} ${whereClause} ORDER BY seq_id DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
176
- try {
177
- const countReq = this.pool.request();
178
- Object.entries(params).forEach(([key, value]) => {
179
- if (value instanceof Date) {
180
- countReq.input(key, sql3__default.default.DateTime, value);
181
- } else {
182
- countReq.input(key, value);
183
- }
184
- });
185
- const countResult = await countReq.query(countQuery);
186
- const total = countResult.recordset[0]?.total || 0;
187
- if (total === 0) {
188
- return {
189
- evals: [],
190
- total: 0,
191
- page,
192
- perPage,
193
- hasMore: false
194
- };
195
- }
196
- const req = this.pool.request();
197
- Object.entries(params).forEach(([key, value]) => {
198
- if (value instanceof Date) {
199
- req.input(key, sql3__default.default.DateTime, value);
200
- } else {
201
- req.input(key, value);
202
- }
203
- });
204
- req.input("offset", offset);
205
- req.input("perPage", perPage);
206
- const result = await req.query(dataQuery);
207
- const rows = result.recordset;
208
- return {
209
- evals: rows?.map((row) => transformEvalRow(row)) ?? [],
210
- total,
211
- page,
212
- perPage,
213
- hasMore: offset + (rows?.length ?? 0) < total
214
- };
215
- } catch (error$1) {
216
- const mastraError = new error.MastraError(
217
- {
218
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_EVALS_FAILED",
219
- domain: error.ErrorDomain.STORAGE,
220
- category: error.ErrorCategory.THIRD_PARTY,
221
- details: {
222
- agentName: agentName || "all",
223
- type: type || "all",
224
- page,
225
- perPage
226
- }
227
- },
228
- error$1
229
- );
230
- this.logger?.error?.(mastraError.toString());
231
- this.logger?.trackException?.(mastraError);
232
- throw mastraError;
233
- }
234
- }
235
- };
89
+ // src/storage/domains/memory/index.ts
236
90
  var MemoryMSSQL = class extends storage.MemoryStorage {
237
91
  pool;
238
92
  schema;
@@ -250,7 +104,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
250
104
  });
251
105
  const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
252
106
  const list = new agent.MessageList().add(cleanMessages, "memory");
253
- return format === "v2" ? list.get.all.v2() : list.get.all.v1();
107
+ return format === "v2" ? list.get.all.db() : list.get.all.v1();
254
108
  }
255
109
  constructor({
256
110
  pool,
@@ -264,7 +118,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
264
118
  }
265
119
  async getThreadById({ threadId }) {
266
120
  try {
267
- const sql6 = `SELECT
121
+ const sql5 = `SELECT
268
122
  id,
269
123
  [resourceId],
270
124
  title,
@@ -275,7 +129,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
275
129
  WHERE id = @threadId`;
276
130
  const request = this.pool.request();
277
131
  request.input("threadId", threadId);
278
- const resultSet = await request.query(sql6);
132
+ const resultSet = await request.query(sql5);
279
133
  const thread = resultSet.recordset[0] || null;
280
134
  if (!thread) {
281
135
  return null;
@@ -300,11 +154,24 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
300
154
  );
301
155
  }
302
156
  }
303
- async getThreadsByResourceIdPaginated(args) {
304
- 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
+ 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
+ }
171
+ const perPage = storage.normalizePerPage(perPageInput, 100);
172
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
173
+ const { field, direction } = this.parseOrderBy(orderBy);
305
174
  try {
306
- const perPage = perPageInput !== void 0 ? perPageInput : 100;
307
- const currentOffset = page * perPage;
308
175
  const baseQuery = `FROM ${getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
309
176
  const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
310
177
  const countRequest = this.pool.request();
@@ -316,17 +183,22 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
316
183
  threads: [],
317
184
  total: 0,
318
185
  page,
319
- perPage,
186
+ perPage: perPageForResponse,
320
187
  hasMore: false
321
188
  };
322
189
  }
323
- const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
324
- const dir = (sortDirection || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
190
+ const orderByField = field === "createdAt" ? "[createdAt]" : "[updatedAt]";
191
+ const dir = (direction || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
192
+ const limitValue = perPageInput === false ? total : perPage;
325
193
  const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${dir} OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
326
194
  const dataRequest = this.pool.request();
327
195
  dataRequest.input("resourceId", resourceId);
328
- dataRequest.input("perPage", perPage);
329
- dataRequest.input("offset", currentOffset);
196
+ dataRequest.input("offset", offset);
197
+ if (limitValue > 2147483647) {
198
+ dataRequest.input("perPage", sql2__default.default.BigInt, limitValue);
199
+ } else {
200
+ dataRequest.input("perPage", limitValue);
201
+ }
330
202
  const rowsResult = await dataRequest.query(dataQuery);
331
203
  const rows = rowsResult.recordset || [];
332
204
  const threads = rows.map((thread) => ({
@@ -339,13 +211,13 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
339
211
  threads,
340
212
  total,
341
213
  page,
342
- perPage,
343
- hasMore: currentOffset + threads.length < total
214
+ perPage: perPageForResponse,
215
+ hasMore: perPageInput === false ? false : offset + perPage < total
344
216
  };
345
217
  } catch (error$1) {
346
218
  const mastraError = new error.MastraError(
347
219
  {
348
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
220
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
349
221
  domain: error.ErrorDomain.STORAGE,
350
222
  category: error.ErrorCategory.THIRD_PARTY,
351
223
  details: {
@@ -357,7 +229,13 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
357
229
  );
358
230
  this.logger?.error?.(mastraError.toString());
359
231
  this.logger?.trackException?.(mastraError);
360
- return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
232
+ return {
233
+ threads: [],
234
+ total: 0,
235
+ page,
236
+ perPage: perPageForResponse,
237
+ hasMore: false
238
+ };
361
239
  }
362
240
  }
363
241
  async saveThread({ thread }) {
@@ -381,12 +259,12 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
381
259
  req.input("title", thread.title);
382
260
  const metadata = thread.metadata ? JSON.stringify(thread.metadata) : null;
383
261
  if (metadata === null) {
384
- req.input("metadata", sql3__default.default.NVarChar, null);
262
+ req.input("metadata", sql2__default.default.NVarChar, null);
385
263
  } else {
386
264
  req.input("metadata", metadata);
387
265
  }
388
- req.input("createdAt", sql3__default.default.DateTime2, thread.createdAt);
389
- req.input("updatedAt", sql3__default.default.DateTime2, thread.updatedAt);
266
+ req.input("createdAt", sql2__default.default.DateTime2, thread.createdAt);
267
+ req.input("updatedAt", sql2__default.default.DateTime2, thread.updatedAt);
390
268
  await req.query(mergeSql);
391
269
  return thread;
392
270
  } catch (error$1) {
@@ -403,31 +281,6 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
403
281
  );
404
282
  }
405
283
  }
406
- /**
407
- * @deprecated use getThreadsByResourceIdPaginated instead
408
- */
409
- async getThreadsByResourceId(args) {
410
- const { resourceId, orderBy = "createdAt", sortDirection = "DESC" } = args;
411
- try {
412
- const baseQuery = `FROM ${getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
413
- const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
414
- const dir = (sortDirection || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
415
- const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${dir}`;
416
- const request = this.pool.request();
417
- request.input("resourceId", resourceId);
418
- const resultSet = await request.query(dataQuery);
419
- const rows = resultSet.recordset || [];
420
- return rows.map((thread) => ({
421
- ...thread,
422
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
423
- createdAt: thread.createdAt,
424
- updatedAt: thread.updatedAt
425
- }));
426
- } catch (error) {
427
- this.logger?.error?.(`Error getting threads for resource ${resourceId}:`, error);
428
- return [];
429
- }
430
- }
431
284
  /**
432
285
  * Updates a thread's title and metadata, merging with existing metadata. Returns the updated thread.
433
286
  */
@@ -455,7 +308,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
455
308
  };
456
309
  try {
457
310
  const table = getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) });
458
- const sql6 = `UPDATE ${table}
311
+ const sql5 = `UPDATE ${table}
459
312
  SET title = @title,
460
313
  metadata = @metadata,
461
314
  [updatedAt] = @updatedAt
@@ -466,7 +319,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
466
319
  req.input("title", title);
467
320
  req.input("metadata", JSON.stringify(mergedMetadata));
468
321
  req.input("updatedAt", /* @__PURE__ */ new Date());
469
- const result = await req.query(sql6);
322
+ const result = await req.query(sql5);
470
323
  let thread = result.recordset && result.recordset[0];
471
324
  if (thread && "seq_id" in thread) {
472
325
  const { seq_id, ...rest } = thread;
@@ -536,11 +389,9 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
536
389
  }
537
390
  async _getIncludedMessages({
538
391
  threadId,
539
- selectBy,
540
- orderByStatement
392
+ include
541
393
  }) {
542
394
  if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
543
- const include = selectBy?.include;
544
395
  if (!include) return null;
545
396
  const unionQueries = [];
546
397
  const paramValues = [];
@@ -565,7 +416,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
565
416
  m.[resourceId],
566
417
  m.seq_id
567
418
  FROM (
568
- SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
419
+ SELECT *, ROW_NUMBER() OVER (ORDER BY [createdAt] ASC) as row_num
569
420
  FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
570
421
  WHERE [thread_id] = ${pThreadId}
571
422
  ) AS m
@@ -573,15 +424,17 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
573
424
  OR EXISTS (
574
425
  SELECT 1
575
426
  FROM (
576
- SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
427
+ SELECT *, ROW_NUMBER() OVER (ORDER BY [createdAt] ASC) as row_num
577
428
  FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
578
429
  WHERE [thread_id] = ${pThreadId}
579
430
  ) AS target
580
431
  WHERE target.id = ${pId}
581
432
  AND (
582
- (m.row_num <= target.row_num + ${pPrev} AND m.row_num > target.row_num)
433
+ -- Get previous messages (messages that come BEFORE the target)
434
+ (m.row_num < target.row_num AND m.row_num >= target.row_num - ${pPrev})
583
435
  OR
584
- (m.row_num >= target.row_num - ${pNext} AND m.row_num < target.row_num)
436
+ -- Get next messages (messages that come AFTER the target)
437
+ (m.row_num > target.row_num AND m.row_num <= target.row_num + ${pNext})
585
438
  )
586
439
  )
587
440
  `
@@ -610,34 +463,16 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
610
463
  });
611
464
  return dedupedRows;
612
465
  }
613
- async getMessages(args) {
614
- const { threadId, resourceId, format, selectBy } = args;
466
+ async listMessagesById({ messageIds }) {
467
+ if (messageIds.length === 0) return { messages: [] };
615
468
  const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
616
469
  const orderByStatement = `ORDER BY [seq_id] DESC`;
617
- const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
618
470
  try {
619
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
620
471
  let rows = [];
621
- const include = selectBy?.include || [];
622
- if (include?.length) {
623
- const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
624
- if (includeMessages) {
625
- rows.push(...includeMessages);
626
- }
627
- }
628
- const excludeIds = rows.map((m) => m.id).filter(Boolean);
629
- let query = `${selectStatement} FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [thread_id] = @threadId`;
472
+ let query = `${selectStatement} FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [id] IN (${messageIds.map((_, i) => `@id${i}`).join(", ")})`;
630
473
  const request = this.pool.request();
631
- request.input("threadId", threadId);
632
- if (excludeIds.length > 0) {
633
- const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
634
- query += ` AND id NOT IN (${excludeParams.join(", ")})`;
635
- excludeIds.forEach((id, idx) => {
636
- request.input(`id${idx}`, id);
637
- });
638
- }
639
- query += ` ${orderByStatement} OFFSET 0 ROWS FETCH NEXT @limit ROWS ONLY`;
640
- request.input("limit", limit);
474
+ messageIds.forEach((id, i) => request.input(`id${i}`, id));
475
+ query += ` ${orderByStatement}`;
641
476
  const result = await request.query(query);
642
477
  const remainingRows = result.recordset || [];
643
478
  rows.push(...remainingRows);
@@ -645,153 +480,171 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
645
480
  const timeDiff = a.seq_id - b.seq_id;
646
481
  return timeDiff;
647
482
  });
648
- rows = rows.map(({ seq_id, ...rest }) => rest);
649
- return this._parseAndFormatMessages(rows, format);
483
+ const messagesWithParsedContent = rows.map((row) => {
484
+ if (typeof row.content === "string") {
485
+ try {
486
+ return { ...row, content: JSON.parse(row.content) };
487
+ } catch {
488
+ return row;
489
+ }
490
+ }
491
+ return row;
492
+ });
493
+ const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
494
+ const list = new agent.MessageList().add(cleanMessages, "memory");
495
+ return { messages: list.get.all.db() };
650
496
  } catch (error$1) {
651
497
  const mastraError = new error.MastraError(
652
498
  {
653
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_FAILED",
499
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_MESSAGES_BY_ID_FAILED",
654
500
  domain: error.ErrorDomain.STORAGE,
655
501
  category: error.ErrorCategory.THIRD_PARTY,
656
502
  details: {
657
- threadId,
658
- resourceId: resourceId ?? ""
503
+ messageIds: JSON.stringify(messageIds)
659
504
  }
660
505
  },
661
506
  error$1
662
507
  );
663
508
  this.logger?.error?.(mastraError.toString());
664
509
  this.logger?.trackException?.(mastraError);
665
- return [];
510
+ return { messages: [] };
666
511
  }
667
512
  }
668
- async getMessagesById({
669
- messageIds,
670
- format
671
- }) {
672
- if (messageIds.length === 0) return [];
673
- const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
674
- const orderByStatement = `ORDER BY [seq_id] DESC`;
675
- try {
676
- let rows = [];
677
- let query = `${selectStatement} FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [id] IN (${messageIds.map((_, i) => `@id${i}`).join(", ")})`;
678
- const request = this.pool.request();
679
- messageIds.forEach((id, i) => request.input(`id${i}`, id));
680
- query += ` ${orderByStatement}`;
681
- const result = await request.query(query);
682
- const remainingRows = result.recordset || [];
683
- rows.push(...remainingRows);
684
- rows.sort((a, b) => {
685
- const timeDiff = a.seq_id - b.seq_id;
686
- return timeDiff;
687
- });
688
- rows = rows.map(({ seq_id, ...rest }) => rest);
689
- if (format === `v1`) return this._parseAndFormatMessages(rows, format);
690
- return this._parseAndFormatMessages(rows, `v2`);
691
- } catch (error$1) {
692
- const mastraError = new error.MastraError(
513
+ async listMessages(args) {
514
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
515
+ if (!threadId.trim()) {
516
+ throw new error.MastraError(
693
517
  {
694
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_BY_ID_FAILED",
518
+ id: "STORAGE_MSSQL_LIST_MESSAGES_INVALID_THREAD_ID",
695
519
  domain: error.ErrorDomain.STORAGE,
696
520
  category: error.ErrorCategory.THIRD_PARTY,
697
- details: {
698
- messageIds: JSON.stringify(messageIds)
699
- }
521
+ details: { threadId }
700
522
  },
701
- error$1
523
+ new Error("threadId must be a non-empty string")
702
524
  );
703
- this.logger?.error?.(mastraError.toString());
704
- this.logger?.trackException?.(mastraError);
705
- return [];
706
525
  }
707
- }
708
- async getMessagesPaginated(args) {
709
- const { threadId, resourceId, format, selectBy } = args;
710
- const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
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
+ }
538
+ const perPage = storage.normalizePerPage(perPageInput, 40);
539
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
711
540
  try {
712
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
713
- const fromDate = dateRange?.start;
714
- const toDate = dateRange?.end;
715
- const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
716
- const orderByStatement = `ORDER BY [seq_id] DESC`;
717
- let messages = [];
718
- if (selectBy?.include?.length) {
719
- const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
720
- if (includeMessages) messages.push(...includeMessages);
721
- }
722
- const perPage = perPageInput !== void 0 ? perPageInput : storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
723
- const currentOffset = page * perPage;
724
- const conditions = ["[thread_id] = @threadId"];
725
- const request = this.pool.request();
726
- request.input("threadId", threadId);
727
- if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
728
- conditions.push("[createdAt] >= @fromDate");
729
- request.input("fromDate", fromDate.toISOString());
730
- }
731
- if (toDate instanceof Date && !isNaN(toDate.getTime())) {
732
- conditions.push("[createdAt] <= @toDate");
733
- request.input("toDate", toDate.toISOString());
734
- }
735
- const whereClause = `WHERE ${conditions.join(" AND ")}`;
736
- const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
737
- const countResult = await request.query(countQuery);
541
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
542
+ const orderByStatement = `ORDER BY [${field}] ${direction}, [seq_id] ${direction}`;
543
+ const tableName = getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
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}`);
738
558
  const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
739
- if (total === 0 && messages.length > 0) {
740
- const parsedIncluded = this._parseAndFormatMessages(messages, format);
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
+ });
579
+ if (total === 0 && messages.length === 0 && (!include || include.length === 0)) {
741
580
  return {
742
- messages: parsedIncluded,
743
- total: parsedIncluded.length,
581
+ messages: [],
582
+ total: 0,
744
583
  page,
745
- perPage,
584
+ perPage: perPageForResponse,
746
585
  hasMore: false
747
586
  };
748
587
  }
749
- const excludeIds = messages.map((m) => m.id);
750
- if (excludeIds.length > 0) {
751
- const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
752
- conditions.push(`id NOT IN (${excludeParams.join(", ")})`);
753
- excludeIds.forEach((id, idx) => request.input(`id${idx}`, id));
754
- }
755
- const finalWhereClause = `WHERE ${conditions.join(" AND ")}`;
756
- const dataQuery = `${selectStatement} FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${finalWhereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
757
- request.input("offset", currentOffset);
758
- request.input("limit", perPage);
759
- const rowsResult = await request.query(dataQuery);
760
- const rows = rowsResult.recordset || [];
761
- rows.sort((a, b) => a.seq_id - b.seq_id);
762
- messages.push(...rows);
763
- const parsed = this._parseAndFormatMessages(messages, format);
588
+ if (include?.length) {
589
+ const messageIds = new Set(messages.map((m) => m.id));
590
+ const includeMessages = await this._getIncludedMessages({ threadId, include });
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);
596
+ }
597
+ });
598
+ }
599
+ const parsed = this._parseAndFormatMessages(messages, "v2");
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);
612
+ });
613
+ const returnedThreadMessageCount = finalMessages.filter((m) => m.threadId === threadId).length;
614
+ const hasMore = perPageInput !== false && returnedThreadMessageCount < total && offset + perPage < total;
764
615
  return {
765
- messages: parsed,
616
+ messages: finalMessages,
766
617
  total,
767
618
  page,
768
- perPage,
769
- hasMore: currentOffset + rows.length < total
619
+ perPage: perPageForResponse,
620
+ hasMore
770
621
  };
771
622
  } catch (error$1) {
772
623
  const mastraError = new error.MastraError(
773
624
  {
774
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_PAGINATED_FAILED",
625
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_MESSAGES_FAILED",
775
626
  domain: error.ErrorDomain.STORAGE,
776
627
  category: error.ErrorCategory.THIRD_PARTY,
777
628
  details: {
778
629
  threadId,
779
- resourceId: resourceId ?? "",
780
- page
630
+ resourceId: resourceId ?? ""
781
631
  }
782
632
  },
783
633
  error$1
784
634
  );
785
635
  this.logger?.error?.(mastraError.toString());
786
636
  this.logger?.trackException?.(mastraError);
787
- return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
637
+ return {
638
+ messages: [],
639
+ total: 0,
640
+ page,
641
+ perPage: perPageForResponse,
642
+ hasMore: false
643
+ };
788
644
  }
789
645
  }
790
- async saveMessages({
791
- messages,
792
- format
793
- }) {
794
- if (messages.length === 0) return messages;
646
+ async saveMessages({ messages }) {
647
+ if (messages.length === 0) return { messages: [] };
795
648
  const threadId = messages[0]?.threadId;
796
649
  if (!threadId) {
797
650
  throw new error.MastraError({
@@ -835,7 +688,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
835
688
  "content",
836
689
  typeof message.content === "string" ? message.content : JSON.stringify(message.content)
837
690
  );
838
- request.input("createdAt", sql3__default.default.DateTime2, message.createdAt);
691
+ request.input("createdAt", sql2__default.default.DateTime2, message.createdAt);
839
692
  request.input("role", message.role);
840
693
  request.input("type", message.type || "v2");
841
694
  request.input("resourceId", message.resourceId);
@@ -854,7 +707,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
854
707
  await request.query(mergeSql);
855
708
  }
856
709
  const threadReq = transaction.request();
857
- threadReq.input("updatedAt", sql3__default.default.DateTime2, /* @__PURE__ */ new Date());
710
+ threadReq.input("updatedAt", sql2__default.default.DateTime2, /* @__PURE__ */ new Date());
858
711
  threadReq.input("id", threadId);
859
712
  await threadReq.query(`UPDATE ${tableThreads} SET [updatedAt] = @updatedAt WHERE id = @id`);
860
713
  await transaction.commit();
@@ -873,8 +726,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
873
726
  return message;
874
727
  });
875
728
  const list = new agent.MessageList().add(messagesWithParsedContent, "memory");
876
- if (format === "v2") return list.get.all.v2();
877
- return list.get.all.v1();
729
+ return { messages: list.get.all.db() };
878
730
  } catch (error$1) {
879
731
  throw new error.MastraError(
880
732
  {
@@ -1153,13 +1005,13 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1153
1005
  this.operations = operations;
1154
1006
  this.schema = schema;
1155
1007
  }
1156
- get aiTracingStrategy() {
1008
+ get tracingStrategy() {
1157
1009
  return {
1158
1010
  preferred: "batch-with-updates",
1159
1011
  supported: ["batch-with-updates", "insert-only"]
1160
1012
  };
1161
1013
  }
1162
- async createAISpan(span) {
1014
+ async createSpan(span) {
1163
1015
  try {
1164
1016
  const startedAt = span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt;
1165
1017
  const endedAt = span.endedAt instanceof Date ? span.endedAt.toISOString() : span.endedAt;
@@ -1169,11 +1021,11 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1169
1021
  endedAt
1170
1022
  // Note: createdAt/updatedAt will be set by default values
1171
1023
  };
1172
- return this.operations.insert({ tableName: storage.TABLE_AI_SPANS, record });
1024
+ return this.operations.insert({ tableName: storage.TABLE_SPANS, record });
1173
1025
  } catch (error$1) {
1174
1026
  throw new error.MastraError(
1175
1027
  {
1176
- id: "MSSQL_STORE_CREATE_AI_SPAN_FAILED",
1028
+ id: "MSSQL_STORE_CREATE_SPAN_FAILED",
1177
1029
  domain: error.ErrorDomain.STORAGE,
1178
1030
  category: error.ErrorCategory.USER,
1179
1031
  details: {
@@ -1187,10 +1039,10 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1187
1039
  );
1188
1040
  }
1189
1041
  }
1190
- async getAITrace(traceId) {
1042
+ async getTrace(traceId) {
1191
1043
  try {
1192
1044
  const tableName = getTableName({
1193
- indexName: storage.TABLE_AI_SPANS,
1045
+ indexName: storage.TABLE_SPANS,
1194
1046
  schemaName: getSchemaName(this.schema)
1195
1047
  });
1196
1048
  const request = this.pool.request();
@@ -1211,7 +1063,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1211
1063
  traceId,
1212
1064
  spans: result.recordset.map(
1213
1065
  (span) => transformFromSqlRow({
1214
- tableName: storage.TABLE_AI_SPANS,
1066
+ tableName: storage.TABLE_SPANS,
1215
1067
  sqlRow: span
1216
1068
  })
1217
1069
  )
@@ -1219,7 +1071,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1219
1071
  } catch (error$1) {
1220
1072
  throw new error.MastraError(
1221
1073
  {
1222
- id: "MSSQL_STORE_GET_AI_TRACE_FAILED",
1074
+ id: "MSSQL_STORE_GET_TRACE_FAILED",
1223
1075
  domain: error.ErrorDomain.STORAGE,
1224
1076
  category: error.ErrorCategory.USER,
1225
1077
  details: {
@@ -1230,7 +1082,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1230
1082
  );
1231
1083
  }
1232
1084
  }
1233
- async updateAISpan({
1085
+ async updateSpan({
1234
1086
  spanId,
1235
1087
  traceId,
1236
1088
  updates
@@ -1244,14 +1096,14 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1244
1096
  data.startedAt = data.startedAt.toISOString();
1245
1097
  }
1246
1098
  await this.operations.update({
1247
- tableName: storage.TABLE_AI_SPANS,
1099
+ tableName: storage.TABLE_SPANS,
1248
1100
  keys: { spanId, traceId },
1249
1101
  data
1250
1102
  });
1251
1103
  } catch (error$1) {
1252
1104
  throw new error.MastraError(
1253
1105
  {
1254
- id: "MSSQL_STORE_UPDATE_AI_SPAN_FAILED",
1106
+ id: "MSSQL_STORE_UPDATE_SPAN_FAILED",
1255
1107
  domain: error.ErrorDomain.STORAGE,
1256
1108
  category: error.ErrorCategory.USER,
1257
1109
  details: {
@@ -1263,7 +1115,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1263
1115
  );
1264
1116
  }
1265
1117
  }
1266
- async getAITracesPaginated({
1118
+ async getTracesPaginated({
1267
1119
  filters,
1268
1120
  pagination
1269
1121
  }) {
@@ -1288,7 +1140,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1288
1140
  name = `agent run: '${entityId}'`;
1289
1141
  } else {
1290
1142
  const error$1 = new error.MastraError({
1291
- id: "MSSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1143
+ id: "MSSQL_STORE_GET_TRACES_PAGINATED_FAILED",
1292
1144
  domain: error.ErrorDomain.STORAGE,
1293
1145
  category: error.ErrorCategory.USER,
1294
1146
  details: {
@@ -1307,7 +1159,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1307
1159
  params[entityParam] = name;
1308
1160
  }
1309
1161
  const tableName = getTableName({
1310
- indexName: storage.TABLE_AI_SPANS,
1162
+ indexName: storage.TABLE_SPANS,
1311
1163
  schemaName: getSchemaName(this.schema)
1312
1164
  });
1313
1165
  try {
@@ -1341,7 +1193,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1341
1193
  );
1342
1194
  const spans = dataResult.recordset.map(
1343
1195
  (row) => transformFromSqlRow({
1344
- tableName: storage.TABLE_AI_SPANS,
1196
+ tableName: storage.TABLE_SPANS,
1345
1197
  sqlRow: row
1346
1198
  })
1347
1199
  );
@@ -1357,7 +1209,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1357
1209
  } catch (error$1) {
1358
1210
  throw new error.MastraError(
1359
1211
  {
1360
- id: "MSSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1212
+ id: "MSSQL_STORE_GET_TRACES_PAGINATED_FAILED",
1361
1213
  domain: error.ErrorDomain.STORAGE,
1362
1214
  category: error.ErrorCategory.USER
1363
1215
  },
@@ -1365,13 +1217,13 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1365
1217
  );
1366
1218
  }
1367
1219
  }
1368
- async batchCreateAISpans(args) {
1220
+ async batchCreateSpans(args) {
1369
1221
  if (!args.records || args.records.length === 0) {
1370
1222
  return;
1371
1223
  }
1372
1224
  try {
1373
1225
  await this.operations.batchInsert({
1374
- tableName: storage.TABLE_AI_SPANS,
1226
+ tableName: storage.TABLE_SPANS,
1375
1227
  records: args.records.map((span) => ({
1376
1228
  ...span,
1377
1229
  startedAt: span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt,
@@ -1381,7 +1233,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1381
1233
  } catch (error$1) {
1382
1234
  throw new error.MastraError(
1383
1235
  {
1384
- id: "MSSQL_STORE_BATCH_CREATE_AI_SPANS_FAILED",
1236
+ id: "MSSQL_STORE_BATCH_CREATE_SPANS_FAILED",
1385
1237
  domain: error.ErrorDomain.STORAGE,
1386
1238
  category: error.ErrorCategory.USER,
1387
1239
  details: {
@@ -1392,7 +1244,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1392
1244
  );
1393
1245
  }
1394
1246
  }
1395
- async batchUpdateAISpans(args) {
1247
+ async batchUpdateSpans(args) {
1396
1248
  if (!args.records || args.records.length === 0) {
1397
1249
  return;
1398
1250
  }
@@ -1411,13 +1263,13 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1411
1263
  };
1412
1264
  });
1413
1265
  await this.operations.batchUpdate({
1414
- tableName: storage.TABLE_AI_SPANS,
1266
+ tableName: storage.TABLE_SPANS,
1415
1267
  updates
1416
1268
  });
1417
1269
  } catch (error$1) {
1418
1270
  throw new error.MastraError(
1419
1271
  {
1420
- id: "MSSQL_STORE_BATCH_UPDATE_AI_SPANS_FAILED",
1272
+ id: "MSSQL_STORE_BATCH_UPDATE_SPANS_FAILED",
1421
1273
  domain: error.ErrorDomain.STORAGE,
1422
1274
  category: error.ErrorCategory.USER,
1423
1275
  details: {
@@ -1428,20 +1280,20 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1428
1280
  );
1429
1281
  }
1430
1282
  }
1431
- async batchDeleteAITraces(args) {
1283
+ async batchDeleteTraces(args) {
1432
1284
  if (!args.traceIds || args.traceIds.length === 0) {
1433
1285
  return;
1434
1286
  }
1435
1287
  try {
1436
1288
  const keys = args.traceIds.map((traceId) => ({ traceId }));
1437
1289
  await this.operations.batchDelete({
1438
- tableName: storage.TABLE_AI_SPANS,
1290
+ tableName: storage.TABLE_SPANS,
1439
1291
  keys
1440
1292
  });
1441
1293
  } catch (error$1) {
1442
1294
  throw new error.MastraError(
1443
1295
  {
1444
- id: "MSSQL_STORE_BATCH_DELETE_AI_TRACES_FAILED",
1296
+ id: "MSSQL_STORE_BATCH_DELETE_TRACES_FAILED",
1445
1297
  domain: error.ErrorDomain.STORAGE,
1446
1298
  category: error.ErrorCategory.USER,
1447
1299
  details: {
@@ -1556,7 +1408,7 @@ var StoreOperationsMSSQL = class extends storage.StoreOperations {
1556
1408
  const value = record[col];
1557
1409
  const preparedValue = this.prepareValue(value, col, tableName);
1558
1410
  if (preparedValue instanceof Date) {
1559
- request.input(`param${i}`, sql3__default.default.DateTime2, preparedValue);
1411
+ request.input(`param${i}`, sql2__default.default.DateTime2, preparedValue);
1560
1412
  } else if (preparedValue === null || preparedValue === void 0) {
1561
1413
  request.input(`param${i}`, this.getMssqlType(tableName, col), null);
1562
1414
  } else {
@@ -1771,7 +1623,7 @@ ${columns}
1771
1623
  try {
1772
1624
  const keyEntries = Object.entries(keys).map(([key, value]) => [utils.parseSqlIdentifier(key, "column name"), value]);
1773
1625
  const conditions = keyEntries.map(([key], i) => `[${key}] = @param${i}`).join(" AND ");
1774
- const sql6 = `SELECT * FROM ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} WHERE ${conditions}`;
1626
+ const sql5 = `SELECT * FROM ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} WHERE ${conditions}`;
1775
1627
  const request = this.pool.request();
1776
1628
  keyEntries.forEach(([key, value], i) => {
1777
1629
  const preparedValue = this.prepareValue(value, key, tableName);
@@ -1781,7 +1633,7 @@ ${columns}
1781
1633
  request.input(`param${i}`, preparedValue);
1782
1634
  }
1783
1635
  });
1784
- const resultSet = await request.query(sql6);
1636
+ const resultSet = await request.query(sql5);
1785
1637
  const result = resultSet.recordset[0] || null;
1786
1638
  if (!result) {
1787
1639
  return null;
@@ -1866,6 +1718,20 @@ ${columns}
1866
1718
  return value ? 1 : 0;
1867
1719
  }
1868
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
+ }
1869
1735
  return JSON.stringify(value);
1870
1736
  }
1871
1737
  if (typeof value === "object") {
@@ -1880,23 +1746,23 @@ ${columns}
1880
1746
  const col = storage.TABLE_SCHEMAS[tableName]?.[columnName];
1881
1747
  switch (col?.type) {
1882
1748
  case "text":
1883
- return sql3__default.default.NVarChar;
1749
+ return sql2__default.default.NVarChar;
1884
1750
  case "timestamp":
1885
- return sql3__default.default.DateTime2;
1751
+ return sql2__default.default.DateTime2;
1886
1752
  case "uuid":
1887
- return sql3__default.default.UniqueIdentifier;
1753
+ return sql2__default.default.UniqueIdentifier;
1888
1754
  case "jsonb":
1889
- return sql3__default.default.NVarChar;
1755
+ return sql2__default.default.NVarChar;
1890
1756
  case "integer":
1891
- return sql3__default.default.Int;
1757
+ return sql2__default.default.Int;
1892
1758
  case "bigint":
1893
- return sql3__default.default.BigInt;
1759
+ return sql2__default.default.BigInt;
1894
1760
  case "float":
1895
- return sql3__default.default.Float;
1761
+ return sql2__default.default.Float;
1896
1762
  case "boolean":
1897
- return sql3__default.default.Bit;
1763
+ return sql2__default.default.Bit;
1898
1764
  default:
1899
- return sql3__default.default.NVarChar;
1765
+ return sql2__default.default.NVarChar;
1900
1766
  }
1901
1767
  }
1902
1768
  /**
@@ -2340,35 +2206,30 @@ ${columns}
2340
2206
  table: storage.TABLE_TRACES,
2341
2207
  columns: ["name", "seq_id DESC"]
2342
2208
  },
2343
- {
2344
- name: `${schemaPrefix}mastra_evals_agent_name_seqid_idx`,
2345
- table: storage.TABLE_EVALS,
2346
- columns: ["agent_name", "seq_id DESC"]
2347
- },
2348
2209
  {
2349
2210
  name: `${schemaPrefix}mastra_scores_trace_id_span_id_seqid_idx`,
2350
2211
  table: storage.TABLE_SCORERS,
2351
2212
  columns: ["traceId", "spanId", "seq_id DESC"]
2352
2213
  },
2353
- // AI Spans indexes for optimal trace querying
2214
+ // Spans indexes for optimal trace querying
2354
2215
  {
2355
2216
  name: `${schemaPrefix}mastra_ai_spans_traceid_startedat_idx`,
2356
- table: storage.TABLE_AI_SPANS,
2217
+ table: storage.TABLE_SPANS,
2357
2218
  columns: ["traceId", "startedAt DESC"]
2358
2219
  },
2359
2220
  {
2360
2221
  name: `${schemaPrefix}mastra_ai_spans_parentspanid_startedat_idx`,
2361
- table: storage.TABLE_AI_SPANS,
2222
+ table: storage.TABLE_SPANS,
2362
2223
  columns: ["parentSpanId", "startedAt DESC"]
2363
2224
  },
2364
2225
  {
2365
2226
  name: `${schemaPrefix}mastra_ai_spans_name_idx`,
2366
- table: storage.TABLE_AI_SPANS,
2227
+ table: storage.TABLE_SPANS,
2367
2228
  columns: ["name"]
2368
2229
  },
2369
2230
  {
2370
2231
  name: `${schemaPrefix}mastra_ai_spans_spantype_startedat_idx`,
2371
- table: storage.TABLE_AI_SPANS,
2232
+ table: storage.TABLE_SPANS,
2372
2233
  columns: ["spanType", "startedAt DESC"]
2373
2234
  }
2374
2235
  ];
@@ -2409,7 +2270,7 @@ function transformScoreRow(row) {
2409
2270
  metadata: storage.safelyParseJSON(row.metadata),
2410
2271
  output: storage.safelyParseJSON(row.output),
2411
2272
  additionalContext: storage.safelyParseJSON(row.additionalContext),
2412
- runtimeContext: storage.safelyParseJSON(row.runtimeContext),
2273
+ requestContext: storage.safelyParseJSON(row.requestContext),
2413
2274
  entity: storage.safelyParseJSON(row.entity),
2414
2275
  createdAt: row.createdAt,
2415
2276
  updatedAt: row.updatedAt
@@ -2455,7 +2316,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2455
2316
  async saveScore(score) {
2456
2317
  let validatedScore;
2457
2318
  try {
2458
- validatedScore = scores.saveScorePayloadSchema.parse(score);
2319
+ validatedScore = evals.saveScorePayloadSchema.parse(score);
2459
2320
  } catch (error$1) {
2460
2321
  throw new error.MastraError(
2461
2322
  {
@@ -2476,7 +2337,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2476
2337
  input,
2477
2338
  output,
2478
2339
  additionalContext,
2479
- runtimeContext,
2340
+ requestContext,
2480
2341
  entity,
2481
2342
  ...rest
2482
2343
  } = validatedScore;
@@ -2491,7 +2352,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2491
2352
  analyzeStepResult: analyzeStepResult || null,
2492
2353
  metadata: metadata || null,
2493
2354
  additionalContext: additionalContext || null,
2494
- runtimeContext: runtimeContext || null,
2355
+ requestContext: requestContext || null,
2495
2356
  entity: entity || null,
2496
2357
  scorer: scorer || null,
2497
2358
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -2511,7 +2372,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2511
2372
  );
2512
2373
  }
2513
2374
  }
2514
- async getScoresByScorerId({
2375
+ async listScoresByScorerId({
2515
2376
  scorerId,
2516
2377
  pagination,
2517
2378
  entityId,
@@ -2545,31 +2406,36 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2545
2406
  });
2546
2407
  const totalResult = await countRequest.query(`SELECT COUNT(*) as count FROM ${tableName} WHERE ${whereClause}`);
2547
2408
  const total = totalResult.recordset[0]?.count || 0;
2409
+ const { page, perPage: perPageInput } = pagination;
2548
2410
  if (total === 0) {
2549
2411
  return {
2550
2412
  pagination: {
2551
2413
  total: 0,
2552
- page: pagination.page,
2553
- perPage: pagination.perPage,
2414
+ page,
2415
+ perPage: perPageInput,
2554
2416
  hasMore: false
2555
2417
  },
2556
2418
  scores: []
2557
2419
  };
2558
2420
  }
2421
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2422
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2423
+ const limitValue = perPageInput === false ? total : perPage;
2424
+ const end = perPageInput === false ? total : start + perPage;
2559
2425
  const dataRequest = this.pool.request();
2560
2426
  Object.entries(params).forEach(([key, value]) => {
2561
2427
  dataRequest.input(key, value);
2562
2428
  });
2563
- dataRequest.input("perPage", pagination.perPage);
2564
- dataRequest.input("offset", pagination.page * pagination.perPage);
2429
+ dataRequest.input("perPage", limitValue);
2430
+ dataRequest.input("offset", start);
2565
2431
  const dataQuery = `SELECT * FROM ${tableName} WHERE ${whereClause} ORDER BY [createdAt] DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
2566
2432
  const result = await dataRequest.query(dataQuery);
2567
2433
  return {
2568
2434
  pagination: {
2569
2435
  total: Number(total),
2570
- page: pagination.page,
2571
- perPage: pagination.perPage,
2572
- hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2436
+ page,
2437
+ perPage: perPageForResponse,
2438
+ hasMore: end < total
2573
2439
  },
2574
2440
  scores: result.recordset.map((row) => transformScoreRow(row))
2575
2441
  };
@@ -2585,7 +2451,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2585
2451
  );
2586
2452
  }
2587
2453
  }
2588
- async getScoresByRunId({
2454
+ async listScoresByRunId({
2589
2455
  runId,
2590
2456
  pagination
2591
2457
  }) {
@@ -2596,30 +2462,35 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2596
2462
  `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [runId] = @p1`
2597
2463
  );
2598
2464
  const total = totalResult.recordset[0]?.count || 0;
2465
+ const { page, perPage: perPageInput } = pagination;
2599
2466
  if (total === 0) {
2600
2467
  return {
2601
2468
  pagination: {
2602
2469
  total: 0,
2603
- page: pagination.page,
2604
- perPage: pagination.perPage,
2470
+ page,
2471
+ perPage: perPageInput,
2605
2472
  hasMore: false
2606
2473
  },
2607
2474
  scores: []
2608
2475
  };
2609
2476
  }
2477
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2478
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2479
+ const limitValue = perPageInput === false ? total : perPage;
2480
+ const end = perPageInput === false ? total : start + perPage;
2610
2481
  const dataRequest = this.pool.request();
2611
2482
  dataRequest.input("p1", runId);
2612
- dataRequest.input("p2", pagination.perPage);
2613
- dataRequest.input("p3", pagination.page * pagination.perPage);
2483
+ dataRequest.input("p2", limitValue);
2484
+ dataRequest.input("p3", start);
2614
2485
  const result = await dataRequest.query(
2615
2486
  `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`
2616
2487
  );
2617
2488
  return {
2618
2489
  pagination: {
2619
2490
  total: Number(total),
2620
- page: pagination.page,
2621
- perPage: pagination.perPage,
2622
- hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2491
+ page,
2492
+ perPage: perPageForResponse,
2493
+ hasMore: end < total
2623
2494
  },
2624
2495
  scores: result.recordset.map((row) => transformScoreRow(row))
2625
2496
  };
@@ -2635,7 +2506,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2635
2506
  );
2636
2507
  }
2637
2508
  }
2638
- async getScoresByEntityId({
2509
+ async listScoresByEntityId({
2639
2510
  entityId,
2640
2511
  entityType,
2641
2512
  pagination
@@ -2648,31 +2519,36 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2648
2519
  `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [entityId] = @p1 AND [entityType] = @p2`
2649
2520
  );
2650
2521
  const total = totalResult.recordset[0]?.count || 0;
2522
+ const { page, perPage: perPageInput } = pagination;
2523
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2524
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2651
2525
  if (total === 0) {
2652
2526
  return {
2653
2527
  pagination: {
2654
2528
  total: 0,
2655
- page: pagination.page,
2656
- perPage: pagination.perPage,
2529
+ page,
2530
+ perPage: perPageForResponse,
2657
2531
  hasMore: false
2658
2532
  },
2659
2533
  scores: []
2660
2534
  };
2661
2535
  }
2536
+ const limitValue = perPageInput === false ? total : perPage;
2537
+ const end = perPageInput === false ? total : start + perPage;
2662
2538
  const dataRequest = this.pool.request();
2663
2539
  dataRequest.input("p1", entityId);
2664
2540
  dataRequest.input("p2", entityType);
2665
- dataRequest.input("p3", pagination.perPage);
2666
- dataRequest.input("p4", pagination.page * pagination.perPage);
2541
+ dataRequest.input("p3", limitValue);
2542
+ dataRequest.input("p4", start);
2667
2543
  const result = await dataRequest.query(
2668
2544
  `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`
2669
2545
  );
2670
2546
  return {
2671
2547
  pagination: {
2672
2548
  total: Number(total),
2673
- page: pagination.page,
2674
- perPage: pagination.perPage,
2675
- hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2549
+ page,
2550
+ perPage: perPageForResponse,
2551
+ hasMore: end < total
2676
2552
  },
2677
2553
  scores: result.recordset.map((row) => transformScoreRow(row))
2678
2554
  };
@@ -2688,7 +2564,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2688
2564
  );
2689
2565
  }
2690
2566
  }
2691
- async getScoresBySpan({
2567
+ async listScoresBySpan({
2692
2568
  traceId,
2693
2569
  spanId,
2694
2570
  pagination
@@ -2701,34 +2577,38 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2701
2577
  `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [traceId] = @p1 AND [spanId] = @p2`
2702
2578
  );
2703
2579
  const total = totalResult.recordset[0]?.count || 0;
2580
+ const { page, perPage: perPageInput } = pagination;
2581
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2582
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2704
2583
  if (total === 0) {
2705
2584
  return {
2706
2585
  pagination: {
2707
2586
  total: 0,
2708
- page: pagination.page,
2709
- perPage: pagination.perPage,
2587
+ page,
2588
+ perPage: perPageForResponse,
2710
2589
  hasMore: false
2711
2590
  },
2712
2591
  scores: []
2713
2592
  };
2714
2593
  }
2715
- const limit = pagination.perPage + 1;
2594
+ const limitValue = perPageInput === false ? total : perPage;
2595
+ const end = perPageInput === false ? total : start + perPage;
2716
2596
  const dataRequest = this.pool.request();
2717
2597
  dataRequest.input("p1", traceId);
2718
2598
  dataRequest.input("p2", spanId);
2719
- dataRequest.input("p3", limit);
2720
- dataRequest.input("p4", pagination.page * pagination.perPage);
2599
+ dataRequest.input("p3", limitValue);
2600
+ dataRequest.input("p4", start);
2721
2601
  const result = await dataRequest.query(
2722
2602
  `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`
2723
2603
  );
2724
2604
  return {
2725
2605
  pagination: {
2726
2606
  total: Number(total),
2727
- page: pagination.page,
2728
- perPage: pagination.perPage,
2729
- hasMore: result.recordset.length > pagination.perPage
2607
+ page,
2608
+ perPage: perPageForResponse,
2609
+ hasMore: end < total
2730
2610
  },
2731
- scores: result.recordset.slice(0, pagination.perPage).map((row) => transformScoreRow(row))
2611
+ scores: result.recordset.map((row) => transformScoreRow(row))
2732
2612
  };
2733
2613
  } catch (error$1) {
2734
2614
  throw new error.MastraError(
@@ -2780,13 +2660,13 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2780
2660
  runId,
2781
2661
  stepId,
2782
2662
  result,
2783
- runtimeContext
2663
+ requestContext
2784
2664
  }) {
2785
2665
  const table = getTableName({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
2786
2666
  const transaction = this.pool.transaction();
2787
2667
  try {
2788
2668
  await transaction.begin();
2789
- const selectRequest = new sql3__default.default.Request(transaction);
2669
+ const selectRequest = new sql2__default.default.Request(transaction);
2790
2670
  selectRequest.input("workflow_name", workflowName);
2791
2671
  selectRequest.input("run_id", runId);
2792
2672
  const existingSnapshotResult = await selectRequest.query(
@@ -2797,28 +2677,29 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2797
2677
  snapshot = {
2798
2678
  context: {},
2799
2679
  activePaths: [],
2680
+ activeStepsPath: {},
2800
2681
  timestamp: Date.now(),
2801
2682
  suspendedPaths: {},
2802
2683
  resumeLabels: {},
2803
2684
  serializedStepGraph: [],
2685
+ status: "pending",
2804
2686
  value: {},
2805
2687
  waitingPaths: {},
2806
- status: "pending",
2807
2688
  runId,
2808
- runtimeContext: {}
2689
+ requestContext: {}
2809
2690
  };
2810
2691
  } else {
2811
2692
  const existingSnapshot = existingSnapshotResult.recordset[0].snapshot;
2812
2693
  snapshot = typeof existingSnapshot === "string" ? JSON.parse(existingSnapshot) : existingSnapshot;
2813
2694
  }
2814
2695
  snapshot.context[stepId] = result;
2815
- snapshot.runtimeContext = { ...snapshot.runtimeContext, ...runtimeContext };
2816
- const upsertReq = new sql3__default.default.Request(transaction);
2696
+ snapshot.requestContext = { ...snapshot.requestContext, ...requestContext };
2697
+ const upsertReq = new sql2__default.default.Request(transaction);
2817
2698
  upsertReq.input("workflow_name", workflowName);
2818
2699
  upsertReq.input("run_id", runId);
2819
2700
  upsertReq.input("snapshot", JSON.stringify(snapshot));
2820
- upsertReq.input("createdAt", sql3__default.default.DateTime2, /* @__PURE__ */ new Date());
2821
- upsertReq.input("updatedAt", sql3__default.default.DateTime2, /* @__PURE__ */ new Date());
2701
+ upsertReq.input("createdAt", sql2__default.default.DateTime2, /* @__PURE__ */ new Date());
2702
+ upsertReq.input("updatedAt", sql2__default.default.DateTime2, /* @__PURE__ */ new Date());
2822
2703
  await upsertReq.query(
2823
2704
  `MERGE ${table} AS target
2824
2705
  USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
@@ -2858,7 +2739,7 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2858
2739
  const transaction = this.pool.transaction();
2859
2740
  try {
2860
2741
  await transaction.begin();
2861
- const selectRequest = new sql3__default.default.Request(transaction);
2742
+ const selectRequest = new sql2__default.default.Request(transaction);
2862
2743
  selectRequest.input("workflow_name", workflowName);
2863
2744
  selectRequest.input("run_id", runId);
2864
2745
  const existingSnapshotResult = await selectRequest.query(
@@ -2886,11 +2767,11 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2886
2767
  );
2887
2768
  }
2888
2769
  const updatedSnapshot = { ...snapshot, ...opts };
2889
- const updateRequest = new sql3__default.default.Request(transaction);
2770
+ const updateRequest = new sql2__default.default.Request(transaction);
2890
2771
  updateRequest.input("snapshot", JSON.stringify(updatedSnapshot));
2891
2772
  updateRequest.input("workflow_name", workflowName);
2892
2773
  updateRequest.input("run_id", runId);
2893
- updateRequest.input("updatedAt", sql3__default.default.DateTime2, /* @__PURE__ */ new Date());
2774
+ updateRequest.input("updatedAt", sql2__default.default.DateTime2, /* @__PURE__ */ new Date());
2894
2775
  await updateRequest.query(
2895
2776
  `UPDATE ${table} SET snapshot = @snapshot, [updatedAt] = @updatedAt WHERE workflow_name = @workflow_name AND run_id = @run_id`
2896
2777
  );
@@ -2929,8 +2810,8 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2929
2810
  request.input("run_id", runId);
2930
2811
  request.input("resourceId", resourceId);
2931
2812
  request.input("snapshot", JSON.stringify(snapshot));
2932
- request.input("createdAt", sql3__default.default.DateTime2, new Date(now));
2933
- request.input("updatedAt", sql3__default.default.DateTime2, new Date(now));
2813
+ request.input("createdAt", sql2__default.default.DateTime2, new Date(now));
2814
+ request.input("updatedAt", sql2__default.default.DateTime2, new Date(now));
2934
2815
  const mergeSql = `MERGE INTO ${table} AS target
2935
2816
  USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
2936
2817
  ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
@@ -3027,13 +2908,14 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
3027
2908
  );
3028
2909
  }
3029
2910
  }
3030
- async getWorkflowRuns({
2911
+ async listWorkflowRuns({
3031
2912
  workflowName,
3032
2913
  fromDate,
3033
2914
  toDate,
3034
- limit,
3035
- offset,
3036
- resourceId
2915
+ page,
2916
+ perPage,
2917
+ resourceId,
2918
+ status
3037
2919
  } = {}) {
3038
2920
  try {
3039
2921
  const conditions = [];
@@ -3042,6 +2924,10 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
3042
2924
  conditions.push(`[workflow_name] = @workflowName`);
3043
2925
  paramMap["workflowName"] = workflowName;
3044
2926
  }
2927
+ if (status) {
2928
+ conditions.push(`JSON_VALUE([snapshot], '$.status') = @status`);
2929
+ paramMap["status"] = status;
2930
+ }
3045
2931
  if (resourceId) {
3046
2932
  const hasResourceId = await this.operations.hasColumn(storage.TABLE_WORKFLOW_SNAPSHOT, "resourceId");
3047
2933
  if (hasResourceId) {
@@ -3065,20 +2951,23 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
3065
2951
  const request = this.pool.request();
3066
2952
  Object.entries(paramMap).forEach(([key, value]) => {
3067
2953
  if (value instanceof Date) {
3068
- request.input(key, sql3__default.default.DateTime, value);
2954
+ request.input(key, sql2__default.default.DateTime, value);
3069
2955
  } else {
3070
2956
  request.input(key, value);
3071
2957
  }
3072
2958
  });
3073
- if (limit !== void 0 && offset !== void 0) {
2959
+ const usePagination = typeof perPage === "number" && typeof page === "number";
2960
+ if (usePagination) {
3074
2961
  const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
3075
2962
  const countResult = await request.query(countQuery);
3076
2963
  total = Number(countResult.recordset[0]?.count || 0);
3077
2964
  }
3078
2965
  let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
3079
- if (limit !== void 0 && offset !== void 0) {
3080
- query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
3081
- request.input("limit", limit);
2966
+ if (usePagination) {
2967
+ const normalizedPerPage = storage.normalizePerPage(perPage, Number.MAX_SAFE_INTEGER);
2968
+ const offset = page * normalizedPerPage;
2969
+ query += ` OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
2970
+ request.input("perPage", normalizedPerPage);
3082
2971
  request.input("offset", offset);
3083
2972
  }
3084
2973
  const result = await request.query(query);
@@ -3087,7 +2976,7 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
3087
2976
  } catch (error$1) {
3088
2977
  throw new error.MastraError(
3089
2978
  {
3090
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
2979
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_WORKFLOW_RUNS_FAILED",
3091
2980
  domain: error.ErrorDomain.STORAGE,
3092
2981
  category: error.ErrorCategory.THIRD_PARTY,
3093
2982
  details: {
@@ -3107,7 +2996,10 @@ var MSSQLStore = class extends storage.MastraStorage {
3107
2996
  isConnected = null;
3108
2997
  stores;
3109
2998
  constructor(config) {
3110
- 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" });
3111
3003
  try {
3112
3004
  if ("connectionString" in config) {
3113
3005
  if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") {
@@ -3122,7 +3014,7 @@ var MSSQLStore = class extends storage.MastraStorage {
3122
3014
  }
3123
3015
  }
3124
3016
  this.schema = config.schemaName || "dbo";
3125
- this.pool = "connectionString" in config ? new sql3__default.default.ConnectionPool(config.connectionString) : new sql3__default.default.ConnectionPool({
3017
+ this.pool = "connectionString" in config ? new sql2__default.default.ConnectionPool(config.connectionString) : new sql2__default.default.ConnectionPool({
3126
3018
  server: config.server,
3127
3019
  database: config.database,
3128
3020
  user: config.user,
@@ -3130,7 +3022,6 @@ var MSSQLStore = class extends storage.MastraStorage {
3130
3022
  port: config.port,
3131
3023
  options: config.options || { encrypt: true, trustServerCertificate: true }
3132
3024
  });
3133
- const legacyEvals = new LegacyEvalsMSSQL({ pool: this.pool, schema: this.schema });
3134
3025
  const operations = new StoreOperationsMSSQL({ pool: this.pool, schemaName: this.schema });
3135
3026
  const scores = new ScoresMSSQL({ pool: this.pool, operations, schema: this.schema });
3136
3027
  const workflows = new WorkflowsMSSQL({ pool: this.pool, operations, schema: this.schema });
@@ -3140,7 +3031,6 @@ var MSSQLStore = class extends storage.MastraStorage {
3140
3031
  operations,
3141
3032
  scores,
3142
3033
  workflows,
3143
- legacyEvals,
3144
3034
  memory,
3145
3035
  observability
3146
3036
  };
@@ -3194,18 +3084,11 @@ var MSSQLStore = class extends storage.MastraStorage {
3194
3084
  hasColumn: true,
3195
3085
  createTable: true,
3196
3086
  deleteMessages: true,
3197
- getScoresBySpan: true,
3198
- aiTracing: true,
3087
+ listScoresBySpan: true,
3088
+ observabilityInstance: true,
3199
3089
  indexManagement: true
3200
3090
  };
3201
3091
  }
3202
- /** @deprecated use getEvals instead */
3203
- async getEvalsByAgentName(agentName, type) {
3204
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
3205
- }
3206
- async getEvals(options = {}) {
3207
- return this.stores.legacyEvals.getEvals(options);
3208
- }
3209
3092
  async createTable({
3210
3093
  tableName,
3211
3094
  schema
@@ -3240,15 +3123,6 @@ var MSSQLStore = class extends storage.MastraStorage {
3240
3123
  async getThreadById({ threadId }) {
3241
3124
  return this.stores.memory.getThreadById({ threadId });
3242
3125
  }
3243
- /**
3244
- * @deprecated use getThreadsByResourceIdPaginated instead
3245
- */
3246
- async getThreadsByResourceId(args) {
3247
- return this.stores.memory.getThreadsByResourceId(args);
3248
- }
3249
- async getThreadsByResourceIdPaginated(args) {
3250
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
3251
- }
3252
3126
  async saveThread({ thread }) {
3253
3127
  return this.stores.memory.saveThread({ thread });
3254
3128
  }
@@ -3262,17 +3136,8 @@ var MSSQLStore = class extends storage.MastraStorage {
3262
3136
  async deleteThread({ threadId }) {
3263
3137
  return this.stores.memory.deleteThread({ threadId });
3264
3138
  }
3265
- async getMessages(args) {
3266
- return this.stores.memory.getMessages(args);
3267
- }
3268
- async getMessagesById({
3269
- messageIds,
3270
- format
3271
- }) {
3272
- return this.stores.memory.getMessagesById({ messageIds, format });
3273
- }
3274
- async getMessagesPaginated(args) {
3275
- return this.stores.memory.getMessagesPaginated(args);
3139
+ async listMessagesById({ messageIds }) {
3140
+ return this.stores.memory.listMessagesById({ messageIds });
3276
3141
  }
3277
3142
  async saveMessages(args) {
3278
3143
  return this.stores.memory.saveMessages(args);
@@ -3306,9 +3171,9 @@ var MSSQLStore = class extends storage.MastraStorage {
3306
3171
  runId,
3307
3172
  stepId,
3308
3173
  result,
3309
- runtimeContext
3174
+ requestContext
3310
3175
  }) {
3311
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
3176
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
3312
3177
  }
3313
3178
  async updateWorkflowState({
3314
3179
  workflowName,
@@ -3331,15 +3196,8 @@ var MSSQLStore = class extends storage.MastraStorage {
3331
3196
  }) {
3332
3197
  return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
3333
3198
  }
3334
- async getWorkflowRuns({
3335
- workflowName,
3336
- fromDate,
3337
- toDate,
3338
- limit,
3339
- offset,
3340
- resourceId
3341
- } = {}) {
3342
- return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
3199
+ async listWorkflowRuns(args = {}) {
3200
+ return this.stores.workflows.listWorkflowRuns(args);
3343
3201
  }
3344
3202
  async getWorkflowRunById({
3345
3203
  runId,
@@ -3366,7 +3224,7 @@ var MSSQLStore = class extends storage.MastraStorage {
3366
3224
  return this.stores.operations.dropIndex(indexName);
3367
3225
  }
3368
3226
  /**
3369
- * AI Tracing / Observability
3227
+ * Tracing / Observability
3370
3228
  */
3371
3229
  getObservabilityStore() {
3372
3230
  if (!this.stores.observability) {
@@ -3379,30 +3237,30 @@ var MSSQLStore = class extends storage.MastraStorage {
3379
3237
  }
3380
3238
  return this.stores.observability;
3381
3239
  }
3382
- async createAISpan(span) {
3383
- return this.getObservabilityStore().createAISpan(span);
3240
+ async createSpan(span) {
3241
+ return this.getObservabilityStore().createSpan(span);
3384
3242
  }
3385
- async updateAISpan({
3243
+ async updateSpan({
3386
3244
  spanId,
3387
3245
  traceId,
3388
3246
  updates
3389
3247
  }) {
3390
- return this.getObservabilityStore().updateAISpan({ spanId, traceId, updates });
3248
+ return this.getObservabilityStore().updateSpan({ spanId, traceId, updates });
3391
3249
  }
3392
- async getAITrace(traceId) {
3393
- return this.getObservabilityStore().getAITrace(traceId);
3250
+ async getTrace(traceId) {
3251
+ return this.getObservabilityStore().getTrace(traceId);
3394
3252
  }
3395
- async getAITracesPaginated(args) {
3396
- return this.getObservabilityStore().getAITracesPaginated(args);
3253
+ async getTracesPaginated(args) {
3254
+ return this.getObservabilityStore().getTracesPaginated(args);
3397
3255
  }
3398
- async batchCreateAISpans(args) {
3399
- return this.getObservabilityStore().batchCreateAISpans(args);
3256
+ async batchCreateSpans(args) {
3257
+ return this.getObservabilityStore().batchCreateSpans(args);
3400
3258
  }
3401
- async batchUpdateAISpans(args) {
3402
- return this.getObservabilityStore().batchUpdateAISpans(args);
3259
+ async batchUpdateSpans(args) {
3260
+ return this.getObservabilityStore().batchUpdateSpans(args);
3403
3261
  }
3404
- async batchDeleteAITraces(args) {
3405
- return this.getObservabilityStore().batchDeleteAITraces(args);
3262
+ async batchDeleteTraces(args) {
3263
+ return this.getObservabilityStore().batchDeleteTraces(args);
3406
3264
  }
3407
3265
  /**
3408
3266
  * Scorers
@@ -3410,14 +3268,14 @@ var MSSQLStore = class extends storage.MastraStorage {
3410
3268
  async getScoreById({ id: _id }) {
3411
3269
  return this.stores.scores.getScoreById({ id: _id });
3412
3270
  }
3413
- async getScoresByScorerId({
3271
+ async listScoresByScorerId({
3414
3272
  scorerId: _scorerId,
3415
3273
  pagination: _pagination,
3416
3274
  entityId: _entityId,
3417
3275
  entityType: _entityType,
3418
3276
  source: _source
3419
3277
  }) {
3420
- return this.stores.scores.getScoresByScorerId({
3278
+ return this.stores.scores.listScoresByScorerId({
3421
3279
  scorerId: _scorerId,
3422
3280
  pagination: _pagination,
3423
3281
  entityId: _entityId,
@@ -3428,29 +3286,29 @@ var MSSQLStore = class extends storage.MastraStorage {
3428
3286
  async saveScore(_score) {
3429
3287
  return this.stores.scores.saveScore(_score);
3430
3288
  }
3431
- async getScoresByRunId({
3289
+ async listScoresByRunId({
3432
3290
  runId: _runId,
3433
3291
  pagination: _pagination
3434
3292
  }) {
3435
- return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
3293
+ return this.stores.scores.listScoresByRunId({ runId: _runId, pagination: _pagination });
3436
3294
  }
3437
- async getScoresByEntityId({
3295
+ async listScoresByEntityId({
3438
3296
  entityId: _entityId,
3439
3297
  entityType: _entityType,
3440
3298
  pagination: _pagination
3441
3299
  }) {
3442
- return this.stores.scores.getScoresByEntityId({
3300
+ return this.stores.scores.listScoresByEntityId({
3443
3301
  entityId: _entityId,
3444
3302
  entityType: _entityType,
3445
3303
  pagination: _pagination
3446
3304
  });
3447
3305
  }
3448
- async getScoresBySpan({
3306
+ async listScoresBySpan({
3449
3307
  traceId,
3450
3308
  spanId,
3451
3309
  pagination: _pagination
3452
3310
  }) {
3453
- return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination: _pagination });
3311
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination: _pagination });
3454
3312
  }
3455
3313
  };
3456
3314