@mastra/mssql 0.0.0-memory-system-message-error-20250813233316 → 0.0.0-model-router-unknown-provider-20251017212006

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
@@ -5,6 +5,7 @@ var storage = require('@mastra/core/storage');
5
5
  var sql2 = require('mssql');
6
6
  var utils = require('@mastra/core/utils');
7
7
  var agent = require('@mastra/core/agent');
8
+ var scores = require('@mastra/core/scores');
8
9
 
9
10
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
11
 
@@ -467,6 +468,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
467
468
  selectBy,
468
469
  orderByStatement
469
470
  }) {
471
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
470
472
  const include = selectBy?.include;
471
473
  if (!include) return null;
472
474
  const unionQueries = [];
@@ -538,11 +540,12 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
538
540
  return dedupedRows;
539
541
  }
540
542
  async getMessages(args) {
541
- const { threadId, format, selectBy } = args;
543
+ const { threadId, resourceId, format, selectBy } = args;
542
544
  const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
543
545
  const orderByStatement = `ORDER BY [seq_id] DESC`;
544
546
  const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
545
547
  try {
548
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
546
549
  let rows = [];
547
550
  const include = selectBy?.include || [];
548
551
  if (include?.length) {
@@ -580,7 +583,8 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
580
583
  domain: error.ErrorDomain.STORAGE,
581
584
  category: error.ErrorCategory.THIRD_PARTY,
582
585
  details: {
583
- threadId
586
+ threadId,
587
+ resourceId: resourceId ?? ""
584
588
  }
585
589
  },
586
590
  error$1
@@ -590,30 +594,65 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
590
594
  return [];
591
595
  }
592
596
  }
