@mastra/mssql 0.0.0-netlify-no-bundle-20251127120354 → 0.0.0-partial-response-backport-20251204204441

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 sql2 = require('mssql');
6
- var agent = require('@mastra/core/agent');
5
+ var sql3 = require('mssql');
7
6
  var utils = require('@mastra/core/utils');
7
+ var agent = require('@mastra/core/agent');
8
8
  var crypto = require('crypto');
9
- var evals = require('@mastra/core/evals');
9
+ var scores = require('@mastra/core/scores');
10
10
 
11
11
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
12
 
13
- var sql2__default = /*#__PURE__*/_interopDefault(sql2);
13
+ var sql3__default = /*#__PURE__*/_interopDefault(sql3);
14
14
 
15
15
  // src/storage/index.ts
16
16
  function getSchemaName(schema) {
@@ -86,7 +86,153 @@ function transformFromSqlRow({
86
86
  return result;
87
87
  }
88
88
 
89
- // src/storage/domains/memory/index.ts
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
+ };
90
236
  var MemoryMSSQL = class extends storage.MemoryStorage {
91
237
  pool;
92
238
  schema;
@@ -104,7 +250,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
104
250
  });
105
251
  const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
106
252
  const list = new agent.MessageList().add(cleanMessages, "memory");
107
- return format === "v2" ? list.get.all.db() : list.get.all.v1();
253
+ return format === "v2" ? list.get.all.v2() : list.get.all.v1();
108
254
  }
109
255
  constructor({
110
256
  pool,
@@ -118,7 +264,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
118
264
  }
119
265
  async getThreadById({ threadId }) {
120
266
  try {
121
- const sql5 = `SELECT
267
+ const sql7 = `SELECT
122
268
  id,
123
269
  [resourceId],
124
270
  title,
@@ -129,7 +275,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
129
275
  WHERE id = @threadId`;
130
276
  const request = this.pool.request();
131
277
  request.input("threadId", threadId);
132
- const resultSet = await request.query(sql5);
278
+ const resultSet = await request.query(sql7);
133
279
  const thread = resultSet.recordset[0] || null;
134
280
  if (!thread) {
135
281
  return null;
@@ -154,24 +300,11 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
154
300
  );
155
301
  }
156
302
  }
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);
303
+ async getThreadsByResourceIdPaginated(args) {
304
+ const { resourceId, page = 0, perPage: perPageInput, orderBy = "createdAt", sortDirection = "DESC" } = args;
174
305
  try {
306
+ const perPage = perPageInput !== void 0 ? perPageInput : 100;
307
+ const currentOffset = page * perPage;
175
308
  const baseQuery = `FROM ${getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
176
309
  const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
177
310
  const countRequest = this.pool.request();
@@ -183,22 +316,17 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
183
316
  threads: [],
184
317
  total: 0,
185
318
  page,
186
- perPage: perPageForResponse,
319
+ perPage,
187
320
  hasMore: false
188
321
  };
189
322
  }
190
- const orderByField = field === "createdAt" ? "[createdAt]" : "[updatedAt]";
191
- const dir = (direction || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
192
- const limitValue = perPageInput === false ? total : perPage;
323
+ const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
324
+ const dir = (sortDirection || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
193
325
  const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${dir} OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
194
326
  const dataRequest = this.pool.request();
195
327
  dataRequest.input("resourceId", resourceId);
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
- }
328
+ dataRequest.input("perPage", perPage);
329
+ dataRequest.input("offset", currentOffset);
202
330
  const rowsResult = await dataRequest.query(dataQuery);
203
331
  const rows = rowsResult.recordset || [];
204
332
  const threads = rows.map((thread) => ({
@@ -211,13 +339,13 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
211
339
  threads,
212
340
  total,
213
341
  page,
214
- perPage: perPageForResponse,
215
- hasMore: perPageInput === false ? false : offset + perPage < total
342
+ perPage,
343
+ hasMore: currentOffset + threads.length < total
216
344
  };
217
345
  } catch (error$1) {
218
346
  const mastraError = new error.MastraError(
219
347
  {
220
- id: "MASTRA_STORAGE_MSSQL_STORE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
348
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
221
349
  domain: error.ErrorDomain.STORAGE,
222
350
  category: error.ErrorCategory.THIRD_PARTY,
223
351
  details: {
@@ -229,13 +357,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
229
357
  );
230
358
  this.logger?.error?.(mastraError.toString());
231
359
  this.logger?.trackException?.(mastraError);
232
- return {
233
- threads: [],
234
- total: 0,
235
- page,
236
- perPage: perPageForResponse,
237
- hasMore: false
238
- };
360
+ return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
239
361
  }
240
362
  }
241
363
  async saveThread({ thread }) {
@@ -259,12 +381,12 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
259
381
  req.input("title", thread.title);
260
382
  const metadata = thread.metadata ? JSON.stringify(thread.metadata) : null;
261
383
  if (metadata === null) {
262
- req.input("metadata", sql2__default.default.NVarChar, null);
384
+ req.input("metadata", sql3__default.default.NVarChar, null);
263
385
  } else {
264
386
  req.input("metadata", metadata);
265
387
  }
266
- req.input("createdAt", sql2__default.default.DateTime2, thread.createdAt);
267
- req.input("updatedAt", sql2__default.default.DateTime2, thread.updatedAt);
388
+ req.input("createdAt", sql3__default.default.DateTime2, thread.createdAt);
389
+ req.input("updatedAt", sql3__default.default.DateTime2, thread.updatedAt);
268
390
  await req.query(mergeSql);
269
391
  return thread;
270
392
  } catch (error$1) {
@@ -281,6 +403,31 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
281
403
  );
282
404
  }
283
405
  }
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
+ }
284
431
  /**
285
432
  * Updates a thread's title and metadata, merging with existing metadata. Returns the updated thread.
286
433
  */
@@ -308,7 +455,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
308
455
  };
309
456
  try {
310
457
  const table = getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) });
311
- const sql5 = `UPDATE ${table}
458
+ const sql7 = `UPDATE ${table}
312
459
  SET title = @title,
313
460
  metadata = @metadata,
314
461
  [updatedAt] = @updatedAt
@@ -319,7 +466,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
319
466
  req.input("title", title);
320
467
  req.input("metadata", JSON.stringify(mergedMetadata));
321
468
  req.input("updatedAt", /* @__PURE__ */ new Date());
322
- const result = await req.query(sql5);
469
+ const result = await req.query(sql7);
323
470
  let thread = result.recordset && result.recordset[0];
324
471
  if (thread && "seq_id" in thread) {
325
472
  const { seq_id, ...rest } = thread;
@@ -389,9 +536,11 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
389
536
  }
390
537
  async _getIncludedMessages({
391
538
  threadId,
392
- include
539
+ selectBy,
540
+ orderByStatement
393
541
  }) {
394
542
  if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
543
+ const include = selectBy?.include;
395
544
  if (!include) return null;
396
545
  const unionQueries = [];
397
546
  const paramValues = [];
@@ -416,7 +565,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
416
565
  m.[resourceId],
417
566
  m.seq_id
418
567
  FROM (
419
- SELECT *, ROW_NUMBER() OVER (ORDER BY [createdAt] ASC) as row_num
568
+ SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
420
569
  FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
421
570
  WHERE [thread_id] = ${pThreadId}
422
571
  ) AS m
@@ -424,17 +573,15 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
424
573
  OR EXISTS (
425
574
  SELECT 1
426
575
  FROM (
427
- SELECT *, ROW_NUMBER() OVER (ORDER BY [createdAt] ASC) as row_num
576
+ SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
428
577
  FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
429
578
  WHERE [thread_id] = ${pThreadId}
430
579
  ) AS target
431
580
  WHERE target.id = ${pId}
432
581
  AND (
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})
582
+ (m.row_num <= target.row_num + ${pPrev} AND m.row_num > target.row_num)
435
583
  OR
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})
584
+ (m.row_num >= target.row_num - ${pNext} AND m.row_num < target.row_num)
438
585
  )
