@mastra/mssql 0.5.1-alpha.0 → 1.0.0-beta.0

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,12 @@ 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
+ const perPage = storage.normalizePerPage(perPageInput, 100);
160
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
161
+ const { field, direction } = this.parseOrderBy(orderBy);
305
162
  try {
306
- const perPage = perPageInput !== void 0 ? perPageInput : 100;
307
- const currentOffset = page * perPage;
308
163
  const baseQuery = `FROM ${getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
309
164
  const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
310
165
  const countRequest = this.pool.request();
@@ -316,17 +171,22 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
316
171
  threads: [],
317
172
  total: 0,
318
173
  page,
319
- perPage,
174
+ perPage: perPageForResponse,
320
175
  hasMore: false
321
176
  };
322
177
  }
323
- const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
324
- const dir = (sortDirection || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
178
+ const orderByField = field === "createdAt" ? "[createdAt]" : "[updatedAt]";
179
+ const dir = (direction || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
180
+ const limitValue = perPageInput === false ? total : perPage;
325
181
  const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${dir} OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
326
182
  const dataRequest = this.pool.request();
327
183
  dataRequest.input("resourceId", resourceId);
328
- dataRequest.input("perPage", perPage);
329
- dataRequest.input("offset", currentOffset);
184
+ dataRequest.input("offset", offset);
185
+ if (limitValue > 2147483647) {
186
+ dataRequest.input("perPage", sql2__default.default.BigInt, limitValue);
187
+ } else {
188
+ dataRequest.input("perPage", limitValue);
189
+ }
330
190
  const rowsResult = await dataRequest.query(dataQuery);
331
191
  const rows = rowsResult.recordset || [];
332
192
  const threads = rows.map((thread) => ({
@@ -339,13 +199,13 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
339
199
  threads,
340
200
  total,
341
201
  page,
342
- perPage,
343
- hasMore: currentOffset + threads.length < total
202
+ perPage: perPageForResponse,
203
+ hasMore: perPageInput === false ? false : offset + perPage < total
344
204
  };
345
205
  } catch (error$1) {
346
206
  const mastraError = new error.MastraError(
347
207
  {
348
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
208
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
349
209
  domain: error.ErrorDomain.STORAGE,
350
210
  category: error.ErrorCategory.THIRD_PARTY,
351
211
  details: {
@@ -357,7 +217,13 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
357
217
  );
358
218
  this.logger?.error?.(mastraError.toString());
359
219
  this.logger?.trackException?.(mastraError);
360
- return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
220
+ return {
221
+ threads: [],
222
+ total: 0,
223
+ page,
224
+ perPage: perPageForResponse,
225
+ hasMore: false
226
+ };
361
227
  }
362
228
  }
363
229
  async saveThread({ thread }) {
@@ -381,12 +247,12 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
381
247
  req.input("title", thread.title);
382
248
  const metadata = thread.metadata ? JSON.stringify(thread.metadata) : null;
383
249
  if (metadata === null) {
384
- req.input("metadata", sql3__default.default.NVarChar, null);
250
+ req.input("metadata", sql2__default.default.NVarChar, null);
385
251
  } else {
386
252
  req.input("metadata", metadata);
387
253
  }
388
- req.input("createdAt", sql3__default.default.DateTime2, thread.createdAt);
389
- req.input("updatedAt", sql3__default.default.DateTime2, thread.updatedAt);
254
+ req.input("createdAt", sql2__default.default.DateTime2, thread.createdAt);
255
+ req.input("updatedAt", sql2__default.default.DateTime2, thread.updatedAt);
390
256
  await req.query(mergeSql);
391
257
  return thread;
392
258
  } catch (error$1) {
@@ -403,31 +269,6 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
403
269
  );
404
270
  }
405
271
  }
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
272
  /**
432
273
  * Updates a thread's title and metadata, merging with existing metadata. Returns the updated thread.
433
274
  */
@@ -455,7 +296,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
455
296
  };
456
297
  try {
457
298
  const table = getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) });
458
- const sql7 = `UPDATE ${table}
299
+ const sql5 = `UPDATE ${table}
459
300
  SET title = @title,
460
301
  metadata = @metadata,
461
302
  [updatedAt] = @updatedAt
@@ -466,7 +307,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
466
307
  req.input("title", title);
467
308
  req.input("metadata", JSON.stringify(mergedMetadata));
468
309
  req.input("updatedAt", /* @__PURE__ */ new Date());
469
- const result = await req.query(sql7);
310
+ const result = await req.query(sql5);
470
311
  let thread = result.recordset && result.recordset[0];
471
312
  if (thread && "seq_id" in thread) {
472
313
  const { seq_id, ...rest } = thread;
@@ -536,11 +377,9 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
536
377
  }
537
378
  async _getIncludedMessages({
538
379
  threadId,
539
- selectBy,
540
- orderByStatement
380
+ include
541
381
  }) {
542
382
  if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
543
- const include = selectBy?.include;
544
383
  if (!include) return null;
545
384
  const unionQueries = [];
546
385
  const paramValues = [];
@@ -565,7 +404,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
565
404
  m.[resourceId],
566
405
  m.seq_id
567
406
  FROM (
568
- SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
407
+ SELECT *, ROW_NUMBER() OVER (ORDER BY [createdAt] ASC) as row_num
569
408
  FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
570
409
  WHERE [thread_id] = ${pThreadId}
571
410
  ) AS m
@@ -573,15 +412,17 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
573
412
  OR EXISTS (
574
413
  SELECT 1
575
414
  FROM (
576
- SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
415
+ SELECT *, ROW_NUMBER() OVER (ORDER BY [createdAt] ASC) as row_num
577
416
  FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
578
417
  WHERE [thread_id] = ${pThreadId}
579
418
  ) AS target
580
419
  WHERE target.id = ${pId}
581
420
  AND (
582
- (m.row_num <= target.row_num + ${pPrev} AND m.row_num > target.row_num)
421
+ -- Get previous messages (messages that come BEFORE the target)
422
+ (m.row_num < target.row_num AND m.row_num >= target.row_num - ${pPrev})
583
423
  OR
584
- (m.row_num >= target.row_num - ${pNext} AND m.row_num < target.row_num)
424
+ -- Get next messages (messages that come AFTER the target)
425
+ (m.row_num > target.row_num AND m.row_num <= target.row_num + ${pNext})
585
426
  )
586
427
  )
587
428
  `
@@ -610,34 +451,16 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
610
451
  });
611
452
  return dedupedRows;
612
453
  }
