@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.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { MastraStorage, LegacyEvalsStorage, StoreOperations, TABLE_WORKFLOW_SNAPSHOT, TABLE_SCHEMAS, TABLE_THREADS, TABLE_MESSAGES, TABLE_TRACES, TABLE_EVALS, TABLE_SCORERS, TABLE_AI_SPANS, ScoresStorage, TracesStorage, WorkflowsStorage, MemoryStorage, resolveMessageLimit, TABLE_RESOURCES, ObservabilityStorage, safelyParseJSON } from '@mastra/core/storage';
3
- import sql3 from 'mssql';
4
- import { parseSqlIdentifier, parseFieldKey } from '@mastra/core/utils';
2
+ import { MastraStorage, StoreOperations, TABLE_WORKFLOW_SNAPSHOT, TABLE_SCHEMAS, TABLE_THREADS, TABLE_MESSAGES, TABLE_TRACES, TABLE_SCORERS, TABLE_SPANS, ScoresStorage, normalizePerPage, calculatePagination, WorkflowsStorage, MemoryStorage, TABLE_RESOURCES, ObservabilityStorage, safelyParseJSON } from '@mastra/core/storage';
3
+ import sql2 from 'mssql';
5
4
  import { MessageList } from '@mastra/core/agent';
5
+ import { parseSqlIdentifier } from '@mastra/core/utils';
6
6
  import { randomUUID } from 'crypto';
7
- import { saveScorePayloadSchema } from '@mastra/core/scores';
7
+ import { saveScorePayloadSchema } from '@mastra/core/evals';
8
8
 
9
9
  // src/storage/index.ts