439
586
  )
440
587
  `
@@ -463,16 +610,34 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
463
610
  });
464
611
  return dedupedRows;
465
612
  }
466
- async listMessagesById({ messageIds }) {
467
- if (messageIds.length === 0) return { messages: [] };
613
+ async getMessages(args) {
614
+ const { threadId, resourceId, format, selectBy } = args;
468
615
  const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
469
616
  const orderByStatement = `ORDER BY [seq_id] DESC`;
617
+ const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
470
618
  try {
619
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
471
620
  let rows = [];
472
- let query = `${selectStatement} FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [id] IN (${messageIds.map((_, i) => `@id${i}`).join(", ")})`;
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`;
473
630
  const request = this.pool.request();
474
- messageIds.forEach((id, i) => request.input(`id${i}`, id));
475
- query += ` ${orderByStatement}`;
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);
476
641
  const result = await request.query(query);
477
642
  const remainingRows = result.recordset || [];
478
643
  rows.push(...remainingRows);
@@ -480,171 +645,154 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
480
645
  const timeDiff = a.seq_id - b.seq_id;
481
646
  return timeDiff;
482
647
  });
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() };
648
+ rows = rows.map(({ seq_id, ...rest }) => rest);
649
+ return this._parseAndFormatMessages(rows, format);
496
650
  } catch (error$1) {
497
651
  const mastraError = new error.MastraError(
498
652
  {
499
- id: "MASTRA_STORAGE_MSSQL_STORE_LIST_MESSAGES_BY_ID_FAILED",
653
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_FAILED",
500
654
  domain: error.ErrorDomain.STORAGE,
501
655
  category: error.ErrorCategory.THIRD_PARTY,
502
656
  details: {
503
- messageIds: JSON.stringify(messageIds)
657
+ threadId,
658
+ resourceId: resourceId ?? ""
504
659
  }
505
660
  },
506
661
  error$1
507
662
  );
508
663
  this.logger?.error?.(mastraError.toString());
509
664
  this.logger?.trackException?.(mastraError);
510
- return { messages: [] };
665
+ return [];
511
666
  }
