@mastra/mssql 0.5.1 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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 sql7 = `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(sql7);
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 sql7 = `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(sql7);
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 sql7 = `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(sql7);
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(
@@ -2743,173 +2623,6 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2743
2623
  }
2744
2624
  }
2745
2625
  };
2746
- var TracesMSSQL = class extends storage.TracesStorage {
2747
- pool;
2748
- operations;
2749
- schema;
2750
- constructor({
2751
- pool,
2752
- operations,
2753
- schema
2754
- }) {
2755
- super();
2756
- this.pool = pool;
2757
- this.operations = operations;
2758
- this.schema = schema;
2759
- }
2760
- /** @deprecated use getTracesPaginated instead*/
2761
- async getTraces(args) {
2762
- if (args.fromDate || args.toDate) {
2763
- args.dateRange = {
2764
- start: args.fromDate,
2765
- end: args.toDate
2766
- };
2767
- }
2768
- const result = await this.getTracesPaginated(args);
2769
- return result.traces;
2770
- }
2771
- async getTracesPaginated(args) {
2772
- const { name, scope, page = 0, perPage: perPageInput, attributes, filters, dateRange } = args;
2773
- const fromDate = dateRange?.start;
2774
- const toDate = dateRange?.end;
2775
- const perPage = perPageInput !== void 0 ? perPageInput : 100;
2776
- const currentOffset = page * perPage;
2777
- const paramMap = {};
2778
- const conditions = [];
2779
- let paramIndex = 1;
2780
- if (name) {
2781
- const paramName = `p${paramIndex++}`;
2782
- conditions.push(`[name] LIKE @${paramName}`);
2783
- paramMap[paramName] = `${name}%`;
2784
- }
2785
- if (scope) {
2786
- const paramName = `p${paramIndex++}`;
2787
- conditions.push(`[scope] = @${paramName}`);
2788
- paramMap[paramName] = scope;
2789
- }
2790
- if (attributes) {
2791
- Object.entries(attributes).forEach(([key, value]) => {
2792
- const parsedKey = utils.parseFieldKey(key);
2793
- const paramName = `p${paramIndex++}`;
2794
- conditions.push(`JSON_VALUE([attributes], '$.${parsedKey}') = @${paramName}`);
2795
- paramMap[paramName] = value;
2796
- });
2797
- }
2798
- if (filters) {
2799
- Object.entries(filters).forEach(([key, value]) => {
2800
- const parsedKey = utils.parseFieldKey(key);
2801
- const paramName = `p${paramIndex++}`;
2802
- conditions.push(`[${parsedKey}] = @${paramName}`);
2803
- paramMap[paramName] = value;
2804
- });
2805
- }
2806
- if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
2807
- const paramName = `p${paramIndex++}`;
2808
- conditions.push(`[createdAt] >= @${paramName}`);
2809
- paramMap[paramName] = fromDate.toISOString();
2810
- }
2811
- if (toDate instanceof Date && !isNaN(toDate.getTime())) {
2812
- const paramName = `p${paramIndex++}`;
2813
- conditions.push(`[createdAt] <= @${paramName}`);
2814
- paramMap[paramName] = toDate.toISOString();
2815
- }
2816
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2817
- const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: storage.TABLE_TRACES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
2818
- let total = 0;
2819
- try {
2820
- const countRequest = this.pool.request();
2821
- Object.entries(paramMap).forEach(([key, value]) => {
2822
- if (value instanceof Date) {
2823
- countRequest.input(key, sql3__default.default.DateTime, value);
2824
- } else {
2825
- countRequest.input(key, value);
2826
- }
2827
- });
2828
- const countResult = await countRequest.query(countQuery);
2829
- total = parseInt(countResult.recordset[0].total, 10);
2830
- } catch (error$1) {
2831
- throw new error.MastraError(
2832
- {
2833
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TOTAL_COUNT",
2834
- domain: error.ErrorDomain.STORAGE,
2835
- category: error.ErrorCategory.THIRD_PARTY,
2836
- details: {
2837
- name: args.name ?? "",
2838
- scope: args.scope ?? ""
2839
- }
2840
- },
2841
- error$1
2842
- );
2843
- }
2844
- if (total === 0) {
2845
- return {
2846
- traces: [],
2847
- total: 0,
2848
- page,
2849
- perPage,
2850
- hasMore: false
2851
- };
2852
- }
2853
- const dataQuery = `SELECT * FROM ${getTableName({ indexName: storage.TABLE_TRACES, schemaName: getSchemaName(this.schema) })} ${whereClause} ORDER BY [seq_id] DESC OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
2854
- const dataRequest = this.pool.request();
2855
- Object.entries(paramMap).forEach(([key, value]) => {
2856
- if (value instanceof Date) {
2857
- dataRequest.input(key, sql3__default.default.DateTime, value);
2858
- } else {
2859
- dataRequest.input(key, value);
2860
- }
2861
- });
2862
- dataRequest.input("offset", currentOffset);
2863
- dataRequest.input("limit", perPage);
2864
- try {
2865
- const rowsResult = await dataRequest.query(dataQuery);
2866
- const rows = rowsResult.recordset;
2867
- const traces = rows.map((row) => ({
2868
- id: row.id,
2869
- parentSpanId: row.parentSpanId,
2870
- traceId: row.traceId,
2871
- name: row.name,
2872
- scope: row.scope,
2873
- kind: row.kind,
2874
- status: JSON.parse(row.status),
2875
- events: JSON.parse(row.events),
2876
- links: JSON.parse(row.links),
2877
- attributes: JSON.parse(row.attributes),
2878
- startTime: row.startTime,
2879
- endTime: row.endTime,
2880
- other: row.other,
2881
- createdAt: row.createdAt
2882
- }));
2883
- return {
2884
- traces,
2885
- total,
2886
- page,
2887
- perPage,
2888
- hasMore: currentOffset + traces.length < total
2889
- };
2890
- } catch (error$1) {
2891
- throw new error.MastraError(
2892
- {
2893
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TRACES",
2894
- domain: error.ErrorDomain.STORAGE,
2895
- category: error.ErrorCategory.THIRD_PARTY,
2896
- details: {
2897
- name: args.name ?? "",
2898
- scope: args.scope ?? ""
2899
- }
2900
- },
2901
- error$1
2902
- );
2903
- }
2904
- }
2905
- async batchTraceInsert({ records }) {
2906
- this.logger.debug("Batch inserting traces", { count: records.length });
2907
- await this.operations.batchInsert({
2908
- tableName: storage.TABLE_TRACES,
2909
- records
2910
- });
2911
- }
2912
- };
2913
2626
  var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2914