10
10
  function getSchemaName(schema) {
@@ -80,153 +80,7 @@ function transformFromSqlRow({
80
80
  return result;
81
81
  }
82
82
 
83
- // src/storage/domains/legacy-evals/index.ts
84
- function transformEvalRow(row) {
85
- let testInfoValue = null, resultValue = null;
86
- if (row.test_info) {
87
- try {
88
- testInfoValue = typeof row.test_info === "string" ? JSON.parse(row.test_info) : row.test_info;
89
- } catch {
90
- }
91
- }
92
- if (row.result) {
93
- try {
94
- resultValue = typeof row.result === "string" ? JSON.parse(row.result) : row.result;
95
- } catch {
96
- }
97
- }
98
- return {
99
- agentName: row.agent_name,
100
- input: row.input,
101
- output: row.output,
102
- result: resultValue,
103
- metricName: row.metric_name,
104
- instructions: row.instructions,
105
- testInfo: testInfoValue,
106
- globalRunId: row.global_run_id,
107
- runId: row.run_id,
108
- createdAt: row.created_at
109
- };
110
- }
111
- var LegacyEvalsMSSQL = class extends LegacyEvalsStorage {
112
- pool;
113
- schema;
114
- constructor({ pool, schema }) {
115
- super();
116
- this.pool = pool;
117
- this.schema = schema;
118
- }
119
- /** @deprecated use getEvals instead */
120
- async getEvalsByAgentName(agentName, type) {
121
- try {
122
- let query = `SELECT * FROM ${getTableName({ indexName: TABLE_EVALS, schemaName: getSchemaName(this.schema) })} WHERE agent_name = @p1`;
123
- if (type === "test") {
124
- query += " AND test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL";
125
- } else if (type === "live") {
126
- query += " AND (test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)";
127
- }
128
- query += " ORDER BY created_at DESC";
129
- const request = this.pool.request();
130
- request.input("p1", agentName);
131
- const result = await request.query(query);
132
- const rows = result.recordset;
133
- return typeof transformEvalRow === "function" ? rows?.map((row) => transformEvalRow(row)) ?? [] : rows ?? [];
134
- } catch (error) {
135
- if (error && error.number === 208 && error.message && error.message.includes("Invalid object name")) {
136
- return [];
137
- }
138
- this.logger?.error?.("Failed to get evals for the specified agent:", error);
139
- throw error;
140
- }
141
- }
142
- async getEvals(options = {}) {
143
- const { agentName, type, page = 0, perPage = 100, dateRange } = options;
144
- const fromDate = dateRange?.start;
145
- const toDate = dateRange?.end;
146
- const where = [];
147
- const params = {};
148
- if (agentName) {
149
- where.push("agent_name = @agentName");
150
- params["agentName"] = agentName;
151
- }
152
- if (type === "test") {
153
- where.push("test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL");
154
- } else if (type === "live") {
155
- where.push("(test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)");
156
- }
157
- if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
158
- where.push(`[created_at] >= @fromDate`);
159
- params[`fromDate`] = fromDate.toISOString();
160
- }
161
- if (toDate instanceof Date && !isNaN(toDate.getTime())) {
162
- where.push(`[created_at] <= @toDate`);
163
- params[`toDate`] = toDate.toISOString();
164
- }
165
- const whereClause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
166
- const tableName = getTableName({ indexName: TABLE_EVALS, schemaName: getSchemaName(this.schema) });
167
- const offset = page * perPage;
168
- const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
169
- const dataQuery = `SELECT * FROM ${tableName} ${whereClause} ORDER BY seq_id DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
170
- try {
171
- const countReq = this.pool.request();
172
- Object.entries(params).forEach(([key, value]) => {
173
- if (value instanceof Date) {
174
- countReq.input(key, sql3.DateTime, value);
175
- } else {
176
- countReq.input(key, value);
177
- }
178
- });
179
- const countResult = await countReq.query(countQuery);
180
- const total = countResult.recordset[0]?.total || 0;
181
- if (total === 0) {
182
- return {
183
- evals: [],
184
- total: 0,
185
- page,
186
- perPage,
187
- hasMore: false
188
- };
189
- }
190
- const req = this.pool.request();
191
- Object.entries(params).forEach(([key, value]) => {
192
- if (value instanceof Date) {
193
- req.input(key, sql3.DateTime, value);
194
- } else {
195
- req.input(key, value);
196
- }
197
- });
198
- req.input("offset", offset);
199
- req.input("perPage", perPage);
200
- const result = await req.query(dataQuery);
201
- const rows = result.recordset;
202
- return {
203
- evals: rows?.map((row) => transformEvalRow(row)) ?? [],
204
- total,
205
- page,
206
- perPage,
207
- hasMore: offset + (rows?.length ?? 0) < total
208
- };
209
- } catch (error) {
210
- const mastraError = new MastraError(
211
- {
212
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_EVALS_FAILED",
213
- domain: ErrorDomain.STORAGE,
214
- category: ErrorCategory.THIRD_PARTY,
215
- details: {
216
- agentName: agentName || "all",
217
- type: type || "all",
218
- page,
219
- perPage
220
- }
221
- },
222
- error
223
- );
224
- this.logger?.error?.(mastraError.toString());
225
- this.logger?.trackException?.(mastraError);
226
- throw mastraError;
227
- }
228
- }
229
- };
83
+ // src/storage/domains/memory/index.ts
230
84
  var MemoryMSSQL = class extends MemoryStorage {
231
85
  pool;
232
86
  schema;
@@ -244,7 +98,7 @@ var MemoryMSSQL = class extends MemoryStorage {
244
98
  });
245
99
  const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
246
100
  const list = new MessageList().add(cleanMessages, "memory");
247
- return format === "v2" ? list.get.all.v2() : list.get.all.v1();
101
+ return format === "v2" ? list.get.all.db() : list.get.all.v1();
248
102
  }
249
103
  constructor({
250
104
  pool,
@@ -258,7 +112,7 @@ var MemoryMSSQL = class extends MemoryStorage {
258
112
  }
259
113
  async getThreadById({ threadId }) {
260
114
  try {
261
- const sql7 = `SELECT
115
+ const sql5 = `SELECT
262
116
  id,
263
117
  [resourceId],
264
118
  title,
@@ -269,7 +123,7 @@ var MemoryMSSQL = class extends MemoryStorage {
269
123
  WHERE id = @threadId`;
270
124
  const request = this.pool.request();
271
125
  request.input("threadId", threadId);
272
- const resultSet = await request.query(sql7);
126
+ const resultSet = await request.query(sql5);
273
127
  const thread = resultSet.recordset[0] || null;
274
128
  if (!thread) {
275
129
  return null;
@@ -294,11 +148,12 @@ var MemoryMSSQL = class extends MemoryStorage {
294
148
  );
295
149
  }
296
150
  }
297
- async getThreadsByResourceIdPaginated(args) {
298
- const { resourceId, page = 0, perPage: perPageInput, orderBy = "createdAt", sortDirection = "DESC" } = args;
151
+ async listThreadsByResourceId(args) {
152
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
153
+ const perPage = normalizePerPage(perPageInput, 100);
154
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
155
+ const { field, direction } = this.parseOrderBy(orderBy);
299
156
  try {
300
- const perPage = perPageInput !== void 0 ? perPageInput : 100;
301
- const currentOffset = page * perPage;
302
157
  const baseQuery = `FROM ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
303
158
  const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
304
159
  const countRequest = this.pool.request();
@@ -310,17 +165,22 @@ var MemoryMSSQL = class extends MemoryStorage {
310
165
  threads: [],
311
166
  total: 0,
312
167
  page,
313
- perPage,
168
+ perPage: perPageForResponse,
314
169
  hasMore: false
315
170
  };
316
171
  }
317
- const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
318
- const dir = (sortDirection || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
172
+ const orderByField = field === "createdAt" ? "[createdAt]" : "[updatedAt]";
173
+ const dir = (direction || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
174
+ const limitValue = perPageInput === false ? total : perPage;
319
175
  const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${dir} OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
320
176
  const dataRequest = this.pool.request();
321
177
  dataRequest.input("resourceId", resourceId);
322
- dataRequest.input("perPage", perPage);
323
- dataRequest.input("offset", currentOffset);
178
+ dataRequest.input("offset", offset);
179
+ if (limitValue > 2147483647) {
180
+ dataRequest.input("perPage", sql2.BigInt, limitValue);
181
+ } else {
182
+ dataRequest.input("perPage", limitValue);
183
+ }
324
184
  const rowsResult = await dataRequest.query(dataQuery);
325
185
  const rows = rowsResult.recordset || [];
326
186
  const threads = rows.map((thread) => ({
@@ -333,13 +193,13 @@ var MemoryMSSQL = class extends MemoryStorage {
333
193
  threads,
334
194
  total,
335
195
  page,
336
- perPage,
337
- hasMore: currentOffset + threads.length < total
196
+ perPage: perPageForResponse,
197
+ hasMore: perPageInput === false ? false : offset + perPage < total
338
198
  };
339
199
  } catch (error) {
340
200
  const mastraError = new MastraError(
341
201
  {
342
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
202
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
343
203
  domain: ErrorDomain.STORAGE,
344
204
  category: ErrorCategory.THIRD_PARTY,
345
205
  details: {
@@ -351,7 +211,13 @@ var MemoryMSSQL = class extends MemoryStorage {
351
211
  );
352
212
  this.logger?.error?.(mastraError.toString());
353
213
  this.logger?.trackException?.(mastraError);
354
- return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
214
+ return {
215
+ threads: [],
216
+ total: 0,
217
+ page,
218
+ perPage: perPageForResponse,
219
+ hasMore: false
220
+ };
355
221
  }
356
222
  }
357
223
  async saveThread({ thread }) {
@@ -375,12 +241,12 @@ var MemoryMSSQL = class extends MemoryStorage {
375
241
  req.input("title", thread.title);
376
242
  const metadata = thread.metadata ? JSON.stringify(thread.metadata) : null;
377
243
  if (metadata === null) {
378
- req.input("metadata", sql3.NVarChar, null);
244
+ req.input("metadata", sql2.NVarChar, null);
379
245
  } else {
380
246
  req.input("metadata", metadata);
381
247
  }
382
- req.input("createdAt", sql3.DateTime2, thread.createdAt);
383
- req.input("updatedAt", sql3.DateTime2, thread.updatedAt);
248
+ req.input("createdAt", sql2.DateTime2, thread.createdAt);
249
+ req.input("updatedAt", sql2.DateTime2, thread.updatedAt);
384
250
  await req.query(mergeSql);
385
251
  return thread;
386
252
  } catch (error) {
@@ -397,31 +263,6 @@ var MemoryMSSQL = class extends MemoryStorage {
397
263
  );
398
264
  }
399
265
  }
400
- /**
401
- * @deprecated use getThreadsByResourceIdPaginated instead
402
- */
403
- async getThreadsByResourceId(args) {
404
- const { resourceId, orderBy = "createdAt", sortDirection = "DESC" } = args;
405
- try {
406
- const baseQuery = `FROM ${getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
407
- const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
408
- const dir = (sortDirection || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
409
- const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${dir}`;
410
- const request = this.pool.request();
411
- request.input("resourceId", resourceId);
412
- const resultSet = await request.query(dataQuery);
413
- const rows = resultSet.recordset || [];
414
- return rows.map((thread) => ({
415
- ...thread,
416
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
417
- createdAt: thread.createdAt,
418
- updatedAt: thread.updatedAt
419
- }));
420
- } catch (error) {
421
- this.logger?.error?.(`Error getting threads for resource ${resourceId}:`, error);
422
- return [];
423
- }
424
- }
425
266
  /**
426
267
  * Updates a thread's title and metadata, merging with existing metadata. Returns the updated thread.
427
268
  */
@@ -449,7 +290,7 @@ var MemoryMSSQL = class extends MemoryStorage {
449
290
  };
450
291
  try {
451
292
  const table = getTableName({ indexName: TABLE_THREADS, schemaName: getSchemaName(this.schema) });
452
- const sql7 = `UPDATE ${table}
293
+ const sql5 = `UPDATE ${table}
453
294
  SET title = @title,
454
295
  metadata = @metadata,
455
296
  [updatedAt] = @updatedAt
@@ -460,7 +301,7 @@ var MemoryMSSQL = class extends MemoryStorage {
460
301
  req.input("title", title);
461
302
  req.input("metadata", JSON.stringify(mergedMetadata));
462
303
  req.input("updatedAt", /* @__PURE__ */ new Date());
463
- const result = await req.query(sql7);
304
+ const result = await req.query(sql5);
464
305
  let thread = result.recordset && result.recordset[0];
465
306
  if (thread && "seq_id" in thread) {
466
307
  const { seq_id, ...rest } = thread;
@@ -530,11 +371,9 @@ var MemoryMSSQL = class extends MemoryStorage {
530
371
  }
531
372
  async _getIncludedMessages({
532
373
  threadId,
533
- selectBy,
534
- orderByStatement
374
+ include
535
375
  }) {
536
376
  if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
537
- const include = selectBy?.include;
538
377
  if (!include) return null;
539
378
  const unionQueries = [];
540
379
  const paramValues = [];
@@ -559,7 +398,7 @@ var MemoryMSSQL = class extends MemoryStorage {
559
398
  m.[resourceId],
560
399
  m.seq_id
561
400
  FROM (
562
- SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
401
+ SELECT *, ROW_NUMBER() OVER (ORDER BY [createdAt] ASC) as row_num
563
402
  FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
564
403
  WHERE [thread_id] = ${pThreadId}
565
404
  ) AS m
@@ -567,15 +406,17 @@ var MemoryMSSQL = class extends MemoryStorage {
567
406
  OR EXISTS (
568
407
  SELECT 1
569
408
  FROM (
570
- SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
409
+ SELECT *, ROW_NUMBER() OVER (ORDER BY [createdAt] ASC) as row_num
571
410
  FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
572
411
  WHERE [thread_id] = ${pThreadId}
573
412
  ) AS target
574
413
  WHERE target.id = ${pId}
575
414
  AND (
576
- (m.row_num <= target.row_num + ${pPrev} AND m.row_num > target.row_num)
415
+ -- Get previous messages (messages that come BEFORE the target)
416
+ (m.row_num < target.row_num AND m.row_num >= target.row_num - ${pPrev})
577
417
  OR
578
- (m.row_num >= target.row_num - ${pNext} AND m.row_num < target.row_num)
418
+ -- Get next messages (messages that come AFTER the target)
419
+ (m.row_num > target.row_num AND m.row_num <= target.row_num + ${pNext})
579
420
  )
580
421
  )
581
422
  `
@@ -604,34 +445,16 @@ var MemoryMSSQL = class extends MemoryStorage {
604
445
  });
605
446
  return dedupedRows;
606
447
  }
607
- async getMessages(args) {
608
- const { threadId, resourceId, format, selectBy } = args;
448
+ async listMessagesById({ messageIds }) {
449
+ if (messageIds.length === 0) return { messages: [] };
609
450
  const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
610
451
  const orderByStatement = `ORDER BY [seq_id] DESC`;
611
- const limit = resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
612
452
  try {
613
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
614
453
  let rows = [];
615
- const include = selectBy?.include || [];
616
- if (include?.length) {
617
- const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
618
- if (includeMessages) {
619
- rows.push(...includeMessages);
620
- }
621
- }
622
- const excludeIds = rows.map((m) => m.id).filter(Boolean);
623
- let query = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [thread_id] = @threadId`;
454
+ let query = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [id] IN (${messageIds.map((_, i) => `@id${i}`).join(", ")})`;
624
455
  const request = this.pool.request();
625
- request.input("threadId", threadId);
626
- if (excludeIds.length > 0) {
627
- const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
628
- query += ` AND id NOT IN (${excludeParams.join(", ")})`;
629
- excludeIds.forEach((id, idx) => {
630
- request.input(`id${idx}`, id);
631
- });
632
- }
633
- query += ` ${orderByStatement} OFFSET 0 ROWS FETCH NEXT @limit ROWS ONLY`;
634
- request.input("limit", limit);
456
+ messageIds.forEach((id, i) => request.input(`id${i}`, id));
457
+ query += ` ${orderByStatement}`;
635
458
  const result = await request.query(query);
636
459
  const remainingRows = result.recordset || [];
637
460
  rows.push(...remainingRows);
@@ -639,153 +462,150 @@ var MemoryMSSQL = class extends MemoryStorage {
639
462
  const timeDiff = a.seq_id - b.seq_id;
640
463
  return timeDiff;
641
464
  });
642
- rows = rows.map(({ seq_id, ...rest }) => rest);
643
- return this._parseAndFormatMessages(rows, format);
465
+ const messagesWithParsedContent = rows.map((row) => {
466
+ if (typeof row.content === "string") {
467
+ try {
468
+ return { ...row, content: JSON.parse(row.content) };
469
+ } catch {
470
+ return row;
471
+ }
472
+ }
473
+ return row;
474
+ });
475
+ const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
476
+ const list = new MessageList().add(cleanMessages, "memory");
477
+ return { messages: list.get.all.db() };
644
478
  } catch (error) {
645
479
  const mastraError = new MastraError(
646
480
  {
647
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_FAILED",
481
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_MESSAGES_BY_ID_FAILED",
648
482
  domain: ErrorDomain.STORAGE,
649
483
  category: ErrorCategory.THIRD_PARTY,
650
484
  details: {
651
- threadId,
652
- resourceId: resourceId ?? ""
485
+ messageIds: JSON.stringify(messageIds)
653
486
  }
654
487
  },
655
488
  error
656
489
  );
657
490
  this.logger?.error?.(mastraError.toString());
658
491
  this.logger?.trackException?.(mastraError);
659
- return [];
492
+ return { messages: [] };
660
493
  }
661
494
  }
662
- async getMessagesById({
663
- messageIds,
664
- format
665
- }) {
666
- if (messageIds.length === 0) return [];
667
- const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
668
- const orderByStatement = `ORDER BY [seq_id] DESC`;
669
- try {
670
- let rows = [];
671
- let query = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [id] IN (${messageIds.map((_, i) => `@id${i}`).join(", ")})`;
672
- const request = this.pool.request();
673
- messageIds.forEach((id, i) => request.input(`id${i}`, id));
674
- query += ` ${orderByStatement}`;
675
- const result = await request.query(query);
676
- const remainingRows = result.recordset || [];
677
- rows.push(...remainingRows);
678
- rows.sort((a, b) => {
679
- const timeDiff = a.seq_id - b.seq_id;
680
- return timeDiff;
681
- });
682
- rows = rows.map(({ seq_id, ...rest }) => rest);
683
- if (format === `v1`) return this._parseAndFormatMessages(rows, format);
684
- return this._parseAndFormatMessages(rows, `v2`);
685
- } catch (error) {
686
- const mastraError = new MastraError(
495
+ async listMessages(args) {
496
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
497
+ if (!threadId.trim()) {
498
+ throw new MastraError(
687
499
  {
688
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_BY_ID_FAILED",
500
+ id: "STORAGE_MSSQL_LIST_MESSAGES_INVALID_THREAD_ID",
689
501
  domain: ErrorDomain.STORAGE,
690
502
  category: ErrorCategory.THIRD_PARTY,
691
- details: {
692
- messageIds: JSON.stringify(messageIds)
693
- }
503
+ details: { threadId }
694
504
  },
695
- error
505
+ new Error("threadId must be a non-empty string")
696
506
  );
697
- this.logger?.error?.(mastraError.toString());
698
- this.logger?.trackException?.(mastraError);
699
- return [];
700
507
  }
701
- }
702
- async getMessagesPaginated(args) {
703
- const { threadId, resourceId, format, selectBy } = args;
704
- const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
508
+ const perPage = normalizePerPage(perPageInput, 40);
509
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
705
510
  try {
706
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
707
- const fromDate = dateRange?.start;
708
- const toDate = dateRange?.end;
511
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
512
+ const orderByStatement = `ORDER BY [${field}] ${direction}`;
709
513
  const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
710
- const orderByStatement = `ORDER BY [seq_id] DESC`;
711
- let messages = [];
712
- if (selectBy?.include?.length) {
713
- const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
714
- if (includeMessages) messages.push(...includeMessages);
715
- }
716
- const perPage = perPageInput !== void 0 ? perPageInput : resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
717
- const currentOffset = page * perPage;
514
+ const tableName = getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
718
515
  const conditions = ["[thread_id] = @threadId"];
719
516
  const request = this.pool.request();
720
517
  request.input("threadId", threadId);
721
- if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
518
+ if (resourceId) {
519
+ conditions.push("[resourceId] = @resourceId");
520
+ request.input("resourceId", resourceId);
521
+ }
522
+ if (filter?.dateRange?.start) {
722
523
  conditions.push("[createdAt] >= @fromDate");
723
- request.input("fromDate", fromDate.toISOString());
524
+ request.input("fromDate", filter.dateRange.start);
724
525
  }
725
- if (toDate instanceof Date && !isNaN(toDate.getTime())) {
526
+ if (filter?.dateRange?.end) {
726
527
  conditions.push("[createdAt] <= @toDate");
727
- request.input("toDate", toDate.toISOString());
528
+ request.input("toDate", filter.dateRange.end);
728
529
  }
729
530
  const whereClause = `WHERE ${conditions.join(" AND ")}`;
730
- const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
531
+ const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
731
532
  const countResult = await request.query(countQuery);
732
533
  const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
733
- if (total === 0 && messages.length > 0) {
734
- const parsedIncluded = this._parseAndFormatMessages(messages, format);
534
+ const limitValue = perPageInput === false ? total : perPage;
535
+ const dataQuery = `${selectStatement} FROM ${tableName} ${whereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
536
+ request.input("offset", offset);
537
+ if (limitValue > 2147483647) {
538
+ request.input("limit", sql2.BigInt, limitValue);
539
+ } else {
540
+ request.input("limit", limitValue);
541
+ }
542
+ const rowsResult = await request.query(dataQuery);
543
+ const rows = rowsResult.recordset || [];
544
+ const messages = [...rows];
545
+ if (total === 0 && messages.length === 0 && (!include || include.length === 0)) {
735
546
  return {
736
- messages: parsedIncluded,
737
- total: parsedIncluded.length,
547
+ messages: [],
548
+ total: 0,
738
549
  page,
739
- perPage,
550
+ perPage: perPageForResponse,
740
551
  hasMore: false
741
552
  };
742
553
  }
743
- const excludeIds = messages.map((m) => m.id);
744
- if (excludeIds.length > 0) {
745
- const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
746
- conditions.push(`id NOT IN (${excludeParams.join(", ")})`);
747
- excludeIds.forEach((id, idx) => request.input(`id${idx}`, id));
554
+ const messageIds = new Set(messages.map((m) => m.id));
555
+ if (include && include.length > 0) {
556
+ const includeMessages = await this._getIncludedMessages({ threadId, include });
557
+ if (includeMessages) {
558
+ for (const includeMsg of includeMessages) {
559
+ if (!messageIds.has(includeMsg.id)) {
560
+ messages.push(includeMsg);
561
+ messageIds.add(includeMsg.id);
562
+ }
563
+ }
564
+ }
748
565
  }
749
- const finalWhereClause = `WHERE ${conditions.join(" AND ")}`;
750
- const dataQuery = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${finalWhereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
751
- request.input("offset", currentOffset);
752
- request.input("limit", perPage);
753
- const rowsResult = await request.query(dataQuery);
754
- const rows = rowsResult.recordset || [];
755
- rows.sort((a, b) => a.seq_id - b.seq_id);
756
- messages.push(...rows);
757
- const parsed = this._parseAndFormatMessages(messages, format);
566
+ const parsed = this._parseAndFormatMessages(messages, "v2");
567
+ let finalMessages = parsed;
568
+ finalMessages = finalMessages.sort((a, b) => {
569
+ const aValue = field === "createdAt" ? new Date(a.createdAt).getTime() : a[field];
570
+ const bValue = field === "createdAt" ? new Date(b.createdAt).getTime() : b[field];
571
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
572
+ });
573
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
574
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
575
+ const hasMore = perPageInput !== false && !allThreadMessagesReturned && offset + perPage < total;
758
576
  return {
759
- messages: parsed,
577
+ messages: finalMessages,
760
578
  total,
761
579
  page,
762
- perPage,
763
- hasMore: currentOffset + rows.length < total
580
+ perPage: perPageForResponse,
581
+ hasMore
764
582
  };
765
583
  } catch (error) {
766
584
  const mastraError = new MastraError(
767
585
  {
768
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_PAGINATED_FAILED",
586
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_MESSAGES_FAILED",
769
587
  domain: ErrorDomain.STORAGE,
770
588
  category: ErrorCategory.THIRD_PARTY,
771
589
  details: {
772
590
  threadId,
773
- resourceId: resourceId ?? "",
774
- page
591
+ resourceId: resourceId ?? ""
775
592
  }
776
593
  },
777
594
  error
778
595
  );
779
596
  this.logger?.error?.(mastraError.toString());
780
597
  this.logger?.trackException?.(mastraError);
781
- return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
598
+ return {
599
+ messages: [],
600
+ total: 0,
601
+ page,
602
+ perPage: perPageForResponse,
603
+ hasMore: false
604
+ };
782
605
  }
783
606
  }
784
- async saveMessages({
785
- messages,
786
- format
787
- }) {
788
- if (messages.length === 0) return messages;
607
+ async saveMessages({ messages }) {
608
+ if (messages.length === 0) return { messages: [] };
789
609
  const threadId = messages[0]?.threadId;
790
610
  if (!threadId) {
791
611
  throw new MastraError({
@@ -829,7 +649,7 @@ var MemoryMSSQL = class extends MemoryStorage {
829
649
  "content",
830
650
  typeof message.content === "string" ? message.content : JSON.stringify(message.content)
831
651
  );
832
- request.input("createdAt", sql3.DateTime2, message.createdAt);
652
+ request.input("createdAt", sql2.DateTime2, message.createdAt);
833
653
  request.input("role", message.role);
834
654
  request.input("type", message.type || "v2");
835
655
  request.input("resourceId", message.resourceId);
@@ -848,7 +668,7 @@ var MemoryMSSQL = class extends MemoryStorage {
848
668
  await request.query(mergeSql);
849
669
  }
850
670
  const threadReq = transaction.request();
851
- threadReq.input("updatedAt", sql3.DateTime2, /* @__PURE__ */ new Date());
671
+ threadReq.input("updatedAt", sql2.DateTime2, /* @__PURE__ */ new Date());
852
672
  threadReq.input("id", threadId);
853
673
  await threadReq.query(`UPDATE ${tableThreads} SET [updatedAt] = @updatedAt WHERE id = @id`);
854
674
  await transaction.commit();
@@ -867,8 +687,7 @@ var MemoryMSSQL = class extends MemoryStorage {
867
687
  return message;
868
688
  });
869
689
  const list = new MessageList().add(messagesWithParsedContent, "memory");
870
- if (format === "v2") return list.get.all.v2();
871
- return list.get.all.v1();
690
+ return { messages: list.get.all.db() };
872
691
  } catch (error) {
873
692
  throw new MastraError(
874
693
  {
@@ -1147,13 +966,13 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
1147
966
  this.operations = operations;
1148
967
  this.schema = schema;
1149
968
  }
1150
- get aiTracingStrategy() {
969
+ get tracingStrategy() {
1151
970
  return {
1152
971
  preferred: "batch-with-updates",
1153
972
  supported: ["batch-with-updates", "insert-only"]
1154
973
  };
1155
974
  }
1156
- async createAISpan(span) {
975
+ async createSpan(span) {
1157
976
  try {
1158
977
  const startedAt = span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt;
1159
978
  const endedAt = span.endedAt instanceof Date ? span.endedAt.toISOString() : span.endedAt;
@@ -1163,11 +982,11 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
1163
982
  endedAt
1164
983
  // Note: createdAt/updatedAt will be set by default values
1165
984
  };
1166
- return this.operations.insert({ tableName: TABLE_AI_SPANS, record });
985
+ return this.operations.insert({ tableName: TABLE_SPANS, record });
1167
986
  } catch (error) {
1168
987
  throw new MastraError(
1169
988
  {
1170
- id: "MSSQL_STORE_CREATE_AI_SPAN_FAILED",
989
+ id: "MSSQL_STORE_CREATE_SPAN_FAILED",
1171
990
  domain: ErrorDomain.STORAGE,
1172
991
  category: ErrorCategory.USER,
1173
992
  details: {
@@ -1181,10 +1000,10 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
1181
1000
  );
1182
1001
  }
1183
1002
  }
1184
- async getAITrace(traceId) {
1003
+ async getTrace(traceId) {
1185
1004
  try {
1186
1005
  const tableName = getTableName({
1187
- indexName: TABLE_AI_SPANS,
1006
+ indexName: TABLE_SPANS,
1188
1007
  schemaName: getSchemaName(this.schema)
1189
1008
  });
1190
1009
  const request = this.pool.request();
@@ -1205,7 +1024,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
1205
1024
  traceId,
1206
1025
  spans: result.recordset.map(
1207
1026
  (span) => transformFromSqlRow({
1208
- tableName: TABLE_AI_SPANS,
1027
+ tableName: TABLE_SPANS,
1209
1028
  sqlRow: span
1210
1029
  })
1211
1030
  )
@@ -1213,7 +1032,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
1213
1032
  } catch (error) {
1214
1033
  throw new MastraError(
1215
1034
  {
1216
- id: "MSSQL_STORE_GET_AI_TRACE_FAILED",
1035
+ id: "MSSQL_STORE_GET_TRACE_FAILED",
1217
1036
  domain: ErrorDomain.STORAGE,
1218
1037
  category: ErrorCategory.USER,
1219
1038
  details: {
@@ -1224,7 +1043,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
1224
1043
  );
1225
1044
  }
1226
1045
  }
1227
- async updateAISpan({
1046
+ async updateSpan({
1228
1047
  spanId,
1229
1048
  traceId,
1230
1049
  updates
@@ -1238,14 +1057,14 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
1238
1057
  data.startedAt = data.startedAt.toISOString();
1239
1058
  }
1240
1059
  await this.operations.update({
1241
- tableName: TABLE_AI_SPANS,
1060
+ tableName: TABLE_SPANS,
1242
1061
  keys: { spanId, traceId },
1243
1062
  data
1244
1063
  });
1245
1064
  } catch (error) {
1246
1065
  throw new MastraError(
1247
1066
  {
1248
- id: "MSSQL_STORE_UPDATE_AI_SPAN_FAILED",
1067
+ id: "MSSQL_STORE_UPDATE_SPAN_FAILED",
1249
1068
  domain: ErrorDomain.STORAGE,
1250
1069
  category: ErrorCategory.USER,
1251
1070
  details: {
@@ -1257,7 +1076,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
1257
1076
  );
1258
1077
  }
1259
1078
  }
1260
- async getAITracesPaginated({
1079
+ async getTracesPaginated({
1261
1080
  filters,
1262
1081
  pagination
1263
1082
  }) {
@@ -1282,7 +1101,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
1282
1101
  name = `agent run: '${entityId}'`;
1283
1102
  } else {
1284
1103
  const error = new MastraError({
1285
- id: "MSSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1104
+ id: "MSSQL_STORE_GET_TRACES_PAGINATED_FAILED",
1286
1105
  domain: ErrorDomain.STORAGE,
1287
1106
  category: ErrorCategory.USER,
1288
1107
  details: {
@@ -1301,7 +1120,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
1301
1120
  params[entityParam] = name;
1302
1121
  }
1303
1122
  const tableName = getTableName({
1304
- indexName: TABLE_AI_SPANS,
1123
+ indexName: TABLE_SPANS,
1305
1124
  schemaName: getSchemaName(this.schema)
1306
1125
  });
1307
1126
  try {
@@ -1335,7 +1154,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
1335
1154
  );
1336
1155
  const spans = dataResult.recordset.map(
1337
1156
  (row) => transformFromSqlRow({
1338
- tableName: TABLE_AI_SPANS,
1157
+ tableName: TABLE_SPANS,
1339
1158
  sqlRow: row
1340
1159
  })
1341
1160
  );
@@ -1351,7 +1170,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
1351
1170
  } catch (error) {
1352
1171
  throw new MastraError(
1353
1172
  {
1354
- id: "MSSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1173
+ id: "MSSQL_STORE_GET_TRACES_PAGINATED_FAILED",
1355
1174
  domain: ErrorDomain.STORAGE,
1356
1175
  category: ErrorCategory.USER
1357
1176
  },
@@ -1359,13 +1178,13 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
1359
1178
  );
1360
1179
  }
1361
1180
  }
1362
- async batchCreateAISpans(args) {
1181
+ async batchCreateSpans(args) {
1363
1182
  if (!args.records || args.records.length === 0) {
1364
1183
  return;
1365
1184
  }
1366
1185
  try {
1367
1186
  await this.operations.batchInsert({
1368
- tableName: TABLE_AI_SPANS,
1187
+ tableName: TABLE_SPANS,
1369
1188
  records: args.records.map((span) => ({
1370
1189
  ...span,
1371
1190
  startedAt: span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt,
@@ -1375,7 +1194,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
1375
1194
  } catch (error) {
1376
1195
  throw new MastraError(
1377
1196
  {
1378
- id: "MSSQL_STORE_BATCH_CREATE_AI_SPANS_FAILED",
1197
+ id: "MSSQL_STORE_BATCH_CREATE_SPANS_FAILED",
1379
1198
  domain: ErrorDomain.STORAGE,
1380
1199
  category: ErrorCategory.USER,
1381
1200
  details: {
@@ -1386,7 +1205,7 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
1386
1205
  );
1387
1206
  }
1388
1207
  }
1389
- async batchUpdateAISpans(args) {
1208
+ async batchUpdateSpans(args) {
1390
1209
  if (!args.records || args.records.length === 0) {
1391
1210
  return;
1392
1211
  }
@@ -1405,13 +1224,13 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
1405
1224
  };
1406
1225
  });
1407
1226
  await this.operations.batchUpdate({
1408
- tableName: TABLE_AI_SPANS,
1227
+ tableName: TABLE_SPANS,
1409
1228
  updates
1410
1229
  });
1411
1230
  } catch (error) {
1412
1231
  throw new MastraError(
1413
1232
  {
1414
- id: "MSSQL_STORE_BATCH_UPDATE_AI_SPANS_FAILED",
1233
+ id: "MSSQL_STORE_BATCH_UPDATE_SPANS_FAILED",
1415
1234
  domain: ErrorDomain.STORAGE,
1416
1235
  category: ErrorCategory.USER,
1417
1236
  details: {
@@ -1422,20 +1241,20 @@ var ObservabilityMSSQL = class extends ObservabilityStorage {
1422
1241
  );
1423
1242
  }
1424
1243
  }
1425
- async batchDeleteAITraces(args) {
1244
+ async batchDeleteTraces(args) {
1426
1245
  if (!args.traceIds || args.traceIds.length === 0) {
1427
1246
  return;
1428
1247
  }
1429
1248
  try {
1430
1249
  const keys = args.traceIds.map((traceId) => ({ traceId }));
1431
1250
  await this.operations.batchDelete({
1432
- tableName: TABLE_AI_SPANS,
1251
+ tableName: TABLE_SPANS,
1433
1252
  keys
1434
1253
  });
1435
1254
  } catch (error) {
1436
1255
  throw new MastraError(
1437
1256
  {
1438
- id: "MSSQL_STORE_BATCH_DELETE_AI_TRACES_FAILED",
1257
+ id: "MSSQL_STORE_BATCH_DELETE_TRACES_FAILED",
1439
1258
  domain: ErrorDomain.STORAGE,
1440
1259
  category: ErrorCategory.USER,
1441
1260
  details: {
@@ -1550,7 +1369,7 @@ var StoreOperationsMSSQL = class extends StoreOperations {
1550
1369
  const value = record[col];
1551
1370
  const preparedValue = this.prepareValue(value, col, tableName);
1552
1371
  if (preparedValue instanceof Date) {
1553
- request.input(`param${i}`, sql3.DateTime2, preparedValue);
1372
+ request.input(`param${i}`, sql2.DateTime2, preparedValue);
1554
1373
  } else if (preparedValue === null || preparedValue === void 0) {
1555
1374
  request.input(`param${i}`, this.getMssqlType(tableName, col), null);
1556
1375
  } else {
@@ -1765,7 +1584,7 @@ ${columns}
1765
1584
  try {
1766
1585
  const keyEntries = Object.entries(keys).map(([key, value]) => [parseSqlIdentifier(key, "column name"), value]);
1767
1586
  const conditions = keyEntries.map(([key], i) => `[${key}] = @param${i}`).join(" AND ");
1768
- const sql7 = `SELECT * FROM ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} WHERE ${conditions}`;
1587
+ const sql5 = `SELECT * FROM ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} WHERE ${conditions}`;
1769
1588
  const request = this.pool.request();
1770
1589
  keyEntries.forEach(([key, value], i) => {
1771
1590
  const preparedValue = this.prepareValue(value, key, tableName);
@@ -1775,7 +1594,7 @@ ${columns}
1775
1594
  request.input(`param${i}`, preparedValue);
1776
1595
  }
1777
1596
  });
1778
- const resultSet = await request.query(sql7);
1597
+ const resultSet = await request.query(sql5);
1779
1598
  const result = resultSet.recordset[0] || null;
1780
1599
  if (!result) {
1781
1600
  return null;
@@ -1874,23 +1693,23 @@ ${columns}
1874
1693
  const col = TABLE_SCHEMAS[tableName]?.[columnName];
1875
1694
  switch (col?.type) {
1876
1695
  case "text":
1877
- return sql3.NVarChar;
1696
+ return sql2.NVarChar;
1878
1697
  case "timestamp":
1879
- return sql3.DateTime2;
1698
+ return sql2.DateTime2;
1880
1699
  case "uuid":
1881
- return sql3.UniqueIdentifier;
1700
+ return sql2.UniqueIdentifier;
1882
1701
  case "jsonb":
1883
- return sql3.NVarChar;
1702
+ return sql2.NVarChar;
1884
1703
  case "integer":
1885
- return sql3.Int;
1704
+ return sql2.Int;
1886
1705
  case "bigint":
1887
- return sql3.BigInt;
1706
+ return sql2.BigInt;
1888
1707
  case "float":
1889
- return sql3.Float;
1708
+ return sql2.Float;
1890
1709
  case "boolean":
1891
- return sql3.Bit;
1710
+ return sql2.Bit;
1892
1711
  default:
1893
- return sql3.NVarChar;
1712
+ return sql2.NVarChar;
1894
1713
  }
1895
1714
  }
1896
1715
  /**
@@ -2334,35 +2153,30 @@ ${columns}
2334
2153
  table: TABLE_TRACES,
2335
2154
  columns: ["name", "seq_id DESC"]
2336
2155
  },
2337
- {
2338
- name: `${schemaPrefix}mastra_evals_agent_name_seqid_idx`,
2339
- table: TABLE_EVALS,
2340
- columns: ["agent_name", "seq_id DESC"]
2341
- },
2342
2156
  {
2343
2157
  name: `${schemaPrefix}mastra_scores_trace_id_span_id_seqid_idx`,
2344
2158
  table: TABLE_SCORERS,
2345
2159
  columns: ["traceId", "spanId", "seq_id DESC"]
2346
2160
  },
2347
- // AI Spans indexes for optimal trace querying
2161
+ // Spans indexes for optimal trace querying
2348
2162
  {
2349
2163
  name: `${schemaPrefix}mastra_ai_spans_traceid_startedat_idx`,
2350
- table: TABLE_AI_SPANS,
2164
+ table: TABLE_SPANS,
2351
2165
  columns: ["traceId", "startedAt DESC"]
2352
2166
  },
2353
2167
  {
2354
2168
  name: `${schemaPrefix}mastra_ai_spans_parentspanid_startedat_idx`,
2355
- table: TABLE_AI_SPANS,
2169
+ table: TABLE_SPANS,
2356
2170
  columns: ["parentSpanId", "startedAt DESC"]
2357
2171
  },
2358
2172
  {
2359
2173
  name: `${schemaPrefix}mastra_ai_spans_name_idx`,
2360
- table: TABLE_AI_SPANS,
2174
+ table: TABLE_SPANS,
2361
2175
  columns: ["name"]
2362
2176
  },
2363
2177
  {
2364
2178
  name: `${schemaPrefix}mastra_ai_spans_spantype_startedat_idx`,
2365
- table: TABLE_AI_SPANS,
2179
+ table: TABLE_SPANS,
2366
2180
  columns: ["spanType", "startedAt DESC"]
2367
2181
  }
2368
2182
  ];
@@ -2403,7 +2217,7 @@ function transformScoreRow(row) {
2403
2217
  metadata: safelyParseJSON(row.metadata),
2404
2218
  output: safelyParseJSON(row.output),
2405
2219
  additionalContext: safelyParseJSON(row.additionalContext),
2406
- runtimeContext: safelyParseJSON(row.runtimeContext),
2220
+ requestContext: safelyParseJSON(row.requestContext),
2407
2221
  entity: safelyParseJSON(row.entity),
2408
2222
  createdAt: row.createdAt,
2409
2223
  updatedAt: row.updatedAt
@@ -2470,7 +2284,7 @@ var ScoresMSSQL = class extends ScoresStorage {
2470
2284
  input,
2471
2285
  output,
2472
2286
  additionalContext,
2473
- runtimeContext,
2287
+ requestContext,
2474
2288
  entity,
2475
2289
  ...rest
2476
2290
  } = validatedScore;
@@ -2485,7 +2299,7 @@ var ScoresMSSQL = class extends ScoresStorage {
2485
2299
  analyzeStepResult: analyzeStepResult || null,
2486
2300
  metadata: metadata || null,
2487
2301
  additionalContext: additionalContext || null,
2488
- runtimeContext: runtimeContext || null,
2302
+ requestContext: requestContext || null,
2489
2303
  entity: entity || null,
2490
2304
  scorer: scorer || null,
2491
2305
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -2505,7 +2319,7 @@ var ScoresMSSQL = class extends ScoresStorage {
2505
2319
  );
2506
2320
  }
2507
2321
  }
2508
- async getScoresByScorerId({
2322
+ async listScoresByScorerId({
2509
2323
  scorerId,
2510
2324
  pagination,
2511
2325
  entityId,
@@ -2539,31 +2353,36 @@ var ScoresMSSQL = class extends ScoresStorage {
2539
2353
  });
2540
2354
  const totalResult = await countRequest.query(`SELECT COUNT(*) as count FROM ${tableName} WHERE ${whereClause}`);
2541
2355
  const total = totalResult.recordset[0]?.count || 0;
2356
+ const { page, perPage: perPageInput } = pagination;
2542
2357
  if (total === 0) {
2543
2358
  return {
2544
2359
  pagination: {
2545
2360
  total: 0,
2546
- page: pagination.page,
2547
- perPage: pagination.perPage,
2361
+ page,
2362
+ perPage: perPageInput,
2548
2363
  hasMore: false
2549
2364
  },
2550
2365
  scores: []
2551
2366
  };
2552
2367
  }
2368
+ const perPage = normalizePerPage(perPageInput, 100);
2369
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2370
+ const limitValue = perPageInput === false ? total : perPage;
2371
+ const end = perPageInput === false ? total : start + perPage;
2553
2372
  const dataRequest = this.pool.request();
2554
2373
  Object.entries(params).forEach(([key, value]) => {
2555
2374
  dataRequest.input(key, value);
2556
2375
  });
2557
- dataRequest.input("perPage", pagination.perPage);
2558
- dataRequest.input("offset", pagination.page * pagination.perPage);
2376
+ dataRequest.input("perPage", limitValue);
2377
+ dataRequest.input("offset", start);
2559
2378
  const dataQuery = `SELECT * FROM ${tableName} WHERE ${whereClause} ORDER BY [createdAt] DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
2560
2379
  const result = await dataRequest.query(dataQuery);
2561
2380
  return {
2562
2381
  pagination: {
2563
2382
  total: Number(total),
2564
- page: pagination.page,
2565
- perPage: pagination.perPage,
2566
- hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2383
+ page,
2384
+ perPage: perPageForResponse,
2385
+ hasMore: end < total
2567
2386
  },
2568
2387
  scores: result.recordset.map((row) => transformScoreRow(row))
2569
2388
  };
@@ -2579,7 +2398,7 @@ var ScoresMSSQL = class extends ScoresStorage {
2579
2398
  );
2580
2399
  }
2581
2400
  }
2582
- async getScoresByRunId({
2401
+ async listScoresByRunId({
2583
2402
  runId,
2584
2403
  pagination
2585
2404
  }) {
@@ -2590,30 +2409,35 @@ var ScoresMSSQL = class extends ScoresStorage {
2590
2409
  `SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [runId] = @p1`
2591
2410
  );
2592
2411
  const total = totalResult.recordset[0]?.count || 0;
2412
+ const { page, perPage: perPageInput } = pagination;
2593
2413
  if (total === 0) {
2594
2414
  return {
2595
2415
  pagination: {
2596
2416
  total: 0,
2597
- page: pagination.page,
2598
- perPage: pagination.perPage,
2417
+ page,
2418
+ perPage: perPageInput,
2599
2419
  hasMore: false
2600
2420
  },
2601
2421
  scores: []
2602
2422
  };
2603
2423
  }
2424
+ const perPage = normalizePerPage(perPageInput, 100);
2425
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2426
+ const limitValue = perPageInput === false ? total : perPage;
2427
+ const end = perPageInput === false ? total : start + perPage;
2604
2428
  const dataRequest = this.pool.request();
2605
2429
  dataRequest.input("p1", runId);
2606
- dataRequest.input("p2", pagination.perPage);
2607
- dataRequest.input("p3", pagination.page * pagination.perPage);
2430
+ dataRequest.input("p2", limitValue);
2431
+ dataRequest.input("p3", start);
2608
2432
  const result = await dataRequest.query(
2609
2433
  `SELECT * FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [runId] = @p1 ORDER BY [createdAt] DESC OFFSET @p3 ROWS FETCH NEXT @p2 ROWS ONLY`
2610
2434
  );
2611
2435
  return {
2612
2436
  pagination: {
2613
2437
  total: Number(total),
2614
- page: pagination.page,
2615
- perPage: pagination.perPage,
2616
- hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2438
+ page,
2439
+ perPage: perPageForResponse,
2440
+ hasMore: end < total
2617
2441
  },
2618
2442
  scores: result.recordset.map((row) => transformScoreRow(row))
2619
2443
  };
@@ -2629,7 +2453,7 @@ var ScoresMSSQL = class extends ScoresStorage {
2629
2453
  );
2630
2454
  }
2631
2455
  }
2632
- async getScoresByEntityId({
2456
+ async listScoresByEntityId({
2633
2457
  entityId,
2634
2458
  entityType,
2635
2459
  pagination
@@ -2642,31 +2466,36 @@ var ScoresMSSQL = class extends ScoresStorage {
2642
2466
  `SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [entityId] = @p1 AND [entityType] = @p2`
2643
2467
  );
2644
2468
  const total = totalResult.recordset[0]?.count || 0;
2469
+ const { page, perPage: perPageInput } = pagination;
2470
+ const perPage = normalizePerPage(perPageInput, 100);
2471
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2645
2472
  if (total === 0) {
2646
2473
  return {
2647
2474
  pagination: {
2648
2475
  total: 0,
2649
- page: pagination.page,
2650
- perPage: pagination.perPage,
2476
+ page,
2477
+ perPage: perPageForResponse,
2651
2478
  hasMore: false
2652
2479
  },
2653
2480
  scores: []
2654
2481
  };
2655
2482
  }
2483
+ const limitValue = perPageInput === false ? total : perPage;
2484
+ const end = perPageInput === false ? total : start + perPage;
2656
2485
  const dataRequest = this.pool.request();
2657
2486
  dataRequest.input("p1", entityId);
2658
2487
  dataRequest.input("p2", entityType);
2659
- dataRequest.input("p3", pagination.perPage);
2660
- dataRequest.input("p4", pagination.page * pagination.perPage);
2488
+ dataRequest.input("p3", limitValue);
2489
+ dataRequest.input("p4", start);
2661
2490
  const result = await dataRequest.query(
2662
2491
  `SELECT * FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [entityId] = @p1 AND [entityType] = @p2 ORDER BY [createdAt] DESC OFFSET @p4 ROWS FETCH NEXT @p3 ROWS ONLY`
2663
2492
  );
2664
2493
  return {
2665
2494
  pagination: {
2666
2495
  total: Number(total),
2667
- page: pagination.page,
2668
- perPage: pagination.perPage,
2669
- hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2496
+ page,
2497
+ perPage: perPageForResponse,
2498
+ hasMore: end < total
2670
2499
  },
2671
2500
  scores: result.recordset.map((row) => transformScoreRow(row))
2672
2501
  };
@@ -2682,7 +2511,7 @@ var ScoresMSSQL = class extends ScoresStorage {
2682
2511
  );
2683
2512
  }
2684
2513
  }
2685
- async getScoresBySpan({
2514
+ async listScoresBySpan({
2686
2515
  traceId,
2687
2516
  spanId,
2688
2517
  pagination
@@ -2695,34 +2524,38 @@ var ScoresMSSQL = class extends ScoresStorage {
2695
2524
  `SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [traceId] = @p1 AND [spanId] = @p2`
2696
2525
  );
2697
2526
  const total = totalResult.recordset[0]?.count || 0;
2527
+ const { page, perPage: perPageInput } = pagination;
2528
+ const perPage = normalizePerPage(perPageInput, 100);
2529
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
2698
2530
  if (total === 0) {
2699
2531
  return {
2700
2532
  pagination: {
2701
2533
  total: 0,
2702
- page: pagination.page,
2703
- perPage: pagination.perPage,
2534
+ page,
2535
+ perPage: perPageForResponse,
2704
2536
  hasMore: false
2705
2537
  },
2706
2538
  scores: []
2707
2539
  };
2708
2540
  }
2709
- const limit = pagination.perPage + 1;
2541
+ const limitValue = perPageInput === false ? total : perPage;
2542
+ const end = perPageInput === false ? total : start + perPage;
2710
2543
  const dataRequest = this.pool.request();
2711
2544
  dataRequest.input("p1", traceId);
2712
2545
  dataRequest.input("p2", spanId);
2713
- dataRequest.input("p3", limit);
2714
- dataRequest.input("p4", pagination.page * pagination.perPage);
2546
+ dataRequest.input("p3", limitValue);
2547
+ dataRequest.input("p4", start);
2715
2548
  const result = await dataRequest.query(
2716
2549
  `SELECT * FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [traceId] = @p1 AND [spanId] = @p2 ORDER BY [createdAt] DESC OFFSET @p4 ROWS FETCH NEXT @p3 ROWS ONLY`
2717
2550
  );
2718
2551
  return {
2719
2552
  pagination: {
2720
2553
  total: Number(total),
2721
- page: pagination.page,
2722
- perPage: pagination.perPage,
2723
- hasMore: result.recordset.length > pagination.perPage
2554
+ page,
2555
+ perPage: perPageForResponse,
2556
+ hasMore: end < total
2724
2557
  },
2725
- scores: result.recordset.slice(0, pagination.perPage).map((row) => transformScoreRow(row))
2558
+ scores: result.recordset.map((row) => transformScoreRow(row))
2726
2559
  };
2727
2560
  } catch (error) {
2728
2561
  throw new MastraError(
@@ -2737,173 +2570,6 @@ var ScoresMSSQL = class extends ScoresStorage {
2737
2570
  }
2738
2571
  }
2739
2572
  };
2740
- var TracesMSSQL = class extends TracesStorage {
2741
- pool;
2742
- operations;
2743
- schema;
2744
- constructor({
2745
- pool,
2746
- operations,
2747
- schema
2748
- }) {
2749
- super();
2750
- this.pool = pool;
2751
- this.operations = operations;
2752
- this.schema = schema;
2753
- }
2754
- /** @deprecated use getTracesPaginated instead*/
2755
- async getTraces(args) {
2756
- if (args.fromDate || args.toDate) {
2757
- args.dateRange = {
2758
- start: args.fromDate,
2759
- end: args.toDate
2760
- };
2761
- }
2762
- const result = await this.getTracesPaginated(args);
2763
- return result.traces;
2764
- }
2765
- async getTracesPaginated(args) {
2766
- const { name, scope, page = 0, perPage: perPageInput, attributes, filters, dateRange } = args;
2767
- const fromDate = dateRange?.start;
2768
- const toDate = dateRange?.end;
2769
- const perPage = perPageInput !== void 0 ? perPageInput : 100;
2770
- const currentOffset = page * perPage;
2771
- const paramMap = {};
2772
- const conditions = [];
2773
- let paramIndex = 1;
2774
- if (name) {
2775
- const paramName = `p${paramIndex++}`;
2776
- conditions.push(`[name] LIKE @${paramName}`);
2777
- paramMap[paramName] = `${name}%`;
2778
- }
2779
- if (scope) {
2780
- const paramName = `p${paramIndex++}`;
2781
- conditions.push(`[scope] = @${paramName}`);
2782
- paramMap[paramName] = scope;
2783
- }
2784
- if (attributes) {
2785
- Object.entries(attributes).forEach(([key, value]) => {
2786
- const parsedKey = parseFieldKey(key);
2787
- const paramName = `p${paramIndex++}`;
2788
- conditions.push(`JSON_VALUE([attributes], '$.${parsedKey}') = @${paramName}`);
2789
- paramMap[paramName] = value;
2790
- });
2791
- }
2792
- if (filters) {
2793
- Object.entries(filters).forEach(([key, value]) => {
2794
- const parsedKey = parseFieldKey(key);
2795
- const paramName = `p${paramIndex++}`;
2796
- conditions.push(`[${parsedKey}] = @${paramName}`);
2797
- paramMap[paramName] = value;
2798
- });
2799
- }
2800
- if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
2801
- const paramName = `p${paramIndex++}`;
2802
- conditions.push(`[createdAt] >= @${paramName}`);
2803
- paramMap[paramName] = fromDate.toISOString();
2804
- }
2805
- if (toDate instanceof Date && !isNaN(toDate.getTime())) {
2806
- const paramName = `p${paramIndex++}`;
2807
- conditions.push(`[createdAt] <= @${paramName}`);
2808
- paramMap[paramName] = toDate.toISOString();
2809
- }
2810
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2811
- const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: TABLE_TRACES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
2812
- let total = 0;
2813
- try {
2814
- const countRequest = this.pool.request();
2815
- Object.entries(paramMap).forEach(([key, value]) => {
2816
- if (value instanceof Date) {
2817
- countRequest.input(key, sql3.DateTime, value);
2818
- } else {
2819
- countRequest.input(key, value);
2820
- }
2821
- });
2822
- const countResult = await countRequest.query(countQuery);
2823
- total = parseInt(countResult.recordset[0].total, 10);
2824
- } catch (error) {
2825
- throw new MastraError(
2826
- {
2827
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TOTAL_COUNT",
2828
- domain: ErrorDomain.STORAGE,
2829
- category: ErrorCategory.THIRD_PARTY,
2830
- details: {
2831
- name: args.name ?? "",
2832
- scope: args.scope ?? ""
2833
- }
2834
- },
2835
- error
2836
- );
2837
- }
2838
- if (total === 0) {
2839
- return {
2840
- traces: [],
2841
- total: 0,
2842
- page,
2843
- perPage,
2844
- hasMore: false
2845
- };
2846
- }
2847
- const dataQuery = `SELECT * FROM ${getTableName({ indexName: TABLE_TRACES, schemaName: getSchemaName(this.schema) })} ${whereClause} ORDER BY [seq_id] DESC OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
2848
- const dataRequest = this.pool.request();
2849
- Object.entries(paramMap).forEach(([key, value]) => {
2850
- if (value instanceof Date) {
2851
- dataRequest.input(key, sql3.DateTime, value);
2852
- } else {
2853
- dataRequest.input(key, value);
2854
- }
2855
- });
2856
- dataRequest.input("offset", currentOffset);
2857
- dataRequest.input("limit", perPage);
2858
- try {
2859
- const rowsResult = await dataRequest.query(dataQuery);
2860
- const rows = rowsResult.recordset;
2861
- const traces = rows.map((row) => ({
2862
- id: row.id,
2863
- parentSpanId: row.parentSpanId,
2864
- traceId: row.traceId,
2865
- name: row.name,
2866
- scope: row.scope,
2867
- kind: row.kind,
2868
- status: JSON.parse(row.status),
2869
- events: JSON.parse(row.events),
2870
- links: JSON.parse(row.links),
2871
- attributes: JSON.parse(row.attributes),
2872
- startTime: row.startTime,
2873
- endTime: row.endTime,
2874
- other: row.other,
2875
- createdAt: row.createdAt
2876
- }));
2877
- return {
2878
- traces,
2879
- total,
2880
- page,
2881
- perPage,
2882
- hasMore: currentOffset + traces.length < total
2883
- };
2884
- } catch (error) {
2885
- throw new MastraError(
2886
- {
2887
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TRACES",
2888
- domain: ErrorDomain.STORAGE,
2889
- category: ErrorCategory.THIRD_PARTY,
2890
- details: {
2891
- name: args.name ?? "",
2892
- scope: args.scope ?? ""
2893
- }
2894
- },
2895
- error
2896
- );
2897
- }
2898
- }
2899
- async batchTraceInsert({ records }) {
2900
- this.logger.debug("Batch inserting traces", { count: records.length });
2901
- await this.operations.batchInsert({
2902
- tableName: TABLE_TRACES,
2903
- records
2904
- });
2905
- }
2906
- };
2907
2573
  var WorkflowsMSSQL = class extends WorkflowsStorage {
2908
2574
  pool;
2909
2575
  operations;
@@ -2941,13 +2607,13 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
2941
2607
  runId,
2942
2608
  stepId,
2943
2609
  result,
2944
- runtimeContext
2610
+ requestContext
2945
2611
  }) {
2946
2612
  const table = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
2947
2613
  const transaction = this.pool.transaction();
2948
2614
  try {
2949
2615
  await transaction.begin();
2950
- const selectRequest = new sql3.Request(transaction);
2616
+ const selectRequest = new sql2.Request(transaction);
2951
2617
  selectRequest.input("workflow_name", workflowName);
2952
2618
  selectRequest.input("run_id", runId);
2953
2619
  const existingSnapshotResult = await selectRequest.query(
@@ -2966,20 +2632,20 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
2966
2632
  waitingPaths: {},
2967
2633
  status: "pending",
2968
2634
  runId,
2969
- runtimeContext: {}
2635
+ requestContext: {}
2970
2636
  };
2971
2637
  } else {
2972
2638
  const existingSnapshot = existingSnapshotResult.recordset[0].snapshot;
2973
2639
  snapshot = typeof existingSnapshot === "string" ? JSON.parse(existingSnapshot) : existingSnapshot;
2974
2640
  }
2975
2641
  snapshot.context[stepId] = result;
2976
- snapshot.runtimeContext = { ...snapshot.runtimeContext, ...runtimeContext };
2977
- const upsertReq = new sql3.Request(transaction);
2642
+ snapshot.requestContext = { ...snapshot.requestContext, ...requestContext };
2643
+ const upsertReq = new sql2.Request(transaction);
2978
2644
  upsertReq.input("workflow_name", workflowName);
2979
2645
  upsertReq.input("run_id", runId);
2980
2646
  upsertReq.input("snapshot", JSON.stringify(snapshot));
2981
- upsertReq.input("createdAt", sql3.DateTime2, /* @__PURE__ */ new Date());
2982
- upsertReq.input("updatedAt", sql3.DateTime2, /* @__PURE__ */ new Date());
2647
+ upsertReq.input("createdAt", sql2.DateTime2, /* @__PURE__ */ new Date());
2648
+ upsertReq.input("updatedAt", sql2.DateTime2, /* @__PURE__ */ new Date());
2983
2649
  await upsertReq.query(
2984
2650
  `MERGE ${table} AS target
2985
2651
  USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
@@ -3019,7 +2685,7 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
3019
2685
  const transaction = this.pool.transaction();
3020
2686
  try {
3021
2687
  await transaction.begin();
3022
- const selectRequest = new sql3.Request(transaction);
2688
+ const selectRequest = new sql2.Request(transaction);
3023
2689
  selectRequest.input("workflow_name", workflowName);
3024
2690
  selectRequest.input("run_id", runId);
3025
2691
  const existingSnapshotResult = await selectRequest.query(
@@ -3047,11 +2713,11 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
3047
2713
  );
3048
2714
  }
3049
2715
  const updatedSnapshot = { ...snapshot, ...opts };
3050
- const updateRequest = new sql3.Request(transaction);
2716
+ const updateRequest = new sql2.Request(transaction);
3051
2717
  updateRequest.input("snapshot", JSON.stringify(updatedSnapshot));
3052
2718
  updateRequest.input("workflow_name", workflowName);
3053
2719
  updateRequest.input("run_id", runId);
3054
- updateRequest.input("updatedAt", sql3.DateTime2, /* @__PURE__ */ new Date());
2720
+ updateRequest.input("updatedAt", sql2.DateTime2, /* @__PURE__ */ new Date());
3055
2721
  await updateRequest.query(
3056
2722
  `UPDATE ${table} SET snapshot = @snapshot, [updatedAt] = @updatedAt WHERE workflow_name = @workflow_name AND run_id = @run_id`
3057
2723
  );
@@ -3090,8 +2756,8 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
3090
2756
  request.input("run_id", runId);
3091
2757
  request.input("resourceId", resourceId);
3092
2758
  request.input("snapshot", JSON.stringify(snapshot));
3093
- request.input("createdAt", sql3.DateTime2, new Date(now));
3094
- request.input("updatedAt", sql3.DateTime2, new Date(now));
2759
+ request.input("createdAt", sql2.DateTime2, new Date(now));
2760
+ request.input("updatedAt", sql2.DateTime2, new Date(now));
3095
2761
  const mergeSql = `MERGE INTO ${table} AS target
3096
2762
  USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
3097
2763
  ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
@@ -3188,12 +2854,12 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
3188
2854
  );
3189
2855
  }
3190
2856
  }
3191
- async getWorkflowRuns({
2857
+ async listWorkflowRuns({
3192
2858
  workflowName,
3193
2859
  fromDate,
3194
2860
  toDate,
3195
- limit,
3196
- offset,
2861
+ page,
2862
+ perPage,
3197
2863
  resourceId
3198
2864
  } = {}) {
3199
2865
  try {
@@ -3226,20 +2892,23 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
3226
2892
  const request = this.pool.request();
3227
2893
  Object.entries(paramMap).forEach(([key, value]) => {
3228
2894
  if (value instanceof Date) {
3229
- request.input(key, sql3.DateTime, value);
2895
+ request.input(key, sql2.DateTime, value);
3230
2896
  } else {
3231
2897
  request.input(key, value);
3232
2898
  }
3233
2899
  });
3234
- if (limit !== void 0 && offset !== void 0) {
2900
+ const usePagination = typeof perPage === "number" && typeof page === "number";
2901
+ if (usePagination) {
3235
2902
  const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
3236
2903
  const countResult = await request.query(countQuery);
3237
2904
  total = Number(countResult.recordset[0]?.count || 0);
3238
2905
  }
3239
2906
  let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
3240
- if (limit !== void 0 && offset !== void 0) {
3241
- query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
3242
- request.input("limit", limit);
2907
+ if (usePagination) {
2908
+ const normalizedPerPage = normalizePerPage(perPage, Number.MAX_SAFE_INTEGER);
2909
+ const offset = page * normalizedPerPage;
2910
+ query += ` OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
2911
+ request.input("perPage", normalizedPerPage);
3243
2912
  request.input("offset", offset);
3244
2913
  }
3245
2914
  const result = await request.query(query);
@@ -3248,7 +2917,7 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
3248
2917
  } catch (error) {
3249
2918
  throw new MastraError(
3250
2919
  {
3251
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
2920
+ id: "MASTRA_STORAGE_MSSQL_STORE_LIST_WORKFLOW_RUNS_FAILED",
3252
2921
  domain: ErrorDomain.STORAGE,
3253
2922
  category: ErrorCategory.THIRD_PARTY,
3254
2923
  details: {
@@ -3268,7 +2937,10 @@ var MSSQLStore = class extends MastraStorage {
3268
2937
  isConnected = null;
3269
2938
  stores;
3270
2939
  constructor(config) {
3271
- super({ name: "MSSQLStore" });
2940
+ if (!config.id || typeof config.id !== "string" || config.id.trim() === "") {
2941
+ throw new Error("MSSQLStore: id must be provided and cannot be empty.");
2942
+ }
2943
+ super({ id: config.id, name: "MSSQLStore" });
3272
2944
  try {
3273
2945
  if ("connectionString" in config) {
3274
2946
  if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") {
@@ -3283,7 +2955,7 @@ var MSSQLStore = class extends MastraStorage {
3283
2955
  }
3284
2956
  }
3285
2957
  this.schema = config.schemaName || "dbo";
3286
- this.pool = "connectionString" in config ? new sql3.ConnectionPool(config.connectionString) : new sql3.ConnectionPool({
2958
+ this.pool = "connectionString" in config ? new sql2.ConnectionPool(config.connectionString) : new sql2.ConnectionPool({
3287
2959
  server: config.server,
3288
2960
  database: config.database,
3289
2961
  user: config.user,
@@ -3291,19 +2963,15 @@ var MSSQLStore = class extends MastraStorage {
3291
2963
  port: config.port,
3292
2964
  options: config.options || { encrypt: true, trustServerCertificate: true }
3293
2965
  });
3294
- const legacyEvals = new LegacyEvalsMSSQL({ pool: this.pool, schema: this.schema });
3295
2966
  const operations = new StoreOperationsMSSQL({ pool: this.pool, schemaName: this.schema });
3296
2967
  const scores = new ScoresMSSQL({ pool: this.pool, operations, schema: this.schema });
3297
- const traces = new TracesMSSQL({ pool: this.pool, operations, schema: this.schema });
3298
2968
  const workflows = new WorkflowsMSSQL({ pool: this.pool, operations, schema: this.schema });
3299
2969
  const memory = new MemoryMSSQL({ pool: this.pool, schema: this.schema, operations });
3300
2970
  const observability = new ObservabilityMSSQL({ pool: this.pool, operations, schema: this.schema });
3301
2971
  this.stores = {
3302
2972
  operations,
3303
2973
  scores,
3304
- traces,
3305
2974
  workflows,
3306
- legacyEvals,
3307
2975
  memory,
3308
2976
  observability
3309
2977
  };
@@ -3357,30 +3025,11 @@ var MSSQLStore = class extends MastraStorage {
3357
3025
  hasColumn: true,
3358
3026
  createTable: true,
3359
3027
  deleteMessages: true,
3360
- getScoresBySpan: true,
3361
- aiTracing: true,
3028
+ listScoresBySpan: true,
3029
+ observabilityInstance: true,
3362
3030
  indexManagement: true
3363
3031
  };
3364
3032
  }
3365
- /** @deprecated use getEvals instead */
3366
- async getEvalsByAgentName(agentName, type) {
3367
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
3368
- }
3369
- async getEvals(options = {}) {
3370
- return this.stores.legacyEvals.getEvals(options);
3371
- }
3372
- /**
3373
- * @deprecated use getTracesPaginated instead
3374
- */
3375
- async getTraces(args) {
3376
- return this.stores.traces.getTraces(args);
3377
- }
3378
- async getTracesPaginated(args) {
3379
- return this.stores.traces.getTracesPaginated(args);
3380
- }
3381
- async batchTraceInsert({ records }) {
3382
- return this.stores.traces.batchTraceInsert({ records });
3383
- }
3384
3033
  async createTable({
3385
3034
  tableName,
3386
3035
  schema
@@ -3415,15 +3064,6 @@ var MSSQLStore = class extends MastraStorage {
3415
3064
  async getThreadById({ threadId }) {
3416
3065
  return this.stores.memory.getThreadById({ threadId });
3417
3066
  }
3418
- /**
3419
- * @deprecated use getThreadsByResourceIdPaginated instead
3420
- */
3421
- async getThreadsByResourceId(args) {
3422
- return this.stores.memory.getThreadsByResourceId(args);
3423
- }
3424
- async getThreadsByResourceIdPaginated(args) {
3425
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
3426
- }
3427
3067
  async saveThread({ thread }) {
3428
3068
  return this.stores.memory.saveThread({ thread });
3429
3069
  }
@@ -3437,17 +3077,8 @@ var MSSQLStore = class extends MastraStorage {
3437
3077
  async deleteThread({ threadId }) {
3438
3078
  return this.stores.memory.deleteThread({ threadId });
3439
3079
  }
3440
- async getMessages(args) {
3441
- return this.stores.memory.getMessages(args);
3442
- }
3443
- async getMessagesById({
3444
- messageIds,
3445
- format
3446
- }) {
3447
- return this.stores.memory.getMessagesById({ messageIds, format });
3448
- }
3449
- async getMessagesPaginated(args) {
3450
- return this.stores.memory.getMessagesPaginated(args);
3080
+ async listMessagesById({ messageIds }) {
3081
+ return this.stores.memory.listMessagesById({ messageIds });
3451
3082
  }
3452
3083
  async saveMessages(args) {
3453
3084
  return this.stores.memory.saveMessages(args);
@@ -3481,9 +3112,9 @@ var MSSQLStore = class extends MastraStorage {
3481
3112
  runId,
3482
3113
  stepId,
3483
3114
  result,
3484
- runtimeContext
3115
+ requestContext
3485
3116
  }) {
3486
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
3117
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
3487
3118
  }
3488
3119
  async updateWorkflowState({
3489
3120
  workflowName,
@@ -3506,15 +3137,15 @@ var MSSQLStore = class extends MastraStorage {
3506
3137
  }) {
3507
3138
  return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
3508
3139
  }
3509
- async getWorkflowRuns({
3140
+ async listWorkflowRuns({
3510
3141
  workflowName,
3511
3142
  fromDate,
3512
3143
  toDate,
3513
- limit,
3514
- offset,
3144
+ perPage,
3145
+ page,
3515
3146
  resourceId
3516
3147
  } = {}) {
3517
- return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
3148
+ return this.stores.workflows.listWorkflowRuns({ workflowName, fromDate, toDate, perPage, page, resourceId });
3518
3149
  }
3519
3150
  async getWorkflowRunById({
3520
3151
  runId,
@@ -3541,7 +3172,7 @@ var MSSQLStore = class extends MastraStorage {
3541
3172
  return this.stores.operations.dropIndex(indexName);
3542
3173
  }
3543
3174
  /**
3544
- * AI Tracing / Observability
3175
+ * Tracing / Observability
3545
3176
  */
3546
3177
  getObservabilityStore() {
3547
3178
  if (!this.stores.observability) {
@@ -3554,30 +3185,30 @@ var MSSQLStore = class extends MastraStorage {
3554
3185
  }
3555
3186
  return this.stores.observability;
3556
3187
  }
3557
- async createAISpan(span) {
3558
- return this.getObservabilityStore().createAISpan(span);
3188
+ async createSpan(span) {
3189
+ return this.getObservabilityStore().createSpan(span);
3559
3190
  }
3560
- async updateAISpan({
3191
+ async updateSpan({
3561
3192
  spanId,
3562
3193
  traceId,
3563
3194
  updates
3564
3195
  }) {
3565
- return this.getObservabilityStore().updateAISpan({ spanId, traceId, updates });
3196
+ return this.getObservabilityStore().updateSpan({ spanId, traceId, updates });
3566
3197
  }
3567
- async getAITrace(traceId) {
3568
- return this.getObservabilityStore().getAITrace(traceId);
3198
+ async getTrace(traceId) {
3199
+ return this.getObservabilityStore().getTrace(traceId);
3569
3200
  }
3570
- async getAITracesPaginated(args) {
3571
- return this.getObservabilityStore().getAITracesPaginated(args);
3201
+ async getTracesPaginated(args) {
3202
+ return this.getObservabilityStore().getTracesPaginated(args);
3572
3203
  }
3573
- async batchCreateAISpans(args) {
3574
- return this.getObservabilityStore().batchCreateAISpans(args);
3204
+ async batchCreateSpans(args) {
3205
+ return this.getObservabilityStore().batchCreateSpans(args);
3575
3206
  }
3576
- async batchUpdateAISpans(args) {
3577
- return this.getObservabilityStore().batchUpdateAISpans(args);
3207
+ async batchUpdateSpans(args) {
3208
+ return this.getObservabilityStore().batchUpdateSpans(args);
3578
3209
  }
3579
- async batchDeleteAITraces(args) {
3580
- return this.getObservabilityStore().batchDeleteAITraces(args);
3210
+ async batchDeleteTraces(args) {
3211
+ return this.getObservabilityStore().batchDeleteTraces(args);
3581
3212
  }
3582
3213
  /**
3583
3214
  * Scorers
@@ -3585,14 +3216,14 @@ var MSSQLStore = class extends MastraStorage {
3585
3216
  async getScoreById({ id: _id }) {
3586
3217
  return this.stores.scores.getScoreById({ id: _id });
3587
3218
  }
3588
- async getScoresByScorerId({
3219
+ async listScoresByScorerId({
3589
3220
  scorerId: _scorerId,
3590
3221
  pagination: _pagination,
3591
3222
  entityId: _entityId,
3592
3223
  entityType: _entityType,
3593
3224
  source: _source
3594
3225
  }) {
3595
- return this.stores.scores.getScoresByScorerId({
3226
+ return this.stores.scores.listScoresByScorerId({
3596
3227
  scorerId: _scorerId,
3597
3228
  pagination: _pagination,
3598
3229
  entityId: _entityId,
@@ -3603,29 +3234,29 @@ var MSSQLStore = class extends MastraStorage {
3603
3234
  async saveScore(_score) {
3604
3235
  return this.stores.scores.saveScore(_score);
3605
3236
  }
3606
- async getScoresByRunId({
3237
+ async listScoresByRunId({
3607
3238
  runId: _runId,
3608
3239
  pagination: _pagination
3609
3240
  }) {
3610
- return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
3241
+ return this.stores.scores.listScoresByRunId({ runId: _runId, pagination: _pagination });
3611
3242
  }
3612
- async getScoresByEntityId({
3243
+ async listScoresByEntityId({
3613
3244
  entityId: _entityId,
3614
3245
  entityType: _entityType,
3615
3246
  pagination: _pagination
3616
3247
  }) {
3617
- return this.stores.scores.getScoresByEntityId({
3248
+ return this.stores.scores.listScoresByEntityId({
3618
3249
  entityId: _entityId,
3619
3250
  entityType: _entityType,
3620
3251
  pagination: _pagination
3621
3252
  });
3622
3253
  }
3623
- async getScoresBySpan({
3254
+ async listScoresBySpan({
3624
3255
  traceId,
3625
3256
  spanId,
3626
3257
  pagination: _pagination
3627
3258
  }) {
3628
- return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination: _pagination });
3259
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination: _pagination });
3629
3260
  }
3630
3261
  };
3631
3262