512
667
  }
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(
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(
517
693
  {
518
- id: "STORAGE_MSSQL_LIST_MESSAGES_INVALID_THREAD_ID",
694
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_BY_ID_FAILED",
519
695
  domain: error.ErrorDomain.STORAGE,
520
696
  category: error.ErrorCategory.THIRD_PARTY,
521
- details: { threadId }
697
+ details: {
698
+ messageIds: JSON.stringify(messageIds)
699
+ }
522
700
  },
523
- new Error("threadId must be a non-empty string")
701
+ error$1
524
702
  );
703
+ this.logger?.error?.(mastraError.toString());
704
+ this.logger?.trackException?.(mastraError);
705
+ return [];
525
706
  }
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);
707
+ }
708
+ async getMessagesPaginated(args) {
709
+ const { threadId, resourceId, format, selectBy } = args;
710
+ const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
540
711
  try {
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}`);
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);
558
738
  const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
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)) {
739
+ if (total === 0 && messages.length > 0) {
740
+ const parsedIncluded = this._parseAndFormatMessages(messages, format);
580
741
  return {
581
- messages: [],
582
- total: 0,
742
+ messages: parsedIncluded,
743
+ total: parsedIncluded.length,
583
744
  page,
584
- perPage: perPageForResponse,
745
+ perPage,
585
746
  hasMore: false
586
747
  };
587
748
  }
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;
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
+ let parsed = this._parseAndFormatMessages(messages, format);
764
+ parsed = parsed.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
615
765
  return {
616
- messages: finalMessages,
766
+ messages: parsed,
617
767
  total,
618
768
  page,
619
- perPage: perPageForResponse,
620
- hasMore
769
+ perPage,
770
+ hasMore: currentOffset + rows.length < total
621
771
  };
622
772
  } catch (error$1) {
623
773
  const mastraError = new error.MastraError(
624
774
  {
625
- id: "MASTRA_STORAGE_MSSQL_STORE_LIST_MESSAGES_FAILED",
775
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_PAGINATED_FAILED",
626
776
  domain: error.ErrorDomain.STORAGE,
627
777
  category: error.ErrorCategory.THIRD_PARTY,
628
778
  details: {
629
779
  threadId,
630
- resourceId: resourceId ?? ""
780
+ resourceId: resourceId ?? "",
781
+ page
631
782
  }
632
783
  },
633
784
  error$1
634
785
  );
635
786
  this.logger?.error?.(mastraError.toString());
636
787
  this.logger?.trackException?.(mastraError);
637
- return {
638
- messages: [],
639
- total: 0,
640
- page,
641
- perPage: perPageForResponse,
642
- hasMore: false
643
- };
788
+ return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
644
789
  }
645
790
  }
646
- async saveMessages({ messages }) {
647
- if (messages.length === 0) return { messages: [] };
791
+ async saveMessages({
792
+ messages,
793
+ format
794
+ }) {
795
+ if (messages.length === 0) return messages;
648
796
  const threadId = messages[0]?.threadId;
649
797
  if (!threadId) {
650
798
  throw new error.MastraError({
@@ -688,7 +836,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
688
836
  "content",
689
837
  typeof message.content === "string" ? message.content : JSON.stringify(message.content)
690
838
  );
691
- request.input("createdAt", sql2__default.default.DateTime2, message.createdAt);
839
+ request.input("createdAt", sql3__default.default.DateTime2, message.createdAt);
692
840
  request.input("role", message.role);
693
841
  request.input("type", message.type || "v2");
694
842
  request.input("resourceId", message.resourceId);
@@ -707,7 +855,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
707
855
  await request.query(mergeSql);
708
856
  }
709
857
  const threadReq = transaction.request();
710
- threadReq.input("updatedAt", sql2__default.default.DateTime2, /* @__PURE__ */ new Date());
858
+ threadReq.input("updatedAt", sql3__default.default.DateTime2, /* @__PURE__ */ new Date());
711
859
  threadReq.input("id", threadId);
712
860
  await threadReq.query(`UPDATE ${tableThreads} SET [updatedAt] = @updatedAt WHERE id = @id`);
713
861
  await transaction.commit();
@@ -726,7 +874,8 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
726
874
  return message;
727
875
  });
728
876
  const list = new agent.MessageList().add(messagesWithParsedContent, "memory");
729
- return { messages: list.get.all.db() };
877
+ if (format === "v2") return list.get.all.v2();
878
+ return list.get.all.v1();
730
879
  } catch (error$1) {
731
880
  throw new error.MastraError(
732
881
  {
@@ -1005,13 +1154,13 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1005
1154
  this.operations = operations;
1006
1155
  this.schema = schema;
1007
1156
  }
1008
- get tracingStrategy() {
1157
+ get aiTracingStrategy() {
1009
1158
  return {
1010
1159
  preferred: "batch-with-updates",
1011
1160
  supported: ["batch-with-updates", "insert-only"]
1012
1161
  };
1013
1162
  }
1014
- async createSpan(span) {
1163
+ async createAISpan(span) {
1015
1164
  try {
1016
1165
  const startedAt = span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt;
1017
1166
  const endedAt = span.endedAt instanceof Date ? span.endedAt.toISOString() : span.endedAt;
@@ -1021,11 +1170,11 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1021
1170
  endedAt
1022
1171
  // Note: createdAt/updatedAt will be set by default values
1023
1172
  };
1024
- return this.operations.insert({ tableName: storage.TABLE_SPANS, record });
1173
+ return this.operations.insert({ tableName: storage.TABLE_AI_SPANS, record });
1025
1174
  } catch (error$1) {
1026
1175
  throw new error.MastraError(
1027
1176
  {
1028
- id: "MSSQL_STORE_CREATE_SPAN_FAILED",
1177
+ id: "MSSQL_STORE_CREATE_AI_SPAN_FAILED",
1029
1178
  domain: error.ErrorDomain.STORAGE,
1030
1179
  category: error.ErrorCategory.USER,
1031
1180
  details: {
@@ -1039,10 +1188,10 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1039
1188
  );
1040
1189
  }
1041
1190
  }
1042
- async getTrace(traceId) {
1191
+ async getAITrace(traceId) {
1043
1192
  try {
1044
1193
  const tableName = getTableName({
1045
- indexName: storage.TABLE_SPANS,
1194
+ indexName: storage.TABLE_AI_SPANS,
1046
1195
  schemaName: getSchemaName(this.schema)
1047
1196
  });
1048
1197
  const request = this.pool.request();
@@ -1063,7 +1212,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1063
1212
  traceId,
1064
1213
  spans: result.recordset.map(
1065
1214
  (span) => transformFromSqlRow({
1066
- tableName: storage.TABLE_SPANS,
1215
+ tableName: storage.TABLE_AI_SPANS,
1067
1216
  sqlRow: span
1068
1217
  })
1069
1218
  )
@@ -1071,7 +1220,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1071
1220
  } catch (error$1) {
1072
1221
  throw new error.MastraError(
1073
1222
  {
1074
- id: "MSSQL_STORE_GET_TRACE_FAILED",
1223
+ id: "MSSQL_STORE_GET_AI_TRACE_FAILED",
1075
1224
  domain: error.ErrorDomain.STORAGE,
1076
1225
  category: error.ErrorCategory.USER,
1077
1226
  details: {
@@ -1082,7 +1231,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1082
1231
  );
1083
1232
  }
1084
1233
  }
1085
- async updateSpan({
1234
+ async updateAISpan({
1086
1235
  spanId,
1087
1236
  traceId,
1088
1237
  updates
@@ -1096,14 +1245,14 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1096
1245
  data.startedAt = data.startedAt.toISOString();
1097
1246
  }
1098
1247
  await this.operations.update({
1099
- tableName: storage.TABLE_SPANS,
1248
+ tableName: storage.TABLE_AI_SPANS,
1100
1249
  keys: { spanId, traceId },
1101
1250
  data
1102
1251
  });
1103
1252
  } catch (error$1) {
1104
1253
  throw new error.MastraError(
1105
1254
  {
1106
- id: "MSSQL_STORE_UPDATE_SPAN_FAILED",
1255
+ id: "MSSQL_STORE_UPDATE_AI_SPAN_FAILED",
1107
1256
  domain: error.ErrorDomain.STORAGE,
1108
1257
  category: error.ErrorCategory.USER,
1109
1258
  details: {
@@ -1115,7 +1264,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1115
1264
  );
1116
1265
  }
1117
1266
  }
1118
- async getTracesPaginated({
1267
+ async getAITracesPaginated({
1119
1268
  filters,
1120
1269
  pagination
1121
1270
  }) {
@@ -1140,7 +1289,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1140
1289
  name = `agent run: '${entityId}'`;
1141
1290
  } else {
1142
1291
  const error$1 = new error.MastraError({
1143
- id: "MSSQL_STORE_GET_TRACES_PAGINATED_FAILED",
1292
+ id: "MSSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1144
1293
  domain: error.ErrorDomain.STORAGE,
1145
1294
  category: error.ErrorCategory.USER,
1146
1295
  details: {
@@ -1159,7 +1308,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1159
1308
  params[entityParam] = name;
1160
1309
  }
1161
1310
  const tableName = getTableName({
1162
- indexName: storage.TABLE_SPANS,
1311
+ indexName: storage.TABLE_AI_SPANS,
1163
1312
  schemaName: getSchemaName(this.schema)
1164
1313
  });
1165
1314
  try {
@@ -1193,7 +1342,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1193
1342
  );
1194
1343
  const spans = dataResult.recordset.map(
1195
1344
  (row) => transformFromSqlRow({
1196
- tableName: storage.TABLE_SPANS,
1345
+ tableName: storage.TABLE_AI_SPANS,
1197
1346
  sqlRow: row
1198
1347
  })
1199
1348
  );
@@ -1209,7 +1358,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1209
1358
  } catch (error$1) {
1210
1359
  throw new error.MastraError(
1211
1360
  {
1212
- id: "MSSQL_STORE_GET_TRACES_PAGINATED_FAILED",
1361
+ id: "MSSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1213
1362
  domain: error.ErrorDomain.STORAGE,
1214
1363
  category: error.ErrorCategory.USER
1215
1364
  },
@@ -1217,13 +1366,13 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1217
1366
  );
1218
1367
  }
1219
1368
  }
1220
- async batchCreateSpans(args) {
1369
+ async batchCreateAISpans(args) {
1221
1370
  if (!args.records || args.records.length === 0) {
1222
1371
  return;
1223
1372
  }
1224
1373
  try {
1225
1374
  await this.operations.batchInsert({
1226
- tableName: storage.TABLE_SPANS,
1375
+ tableName: storage.TABLE_AI_SPANS,
1227
1376
  records: args.records.map((span) => ({
1228
1377
  ...span,
1229
1378
  startedAt: span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt,
@@ -1233,7 +1382,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1233
1382
  } catch (error$1) {
1234
1383
  throw new error.MastraError(
1235
1384
  {
1236
- id: "MSSQL_STORE_BATCH_CREATE_SPANS_FAILED",
1385
+ id: "MSSQL_STORE_BATCH_CREATE_AI_SPANS_FAILED",
1237
1386
  domain: error.ErrorDomain.STORAGE,
1238
1387
  category: error.ErrorCategory.USER,
1239
1388
  details: {
@@ -1244,7 +1393,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1244
1393
  );
1245
1394
  }
1246
1395
  }
1247
- async batchUpdateSpans(args) {
1396
+ async batchUpdateAISpans(args) {
1248
1397
  if (!args.records || args.records.length === 0) {
1249
1398
  return;
1250
1399
  }
@@ -1263,13 +1412,13 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1263
1412
  };
1264
1413
  });
1265
1414
  await this.operations.batchUpdate({
1266
- tableName: storage.TABLE_SPANS,
1415
+ tableName: storage.TABLE_AI_SPANS,
1267
1416
  updates
1268
1417
  });
1269
1418
  } catch (error$1) {
1270
1419
  throw new error.MastraError(
1271
1420
  {
1272
- id: "MSSQL_STORE_BATCH_UPDATE_SPANS_FAILED",
1421
+ id: "MSSQL_STORE_BATCH_UPDATE_AI_SPANS_FAILED",
1273
1422
  domain: error.ErrorDomain.STORAGE,
1274
1423
  category: error.ErrorCategory.USER,
1275
1424
  details: {
@@ -1280,20 +1429,20 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1280
1429
  );
1281
1430
  }
1282
1431
  }
1283
- async batchDeleteTraces(args) {
1432
+ async batchDeleteAITraces(args) {
1284
1433
  if (!args.traceIds || args.traceIds.length === 0) {
1285
1434
  return;
1286
1435
  }
1287
1436
  try {
1288
1437
  const keys = args.traceIds.map((traceId) => ({ traceId }));
1289
1438
  await this.operations.batchDelete({
1290
- tableName: storage.TABLE_SPANS,
1439
+ tableName: storage.TABLE_AI_SPANS,
1291
1440
  keys
1292
1441
  });
1293
1442
  } catch (error$1) {
1294
1443
  throw new error.MastraError(
1295
1444
  {
1296
- id: "MSSQL_STORE_BATCH_DELETE_TRACES_FAILED",
1445
+ id: "MSSQL_STORE_BATCH_DELETE_AI_TRACES_FAILED",
1297
1446
  domain: error.ErrorDomain.STORAGE,
1298
1447
  category: error.ErrorCategory.USER,
1299
1448
  details: {
@@ -1408,7 +1557,7 @@ var StoreOperationsMSSQL = class extends storage.StoreOperations {
1408
1557
  const value = record[col];
1409
1558
  const preparedValue = this.prepareValue(value, col, tableName);
1410
1559
  if (preparedValue instanceof Date) {
1411
- request.input(`param${i}`, sql2__default.default.DateTime2, preparedValue);
1560
+ request.input(`param${i}`, sql3__default.default.DateTime2, preparedValue);
1412
1561
  } else if (preparedValue === null || preparedValue === void 0) {
1413
1562
  request.input(`param${i}`, this.getMssqlType(tableName, col), null);
1414
1563
  } else {
@@ -1623,7 +1772,7 @@ ${columns}
1623
1772
  try {
1624
1773
  const keyEntries = Object.entries(keys).map(([key, value]) => [utils.parseSqlIdentifier(key, "column name"), value]);
1625
1774
  const conditions = keyEntries.map(([key], i) => `[${key}] = @param${i}`).join(" AND ");
1626
- const sql5 = `SELECT * FROM ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} WHERE ${conditions}`;
1775
+ const sql7 = `SELECT * FROM ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} WHERE ${conditions}`;
1627
1776
  const request = this.pool.request();
1628
1777
  keyEntries.forEach(([key, value], i) => {
1629
1778
  const preparedValue = this.prepareValue(value, key, tableName);
@@ -1633,7 +1782,7 @@ ${columns}
1633
1782
  request.input(`param${i}`, preparedValue);
1634
1783
  }
1635
1784
  });
1636
- const resultSet = await request.query(sql5);
1785
+ const resultSet = await request.query(sql7);
1637
1786
  const result = resultSet.recordset[0] || null;
1638
1787
  if (!result) {
1639
1788
  return null;
@@ -1746,23 +1895,23 @@ ${columns}
1746
1895
  const col = storage.TABLE_SCHEMAS[tableName]?.[columnName];
1747
1896
  switch (col?.type) {
1748
1897
  case "text":
1749
- return sql2__default.default.NVarChar;
1898
+ return sql3__default.default.NVarChar;
1750
1899
  case "timestamp":
1751
- return sql2__default.default.DateTime2;
1900
+ return sql3__default.default.DateTime2;
1752
1901
  case "uuid":
1753
- return sql2__default.default.UniqueIdentifier;
1902
+ return sql3__default.default.UniqueIdentifier;
1754
1903
  case "jsonb":
1755
- return sql2__default.default.NVarChar;
1904
+ return sql3__default.default.NVarChar;
1756
1905
  case "integer":
1757
- return sql2__default.default.Int;
1906
+ return sql3__default.default.Int;
1758
1907
  case "bigint":
1759
- return sql2__default.default.BigInt;
1908
+ return sql3__default.default.BigInt;
1760
1909
  case "float":
1761
- return sql2__default.default.Float;
1910
+ return sql3__default.default.Float;
1762
1911
  case "boolean":
1763
- return sql2__default.default.Bit;
1912
+ return sql3__default.default.Bit;
1764
1913
  default:
1765
- return sql2__default.default.NVarChar;
1914
+ return sql3__default.default.NVarChar;
1766
1915
  }
1767
1916
  }
1768
1917
  /**
@@ -2206,30 +2355,35 @@ ${columns}
2206
2355
  table: storage.TABLE_TRACES,
2207
2356
  columns: ["name", "seq_id DESC"]
2208
2357
  },
2358
+ {
2359
+ name: `${schemaPrefix}mastra_evals_agent_name_seqid_idx`,
2360
+ table: storage.TABLE_EVALS,
2361
+ columns: ["agent_name", "seq_id DESC"]
2362
+ },
2209
2363
  {
2210
2364
  name: `${schemaPrefix}mastra_scores_trace_id_span_id_seqid_idx`,
2211
2365
  table: storage.TABLE_SCORERS,
2212
2366
  columns: ["traceId", "spanId", "seq_id DESC"]
2213
2367
  },
2214
- // Spans indexes for optimal trace querying
2368
+ // AI Spans indexes for optimal trace querying
2215
2369
  {
2216
2370
  name: `${schemaPrefix}mastra_ai_spans_traceid_startedat_idx`,
2217
- table: storage.TABLE_SPANS,
2371
+ table: storage.TABLE_AI_SPANS,
2218
2372
  columns: ["traceId", "startedAt DESC"]
2219
2373
  },
2220
2374
  {
2221
2375
  name: `${schemaPrefix}mastra_ai_spans_parentspanid_startedat_idx`,
2222
- table: storage.TABLE_SPANS,
2376
+ table: storage.TABLE_AI_SPANS,
2223
2377
  columns: ["parentSpanId", "startedAt DESC"]
2224
2378
  },
2225
2379
  {
2226
2380
  name: `${schemaPrefix}mastra_ai_spans_name_idx`,
2227
- table: storage.TABLE_SPANS,
2381
+ table: storage.TABLE_AI_SPANS,
2228
2382
  columns: ["name"]
2229
2383
  },
2230
2384
  {
2231
2385
  name: `${schemaPrefix}mastra_ai_spans_spantype_startedat_idx`,
2232
- table: storage.TABLE_SPANS,
2386
+ table: storage.TABLE_AI_SPANS,
2233
2387
  columns: ["spanType", "startedAt DESC"]
2234
2388
  }
2235
2389
  ];
@@ -2270,7 +2424,7 @@ function transformScoreRow(row) {
2270
2424
  metadata: storage.safelyParseJSON(row.metadata),
2271
2425
  output: storage.safelyParseJSON(row.output),
2272
2426
  additionalContext: storage.safelyParseJSON(row.additionalContext),
2273
- requestContext: storage.safelyParseJSON(row.requestContext),
2427
+ runtimeContext: storage.safelyParseJSON(row.runtimeContext),
2274
2428
  entity: storage.safelyParseJSON(row.entity),
2275
2429
  createdAt: new Date(row.createdAt),
2276
2430
  updatedAt: new Date(row.updatedAt)
@@ -2316,7 +2470,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2316
2470
  async saveScore(score) {
2317
2471
  let validatedScore;
2318
2472
  try {
2319
- validatedScore = evals.saveScorePayloadSchema.parse(score);
2473
+ validatedScore = scores.saveScorePayloadSchema.parse(score);
2320
2474
  } catch (error$1) {
2321
2475
  throw new error.MastraError(
2322
2476
  {
@@ -2337,7 +2491,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2337
2491
  input,
2338
2492
  output,
2339
2493
  additionalContext,
2340
- requestContext,
2494
+ runtimeContext,
2341
2495
  entity,
2342
2496
  ...rest
2343
2497
  } = validatedScore;
@@ -2352,7 +2506,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2352
2506
  analyzeStepResult: analyzeStepResult || null,
2353
2507
  metadata: metadata || null,
2354
2508
  additionalContext: additionalContext || null,
2355
- requestContext: requestContext || null,
2509
+ runtimeContext: runtimeContext || null,
2356
2510
  entity: entity || null,
2357
2511
  scorer: scorer || null,
2358
2512
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -2372,7 +2526,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2372
2526
  );
2373
2527
  }
2374
2528
  }
2375
- async listScoresByScorerId({
2529
+ async getScoresByScorerId({
2376
2530
  scorerId,
2377
2531
  pagination,
2378
2532
  entityId,
@@ -2406,36 +2560,31 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2406
2560
  });
2407
2561
  const totalResult = await countRequest.query(`SELECT COUNT(*) as count FROM ${tableName} WHERE ${whereClause}`);
2408
2562
  const total = totalResult.recordset[0]?.count || 0;
2409
- const { page, perPage: perPageInput } = pagination;
2410
2563
  if (total === 0) {
2411
2564
  return {
2412
2565
  pagination: {
2413
2566
  total: 0,
2414
- page,
2415
- perPage: perPageInput,
2567
+ page: pagination.page,
2568
+ perPage: pagination.perPage,
2416
2569
  hasMore: false
2417
2570
  },
2418
2571
  scores: []
2419
2572
  };
2420
2573
  }
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;
2425
2574
  const dataRequest = this.pool.request();
2426
2575
  Object.entries(params).forEach(([key, value]) => {
2427
2576
  dataRequest.input(key, value);
2428
2577
  });
2429
- dataRequest.input("perPage", limitValue);
2430
- dataRequest.input("offset", start);
2578
+ dataRequest.input("perPage", pagination.perPage);
2579
+ dataRequest.input("offset", pagination.page * pagination.perPage);
2431
2580
  const dataQuery = `SELECT * FROM ${tableName} WHERE ${whereClause} ORDER BY [createdAt] DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