613
- async getMessages(args) {
614
- const { threadId, resourceId, format, selectBy } = args;
454
+ async listMessagesById({ messageIds }) {
455
+ if (messageIds.length === 0) return { messages: [] };
615
456
  const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
616
457
  const orderByStatement = `ORDER BY [seq_id] DESC`;
617
- const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
618
458
  try {
619
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
620
459
  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`;
460
+ let query = `${selectStatement} FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [id] IN (${messageIds.map((_, i) => `@id${i}`).join(", ")})`;
630
461
  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);
462
+ messageIds.forEach((id, i) => request.input(`id${i}`, id));
463
+ query += ` ${orderByStatement}`;
641
464
  const result = await request.query(query);
642
465
  const remainingRows = result.recordset || [];
643
466
  rows.push(...remainingRows);
@@ -645,153 +468,150 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
645
468
  const timeDiff = a.seq_id - b.seq_id;
646
469
  return timeDiff;
647
470
  });
648
- rows = rows.map(({ seq_id, ...rest }) => rest);
649
- return this._parseAndFormatMessages(rows, format);
471
+ const messagesWithParsedContent = rows.map((row) => {
472
+ if (typeof row.content === "string") {
473
+ try {
474
+ return { ...row, content: JSON.parse(row.content) };
475
+ } catch {
476
+ return row;
477
+ }
478
+ }
479
+ return row;
480
+ });
481
+ const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
482
+ const list = new agent.MessageList().add(cleanMessages, "memory");
483
+ return { messages: list.get.all.db() };
650
484
  } catch (error$1) {
651
485
  const mastraError = new error.MastraError(
652
486
  {
653
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_FAILED",
487
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_MESSAGES_BY_ID_FAILED",
654
488
  domain: error.ErrorDomain.STORAGE,
655
489
  category: error.ErrorCategory.THIRD_PARTY,
656
490
  details: {
657
- threadId,
658
- resourceId: resourceId ?? ""
491
+ messageIds: JSON.stringify(messageIds)
659
492
  }
660
493
  },
661
494
  error$1
662
495
  );
663
496
  this.logger?.error?.(mastraError.toString());
664
497
  this.logger?.trackException?.(mastraError);
665
- return [];
498
+ return { messages: [] };
666
499
  }
667
500
  }
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(
501
+ async listMessages(args) {
502
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
503
+ if (!threadId.trim()) {
504
+ throw new error.MastraError(
693
505
  {
694
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_BY_ID_FAILED",
506
+ id: "STORAGE_MSSQL_LIST_MESSAGES_INVALID_THREAD_ID",
695
507
  domain: error.ErrorDomain.STORAGE,
696
508
  category: error.ErrorCategory.THIRD_PARTY,
697
- details: {
698
- messageIds: JSON.stringify(messageIds)
699
- }
509
+ details: { threadId }
700
510
  },
701
- error$1
511
+ new Error("threadId must be a non-empty string")
702
512
  );
703
- this.logger?.error?.(mastraError.toString());
704
- this.logger?.trackException?.(mastraError);
705
- return [];
706
513
  }
707
- }
708
- async getMessagesPaginated(args) {
709
- const { threadId, resourceId, format, selectBy } = args;
710
- const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
514
+ const perPage = storage.normalizePerPage(perPageInput, 40);
515
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
711
516
  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;
517
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
518
+ const orderByStatement = `ORDER BY [${field}] ${direction}`;
715
519
  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;
520
+ const tableName = getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
724
521
  const conditions = ["[thread_id] = @threadId"];
725
522
  const request = this.pool.request();
726
523
  request.input("threadId", threadId);
727
- if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
524
+ if (resourceId) {
525
+ conditions.push("[resourceId] = @resourceId");
526
+ request.input("resourceId", resourceId);
527
+ }
528
+ if (filter?.dateRange?.start) {
728
529
  conditions.push("[createdAt] >= @fromDate");
729
- request.input("fromDate", fromDate.toISOString());
530
+ request.input("fromDate", filter.dateRange.start);
730
531
  }
731
- if (toDate instanceof Date && !isNaN(toDate.getTime())) {
532
+ if (filter?.dateRange?.end) {
732
533
  conditions.push("[createdAt] <= @toDate");
733
- request.input("toDate", toDate.toISOString());
534
+ request.input("toDate", filter.dateRange.end);
734
535
  }
735
536
  const whereClause = `WHERE ${conditions.join(" AND ")}`;
736
- const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
537
+ const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
737
538
  const countResult = await request.query(countQuery);
738
539
  const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
739
- if (total === 0 && messages.length > 0) {
740
- const parsedIncluded = this._parseAndFormatMessages(messages, format);
540
+ const limitValue = perPageInput === false ? total : perPage;
541
+ const dataQuery = `${selectStatement} FROM ${tableName} ${whereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
542
+ request.input("offset", offset);
543
+ if (limitValue > 2147483647) {
544
+ request.input("limit", sql2__default.default.BigInt, limitValue);
545
+ } else {
546
+ request.input("limit", limitValue);
547
+ }
548
+ const rowsResult = await request.query(dataQuery);
549
+ const rows = rowsResult.recordset || [];
550
+ const messages = [...rows];
551
+ if (total === 0 && messages.length === 0 && (!include || include.length === 0)) {
741
552
  return {
742
- messages: parsedIncluded,
743
- total: parsedIncluded.length,
553
+ messages: [],
554
+ total: 0,
744
555
  page,
745
- perPage,
556
+ perPage: perPageForResponse,
746
557
  hasMore: false
747
558
  };
748
559
  }
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));
560
+ const messageIds = new Set(messages.map((m) => m.id));
561
+ if (include && include.length > 0) {
562
+ const includeMessages = await this._getIncludedMessages({ threadId, include });
563
+ if (includeMessages) {
564
+ for (const includeMsg of includeMessages) {
565
+ if (!messageIds.has(includeMsg.id)) {
566
+ messages.push(includeMsg);
567
+ messageIds.add(includeMsg.id);
568
+ }
569
+ }
570
+ }
754
571
  }
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);
572
+ const parsed = this._parseAndFormatMessages(messages, "v2");
573
+ let finalMessages = parsed;
574
+ finalMessages = finalMessages.sort((a, b) => {
575
+ const aValue = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
576
+ const bValue = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
577
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
578
+ });
579
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
580
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
581
+ const hasMore = perPageInput !== false && !allThreadMessagesReturned && offset + perPage < total;
764
582
  return {
765
- messages: parsed,
583
+ messages: finalMessages,
766
584
  total,
767
585
  page,
768
- perPage,
769
- hasMore: currentOffset + rows.length < total
586
+ perPage: perPageForResponse,
587
+ hasMore
770
588
  };
771
589
  } catch (error$1) {
772
590
  const mastraError = new error.MastraError(
773
591
  {
774
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_PAGINATED_FAILED",
592
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_MESSAGES_FAILED",
775
593
  domain: error.ErrorDomain.STORAGE,
776
594
  category: error.ErrorCategory.THIRD_PARTY,
777
595
  details: {
778
596
  threadId,
779
- resourceId: resourceId ?? "",
780
- page
597
+ resourceId: resourceId ?? ""
781
598
  }
782
599
  },
783
600
  error$1
784
601
  );
785
602
  this.logger?.error?.(mastraError.toString());
786
603
  this.logger?.trackException?.(mastraError);
787
- return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
604
+ return {
605
+ messages: [],
606
+ total: 0,
607
+ page,
608
+ perPage: perPageForResponse,
609
+ hasMore: false
610
+ };
788
611
  }
789
612
  }