2627
  pool;
2915
2628
  operations;
@@ -2947,13 +2660,13 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2947
2660
  runId,
2948
2661
  stepId,
2949
2662
  result,
2950
- runtimeContext
2663
+ requestContext
2951
2664
  }) {
2952
2665
  const table = getTableName({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
2953
2666
  const transaction = this.pool.transaction();
2954
2667
  try {
2955
2668
  await transaction.begin();
2956
- const selectRequest = new sql3__default.default.Request(transaction);
2669
+ const selectRequest = new sql2__default.default.Request(transaction);
2957
2670
  selectRequest.input("workflow_name", workflowName);
2958
2671
  selectRequest.input("run_id", runId);
2959
2672
  const existingSnapshotResult = await selectRequest.query(
@@ -2972,20 +2685,20 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2972
2685
  waitingPaths: {},
2973
2686
  status: "pending",
2974
2687
  runId,
2975
- runtimeContext: {}
2688
+ requestContext: {}
2976
2689
  };
2977
2690
  } else {
2978
2691
  const existingSnapshot = existingSnapshotResult.recordset[0].snapshot;
2979
2692
  snapshot = typeof existingSnapshot === "string" ? JSON.parse(existingSnapshot) : existingSnapshot;
2980
2693
  }
2981
2694
  snapshot.context[stepId] = result;
2982
- snapshot.runtimeContext = { ...snapshot.runtimeContext, ...runtimeContext };
2983
- const upsertReq = new sql3__default.default.Request(transaction);
2695
+ snapshot.requestContext = { ...snapshot.requestContext, ...requestContext };
2696
+ const upsertReq = new sql2__default.default.Request(transaction);
2984
2697
  upsertReq.input("workflow_name", workflowName);
2985
2698
  upsertReq.input("run_id", runId);
2986
2699
  upsertReq.input("snapshot", JSON.stringify(snapshot));
2987
- upsertReq.input("createdAt", sql3__default.default.DateTime2, /* @__PURE__ */ new Date());
2988
- upsertReq.input("updatedAt", sql3__default.default.DateTime2, /* @__PURE__ */ new Date());
2700
+ upsertReq.input("createdAt", sql2__default.default.DateTime2, /* @__PURE__ */ new Date());
2701
+ upsertReq.input("updatedAt", sql2__default.default.DateTime2, /* @__PURE__ */ new Date());
2989
2702
  await upsertReq.query(
2990
2703
  `MERGE ${table} AS target
2991
2704
  USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
@@ -3025,7 +2738,7 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
3025
2738
  const transaction = this.pool.transaction();
3026
2739
  try {
3027
2740
  await transaction.begin();
3028
- const selectRequest = new sql3__default.default.Request(transaction);
2741
+ const selectRequest = new sql2__default.default.Request(transaction);
3029
2742
  selectRequest.input("workflow_name", workflowName);
3030
2743
  selectRequest.input("run_id", runId);
3031
2744
  const existingSnapshotResult = await selectRequest.query(
@@ -3053,11 +2766,11 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
3053
2766
  );
3054
2767
  }
3055
2768
  const updatedSnapshot = { ...snapshot, ...opts };
3056
- const updateRequest = new sql3__default.default.Request(transaction);
2769
+ const updateRequest = new sql2__default.default.Request(transaction);
3057
2770
  updateRequest.input("snapshot", JSON.stringify(updatedSnapshot));
3058
2771
  updateRequest.input("workflow_name", workflowName);
3059
2772
  updateRequest.input("run_id", runId);
3060
- updateRequest.input("updatedAt", sql3__default.default.DateTime2, /* @__PURE__ */ new Date());
2773
+ updateRequest.input("updatedAt", sql2__default.default.DateTime2, /* @__PURE__ */ new Date());
3061
2774
  await updateRequest.query(
3062
2775
  `UPDATE ${table} SET snapshot = @snapshot, [updatedAt] = @updatedAt WHERE workflow_name = @workflow_name AND run_id = @run_id`
3063
2776
  );
@@ -3096,8 +2809,8 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
3096
2809
  request.input("run_id", runId);
3097
2810
  request.input("resourceId", resourceId);
3098
2811
  request.input("snapshot", JSON.stringify(snapshot));
3099
- request.input("createdAt", sql3__default.default.DateTime2, new Date(now));
3100
- request.input("updatedAt", sql3__default.default.DateTime2, new Date(now));
2812
+ request.input("createdAt", sql2__default.default.DateTime2, new Date(now));
2813
+ request.input("updatedAt", sql2__default.default.DateTime2, new Date(now));
3101
2814
  const mergeSql = `MERGE INTO ${table} AS target
3102
2815
  USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
3103
2816
  ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
@@ -3194,12 +2907,12 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
3194
2907
  );
3195
2908
  }
3196
2909
  }
3197
- async getWorkflowRuns({
2910
+ async listWorkflowRuns({
3198
2911
  workflowName,
3199
2912
  fromDate,
3200
2913
  toDate,
3201
- limit,
3202
- offset,
2914
+ page,
2915
+ perPage,
3203
2916
  resourceId
3204
2917
  } = {}) {
3205
2918
  try {
@@ -3232,20 +2945,23 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
3232
2945
  const request = this.pool.request();
3233
2946
  Object.entries(paramMap).forEach(([key, value]) => {
3234
2947
  if (value instanceof Date) {
3235
- request.input(key, sql3__default.default.DateTime, value);
2948
+ request.input(key, sql2__default.default.DateTime, value);
3236
2949
  } else {
3237
2950
  request.input(key, value);
3238
2951
  }
3239
2952
  });
3240
- if (limit !== void 0 && offset !== void 0) {
2953
+ const usePagination = typeof perPage === "number" && typeof page === "number";
2954
+ if (usePagination) {
3241
2955
  const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
3242
2956
  const countResult = await request.query(countQuery);
3243
2957
  total = Number(countResult.recordset[0]?.count || 0);
3244
2958
  }
3245
2959
  let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
3246
- if (limit !== void 0 && offset !== void 0) {
3247
- query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
3248
- request.input("limit", limit);
2960
+ if (usePagination) {
2961
+ const normalizedPerPage = storage.normalizePerPage(perPage, Number.MAX_SAFE_INTEGER);
2962
+ const offset = page * normalizedPerPage;
2963
+ query += ` OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
2964
+ request.input("perPage", normalizedPerPage);
3249
2965
  request.input("offset", offset);
3250
2966
  }
3251
2967
  const result = await request.query(query);
@@ -3254,7 +2970,7 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
3254
2970
  } catch (error$1) {
3255
2971
  throw new error.MastraError(
3256
2972
  {
3257
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
2973
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_WORKFLOW_RUNS_FAILED",
3258
2974
  domain: error.ErrorDomain.STORAGE,
3259
2975
  category: error.ErrorCategory.THIRD_PARTY,
3260
2976
  details: {
@@ -3274,7 +2990,10 @@ var MSSQLStore = class extends storage.MastraStorage {
3274
2990
  isConnected = null;
3275
2991
  stores;
3276
2992
  constructor(config) {
3277
- super({ name: "MSSQLStore" });
2993
+ if (!config.id || typeof config.id !== "string" || config.id.trim() === "") {
2994
+ throw new Error("MSSQLStore: id must be provided and cannot be empty.");
2995
+ }
2996
+ super({ id: config.id, name: "MSSQLStore" });
3278
2997
  try {
3279
2998
  if ("connectionString" in config) {
3280
2999
  if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") {
@@ -3289,7 +3008,7 @@ var MSSQLStore = class extends storage.MastraStorage {
3289
3008
  }
3290
3009
  }
3291
3010
  this.schema = config.schemaName || "dbo";
3292
- this.pool = "connectionString" in config ? new sql3__default.default.ConnectionPool(config.connectionString) : new sql3__default.default.ConnectionPool({
3011
+ this.pool = "connectionString" in config ? new sql2__default.default.ConnectionPool(config.connectionString) : new sql2__default.default.ConnectionPool({
3293
3012
  server: config.server,
3294
3013
  database: config.database,
3295
3014
  user: config.user,
@@ -3297,19 +3016,15 @@ var MSSQLStore = class extends storage.MastraStorage {
3297
3016
  port: config.port,
3298
3017
  options: config.options || { encrypt: true, trustServerCertificate: true }
3299
3018
  });
3300
- const legacyEvals = new LegacyEvalsMSSQL({ pool: this.pool, schema: this.schema });
3301
3019
  const operations = new StoreOperationsMSSQL({ pool: this.pool, schemaName: this.schema });
3302
3020
  const scores = new ScoresMSSQL({ pool: this.pool, operations, schema: this.schema });
3303
- const traces = new TracesMSSQL({ pool: this.pool, operations, schema: this.schema });
3304
3021
  const workflows = new WorkflowsMSSQL({ pool: this.pool, operations, schema: this.schema });
3305
3022
  const memory = new MemoryMSSQL({ pool: this.pool, schema: this.schema, operations });
3306
3023
  const observability = new ObservabilityMSSQL({ pool: this.pool, operations, schema: this.schema });
3307
3024
  this.stores = {
3308
3025
  operations,
3309
3026
  scores,
3310
- traces,
3311
3027
  workflows,
3312
- legacyEvals,
3313
3028
  memory,
3314
3029
  observability
3315
3030
  };
@@ -3363,30 +3078,11 @@ var MSSQLStore = class extends storage.MastraStorage {
3363
3078
  hasColumn: true,
3364
3079
  createTable: true,
3365
3080
  deleteMessages: true,
3366
- getScoresBySpan: true,
3367
- aiTracing: true,
3081
+ listScoresBySpan: true,
3082
+ observabilityInstance: true,
3368
3083
  indexManagement: true
3369
3084
  };
3370
3085
  }
3371
- /** @deprecated use getEvals instead */
3372
- async getEvalsByAgentName(agentName, type) {
3373
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
3374
- }
3375
- async getEvals(options = {}) {
3376
- return this.stores.legacyEvals.getEvals(options);
3377
- }
3378
- /**
3379
- * @deprecated use getTracesPaginated instead
3380
- */
3381
- async getTraces(args) {
3382
- return this.stores.traces.getTraces(args);
3383
- }
3384
- async getTracesPaginated(args) {
3385
- return this.stores.traces.getTracesPaginated(args);
3386
- }
3387
- async batchTraceInsert({ records }) {
3388
- return this.stores.traces.batchTraceInsert({ records });
3389
- }
3390
3086
  async createTable({
3391
3087
  tableName,
3392
3088
  schema
@@ -3421,15 +3117,6 @@ var MSSQLStore = class extends storage.MastraStorage {
3421
3117
  async getThreadById({ threadId }) {
3422
3118
  return this.stores.memory.getThreadById({ threadId });
3423
3119
  }
3424
- /**
3425
- * @deprecated use getThreadsByResourceIdPaginated instead
3426
- */
3427
- async getThreadsByResourceId(args) {
3428
- return this.stores.memory.getThreadsByResourceId(args);
3429
- }
3430
- async getThreadsByResourceIdPaginated(args) {
3431
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
3432
- }
3433
3120
  async saveThread({ thread }) {
3434
3121
  return this.stores.memory.saveThread({ thread });
3435
3122
  }
@@ -3443,17 +3130,8 @@ var MSSQLStore = class extends storage.MastraStorage {
3443
3130
  async deleteThread({ threadId }) {
3444
3131
  return this.stores.memory.deleteThread({ threadId });
3445
3132
  }
3446
- async getMessages(args) {
3447
- return this.stores.memory.getMessages(args);
3448
- }
3449
- async getMessagesById({
3450
- messageIds,
3451
- format
3452
- }) {
3453
- return this.stores.memory.getMessagesById({ messageIds, format });
3454
- }
3455
- async getMessagesPaginated(args) {
3456
- return this.stores.memory.getMessagesPaginated(args);
3133
+ async listMessagesById({ messageIds }) {
3134
+ return this.stores.memory.listMessagesById({ messageIds });
3457
3135
  }
3458
3136
  async saveMessages(args) {
3459
3137
  return this.stores.memory.saveMessages(args);
@@ -3487,9 +3165,9 @@ var MSSQLStore = class extends storage.MastraStorage {
3487
3165
  runId,
3488
3166
  stepId,
3489
3167
  result,
3490
- runtimeContext
3168
+ requestContext
3491
3169
  }) {
3492
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
3170
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
3493
3171
  }
3494
3172
  async updateWorkflowState({
3495
3173
  workflowName,
@@ -3512,15 +3190,15 @@ var MSSQLStore = class extends storage.MastraStorage {
3512
3190
  }) {
3513
3191
  return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
3514
3192
  }
3515
- async getWorkflowRuns({
3193
+ async listWorkflowRuns({
3516
3194
  workflowName,
3517
3195
  fromDate,
3518
3196
  toDate,
3519
- limit,
3520
- offset,
3197
+ perPage,
3198
+ page,
3521
3199
  resourceId
3522
3200
  } = {}) {
3523
- return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
3201
+ return this.stores.workflows.listWorkflowRuns({ workflowName, fromDate, toDate, perPage, page, resourceId });
3524
3202
  }
3525
3203
  async getWorkflowRunById({
3526
3204
  runId,
@@ -3547,7 +3225,7 @@ var MSSQLStore = class extends storage.MastraStorage {
3547
3225
  return this.stores.operations.dropIndex(indexName);
3548
3226
  }
3549
3227
  /**
3550
- * AI Tracing / Observability
3228
+ * Tracing / Observability
3551
3229
  */
3552
3230
  getObservabilityStore() {
3553
3231
  if (!this.stores.observability) {
@@ -3560,30 +3238,30 @@ var MSSQLStore = class extends storage.MastraStorage {
3560
3238
  }
3561
3239
  return this.stores.observability;
3562
3240
  }
3563
- async createAISpan(span) {
3564
- return this.getObservabilityStore().createAISpan(span);
3241
+ async createSpan(span) {
3242
+ return this.getObservabilityStore().createSpan(span);
3565
3243
  }
3566
- async updateAISpan({
3244
+ async updateSpan({
3567
3245
  spanId,
3568
3246
  traceId,
3569
3247
  updates
3570
3248
  }) {
3571
- return this.getObservabilityStore().updateAISpan({ spanId, traceId, updates });
3249
+ return this.getObservabilityStore().updateSpan({ spanId, traceId, updates });
3572
3250
  }
3573
- async getAITrace(traceId) {
3574
- return this.getObservabilityStore().getAITrace(traceId);
3251
+ async getTrace(traceId) {
3252
+ return this.getObservabilityStore().getTrace(traceId);
3575
3253
  }
3576
- async getAITracesPaginated(args) {
3577
- return this.getObservabilityStore().getAITracesPaginated(args);
3254
+ async getTracesPaginated(args) {
3255
+ return this.getObservabilityStore().getTracesPaginated(args);
3578
3256
  }
3579
- async batchCreateAISpans(args) {
3580
- return this.getObservabilityStore().batchCreateAISpans(args);
3257
+ async batchCreateSpans(args) {
3258
+ return this.getObservabilityStore().batchCreateSpans(args);
3581
3259
  }
3582
- async batchUpdateAISpans(args) {
3583
- return this.getObservabilityStore().batchUpdateAISpans(args);
3260
+ async batchUpdateSpans(args) {
3261
+ return this.getObservabilityStore().batchUpdateSpans(args);
3584
3262
  }
3585
- async batchDeleteAITraces(args) {
3586
- return this.getObservabilityStore().batchDeleteAITraces(args);
3263
+ async batchDeleteTraces(args) {
3264
+ return this.getObservabilityStore().batchDeleteTraces(args);
3587
3265
  }
3588
3266
  /**
3589
3267
  * Scorers
@@ -3591,14 +3269,14 @@ var MSSQLStore = class extends storage.MastraStorage {
3591
3269
  async getScoreById({ id: _id }) {
3592
3270
  return this.stores.scores.getScoreById({ id: _id });
3593
3271
  }
3594
- async getScoresByScorerId({
3272
+ async listScoresByScorerId({
3595
3273
  scorerId: _scorerId,
3596
3274
  pagination: _pagination,
3597
3275
  entityId: _entityId,
3598
3276
  entityType: _entityType,
3599
3277
  source: _source
3600
3278
  }) {
3601
- return this.stores.scores.getScoresByScorerId({
3279
+ return this.stores.scores.listScoresByScorerId({
3602
3280
  scorerId: _scorerId,
3603
3281
  pagination: _pagination,
3604
3282
  entityId: _entityId,
@@ -3609,29 +3287,29 @@ var MSSQLStore = class extends storage.MastraStorage {
3609
3287
  async saveScore(_score) {
3610
3288
  return this.stores.scores.saveScore(_score);
3611
3289
  }
3612
- async getScoresByRunId({
3290
+ async listScoresByRunId({
3613
3291
  runId: _runId,
3614
3292
  pagination: _pagination
3615
3293
  }) {
3616
- return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
3294
+ return this.stores.scores.listScoresByRunId({ runId: _runId, pagination: _pagination });
3617
3295
  }
3618
- async getScoresByEntityId({
3296
+ async listScoresByEntityId({
3619
3297
  entityId: _entityId,
3620
3298
  entityType: _entityType,
3621
3299
  pagination: _pagination
3622
3300
  }) {
3623
- return this.stores.scores.getScoresByEntityId({
3301
+ return this.stores.scores.listScoresByEntityId({
3624
3302
  entityId: _entityId,
3625
3303
  entityType: _entityType,
3626
3304
  pagination: _pagination
3627
3305
  });
3628
3306
  }
3629
- async getScoresBySpan({
3307
+ async listScoresBySpan({
3630
3308
  traceId,
3631
3309
  spanId,
3632
3310
  pagination: _pagination
3633
3311
  }) {
3634
- return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination: _pagination });
3312
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination: _pagination });
3635
3313
  }
3636
3314
  };
3637
3315