2432
2581
  const result = await dataRequest.query(dataQuery);
2433
2582
  return {
2434
2583
  pagination: {
2435
2584
  total: Number(total),
2436
- page,
2437
- perPage: perPageForResponse,
2438
- hasMore: end < total
2585
+ page: pagination.page,
2586
+ perPage: pagination.perPage,
2587
+ hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2439
2588
  },
2440
2589
  scores: result.recordset.map((row) => transformScoreRow(row))
2441
2590
  };
@@ -2451,7 +2600,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2451
2600
  );
2452
2601
  }
2453
2602
  }
2454
- async listScoresByRunId({
2603
+ async getScoresByRunId({
2455
2604
  runId,
2456
2605
  pagination
2457
2606
  }) {
@@ -2462,35 +2611,30 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2462
2611
  `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [runId] = @p1`
2463
2612
  );
2464
2613
  const total = totalResult.recordset[0]?.count || 0;
2465
- const { page, perPage: perPageInput } = pagination;
2466
2614
  if (total === 0) {
2467
2615
  return {
2468
2616
  pagination: {
2469
2617
  total: 0,
2470
- page,
2471
- perPage: perPageInput,
2618
+ page: pagination.page,
2619
+ perPage: pagination.perPage,
2472
2620
  hasMore: false
2473
2621
  },
2474
2622
  scores: []
2475
2623
  };
2476
2624
  }
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;
2481
2625
  const dataRequest = this.pool.request();
2482
2626
  dataRequest.input("p1", runId);
2483
- dataRequest.input("p2", limitValue);
2484
- dataRequest.input("p3", start);
2627
+ dataRequest.input("p2", pagination.perPage);
2628
+ dataRequest.input("p3", pagination.page * pagination.perPage);
2485
2629
  const result = await dataRequest.query(
2486
2630
  `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`
2487
2631
  );
2488
2632
  return {
2489
2633
  pagination: {
2490
2634
  total: Number(total),
2491
- page,
2492
- perPage: perPageForResponse,
2493
- hasMore: end < total
2635
+ page: pagination.page,
2636
+ perPage: pagination.perPage,
2637
+ hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2494
2638
  },
2495
2639
  scores: result.recordset.map((row) => transformScoreRow(row))
2496
2640
  };
@@ -2506,7 +2650,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2506
2650
  );
2507
2651
  }