593
- async getMessagesPaginated(args) {
594
- const { threadId, selectBy } = args;
595
- const { page = 0, perPage: perPageInput } = selectBy?.pagination || {};
597
+ async getMessagesById({
598
+ messageIds,
599
+ format
600
+ }) {
601
+ if (messageIds.length === 0) return [];
602
+ const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
596
603
  const orderByStatement = `ORDER BY [seq_id] DESC`;
597
- if (selectBy?.include?.length) {
598
- await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
604
+ try {
605
+ let rows = [];
606
+ let query = `${selectStatement} FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [id] IN (${messageIds.map((_, i) => `@id${i}`).join(", ")})`;
607
+ const request = this.pool.request();
608
+ messageIds.forEach((id, i) => request.input(`id${i}`, id));
609
+ query += ` ${orderByStatement}`;
610
+ const result = await request.query(query);
611
+ const remainingRows = result.recordset || [];
612
+ rows.push(...remainingRows);
613
+ rows.sort((a, b) => {
614
+ const timeDiff = a.seq_id - b.seq_id;
615
+ return timeDiff;
616
+ });
617
+ rows = rows.map(({ seq_id, ...rest }) => rest);
618
+ if (format === `v1`) return this._parseAndFormatMessages(rows, format);
619
+ return this._parseAndFormatMessages(rows, `v2`);
620
+ } catch (error$1) {
621
+ const mastraError = new error.MastraError(
622
+ {
623
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_BY_ID_FAILED",
624
+ domain: error.ErrorDomain.STORAGE,
625
+ category: error.ErrorCategory.THIRD_PARTY,
626
+ details: {
627
+ messageIds: JSON.stringify(messageIds)
628
+ }
629
+ },
630
+ error$1
631
+ );
632
+ this.logger?.error?.(mastraError.toString());
633
+ this.logger?.trackException(mastraError);
634
+ return [];
599
635
  }
636
+ }
637
+ async getMessagesPaginated(args) {
638
+ const { threadId, resourceId, format, selectBy } = args;
639
+ const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
600
640
  try {
601
- const { threadId: threadId2, format, selectBy: selectBy2 } = args;
602
- const { page: page2 = 0, perPage: perPageInput2, dateRange } = selectBy2?.pagination || {};
641
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
603
642
  const fromDate = dateRange?.start;
604
643
  const toDate = dateRange?.end;
605
644
  const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
606
- const orderByStatement2 = `ORDER BY [seq_id] DESC`;
607
- let messages2 = [];
608
- if (selectBy2?.include?.length) {
609
- const includeMessages = await this._getIncludedMessages({ threadId: threadId2, selectBy: selectBy2, orderByStatement: orderByStatement2 });
610
- if (includeMessages) messages2.push(...includeMessages);
645
+ const orderByStatement = `ORDER BY [seq_id] DESC`;
646
+ let messages = [];
647
+ if (selectBy?.include?.length) {
648
+ const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
649
+ if (includeMessages) messages.push(...includeMessages);
611
650
  }
612
- const perPage = perPageInput2 !== void 0 ? perPageInput2 : storage.resolveMessageLimit({ last: selectBy2?.last, defaultLimit: 40 });
613
- const currentOffset = page2 * perPage;
651
+ const perPage = perPageInput !== void 0 ? perPageInput : storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
652
+ const currentOffset = page * perPage;
614
653
  const conditions = ["[thread_id] = @threadId"];
615
654
  const request = this.pool.request();
616
- request.input("threadId", threadId2);
655
+ request.input("threadId", threadId);
617
656
  if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
618
657
  conditions.push("[createdAt] >= @fromDate");
619
658
  request.input("fromDate", fromDate.toISOString());
@@ -626,35 +665,35 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
626
665
  const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
627
666
  const countResult = await request.query(countQuery);
628
667
  const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
629
- if (total === 0 && messages2.length > 0) {
630
- const parsedIncluded = this._parseAndFormatMessages(messages2, format);
668
+ if (total === 0 && messages.length > 0) {
669
+ const parsedIncluded = this._parseAndFormatMessages(messages, format);
631
670
  return {
632
671
  messages: parsedIncluded,
633
672
  total: parsedIncluded.length,
634
- page: page2,
673
+ page,
635
674
  perPage,
636
675
  hasMore: false
637
676
  };
638
677
  }
639
- const excludeIds = messages2.map((m) => m.id);
678
+ const excludeIds = messages.map((m) => m.id);
640
679
  if (excludeIds.length > 0) {
641
680
  const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
642
681
  conditions.push(`id NOT IN (${excludeParams.join(", ")})`);
643
682
  excludeIds.forEach((id, idx) => request.input(`id${idx}`, id));
644
683
  }
645
684
  const finalWhereClause = `WHERE ${conditions.join(" AND ")}`;
646
- const dataQuery = `${selectStatement} FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${finalWhereClause} ${orderByStatement2} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
685
+ const dataQuery = `${selectStatement} FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${finalWhereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
647
686
  request.input("offset", currentOffset);
648
687
  request.input("limit", perPage);
649
688
  const rowsResult = await request.query(dataQuery);
650
689
  const rows = rowsResult.recordset || [];
651
690
  rows.sort((a, b) => a.seq_id - b.seq_id);
652
- messages2.push(...rows);
653
- const parsed = this._parseAndFormatMessages(messages2, format);
691
+ messages.push(...rows);
692
+ const parsed = this._parseAndFormatMessages(messages, format);
654
693
  return {
655
694
  messages: parsed,
656
695
  total: total + excludeIds.length,
657
- page: page2,
696
+ page,
658
697
  perPage,
659
698
  hasMore: currentOffset + rows.length < total
660
699
  };
@@ -666,6 +705,7 @@ var MemoryMSSQL = class extends storage.MemoryStorage {
666
705
  category: error.ErrorCategory.THIRD_PARTY,
667
706
  details: {
668
707
  threadId,
708
+ resourceId: resourceId ?? "",
669
709
  page
670
710
  }
671
711
  },
@@ -1440,6 +1480,19 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
1440
1480
  }
1441
1481
  }
1442
1482
  async saveScore(score) {
1483
+ let validatedScore;
1484
+ try {
1485
+ validatedScore = scores.saveScorePayloadSchema.parse(score);
1486
+ } catch (error$1) {
1487
+ throw new error.MastraError(
1488
+ {
1489
+ id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_SCORE_VALIDATION_FAILED",
1490
+ domain: error.ErrorDomain.STORAGE,
1491
+ category: error.ErrorCategory.THIRD_PARTY
1492
+ },
1493
+ error$1
1494
+ );
1495
+ }
1443
1496
  try {
1444
1497
  const scoreId = crypto.randomUUID();
1445
1498
  const {
@@ -1453,7 +1506,7 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
1453
1506
  runtimeContext,
1454
1507
  entity,
1455
1508
  ...rest
1456
- } = score;
1509
+ } = validatedScore;
1457
1510
  await this.operations.insert({
1458
1511
  tableName: storage.TABLE_SCORERS,
1459
1512
  record: {
@@ -1638,6 +1691,60 @@ var ScoresMSSQL = class extends storage.ScoresStorage {
1638
1691
  );
1639
1692
  }
1640
1693
  }
1694
+ async getScoresBySpan({
1695
+ traceId,
1696
+ spanId,
1697
+ pagination
1698
+ }) {
1699
+ try {
1700
+ const request = this.pool.request();
1701
+ request.input("p1", traceId);
1702
+ request.input("p2", spanId);
1703
+ const totalResult = await request.query(
1704
+ `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [traceId] = @p1 AND [spanId] = @p2`
1705
+ );
1706
+ const total = totalResult.recordset[0]?.count || 0;
1707
+ if (total === 0) {
1708
+ return {
1709
+ pagination: {
1710
+ total: 0,
1711
+ page: pagination.page,
1712
+ perPage: pagination.perPage,
1713
+ hasMore: false
1714
+ },
1715
+ scores: []
1716
+ };
1717
+ }
1718
+ const limit = pagination.perPage + 1;
1719
+ const dataRequest = this.pool.request();
1720
+ dataRequest.input("p1", traceId);
1721
+ dataRequest.input("p2", spanId);
1722
+ dataRequest.input("p3", limit);
1723
+ dataRequest.input("p4", pagination.page * pagination.perPage);
1724
+ const result = await dataRequest.query(
1725
+ `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`
1726
+ );
1727
+ return {
1728
+ pagination: {
1729
+ total: Number(total),
1730
+ page: pagination.page,
1731
+ perPage: pagination.perPage,
1732
+ hasMore: result.recordset.length > pagination.perPage
1733
+ },
1734
+ scores: result.recordset.slice(0, pagination.perPage).map((row) => transformScoreRow(row))
1735
+ };
1736
+ } catch (error$1) {
1737
+ throw new error.MastraError(
1738
+ {
1739
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_SPAN_FAILED",
1740
+ domain: error.ErrorDomain.STORAGE,
1741
+ category: error.ErrorCategory.THIRD_PARTY,
1742
+ details: { traceId, spanId }
1743
+ },
1744
+ error$1
1745
+ );
1746
+ }
1747
+ }
1641
1748
  };
1642
1749
  var TracesMSSQL = class extends storage.TracesStorage {
1643
1750
  pool;
@@ -1838,9 +1945,26 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
1838
1945
  this.operations = operations;
1839
1946
  this.schema = schema;
1840
1947
  }
1948
+ updateWorkflowResults({
1949
+ // workflowName,
1950
+ // runId,
1951
+ // stepId,
1952
+ // result,
1953
+ // runtimeContext,
1954
+ }) {
1955
+ throw new Error("Method not implemented.");
1956
+ }
1957
+ updateWorkflowState({
1958
+ // workflowName,
1959
+ // runId,
1960
+ // opts,
1961
+ }) {
1962
+ throw new Error("Method not implemented.");
1963
+ }
1841
1964
  async persistWorkflowSnapshot({
1842
1965
  workflowName,
1843
1966
  runId,
1967
+ resourceId,
1844
1968
  snapshot
1845
1969
  }) {
1846
1970
  const table = getTableName({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
@@ -1849,6 +1973,7 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
1849
1973
  const request = this.pool.request();
1850
1974
  request.input("workflow_name", workflowName);
1851
1975
  request.input("run_id", runId);
1976
+ request.input("resourceId", resourceId);
1852
1977
  request.input("snapshot", JSON.stringify(snapshot));
1853
1978
  request.input("createdAt", sql2__default.default.DateTime2, new Date(now));
1854
1979
  request.input("updatedAt", sql2__default.default.DateTime2, new Date(now));
@@ -1856,10 +1981,11 @@ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
1856
1981
  USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
1857
1982
  ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
1858
1983
  WHEN MATCHED THEN UPDATE SET
1984
+ resourceId = @resourceId,
1859
1985
  snapshot = @snapshot,
1860
1986
  [updatedAt] = @updatedAt
1861
- WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, snapshot, [createdAt], [updatedAt])
1862
- VALUES (@workflow_name, @run_id, @snapshot, @createdAt, @updatedAt);`;
1987
+ WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, resourceId, snapshot, [createdAt], [updatedAt])
1988
+ VALUES (@workflow_name, @run_id, @resourceId, @snapshot, @createdAt, @updatedAt);`;
1863
1989
  await request.query(mergeSql);
1864
1990
  } catch (error$1) {
1865
1991
  throw new error.MastraError(
@@ -2108,7 +2234,8 @@ var MSSQLStore = class extends storage.MastraStorage {
2108
2234
  resourceWorkingMemory: true,
2109
2235
  hasColumn: true,
2110
2236
  createTable: true,
2111
- deleteMessages: true
2237
+ deleteMessages: true,
2238
+ getScoresBySpan: true
2112
2239
  };
2113
2240
  }
2114
2241
  /** @deprecated use getEvals instead */
@@ -2189,6 +2316,12 @@ var MSSQLStore = class extends storage.MastraStorage {
2189
2316
  async getMessages(args) {
2190
2317
  return this.stores.memory.getMessages(args);
2191
2318
  }
2319
+ async getMessagesById({
2320
+ messageIds,
2321
+ format
2322
+ }) {
2323
+ return this.stores.memory.getMessagesById({ messageIds, format });
2324
+ }
2192
2325
  async getMessagesPaginated(args) {
2193
2326
  return this.stores.memory.getMessagesPaginated(args);
2194
2327
  }
@@ -2219,12 +2352,29 @@ var MSSQLStore = class extends storage.MastraStorage {
2219
2352
  /**
2220
2353
  * Workflows
2221
2354
  */
2355
+ async updateWorkflowResults({
2356
+ workflowName,
2357
+ runId,
2358
+ stepId,
2359
+ result,
2360
+ runtimeContext
2361
+ }) {
2362
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2363
+ }
2364
+ async updateWorkflowState({
2365
+ workflowName,
2366
+ runId,
2367
+ opts
2368
+ }) {
2369
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2370
+ }
2222
2371
  async persistWorkflowSnapshot({
2223
2372
  workflowName,
2224
2373
  runId,
2374
+ resourceId,
2225
2375
  snapshot
2226
2376
  }) {
2227
- return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2377
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
2228
2378
  }
2229
2379
  async loadWorkflowSnapshot({
2230
2380
  workflowName,
@@ -2283,6 +2433,13 @@ var MSSQLStore = class extends storage.MastraStorage {
2283
2433
  pagination: _pagination
2284
2434
  });
2285
2435
  }
2436
+ async getScoresBySpan({
2437
+ traceId,
2438
+ spanId,
2439
+ pagination: _pagination
2440
+ }) {
2441
+ return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination: _pagination });
2442
+ }
2286
2443
  };
2287
2444
 
2288
2445
  exports.MSSQLStore = MSSQLStore;