790
- async saveMessages({
791
- messages,
792
- format
793
- }) {
794
- if (messages.length === 0) return messages;
613
+ async saveMessages({ messages }) {
614
+ if (messages.length === 0) return { messages: [] };
795
615
  const threadId = messages[0]?.threadId;
796
616
  if (!threadId) {
797
617
  throw new error.MastraError({
@@ -835,7 +655,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
835
655
  "content",
836
656
  typeof message.content === "string" ? message.content : JSON.stringify(message.content)
837
657
  );
838
- request.input("createdAt", sql3__default.default.DateTime2, message.createdAt);
658
+ request.input("createdAt", sql2__default.default.DateTime2, message.createdAt);
839
659
  request.input("role", message.role);
840
660
  request.input("type", message.type || "v2");
841
661
  request.input("resourceId", message.resourceId);
@@ -854,7 +674,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
854
674
  await request.query(mergeSql);
855
675
  }
856
676
  const threadReq = transaction.request();
857
- threadReq.input("updatedAt", sql3__default.default.DateTime2, /* @__PURE__ */ new Date());
677
+ threadReq.input("updatedAt", sql2__default.default.DateTime2, /* @__PURE__ */ new Date());
858
678
  threadReq.input("id", threadId);
859
679
  await threadReq.query(`UPDATE ${tableThreads} SET [updatedAt] = @updatedAt WHERE id = @id`);
860
680
  await transaction.commit();
@@ -873,8 +693,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
873
693
  return message;
874
694
  });
875
695
  const list = new agent.MessageList().add(messagesWithParsedContent, "memory");
876
- if (format === "v2") return list.get.all.v2();
877
- return list.get.all.v1();
696
+ return { messages: list.get.all.db() };
878
697
  } catch (error$1) {
879
698
  throw new error.MastraError(
880
699
  {
@@ -1153,13 +972,13 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1153
972
  this.operations = operations;
1154
973
  this.schema = schema;
1155
974
  }
1156
- get aiTracingStrategy() {
975
+ get tracingStrategy() {
1157
976
  return {
1158
977
  preferred: "batch-with-updates",
1159
978
  supported: ["batch-with-updates", "insert-only"]
1160
979
  };
1161
980
  }
1162
- async createAISpan(span) {
981
+ async createSpan(span) {
1163
982
  try {
1164
983
  const startedAt = span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt;
1165
984
  const endedAt = span.endedAt instanceof Date ? span.endedAt.toISOString() : span.endedAt;
@@ -1169,11 +988,11 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1169
988
  endedAt
1170
989
  // Note: createdAt/updatedAt will be set by default values
1171
990
  };
1172
- return this.operations.insert({ tableName: storage.TABLE_AI_SPANS, record });
991
+ return this.operations.insert({ tableName: storage.TABLE_SPANS, record });
1173
992
  } catch (error$1) {
1174
993
  throw new error.MastraError(
1175
994
  {
1176
- id: "MSSQL_STORE_CREATE_AI_SPAN_FAILED",
995
+ id: "MSSQL_STORE_CREATE_SPAN_FAILED",
1177
996
  domain: error.ErrorDomain.STORAGE,
1178
997
  category: error.ErrorCategory.USER,
1179
998
  details: {
@@ -1187,10 +1006,10 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1187
1006
  );
1188
1007
  }
1189
1008
  }
1190
- async getAITrace(traceId) {
1009
+ async getTrace(traceId) {
1191
1010
  try {
1192
1011
  const tableName = getTableName({
1193
- indexName: storage.TABLE_AI_SPANS,
1012
+ indexName: storage.TABLE_SPANS,
1194
1013
  schemaName: getSchemaName(this.schema)
1195
1014
  });
1196
1015
  const request = this.pool.request();
@@ -1211,7 +1030,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1211
1030
  traceId,
1212
1031
  spans: result.recordset.map(
1213
1032
  (span) => transformFromSqlRow({
1214
- tableName: storage.TABLE_AI_SPANS,
1033
+ tableName: storage.TABLE_SPANS,
1215
1034
  sqlRow: span
1216
1035
  })
1217
1036
  )
@@ -1219,7 +1038,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1219
1038
  } catch (error$1) {
1220
1039
  throw new error.MastraError(
1221
1040
  {
1222
- id: "MSSQL_STORE_GET_AI_TRACE_FAILED",
1041
+ id: "MSSQL_STORE_GET_TRACE_FAILED",
1223
1042
  domain: error.ErrorDomain.STORAGE,
1224
1043
  category: error.ErrorCategory.USER,
1225
1044
  details: {
@@ -1230,7 +1049,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1230
1049
  );
1231
1050
  }
1232
1051
  }
1233
- async updateAISpan({
1052
+ async updateSpan({
1234
1053
  spanId,
1235
1054
  traceId,
1236
1055
  updates
@@ -1244,14 +1063,14 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1244
1063
  data.startedAt = data.startedAt.toISOString();
1245
1064
  }
1246
1065
  await this.operations.update({
1247
- tableName: storage.TABLE_AI_SPANS,
1066
+ tableName: storage.TABLE_SPANS,
1248
1067
  keys: { spanId, traceId },
1249
1068
  data
1250
1069
  });
1251
1070
  } catch (error$1) {
1252
1071
  throw new error.MastraError(
1253
1072
  {
1254
- id: "MSSQL_STORE_UPDATE_AI_SPAN_FAILED",
1073
+ id: "MSSQL_STORE_UPDATE_SPAN_FAILED",
1255
1074
  domain: error.ErrorDomain.STORAGE,
1256
1075
  category: error.ErrorCategory.USER,
1257
1076
  details: {
@@ -1263,7 +1082,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1263
1082
  );
1264
1083
  }
1265
1084
  }
1266
- async getAITracesPaginated({
1085
+ async getTracesPaginated({
1267
1086
  filters,
1268
1087
  pagination
1269
1088
  }) {
@@ -1288,7 +1107,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1288
1107
  name = `agent run: '${entityId}'`;
1289
1108
  } else {
1290
1109
  const error$1 = new error.MastraError({
1291
- id: "MSSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1110
+ id: "MSSQL_STORE_GET_TRACES_PAGINATED_FAILED",
1292
1111
  domain: error.ErrorDomain.STORAGE,
1293
1112
  category: error.ErrorCategory.USER,
1294
1113
  details: {
@@ -1307,7 +1126,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1307
1126
  params[entityParam] = name;
1308
1127
  }
1309
1128
  const tableName = getTableName({
1310
- indexName: storage.TABLE_AI_SPANS,
1129
+ indexName: storage.TABLE_SPANS,
1311
1130
  schemaName: getSchemaName(this.schema)
1312
1131
  });
1313
1132
  try {
@@ -1341,7 +1160,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1341
1160
  );
1342
1161
  const spans = dataResult.recordset.map(
1343
1162
  (row) => transformFromSqlRow({
1344
- tableName: storage.TABLE_AI_SPANS,
1163
+ tableName: storage.TABLE_SPANS,
1345
1164
  sqlRow: row
1346
1165
  })
1347
1166
  );
@@ -1357,7 +1176,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1357
1176
  } catch (error$1) {
1358
1177
  throw new error.MastraError(
1359
1178
  {
1360
- id: "MSSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1179
+ id: "MSSQL_STORE_GET_TRACES_PAGINATED_FAILED",
1361
1180
  domain: error.ErrorDomain.STORAGE,
1362
1181
  category: error.ErrorCategory.USER
1363
1182
  },
@@ -1365,13 +1184,13 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1365
1184
  );
1366
1185
  }
1367
1186
  }
1368
- async batchCreateAISpans(args) {
1187
+ async batchCreateSpans(args) {
1369
1188
  if (!args.records || args.records.length === 0) {
1370
1189
  return;
1371
1190
  }
1372
1191
  try {
1373
1192
  await this.operations.batchInsert({
1374
- tableName: storage.TABLE_AI_SPANS,
1193
+ tableName: storage.TABLE_SPANS,
1375
1194
  records: args.records.map((span) => ({
1376
1195
  ...span,
1377
1196
  startedAt: span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt,
@@ -1381,7 +1200,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1381
1200
  } catch (error$1) {
1382
1201
  throw new error.MastraError(
1383
1202
  {
1384
- id: "MSSQL_STORE_BATCH_CREATE_AI_SPANS_FAILED",
1203
+ id: "MSSQL_STORE_BATCH_CREATE_SPANS_FAILED",
1385
1204
  domain: error.ErrorDomain.STORAGE,
1386
1205
  category: error.ErrorCategory.USER,
1387
1206
  details: {
@@ -1392,7 +1211,7 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1392
1211
  );
1393
1212
  }
1394
1213
  }
1395
- async batchUpdateAISpans(args) {
1214
+ async batchUpdateSpans(args) {
1396
1215
  if (!args.records || args.records.length === 0) {
1397
1216
  return;
1398
1217
  }
@@ -1411,13 +1230,13 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1411
1230
  };
1412
1231
  });
1413
1232
  await this.operations.batchUpdate({
1414
- tableName: storage.TABLE_AI_SPANS,
1233
+ tableName: storage.TABLE_SPANS,
1415
1234
  updates
1416
1235
  });
1417
1236
  } catch (error$1) {
1418
1237
  throw new error.MastraError(
1419
1238
  {
1420
- id: "MSSQL_STORE_BATCH_UPDATE_AI_SPANS_FAILED",
1239
+ id: "MSSQL_STORE_BATCH_UPDATE_SPANS_FAILED",
1421
1240
  domain: error.ErrorDomain.STORAGE,
1422
1241
  category: error.ErrorCategory.USER,
1423
1242
  details: {
@@ -1428,20 +1247,20 @@ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1428
1247
  );
1429
1248
  }
1430
1249
  }
1431
- async batchDeleteAITraces(args) {
1250
+ async batchDeleteTraces(args) {
1432
1251
  if (!args.traceIds || args.traceIds.length === 0) {
1433
1252
  return;
1434
1253
  }
1435
1254
  try {
1436
1255
  const keys = args.traceIds.map((traceId) => ({ traceId }));
1437
1256
  await this.operations.batchDelete({
1438
- tableName: storage.TABLE_AI_SPANS,
1257
+ tableName: storage.TABLE_SPANS,
1439
1258
  keys
1440
1259
  });
1441
1260
  } catch (error$1) {
1442
1261
  throw new error.MastraError(
1443
1262
  {
1444
- id: "MSSQL_STORE_BATCH_DELETE_AI_TRACES_FAILED",
1263
+ id: "MSSQL_STORE_BATCH_DELETE_TRACES_FAILED",
1445
1264
  domain: error.ErrorDomain.STORAGE,
1446
1265
  category: error.ErrorCategory.USER,
1447
1266
  details: {
@@ -1556,7 +1375,7 @@ var StoreOperationsMSSQL = class extends storage.StoreOperations {
1556
1375
  const value = record[col];
1557
1376
  const preparedValue = this.prepareValue(value, col, tableName);
1558
1377
  if (preparedValue instanceof Date) {
1559
- request.input(`param${i}`, sql3__default.default.DateTime2, preparedValue);
1378
+ request.input(`param${i}`, sql2__default.default.DateTime2, preparedValue);
1560
1379
  } else if (preparedValue === null || preparedValue === void 0) {
1561
1380
  request.input(`param${i}`, this.getMssqlType(tableName, col), null);
1562
1381
  } else {
@@ -1771,7 +1590,7 @@ ${columns}
1771
1590
  try {
1772
1591
  const keyEntries = Object.entries(keys).map(([key, value]) => [utils.parseSqlIdentifier(key, "column name"), value]);
1773
1592
  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}`;
1593
+ const sql5 = `SELECT * FROM ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} WHERE ${conditions}`;
1775
1594
  const request = this.pool.request();
1776
1595
  keyEntries.forEach(([key, value], i) => {
1777
1596
  const preparedValue = this.prepareValue(value, key, tableName);
@@ -1781,7 +1600,7 @@ ${columns}
1781
1600
  request.input(`param${i}`, preparedValue);
1782
1601
  }
1783
1602
  });
1784
- const resultSet = await request.query(sql7);
1603
+ const resultSet = await request.query(sql5);
1785
1604
  const result = resultSet.recordset[0] || null;
1786
1605
  if (!result) {
1787
1606
  return null;
@@ -1880,23 +1699,23 @@ ${columns}
1880
1699
  const col = storage.TABLE_SCHEMAS[tableName]?.[columnName];
1881
1700
  switch (col?.type) {
1882
1701
  case "text":
1883
- return sql3__default.default.NVarChar;
1702
+ return sql2__default.default.NVarChar;
1884
1703
  case "timestamp":
1885
- return sql3__default.default.DateTime2;
1704
+ return sql2__default.default.DateTime2;
1886
1705
  case "uuid":
1887
- return sql3__default.default.UniqueIdentifier;
1706
+ return sql2__default.default.UniqueIdentifier;
1888
1707
  case "jsonb":
1889
- return sql3__default.default.NVarChar;
1708
+ return sql2__default.default.NVarChar;
1890
1709
  case "integer":
1891
- return sql3__default.default.Int;
1710
+ return sql2__default.default.Int;
1892
1711
  case "bigint":
1893
- return sql3__default.default.BigInt;
1712
+ return sql2__default.default.BigInt;
1894
1713
  case "float":
1895
- return sql3__default.default.Float;
1714
+ return sql2__default.default.Float;
1896
1715
  case "boolean":
1897
- return sql3__default.default.Bit;
1716
+ return sql2__default.default.Bit;
1898
1717
  default:
1899
- return sql3__default.default.NVarChar;
1718
+ return sql2__default.default.NVarChar;
1900
1719
  }
1901
1720
  }
1902
1721
  /**
@@ -2340,35 +2159,30 @@ ${columns}
2340
2159
  table: storage.TABLE_TRACES,
2341
2160
  columns: ["name", "seq_id DESC"]
2342
2161
  },
2343
- {
2344
- name: `${schemaPrefix}mastra_evals_agent_name_seqid_idx`,
2345
- table: storage.TABLE_EVALS,
2346
- columns: ["agent_name", "seq_id DESC"]
2347
- },
2348
2162
  {
2349
2163
  name: `${schemaPrefix}mastra_scores_trace_id_span_id_seqid_idx`,
2350
2164
  table: storage.TABLE_SCORERS,
2351
2165
  columns: ["traceId", "spanId", "seq_id DESC"]
2352
2166
  },
2353
- // AI Spans indexes for optimal trace querying
2167
+ // Spans indexes for optimal trace querying
2354
2168
  {
2355
2169
  name: `${schemaPrefix}mastra_ai_spans_traceid_startedat_idx`,
2356
- table: storage.TABLE_AI_SPANS,
2170
+ table: storage.TABLE_SPANS,
2357
2171
  columns: ["traceId", "startedAt DESC"]
2358
2172
  },
2359
2173
  {
2360
2174
  name: `${schemaPrefix}mastra_ai_spans_parentspanid_startedat_idx`,
2361
- table: storage.TABLE_AI_SPANS,
2175
+ table: storage.TABLE_SPANS,
2362
2176
  columns: ["parentSpanId", "startedAt DESC"]
2363
2177
  },
2364
2178
  {
2365
2179
  name: `${schemaPrefix}mastra_ai_spans_name_idx`,
2366
- table: storage.TABLE_AI_SPANS,
2180
+ table: storage.TABLE_SPANS,
2367
2181
  columns: ["name"]
2368
2182
  },
2369
2183
  {
2370
2184
  name: `${schemaPrefix}mastra_ai_spans_spantype_startedat_idx`,
2371
- table: storage.TABLE_AI_SPANS,
2185
+ table: storage.TABLE_SPANS,
2372
2186
  columns: ["spanType", "startedAt DESC"]
2373
2187
  }
2374
2188
  ];
@@ -2409,7 +2223,7 @@ function transformScoreRow(row) {
2409
2223
  metadata: storage.safelyParseJSON(row.metadata),
2410
2224
  output: storage.safelyParseJSON(row.output),
2411
2225
  additionalContext: storage.safelyParseJSON(row.additionalContext),
2412
- runtimeContext: storage.safelyParseJSON(row.runtimeContext),
2226
+ requestContext: storage.safelyParseJSON(row.requestContext),
2413
2227
  entity: storage.safelyParseJSON(row.entity),
2414
2228
  createdAt: row.createdAt,
2415
2229
  updatedAt: row.updatedAt
@@ -2455,7 +2269,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2455
2269
  async saveScore(score) {
2456
2270
  let validatedScore;
2457
2271
  try {
2458
- validatedScore = scores.saveScorePayloadSchema.parse(score);
2272
+ validatedScore = evals.saveScorePayloadSchema.parse(score);
2459
2273
  } catch (error$1) {
2460
2274
  throw new error.MastraError(
2461
2275
  {
@@ -2476,7 +2290,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2476
2290
  input,
2477
2291
  output,
2478
2292
  additionalContext,
2479
- runtimeContext,
2293
+ requestContext,
2480
2294
  entity,
2481
2295
  ...rest
2482
2296
  } = validatedScore;
@@ -2491,7 +2305,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2491
2305
  analyzeStepResult: analyzeStepResult || null,
2492
2306
  metadata: metadata || null,
2493
2307
  additionalContext: additionalContext || null,
2494
- runtimeContext: runtimeContext || null,
2308
+ requestContext: requestContext || null,
2495
2309
  entity: entity || null,
2496
2310
  scorer: scorer || null,
2497
2311
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -2511,7 +2325,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2511
2325
  );
2512
2326
  }
2513
2327
  }
2514
- async getScoresByScorerId({
2328
+ async listScoresByScorerId({
2515
2329
  scorerId,
2516
2330
  pagination,
2517
2331
  entityId,
@@ -2545,31 +2359,36 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2545
2359
  });
2546
2360
  const totalResult = await countRequest.query(`SELECT COUNT(*) as count FROM ${tableName} WHERE ${whereClause}`);
2547
2361
  const total = totalResult.recordset[0]?.count || 0;
2362
+ const { page, perPage: perPageInput } = pagination;
2548
2363
  if (total === 0) {
2549
2364
  return {
2550
2365
  pagination: {
2551
2366
  total: 0,
2552
- page: pagination.page,
2553
- perPage: pagination.perPage,
2367
+ page,
2368
+ perPage: perPageInput,
2554
2369
  hasMore: false
2555
2370
  },
2556
2371
  scores: []
2557
2372
  };
2558
2373
  }
2374
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2375
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2376
+ const limitValue = perPageInput === false ? total : perPage;
2377
+ const end = perPageInput === false ? total : start + perPage;
2559
2378
  const dataRequest = this.pool.request();
2560
2379
  Object.entries(params).forEach(([key, value]) => {
2561
2380
  dataRequest.input(key, value);
2562
2381
  });
2563
- dataRequest.input("perPage", pagination.perPage);
2564
- dataRequest.input("offset", pagination.page * pagination.perPage);
2382
+ dataRequest.input("perPage", limitValue);
2383
+ dataRequest.input("offset", start);
2565
2384
  const dataQuery = `SELECT * FROM ${tableName} WHERE ${whereClause} ORDER BY [createdAt] DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
2566
2385
  const result = await dataRequest.query(dataQuery);
2567
2386
  return {
2568
2387
  pagination: {
2569
2388
  total: Number(total),
2570
- page: pagination.page,
2571
- perPage: pagination.perPage,
2572
- hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2389
+ page,
2390
+ perPage: perPageForResponse,
2391
+ hasMore: end < total
2573
2392
  },
2574
2393
  scores: result.recordset.map((row) => transformScoreRow(row))
2575
2394
  };
@@ -2585,7 +2404,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2585
2404
  );
2586
2405
  }
2587
2406
  }
2588
- async getScoresByRunId({
2407
+ async listScoresByRunId({
2589
2408
  runId,
2590
2409
  pagination
2591
2410
  }) {
@@ -2596,30 +2415,35 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2596
2415
  `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [runId] = @p1`
2597
2416
  );
2598
2417
  const total = totalResult.recordset[0]?.count || 0;
2418
+ const { page, perPage: perPageInput } = pagination;
2599
2419
  if (total === 0) {
2600
2420
  return {
2601
2421
  pagination: {
2602
2422
  total: 0,
2603
- page: pagination.page,
2604
- perPage: pagination.perPage,
2423
+ page,
2424
+ perPage: perPageInput,
2605
2425
  hasMore: false
2606
2426
  },
2607
2427
  scores: []
2608
2428
  };
2609
2429
  }
2430
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2431
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2432
+ const limitValue = perPageInput === false ? total : perPage;
2433
+ const end = perPageInput === false ? total : start + perPage;
2610
2434
  const dataRequest = this.pool.request();
2611
2435
  dataRequest.input("p1", runId);
2612
- dataRequest.input("p2", pagination.perPage);
2613
- dataRequest.input("p3", pagination.page * pagination.perPage);
2436
+ dataRequest.input("p2", limitValue);
2437
+ dataRequest.input("p3", start);
2614
2438
  const result = await dataRequest.query(
2615
2439
  `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
2440
  );
2617
2441
  return {
2618
2442
  pagination: {
2619
2443
  total: Number(total),
2620
- page: pagination.page,
2621
- perPage: pagination.perPage,
2622
- hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2444
+ page,
2445
+ perPage: perPageForResponse,
2446
+ hasMore: end < total
2623
2447
  },
2624
2448
  scores: result.recordset.map((row) => transformScoreRow(row))
2625
2449
  };
@@ -2635,7 +2459,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2635
2459
  );
2636
2460
  }
2637
2461
  }
2638
- async getScoresByEntityId({
2462
+ async listScoresByEntityId({
2639
2463
  entityId,
2640
2464
  entityType,
2641
2465
  pagination
@@ -2648,31 +2472,36 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2648
2472
  `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [entityId] = @p1 AND [entityType] = @p2`
2649
2473
  );
2650
2474
  const total = totalResult.recordset[0]?.count || 0;
2475
+ const { page, perPage: perPageInput } = pagination;
2476
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2477
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2651
2478
  if (total === 0) {
2652
2479
  return {
2653
2480
  pagination: {
2654
2481
  total: 0,
2655
- page: pagination.page,
2656
- perPage: pagination.perPage,
2482
+ page,
2483
+ perPage: perPageForResponse,
2657
2484
  hasMore: false
2658
2485
  },
2659
2486
  scores: []
2660
2487
  };
2661
2488
  }
2489
+ const limitValue = perPageInput === false ? total : perPage;
2490
+ const end = perPageInput === false ? total : start + perPage;
2662
2491
  const dataRequest = this.pool.request();
2663
2492
  dataRequest.input("p1", entityId);
2664
2493
  dataRequest.input("p2", entityType);
2665
- dataRequest.input("p3", pagination.perPage);
2666
- dataRequest.input("p4", pagination.page * pagination.perPage);
2494
+ dataRequest.input("p3", limitValue);
2495
+ dataRequest.input("p4", start);
2667
2496
  const result = await dataRequest.query(
2668
2497
  `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
2498
  );
2670
2499
  return {
2671
2500
  pagination: {
2672
2501
  total: Number(total),
2673
- page: pagination.page,
2674
- perPage: pagination.perPage,
2675
- hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2502
+ page,
2503
+ perPage: perPageForResponse,
2504
+ hasMore: end < total
2676
2505
  },
2677
2506
  scores: result.recordset.map((row) => transformScoreRow(row))
2678
2507
  };
@@ -2688,7 +2517,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2688
2517
  );
2689
2518
  }
2690
2519
  }
2691
- async getScoresBySpan({
2520
+ async listScoresBySpan({
2692
2521
  traceId,
2693
2522
  spanId,
2694
2523
  pagination
@@ -2701,34 +2530,38 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2701
2530
  `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [traceId] = @p1 AND [spanId] = @p2`
2702
2531
  );
2703
2532
  const total = totalResult.recordset[0]?.count || 0;
2533
+ const { page, perPage: perPageInput } = pagination;
2534
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2535
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2704
2536
  if (total === 0) {
2705
2537
  return {
2706
2538
  pagination: {
2707
2539
  total: 0,
2708
- page: pagination.page,
2709
- perPage: pagination.perPage,
2540
+ page,
2541
+ perPage: perPageForResponse,
2710
2542
  hasMore: false
2711
2543
  },
2712
2544
  scores: []
2713
2545
  };
2714
2546
  }
2715
- const limit = pagination.perPage + 1;
2547
+ const limitValue = perPageInput === false ? total : perPage;
2548
+ const end = perPageInput === false ? total : start + perPage;
2716
2549
  const dataRequest = this.pool.request();
2717
2550
  dataRequest.input("p1", traceId);
2718
2551
  dataRequest.input("p2", spanId);
2719
- dataRequest.input("p3", limit);
2720
- dataRequest.input("p4", pagination.page * pagination.perPage);
2552
+ dataRequest.input("p3", limitValue);
2553
+ dataRequest.input("p4", start);
2721
2554
  const result = await dataRequest.query(
2722
2555
  `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
2556
  );
2724
2557
  return {
2725
2558
  pagination: {
2726
2559
  total: Number(total),
2727
- page: pagination.page,
2728
- perPage: pagination.perPage,
2729
- hasMore: result.recordset.length > pagination.perPage
2560
+ page,
2561
+ perPage: perPageForResponse,
2562
+ hasMore: end < total
2730
2563
  },
2731
- scores: result.recordset.slice(0, pagination.perPage).map((row) => transformScoreRow(row))
2564
+ scores: result.recordset.map((row) => transformScoreRow(row))
2732
2565
  };
2733
2566
  } catch (error$1) {
2734
2567
  throw new error.MastraError(
@@ -2743,173 +2576,6 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
2743
2576
  }
2744
2577
  }
2745
2578
  };
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
2579
  var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2914
2580
  pool;
2915
2581
  operations;
@@ -2947,13 +2613,13 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2947
2613
  runId,
2948
2614
  stepId,
2949
2615
  result,
2950
- runtimeContext
2616
+ requestContext
2951
2617
  }) {
2952
2618
  const table = getTableName({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
2953
2619
  const transaction = this.pool.transaction();
2954
2620
  try {
2955
2621
  await transaction.begin();
2956
- const selectRequest = new sql3__default.default.Request(transaction);
2622
+ const selectRequest = new sql2__default.default.Request(transaction);
2957
2623
  selectRequest.input("workflow_name", workflowName);
2958
2624
  selectRequest.input("run_id", runId);
2959
2625
  const existingSnapshotResult = await selectRequest.query(
@@ -2972,20 +2638,20 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2972
2638
  waitingPaths: {},
2973
2639
  status: "pending",
2974
2640
  runId,
2975
- runtimeContext: {}
2641
+ requestContext: {}
2976
2642
  };
2977
2643
  } else {
2978
2644
  const existingSnapshot = existingSnapshotResult.recordset[0].snapshot;
2979
2645
  snapshot = typeof existingSnapshot === "string" ? JSON.parse(existingSnapshot) : existingSnapshot;
2980
2646
  }
2981
2647
  snapshot.context[stepId] = result;
2982
- snapshot.runtimeContext = { ...snapshot.runtimeContext, ...runtimeContext };
2983
- const upsertReq = new sql3__default.default.Request(transaction);
2648
+ snapshot.requestContext = { ...snapshot.requestContext, ...requestContext };
2649
+ const upsertReq = new sql2__default.default.Request(transaction);
2984
2650
  upsertReq.input("workflow_name", workflowName);
2985
2651
  upsertReq.input("run_id", runId);
2986
2652
  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());
2653
+ upsertReq.input("createdAt", sql2__default.default.DateTime2, /* @__PURE__ */ new Date());
2654
+ upsertReq.input("updatedAt", sql2__default.default.DateTime2, /* @__PURE__ */ new Date());
2989
2655
  await upsertReq.query(
2990
2656
  `MERGE ${table} AS target
2991
2657
  USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
@@ -3025,7 +2691,7 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
3025
2691
  const transaction = this.pool.transaction();
3026
2692
  try {
3027
2693
  await transaction.begin();
3028
- const selectRequest = new sql3__default.default.Request(transaction);
2694
+ const selectRequest = new sql2__default.default.Request(transaction);
3029
2695
  selectRequest.input("workflow_name", workflowName);
3030
2696
  selectRequest.input("run_id", runId);
3031
2697
  const existingSnapshotResult = await selectRequest.query(
@@ -3053,11 +2719,11 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
3053
2719
  );
3054
2720
  }
3055
2721
  const updatedSnapshot = { ...snapshot, ...opts };
3056
- const updateRequest = new sql3__default.default.Request(transaction);
2722
+ const updateRequest = new sql2__default.default.Request(transaction);
3057
2723
  updateRequest.input("snapshot", JSON.stringify(updatedSnapshot));
3058
2724
  updateRequest.input("workflow_name", workflowName);
3059
2725
  updateRequest.input("run_id", runId);
3060
- updateRequest.input("updatedAt", sql3__default.default.DateTime2, /* @__PURE__ */ new Date());
2726
+ updateRequest.input("updatedAt", sql2__default.default.DateTime2, /* @__PURE__ */ new Date());
3061
2727
  await updateRequest.query(
3062
2728
  `UPDATE ${table} SET snapshot = @snapshot, [updatedAt] = @updatedAt WHERE workflow_name = @workflow_name AND run_id = @run_id`
3063
2729
  );
@@ -3096,8 +2762,8 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
3096
2762
  request.input("run_id", runId);
3097
2763
  request.input("resourceId", resourceId);
3098
2764
  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));
2765
+ request.input("createdAt", sql2__default.default.DateTime2, new Date(now));
2766
+ request.input("updatedAt", sql2__default.default.DateTime2, new Date(now));
3101
2767
  const mergeSql = `MERGE INTO ${table} AS target
3102
2768
  USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
3103
2769
  ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
@@ -3194,12 +2860,12 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
3194
2860
  );
3195
2861
  }
3196
2862
  }
3197
- async getWorkflowRuns({
2863
+ async listWorkflowRuns({
3198
2864
  workflowName,
3199
2865
  fromDate,
3200
2866
  toDate,
3201
- limit,
3202
- offset,
2867
+ page,
2868
+ perPage,
3203
2869
  resourceId
3204
2870
  } = {}) {
3205
2871
  try {
@@ -3232,20 +2898,23 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
3232
2898
  const request = this.pool.request();
3233
2899
  Object.entries(paramMap).forEach(([key, value]) => {
3234
2900
  if (value instanceof Date) {
3235
- request.input(key, sql3__default.default.DateTime, value);
2901
+ request.input(key, sql2__default.default.DateTime, value);
3236
2902
  } else {
3237
2903
  request.input(key, value);
3238
2904
  }
3239
2905
  });
3240
- if (limit !== void 0 && offset !== void 0) {
2906
+ const usePagination = typeof perPage === "number" && typeof page === "number";
2907
+ if (usePagination) {
3241
2908
  const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
3242
2909
  const countResult = await request.query(countQuery);
3243
2910
  total = Number(countResult.recordset[0]?.count || 0);
3244
2911
  }
3245
2912
  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);
2913
+ if (usePagination) {
2914
+ const normalizedPerPage = storage.normalizePerPage(perPage, Number.MAX_SAFE_INTEGER);
2915
+ const offset = page * normalizedPerPage;
2916
+ query += ` OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
2917
+ request.input("perPage", normalizedPerPage);
3249
2918
  request.input("offset", offset);
3250
2919
  }
3251
2920
  const result = await request.query(query);
@@ -3254,7 +2923,7 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
3254
2923
  } catch (error$1) {
3255
2924
  throw new error.MastraError(
3256
2925
  {
3257
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
2926
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_WORKFLOW_RUNS_FAILED",
3258
2927
  domain: error.ErrorDomain.STORAGE,
3259
2928
  category: error.ErrorCategory.THIRD_PARTY,
3260
2929
  details: {
@@ -3274,7 +2943,10 @@ var MSSQLStore = class extends storage.MastraStorage {
3274
2943
  isConnected = null;
3275
2944
  stores;
3276
2945
  constructor(config) {
3277
- super({ name: "MSSQLStore" });
2946
+ if (!config.id || typeof config.id !== "string" || config.id.trim() === "") {
2947
+ throw new Error("MSSQLStore: id must be provided and cannot be empty.");
2948
+ }
2949
+ super({ id: config.id, name: "MSSQLStore" });
3278
2950
  try {
3279
2951
  if ("connectionString" in config) {
3280
2952
  if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") {
@@ -3289,7 +2961,7 @@ var MSSQLStore = class extends storage.MastraStorage {
3289
2961
  }
3290
2962
  }
3291
2963
  this.schema = config.schemaName || "dbo";
3292
- this.pool = "connectionString" in config ? new sql3__default.default.ConnectionPool(config.connectionString) : new sql3__default.default.ConnectionPool({
2964
+ this.pool = "connectionString" in config ? new sql2__default.default.ConnectionPool(config.connectionString) : new sql2__default.default.ConnectionPool({
3293
2965
  server: config.server,
3294
2966
  database: config.database,
3295
2967
  user: config.user,
@@ -3297,19 +2969,15 @@ var MSSQLStore = class extends storage.MastraStorage {
3297
2969
  port: config.port,
3298
2970
  options: config.options || { encrypt: true, trustServerCertificate: true }
3299
2971
  });
3300
- const legacyEvals = new LegacyEvalsMSSQL({ pool: this.pool, schema: this.schema });
3301
2972
  const operations = new StoreOperationsMSSQL({ pool: this.pool, schemaName: this.schema });
3302
2973
  const scores = new ScoresMSSQL({ pool: this.pool, operations, schema: this.schema });
3303
- const traces = new TracesMSSQL({ pool: this.pool, operations, schema: this.schema });
3304
2974
  const workflows = new WorkflowsMSSQL({ pool: this.pool, operations, schema: this.schema });
3305
2975
  const memory = new MemoryMSSQL({ pool: this.pool, schema: this.schema, operations });
3306
2976
  const observability = new ObservabilityMSSQL({ pool: this.pool, operations, schema: this.schema });
3307
2977
  this.stores = {
3308
2978
  operations,
3309
2979
  scores,
3310
- traces,
3311
2980
  workflows,
3312
- legacyEvals,
3313
2981
  memory,
3314
2982
  observability
3315
2983
  };
@@ -3363,30 +3031,11 @@ var MSSQLStore = class extends storage.MastraStorage {
3363
3031
  hasColumn: true,
3364
3032
  createTable: true,
3365
3033
  deleteMessages: true,
3366
- getScoresBySpan: true,
3367
- aiTracing: true,
3034
+ listScoresBySpan: true,
3035
+ observabilityInstance: true,
3368
3036
  indexManagement: true
3369
3037
  };
3370
3038
  }
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
3039
  async createTable({
3391
3040
  tableName,
3392
3041
  schema
@@ -3421,15 +3070,6 @@ var MSSQLStore = class extends storage.MastraStorage {
3421
3070
  async getThreadById({ threadId }) {
3422
3071
  return this.stores.memory.getThreadById({ threadId });
3423
3072
  }
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
3073
  async saveThread({ thread }) {
3434
3074
  return this.stores.memory.saveThread({ thread });
3435
3075
  }
@@ -3443,17 +3083,8 @@ var MSSQLStore = class extends storage.MastraStorage {
3443
3083
  async deleteThread({ threadId }) {
3444
3084
  return this.stores.memory.deleteThread({ threadId });
3445
3085
  }
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);
3086
+ async listMessagesById({ messageIds }) {
3087
+ return this.stores.memory.listMessagesById({ messageIds });
3457
3088
  }
3458
3089
  async saveMessages(args) {
3459
3090
  return this.stores.memory.saveMessages(args);
@@ -3487,9 +3118,9 @@ var MSSQLStore = class extends storage.MastraStorage {
3487
3118
  runId,
3488
3119
  stepId,
3489
3120
  result,
3490
- runtimeContext
3121
+ requestContext
3491
3122
  }) {
3492
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
3123
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
3493
3124
  }
3494
3125
  async updateWorkflowState({
3495
3126
  workflowName,
@@ -3512,15 +3143,15 @@ var MSSQLStore = class extends storage.MastraStorage {
3512
3143
  }) {
3513
3144
  return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
3514
3145
  }
3515
- async getWorkflowRuns({
3146
+ async listWorkflowRuns({
3516
3147
  workflowName,
3517
3148
  fromDate,
3518
3149
  toDate,
3519
- limit,
3520
- offset,
3150
+ perPage,
3151
+ page,
3521
3152
  resourceId
3522
3153
  } = {}) {
3523
- return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
3154
+ return this.stores.workflows.listWorkflowRuns({ workflowName, fromDate, toDate, perPage, page, resourceId });
3524
3155
  }
3525
3156
  async getWorkflowRunById({
3526
3157
  runId,
@@ -3547,7 +3178,7 @@ var MSSQLStore = class extends storage.MastraStorage {
3547
3178
  return this.stores.operations.dropIndex(indexName);
3548
3179
  }
3549
3180
  /**
3550
- * AI Tracing / Observability
3181
+ * Tracing / Observability
3551
3182
  */
3552
3183
  getObservabilityStore() {
3553
3184
  if (!this.stores.observability) {
@@ -3560,30 +3191,30 @@ var MSSQLStore = class extends storage.MastraStorage {
3560
3191
  }
3561
3192
  return this.stores.observability;
3562
3193
  }
3563
- async createAISpan(span) {
3564
- return this.getObservabilityStore().createAISpan(span);
3194
+ async createSpan(span) {
3195
+ return this.getObservabilityStore().createSpan(span);
3565
3196
  }
3566
- async updateAISpan({
3197
+ async updateSpan({
3567
3198
  spanId,
3568
3199
  traceId,
3569
3200
  updates
3570
3201
  }) {
3571
- return this.getObservabilityStore().updateAISpan({ spanId, traceId, updates });
3202
+ return this.getObservabilityStore().updateSpan({ spanId, traceId, updates });
3572
3203
  }
3573
- async getAITrace(traceId) {
3574
- return this.getObservabilityStore().getAITrace(traceId);
3204
+ async getTrace(traceId) {
3205
+ return this.getObservabilityStore().getTrace(traceId);
3575
3206
  }
3576
- async getAITracesPaginated(args) {
3577
- return this.getObservabilityStore().getAITracesPaginated(args);
3207
+ async getTracesPaginated(args) {
3208
+ return this.getObservabilityStore().getTracesPaginated(args);
3578
3209
  }
3579
- async batchCreateAISpans(args) {
3580
- return this.getObservabilityStore().batchCreateAISpans(args);
3210
+ async batchCreateSpans(args) {
3211
+ return this.getObservabilityStore().batchCreateSpans(args);
3581
3212
  }
3582
- async batchUpdateAISpans(args) {
3583
- return this.getObservabilityStore().batchUpdateAISpans(args);
3213
+ async batchUpdateSpans(args) {
3214
+ return this.getObservabilityStore().batchUpdateSpans(args);
3584
3215
  }
3585
- async batchDeleteAITraces(args) {
3586
- return this.getObservabilityStore().batchDeleteAITraces(args);
3216
+ async batchDeleteTraces(args) {
3217
+ return this.getObservabilityStore().batchDeleteTraces(args);
3587
3218
  }
3588
3219
  /**
3589
3220
  * Scorers
@@ -3591,14 +3222,14 @@ var MSSQLStore = class extends storage.MastraStorage {
3591
3222
  async getScoreById({ id: _id }) {
3592
3223
  return this.stores.scores.getScoreById({ id: _id });
3593
3224
  }
3594
- async getScoresByScorerId({
3225
+ async listScoresByScorerId({
3595
3226
  scorerId: _scorerId,
3596
3227
  pagination: _pagination,
3597
3228
  entityId: _entityId,
3598
3229
  entityType: _entityType,
3599
3230
  source: _source
3600
3231
  }) {
3601
- return this.stores.scores.getScoresByScorerId({
3232
+ return this.stores.scores.listScoresByScorerId({
3602
3233
  scorerId: _scorerId,
3603
3234
  pagination: _pagination,
3604
3235
  entityId: _entityId,
@@ -3609,29 +3240,29 @@ var MSSQLStore = class extends storage.MastraStorage {
3609
3240
  async saveScore(_score) {
3610
3241
  return this.stores.scores.saveScore(_score);
3611
3242
  }
3612
- async getScoresByRunId({
3243
+ async listScoresByRunId({
3613
3244
  runId: _runId,
3614
3245
  pagination: _pagination
3615
3246
  }) {
3616
- return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
3247
+ return this.stores.scores.listScoresByRunId({ runId: _runId, pagination: _pagination });
3617
3248
  }
3618
- async getScoresByEntityId({
3249
+ async listScoresByEntityId({
3619
3250
  entityId: _entityId,
3620
3251
  entityType: _entityType,
3621
3252
  pagination: _pagination
3622
3253
  }) {
3623
- return this.stores.scores.getScoresByEntityId({
3254
+ return this.stores.scores.listScoresByEntityId({
3624
3255
  entityId: _entityId,
3625
3256
  entityType: _entityType,
3626
3257
  pagination: _pagination
3627
3258
  });
3628
3259
  }
3629
- async getScoresBySpan({
3260
+ async listScoresBySpan({
3630
3261
  traceId,
3631
3262
  spanId,
3632
3263
  pagination: _pagination
3633
3264
  }) {
3634
- return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination: _pagination });
3265
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination: _pagination });
3635
3266
  }
3636
3267
  };
3637
3268