2508
2652
  }
2509
- async listScoresByEntityId({
2653
+ async getScoresByEntityId({
2510
2654
  entityId,
2511
2655
  entityType,
2512
2656
  pagination
@@ -2519,36 +2663,31 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2519
2663
  `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [entityId] = @p1 AND [entityType] = @p2`
2520
2664
  );
2521
2665
  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);
2525
2666
  if (total === 0) {
2526
2667
  return {
2527
2668
  pagination: {
2528
2669
  total: 0,
2529
- page,
2530
- perPage: perPageForResponse,
2670
+ page: pagination.page,
2671
+ perPage: pagination.perPage,
2531
2672
  hasMore: false
2532
2673
  },
2533
2674
  scores: []
2534
2675
  };
2535
2676
  }
2536
- const limitValue = perPageInput === false ? total : perPage;
2537
- const end = perPageInput === false ? total : start + perPage;
2538
2677
  const dataRequest = this.pool.request();
2539
2678
  dataRequest.input("p1", entityId);
2540
2679
  dataRequest.input("p2", entityType);
2541
- dataRequest.input("p3", limitValue);
2542
- dataRequest.input("p4", start);
2680
+ dataRequest.input("p3", pagination.perPage);
2681
+ dataRequest.input("p4", pagination.page * pagination.perPage);
2543
2682
  const result = await dataRequest.query(
2544
2683
  `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`
2545
2684
  );
2546
2685
  return {
2547
2686
  pagination: {
2548
2687
  total: Number(total),
2549
- page,
2550
- perPage: perPageForResponse,
2551
- hasMore: end < total
2688
+ page: pagination.page,
2689
+ perPage: pagination.perPage,
2690
+ hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2552
2691
  },
2553
2692
  scores: result.recordset.map((row) => transformScoreRow(row))
2554
2693
  };
@@ -2564,7 +2703,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2564
2703
  );
2565
2704
  }
2566
2705
  }
2567
- async listScoresBySpan({
2706
+ async getScoresBySpan({
2568
2707
  traceId,
2569
2708
  spanId,
2570
2709
  pagination
@@ -2577,38 +2716,34 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2577
2716
  `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [traceId] = @p1 AND [spanId] = @p2`
2578
2717
  );
2579
2718
  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);
2583
2719
  if (total === 0) {
2584
2720
  return {
2585
2721
  pagination: {
2586
2722
  total: 0,
2587
- page,
2588
- perPage: perPageForResponse,
2723
+ page: pagination.page,
2724
+ perPage: pagination.perPage,
2589
2725
  hasMore: false
2590
2726
  },
2591
2727
  scores: []
2592
2728
  };
2593
2729
  }
2594
- const limitValue = perPageInput === false ? total : perPage;
2595
- const end = perPageInput === false ? total : start + perPage;
2730
+ const limit = pagination.perPage + 1;
2596
2731
  const dataRequest = this.pool.request();
2597
2732
  dataRequest.input("p1", traceId);
2598
2733
  dataRequest.input("p2", spanId);
2599
- dataRequest.input("p3", limitValue);
2600
- dataRequest.input("p4", start);
2734
+ dataRequest.input("p3", limit);
2735
+ dataRequest.input("p4", pagination.page * pagination.perPage);
2601
2736
  const result = await dataRequest.query(
2602
2737
  `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`
2603
2738
  );
2604
2739
  return {
2605
2740
  pagination: {
2606
2741
  total: Number(total),
2607
- page,
2608
- perPage: perPageForResponse,
2609
- hasMore: end < total
2742
+ page: pagination.page,
2743
+ perPage: pagination.perPage,
2744
+ hasMore: result.recordset.length > pagination.perPage
2610
2745
  },
2611
- scores: result.recordset.map((row) => transformScoreRow(row))
2746
+ scores: result.recordset.slice(0, pagination.perPage).map((row) => transformScoreRow(row))
2612
2747
  };
2613
2748
  } catch (error$1) {
2614
2749
  throw new error.MastraError(
@@ -2623,6 +2758,173 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2623
2758
  }
2624
2759
  }
2625
2760
  };
2761
+ var TracesMSSQL = class extends storage.TracesStorage {
2762
+ pool;
2763
+ operations;
2764
+ schema;
2765
+ constructor({
2766
+ pool,
2767
+ operations,
2768
+ schema
2769
+ }) {
2770
+ super();
2771
+ this.pool = pool;
2772
+ this.operations = operations;
2773
+ this.schema = schema;
2774
+ }
2775
+ /** @deprecated use getTracesPaginated instead*/
2776
+ async getTraces(args) {
2777
+ if (args.fromDate || args.toDate) {
2778
+ args.dateRange = {
2779
+ start: args.fromDate,
2780
+ end: args.toDate
2781
+ };
2782
+ }
2783
+ const result = await this.getTracesPaginated(args);
2784
+ return result.traces;
2785
+ }
2786
+ async getTracesPaginated(args) {
2787
+ const { name, scope, page = 0, perPage: perPageInput, attributes, filters, dateRange } = args;
2788
+ const fromDate = dateRange?.start;
2789
+ const toDate = dateRange?.end;
2790
+ const perPage = perPageInput !== void 0 ? perPageInput : 100;
2791
+ const currentOffset = page * perPage;
2792
+ const paramMap = {};
2793
+ const conditions = [];
2794
+ let paramIndex = 1;
2795
+ if (name) {
2796
+ const paramName = `p${paramIndex++}`;
2797
+ conditions.push(`[name] LIKE @${paramName}`);
2798
+ paramMap[paramName] = `${name}%`;
2799
+ }
2800
+ if (scope) {
2801
+ const paramName = `p${paramIndex++}`;
2802
+ conditions.push(`[scope] = @${paramName}`);
2803
+ paramMap[paramName] = scope;
2804
+ }
2805
+ if (attributes) {
2806
+ Object.entries(attributes).forEach(([key, value]) => {
2807
+ const parsedKey = utils.parseFieldKey(key);
2808
+ const paramName = `p${paramIndex++}`;
2809
+ conditions.push(`JSON_VALUE([attributes], '$.${parsedKey}') = @${paramName}`);
2810
+ paramMap[paramName] = value;
2811
+ });
2812
+ }
2813
+ if (filters) {
2814
+ Object.entries(filters).forEach(([key, value]) => {
2815
+ const parsedKey = utils.parseFieldKey(key);
2816
+ const paramName = `p${paramIndex++}`;
2817
+ conditions.push(`[${parsedKey}] = @${paramName}`);
2818
+ paramMap[paramName] = value;
2819
+ });
2820
+ }
2821
+ if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
2822
+ const paramName = `p${paramIndex++}`;
2823
+ conditions.push(`[createdAt] >= @${paramName}`);
2824
+ paramMap[paramName] = fromDate.toISOString();
2825
+ }
2826
+ if (toDate instanceof Date && !isNaN(toDate.getTime())) {
2827
+ const paramName = `p${paramIndex++}`;
2828
+ conditions.push(`[createdAt] <= @${paramName}`);
2829
+ paramMap[paramName] = toDate.toISOString();
2830
+ }
2831
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2832
+ const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: storage.TABLE_TRACES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
2833
+ let total = 0;
2834
+ try {
2835
+ const countRequest = this.pool.request();
2836
+ Object.entries(paramMap).forEach(([key, value]) => {
2837
+ if (value instanceof Date) {
2838
+ countRequest.input(key, sql3__default.default.DateTime, value);
2839
+ } else {
2840
+ countRequest.input(key, value);
2841
+ }
2842
+ });
2843
+ const countResult = await countRequest.query(countQuery);
2844
+ total = parseInt(countResult.recordset[0].total, 10);
2845
+ } catch (error$1) {
2846
+ throw new error.MastraError(
2847
+ {
2848
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TOTAL_COUNT",
2849
+ domain: error.ErrorDomain.STORAGE,
2850
+ category: error.ErrorCategory.THIRD_PARTY,
2851
+ details: {
2852
+ name: args.name ?? "",
2853
+ scope: args.scope ?? ""
2854
+ }
2855
+ },
2856
+ error$1
2857
+ );
2858
+ }
2859
+ if (total === 0) {
2860
+ return {
2861
+ traces: [],
2862
+ total: 0,
2863
+ page,
2864
+ perPage,
2865
+ hasMore: false
2866
+ };
2867
+ }
2868
+ 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`;
2869
+ const dataRequest = this.pool.request();
2870
+ Object.entries(paramMap).forEach(([key, value]) => {
2871
+ if (value instanceof Date) {
2872
+ dataRequest.input(key, sql3__default.default.DateTime, value);
2873
+ } else {
2874
+ dataRequest.input(key, value);
2875
+ }
2876
+ });
2877
+ dataRequest.input("offset", currentOffset);
2878
+ dataRequest.input("limit", perPage);
2879
+ try {
2880
+ const rowsResult = await dataRequest.query(dataQuery);
2881
+ const rows = rowsResult.recordset;
2882
+ const traces = rows.map((row) => ({
2883
+ id: row.id,
2884
+ parentSpanId: row.parentSpanId,
2885
+ traceId: row.traceId,
2886
+ name: row.name,
2887
+ scope: row.scope,
2888
+ kind: row.kind,
2889
+ status: JSON.parse(row.status),
2890
+ events: JSON.parse(row.events),
2891
+ links: JSON.parse(row.links),
2892
+ attributes: JSON.parse(row.attributes),
2893
+ startTime: row.startTime,
2894
+ endTime: row.endTime,
2895
+ other: row.other,
2896
+ createdAt: row.createdAt
2897
+ }));
2898
+ return {
2899
+ traces,
2900
+ total,
2901
+ page,
2902
+ perPage,
2903
+ hasMore: currentOffset + traces.length < total
2904
+ };
2905
+ } catch (error$1) {
2906
+ throw new error.MastraError(
2907
+ {
2908
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TRACES",
2909
+ domain: error.ErrorDomain.STORAGE,
2910
+ category: error.ErrorCategory.THIRD_PARTY,
2911
+ details: {
2912
+ name: args.name ?? "",
2913
+ scope: args.scope ?? ""
2914
+ }
2915
+ },
2916
+ error$1
2917
+ );
2918
+ }
2919
+ }
2920
+ async batchTraceInsert({ records }) {
2921
+ this.logger.debug("Batch inserting traces", { count: records.length });
2922
+ await this.operations.batchInsert({
2923
+ tableName: storage.TABLE_TRACES,
2924
+ records
2925
+ });
2926
+ }
2927
+ };
2626
2928
  var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2627
2929
  pool;
2628
2930
  operations;
@@ -2660,13 +2962,13 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2660
2962
  runId,
2661
2963
  stepId,
2662
2964
  result,
2663
- requestContext
2965
+ runtimeContext
2664
2966
  }) {
2665
2967
  const table = getTableName({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
2666
2968
  const transaction = this.pool.transaction();
2667
2969
  try {
2668
2970
  await transaction.begin();
2669
- const selectRequest = new sql2__default.default.Request(transaction);
2971
+ const selectRequest = new sql3__default.default.Request(transaction);
2670
2972
  selectRequest.input("workflow_name", workflowName);
2671
2973
  selectRequest.input("run_id", runId);
2672
2974
  const existingSnapshotResult = await selectRequest.query(
@@ -2686,20 +2988,20 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2686
2988
  value: {},
2687
2989
  waitingPaths: {},
2688
2990
  runId,
2689
- requestContext: {}
2991
+ runtimeContext: {}
2690
2992
  };
2691
2993
  } else {
2692
2994
  const existingSnapshot = existingSnapshotResult.recordset[0].snapshot;
2693
2995
  snapshot = typeof existingSnapshot === "string" ? JSON.parse(existingSnapshot) : existingSnapshot;
2694
2996
  }
2695
2997
  snapshot.context[stepId] = result;
2696
- snapshot.requestContext = { ...snapshot.requestContext, ...requestContext };
2697
- const upsertReq = new sql2__default.default.Request(transaction);
2998
+ snapshot.runtimeContext = { ...snapshot.runtimeContext, ...runtimeContext };
2999
+ const upsertReq = new sql3__default.default.Request(transaction);
2698
3000
  upsertReq.input("workflow_name", workflowName);
2699
3001
  upsertReq.input("run_id", runId);
2700
3002
  upsertReq.input("snapshot", JSON.stringify(snapshot));
2701
- upsertReq.input("createdAt", sql2__default.default.DateTime2, /* @__PURE__ */ new Date());
2702
- upsertReq.input("updatedAt", sql2__default.default.DateTime2, /* @__PURE__ */ new Date());
3003
+ upsertReq.input("createdAt", sql3__default.default.DateTime2, /* @__PURE__ */ new Date());
3004
+ upsertReq.input("updatedAt", sql3__default.default.DateTime2, /* @__PURE__ */ new Date());
2703
3005
  await upsertReq.query(
2704
3006
  `MERGE ${table} AS target
2705
3007
  USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
@@ -2739,7 +3041,7 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2739
3041
  const transaction = this.pool.transaction();
2740
3042
  try {
2741
3043
  await transaction.begin();
2742
- const selectRequest = new sql2__default.default.Request(transaction);
3044
+ const selectRequest = new sql3__default.default.Request(transaction);
2743
3045
  selectRequest.input("workflow_name", workflowName);
2744
3046
  selectRequest.input("run_id", runId);
2745
3047
  const existingSnapshotResult = await selectRequest.query(
@@ -2767,11 +3069,11 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2767
3069
  );
2768
3070
  }
2769
3071
  const updatedSnapshot = { ...snapshot, ...opts };
2770
- const updateRequest = new sql2__default.default.Request(transaction);
3072
+ const updateRequest = new sql3__default.default.Request(transaction);
2771
3073
  updateRequest.input("snapshot", JSON.stringify(updatedSnapshot));
2772
3074
  updateRequest.input("workflow_name", workflowName);
2773
3075
  updateRequest.input("run_id", runId);
2774
- updateRequest.input("updatedAt", sql2__default.default.DateTime2, /* @__PURE__ */ new Date());
3076
+ updateRequest.input("updatedAt", sql3__default.default.DateTime2, /* @__PURE__ */ new Date());
2775
3077
  await updateRequest.query(
2776
3078
  `UPDATE ${table} SET snapshot = @snapshot, [updatedAt] = @updatedAt WHERE workflow_name = @workflow_name AND run_id = @run_id`
2777
3079
  );
@@ -2810,8 +3112,8 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2810
3112
  request.input("run_id", runId);
2811
3113
  request.input("resourceId", resourceId);
2812
3114
  request.input("snapshot", JSON.stringify(snapshot));
2813
- request.input("createdAt", sql2__default.default.DateTime2, new Date(now));
2814
- request.input("updatedAt", sql2__default.default.DateTime2, new Date(now));
3115
+ request.input("createdAt", sql3__default.default.DateTime2, new Date(now));
3116
+ request.input("updatedAt", sql3__default.default.DateTime2, new Date(now));
2815
3117
  const mergeSql = `MERGE INTO ${table} AS target
2816
3118
  USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
2817
3119
  ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
@@ -2908,12 +3210,12 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2908
3210
  );
2909
3211
  }
2910
3212
  }
2911
- async listWorkflowRuns({
3213
+ async getWorkflowRuns({
2912
3214
  workflowName,
2913
3215
  fromDate,
2914
3216
  toDate,
2915
- page,
2916
- perPage,
3217
+ limit,
3218
+ offset,
2917
3219
  resourceId,
2918
3220
  status
2919
3221
  } = {}) {
@@ -2951,23 +3253,20 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2951
3253
  const request = this.pool.request();
2952
3254
  Object.entries(paramMap).forEach(([key, value]) => {
2953
3255
  if (value instanceof Date) {
2954
- request.input(key, sql2__default.default.DateTime, value);
3256
+ request.input(key, sql3__default.default.DateTime, value);
2955
3257
  } else {
2956
3258
  request.input(key, value);
2957
3259
  }
2958
3260
  });
2959
- const usePagination = typeof perPage === "number" && typeof page === "number";
2960
- if (usePagination) {
3261
+ if (limit !== void 0 && offset !== void 0) {
2961
3262
  const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
2962
3263
  const countResult = await request.query(countQuery);
2963
3264
  total = Number(countResult.recordset[0]?.count || 0);
2964
3265
  }
2965
3266
  let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
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);
3267
+ if (limit !== void 0 && offset !== void 0) {
3268
+ query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
3269
+ request.input("limit", limit);
2971
3270
  request.input("offset", offset);
2972
3271
  }
2973
3272
  const result = await request.query(query);
@@ -2976,7 +3275,7 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2976
3275
  } catch (error$1) {
2977
3276
  throw new error.MastraError(
2978
3277
  {
2979
- id: "MASTRA_STORAGE_MSSQL_STORE_LIST_WORKFLOW_RUNS_FAILED",
3278
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
2980
3279
  domain: error.ErrorDomain.STORAGE,
2981
3280
  category: error.ErrorCategory.THIRD_PARTY,
2982
3281
  details: {
@@ -2996,10 +3295,7 @@ var MSSQLStore = class extends storage.MastraStorage {
2996
3295
  isConnected = null;
2997
3296
  stores;
2998
3297
  constructor(config) {
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" });
3298
+ super({ name: "MSSQLStore" });
3003
3299
  try {
3004
3300
  if ("connectionString" in config) {
3005
3301
  if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") {
@@ -3014,7 +3310,7 @@ var MSSQLStore = class extends storage.MastraStorage {
3014
3310
  }
3015
3311
  }
3016
3312
  this.schema = config.schemaName || "dbo";
3017
- this.pool = "connectionString" in config ? new sql2__default.default.ConnectionPool(config.connectionString) : new sql2__default.default.ConnectionPool({
3313
+ this.pool = "connectionString" in config ? new sql3__default.default.ConnectionPool(config.connectionString) : new sql3__default.default.ConnectionPool({
3018
3314
  server: config.server,
3019
3315
  database: config.database,
3020
3316
  user: config.user,
@@ -3022,15 +3318,19 @@ var MSSQLStore = class extends storage.MastraStorage {
3022
3318
  port: config.port,
3023
3319
  options: config.options || { encrypt: true, trustServerCertificate: true }
3024
3320
  });
3321
+ const legacyEvals = new LegacyEvalsMSSQL({ pool: this.pool, schema: this.schema });
3025
3322
  const operations = new StoreOperationsMSSQL({ pool: this.pool, schemaName: this.schema });
3026
3323
  const scores = new ScoresMSSQL({ pool: this.pool, operations, schema: this.schema });
3324
+ const traces = new TracesMSSQL({ pool: this.pool, operations, schema: this.schema });
3027
3325
  const workflows = new WorkflowsMSSQL({ pool: this.pool, operations, schema: this.schema });
3028
3326
  const memory = new MemoryMSSQL({ pool: this.pool, schema: this.schema, operations });
3029
3327
  const observability = new ObservabilityMSSQL({ pool: this.pool, operations, schema: this.schema });
3030
3328
  this.stores = {
3031
3329
  operations,
3032
3330
  scores,
3331
+ traces,
3033
3332
  workflows,
3333
+ legacyEvals,
3034
3334
  memory,
3035
3335
  observability
3036
3336
  };
@@ -3084,11 +3384,30 @@ var MSSQLStore = class extends storage.MastraStorage {
3084
3384
  hasColumn: true,
3085
3385
  createTable: true,
3086
3386
  deleteMessages: true,
3087
- listScoresBySpan: true,
3088
- observabilityInstance: true,
3387
+ getScoresBySpan: true,
3388
+ aiTracing: true,
3089
3389
  indexManagement: true
3090
3390
  };
3091
3391
  }
3392
+ /** @deprecated use getEvals instead */
3393
+ async getEvalsByAgentName(agentName, type) {
3394
+ return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
3395
+ }
3396
+ async getEvals(options = {}) {
3397
+ return this.stores.legacyEvals.getEvals(options);
3398
+ }
3399
+ /**
3400
+ * @deprecated use getTracesPaginated instead
3401
+ */
3402
+ async getTraces(args) {
3403
+ return this.stores.traces.getTraces(args);
3404
+ }
3405
+ async getTracesPaginated(args) {
3406
+ return this.stores.traces.getTracesPaginated(args);
3407
+ }
3408
+ async batchTraceInsert({ records }) {
3409
+ return this.stores.traces.batchTraceInsert({ records });
3410
+ }
3092
3411
  async createTable({
3093
3412
  tableName,
3094
3413
  schema
@@ -3123,6 +3442,15 @@ var MSSQLStore = class extends storage.MastraStorage {
3123
3442
  async getThreadById({ threadId }) {
3124
3443
  return this.stores.memory.getThreadById({ threadId });
3125
3444
  }
3445
+ /**
3446
+ * @deprecated use getThreadsByResourceIdPaginated instead
3447
+ */
3448
+ async getThreadsByResourceId(args) {
3449
+ return this.stores.memory.getThreadsByResourceId(args);
3450
+ }
3451
+ async getThreadsByResourceIdPaginated(args) {
3452
+ return this.stores.memory.getThreadsByResourceIdPaginated(args);
3453
+ }
3126
3454
  async saveThread({ thread }) {
3127
3455
  return this.stores.memory.saveThread({ thread });
3128
3456
  }
@@ -3136,8 +3464,17 @@ var MSSQLStore = class extends storage.MastraStorage {
3136
3464
  async deleteThread({ threadId }) {
3137
3465
  return this.stores.memory.deleteThread({ threadId });
3138
3466
  }
3139
- async listMessagesById({ messageIds }) {
3140
- return this.stores.memory.listMessagesById({ messageIds });
3467
+ async getMessages(args) {
3468
+ return this.stores.memory.getMessages(args);
3469
+ }
3470
+ async getMessagesById({
3471
+ messageIds,
3472
+ format
3473
+ }) {
3474
+ return this.stores.memory.getMessagesById({ messageIds, format });
3475
+ }
3476
+ async getMessagesPaginated(args) {
3477
+ return this.stores.memory.getMessagesPaginated(args);
3141
3478
  }
3142
3479
  async saveMessages(args) {
3143
3480
  return this.stores.memory.saveMessages(args);
@@ -3171,9 +3508,9 @@ var MSSQLStore = class extends storage.MastraStorage {
3171
3508
  runId,
3172
3509
  stepId,
3173
3510
  result,
3174
- requestContext
3511
+ runtimeContext
3175
3512
  }) {
3176
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
3513
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
3177
3514
  }
3178
3515
  async updateWorkflowState({
3179
3516
  workflowName,
@@ -3196,8 +3533,8 @@ var MSSQLStore = class extends storage.MastraStorage {
3196
3533
  }) {
3197
3534
  return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
3198
3535
  }
3199
- async listWorkflowRuns(args = {}) {
3200
- return this.stores.workflows.listWorkflowRuns(args);
3536
+ async getWorkflowRuns(args = {}) {
3537
+ return this.stores.workflows.getWorkflowRuns(args);
3201
3538
  }
3202
3539
  async getWorkflowRunById({
3203
3540
  runId,
@@ -3224,7 +3561,7 @@ var MSSQLStore = class extends storage.MastraStorage {
3224
3561
  return this.stores.operations.dropIndex(indexName);
3225
3562
  }
3226
3563
  /**
3227
- * Tracing / Observability
3564
+ * AI Tracing / Observability
3228
3565
  */
3229
3566
  getObservabilityStore() {
3230
3567
  if (!this.stores.observability) {
@@ -3237,30 +3574,30 @@ var MSSQLStore = class extends storage.MastraStorage {
3237
3574
  }
3238
3575
  return this.stores.observability;
3239
3576
  }
3240
- async createSpan(span) {
3241
- return this.getObservabilityStore().createSpan(span);
3577
+ async createAISpan(span) {
3578
+ return this.getObservabilityStore().createAISpan(span);
3242
3579
  }
3243
- async updateSpan({
3580
+ async updateAISpan({
3244
3581
  spanId,
3245
3582
  traceId,
3246
3583
  updates
3247
3584
  }) {
3248
- return this.getObservabilityStore().updateSpan({ spanId, traceId, updates });
3585
+ return this.getObservabilityStore().updateAISpan({ spanId, traceId, updates });
3249
3586
  }
3250
- async getTrace(traceId) {
3251
- return this.getObservabilityStore().getTrace(traceId);
3587
+ async getAITrace(traceId) {
3588
+ return this.getObservabilityStore().getAITrace(traceId);
3252
3589
  }
3253
- async getTracesPaginated(args) {
3254
- return this.getObservabilityStore().getTracesPaginated(args);
3590
+ async getAITracesPaginated(args) {
3591
+ return this.getObservabilityStore().getAITracesPaginated(args);
3255
3592
  }
3256
- async batchCreateSpans(args) {
3257
- return this.getObservabilityStore().batchCreateSpans(args);
3593
+ async batchCreateAISpans(args) {
3594
+ return this.getObservabilityStore().batchCreateAISpans(args);
3258
3595
  }
3259
- async batchUpdateSpans(args) {
3260
- return this.getObservabilityStore().batchUpdateSpans(args);
3596
+ async batchUpdateAISpans(args) {
3597
+ return this.getObservabilityStore().batchUpdateAISpans(args);
3261
3598
  }
3262
- async batchDeleteTraces(args) {
3263
- return this.getObservabilityStore().batchDeleteTraces(args);
3599
+ async batchDeleteAITraces(args) {
3600
+ return this.getObservabilityStore().batchDeleteAITraces(args);
3264
3601
  }
3265
3602
  /**
3266
3603
  * Scorers
@@ -3268,14 +3605,14 @@ var MSSQLStore = class extends storage.MastraStorage {
3268
3605
  async getScoreById({ id: _id }) {
3269
3606
  return this.stores.scores.getScoreById({ id: _id });
3270
3607
  }
3271
- async listScoresByScorerId({
3608
+ async getScoresByScorerId({
3272
3609
  scorerId: _scorerId,
3273
3610
  pagination: _pagination,
3274
3611
  entityId: _entityId,
3275
3612
  entityType: _entityType,
3276
3613
  source: _source
3277
3614
  }) {
3278
- return this.stores.scores.listScoresByScorerId({
3615
+ return this.stores.scores.getScoresByScorerId({
3279
3616
  scorerId: _scorerId,
3280
3617
  pagination: _pagination,
3281
3618
  entityId: _entityId,
@@ -3286,29 +3623,29 @@ var MSSQLStore = class extends storage.MastraStorage {
3286
3623
  async saveScore(_score) {
3287
3624
  return this.stores.scores.saveScore(_score);
3288
3625
  }
3289
- async listScoresByRunId({
3626
+ async getScoresByRunId({
3290
3627
  runId: _runId,
3291
3628
  pagination: _pagination
3292
3629
  }) {
3293
- return this.stores.scores.listScoresByRunId({ runId: _runId, pagination: _pagination });
3630
+ return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
3294
3631
  }
3295
- async listScoresByEntityId({
3632
+ async getScoresByEntityId({
3296
3633
  entityId: _entityId,
3297
3634
  entityType: _entityType,
3298
3635
  pagination: _pagination
3299
3636
  }) {
3300
- return this.stores.scores.listScoresByEntityId({
3637
+ return this.stores.scores.getScoresByEntityId({
3301
3638
  entityId: _entityId,
3302
3639
  entityType: _entityType,
3303
3640
  pagination: _pagination
3304
3641
  });
3305
3642
  }
3306
- async listScoresBySpan({
3643
+ async getScoresBySpan({
3307
3644
  traceId,
3308
3645
  spanId,
3309
3646
  pagination: _pagination
3310
3647
  }) {
3311
- return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination: _pagination });
3648
+ return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination: _pagination });
3312
3649
  }
3313
3650
  };
3314
3651