@mastra/mssql 0.0.0-memory-system-message-error-20250813233316 → 0.0.0-monorepo-binary-20251013210052

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
@@ -3,6 +3,7 @@ import { MastraStorage, LegacyEvalsStorage, StoreOperations, TABLE_WORKFLOW_SNAP
3
3
  import sql2 from 'mssql';
4
4
  import { parseSqlIdentifier, parseFieldKey } from '@mastra/core/utils';
5
5
  import { MessageList } from '@mastra/core/agent';
6
+ import { saveScorePayloadSchema } from '@mastra/core/scores';
6
7
 
7
8
  // src/storage/index.ts
8
9
  function getSchemaName(schema) {
@@ -461,6 +462,7 @@ var MemoryMSSQL = class extends MemoryStorage {
461
462
  selectBy,
462
463
  orderByStatement
463
464
  }) {
465
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
464
466
  const include = selectBy?.include;
465
467
  if (!include) return null;
466
468
  const unionQueries = [];
@@ -532,11 +534,12 @@ var MemoryMSSQL = class extends MemoryStorage {
532
534
  return dedupedRows;
533
535
  }
534
536
  async getMessages(args) {
535
- const { threadId, format, selectBy } = args;
537
+ const { threadId, resourceId, format, selectBy } = args;
536
538
  const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
537
539
  const orderByStatement = `ORDER BY [seq_id] DESC`;
538
540
  const limit = resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
539
541
  try {
542
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
540
543
  let rows = [];
541
544
  const include = selectBy?.include || [];
542
545
  if (include?.length) {
@@ -574,7 +577,8 @@ var MemoryMSSQL = class extends MemoryStorage {
574
577
  domain: ErrorDomain.STORAGE,
575
578
  category: ErrorCategory.THIRD_PARTY,
576
579
  details: {
577
- threadId
580
+ threadId,
581
+ resourceId: resourceId ?? ""
578
582
  }
579
583
  },
580
584
  error
@@ -584,30 +588,65 @@ var MemoryMSSQL = class extends MemoryStorage {
584
588
  return [];
585
589
  }
586
590
  }
587
- async getMessagesPaginated(args) {
588
- const { threadId, selectBy } = args;
589
- const { page = 0, perPage: perPageInput } = selectBy?.pagination || {};
591
+ async getMessagesById({
592
+ messageIds,
593
+ format
594
+ }) {
595
+ if (messageIds.length === 0) return [];
596
+ const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
590
597
  const orderByStatement = `ORDER BY [seq_id] DESC`;
591
- if (selectBy?.include?.length) {
592
- await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
598
+ try {
599
+ let rows = [];
600
+ let query = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [id] IN (${messageIds.map((_, i) => `@id${i}`).join(", ")})`;
601
+ const request = this.pool.request();
602
+ messageIds.forEach((id, i) => request.input(`id${i}`, id));
603
+ query += ` ${orderByStatement}`;
604
+ const result = await request.query(query);
605
+ const remainingRows = result.recordset || [];
606
+ rows.push(...remainingRows);
607
+ rows.sort((a, b) => {
608
+ const timeDiff = a.seq_id - b.seq_id;
609
+ return timeDiff;
610
+ });
611
+ rows = rows.map(({ seq_id, ...rest }) => rest);
612
+ if (format === `v1`) return this._parseAndFormatMessages(rows, format);
613
+ return this._parseAndFormatMessages(rows, `v2`);
614
+ } catch (error) {
615
+ const mastraError = new MastraError(
616
+ {
617
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_BY_ID_FAILED",
618
+ domain: ErrorDomain.STORAGE,
619
+ category: ErrorCategory.THIRD_PARTY,
620
+ details: {
621
+ messageIds: JSON.stringify(messageIds)
622
+ }
623
+ },
624
+ error
625
+ );
626
+ this.logger?.error?.(mastraError.toString());
627
+ this.logger?.trackException(mastraError);
628
+ return [];
593
629
  }
630
+ }
631
+ async getMessagesPaginated(args) {
632
+ const { threadId, resourceId, format, selectBy } = args;
633
+ const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
594
634
  try {
595
- const { threadId: threadId2, format, selectBy: selectBy2 } = args;
596
- const { page: page2 = 0, perPage: perPageInput2, dateRange } = selectBy2?.pagination || {};
635
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
597
636
  const fromDate = dateRange?.start;
598
637
  const toDate = dateRange?.end;
599
638
  const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
600
- const orderByStatement2 = `ORDER BY [seq_id] DESC`;
601
- let messages2 = [];
602
- if (selectBy2?.include?.length) {
603
- const includeMessages = await this._getIncludedMessages({ threadId: threadId2, selectBy: selectBy2, orderByStatement: orderByStatement2 });
604
- if (includeMessages) messages2.push(...includeMessages);
639
+ const orderByStatement = `ORDER BY [seq_id] DESC`;
640
+ let messages = [];
641
+ if (selectBy?.include?.length) {
642
+ const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
643
+ if (includeMessages) messages.push(...includeMessages);
605
644
  }
606
- const perPage = perPageInput2 !== void 0 ? perPageInput2 : resolveMessageLimit({ last: selectBy2?.last, defaultLimit: 40 });
607
- const currentOffset = page2 * perPage;
645
+ const perPage = perPageInput !== void 0 ? perPageInput : resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
646
+ const currentOffset = page * perPage;
608
647
  const conditions = ["[thread_id] = @threadId"];
609
648
  const request = this.pool.request();
610
- request.input("threadId", threadId2);
649
+ request.input("threadId", threadId);
611
650
  if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
612
651
  conditions.push("[createdAt] >= @fromDate");
613
652
  request.input("fromDate", fromDate.toISOString());
@@ -620,35 +659,35 @@ var MemoryMSSQL = class extends MemoryStorage {
620
659
  const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
621
660
  const countResult = await request.query(countQuery);
622
661
  const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
623
- if (total === 0 && messages2.length > 0) {
624
- const parsedIncluded = this._parseAndFormatMessages(messages2, format);
662
+ if (total === 0 && messages.length > 0) {
663
+ const parsedIncluded = this._parseAndFormatMessages(messages, format);
625
664
  return {
626
665
  messages: parsedIncluded,
627
666
  total: parsedIncluded.length,
628
- page: page2,
667
+ page,
629
668
  perPage,
630
669
  hasMore: false
631
670
  };
632
671
  }
633
- const excludeIds = messages2.map((m) => m.id);
672
+ const excludeIds = messages.map((m) => m.id);
634
673
  if (excludeIds.length > 0) {
635
674
  const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
636
675
  conditions.push(`id NOT IN (${excludeParams.join(", ")})`);
637
676
  excludeIds.forEach((id, idx) => request.input(`id${idx}`, id));
638
677
  }
639
678
  const finalWhereClause = `WHERE ${conditions.join(" AND ")}`;
640
- const dataQuery = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${finalWhereClause} ${orderByStatement2} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
679
+ const dataQuery = `${selectStatement} FROM ${getTableName({ indexName: TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${finalWhereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
641
680
  request.input("offset", currentOffset);
642
681
  request.input("limit", perPage);
643
682
  const rowsResult = await request.query(dataQuery);
644
683
  const rows = rowsResult.recordset || [];
645
684
  rows.sort((a, b) => a.seq_id - b.seq_id);
646
- messages2.push(...rows);
647
- const parsed = this._parseAndFormatMessages(messages2, format);
685
+ messages.push(...rows);
686
+ const parsed = this._parseAndFormatMessages(messages, format);
648
687
  return {
649
688
  messages: parsed,
650
689
  total: total + excludeIds.length,
651
- page: page2,
690
+ page,
652
691
  perPage,
653
692
  hasMore: currentOffset + rows.length < total
654
693
  };
@@ -660,6 +699,7 @@ var MemoryMSSQL = class extends MemoryStorage {
660
699
  category: ErrorCategory.THIRD_PARTY,
661
700
  details: {
662
701
  threadId,
702
+ resourceId: resourceId ?? "",
663
703
  page
664
704
  }
665
705
  },
@@ -1434,6 +1474,19 @@ var ScoresMSSQL = class extends ScoresStorage {
1434
1474
  }
1435
1475
  }
1436
1476
  async saveScore(score) {
1477
+ let validatedScore;
1478
+ try {
1479
+ validatedScore = saveScorePayloadSchema.parse(score);
1480
+ } catch (error) {
1481
+ throw new MastraError(
1482
+ {
1483
+ id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_SCORE_VALIDATION_FAILED",
1484
+ domain: ErrorDomain.STORAGE,
1485
+ category: ErrorCategory.THIRD_PARTY
1486
+ },
1487
+ error
1488
+ );
1489
+ }
1437
1490
  try {
1438
1491
  const scoreId = crypto.randomUUID();
1439
1492
  const {
@@ -1447,7 +1500,7 @@ var ScoresMSSQL = class extends ScoresStorage {
1447
1500
  runtimeContext,
1448
1501
  entity,
1449
1502
  ...rest
1450
- } = score;
1503
+ } = validatedScore;
1451
1504
  await this.operations.insert({
1452
1505
  tableName: TABLE_SCORERS,
1453
1506
  record: {
@@ -1632,6 +1685,60 @@ var ScoresMSSQL = class extends ScoresStorage {
1632
1685
  );
1633
1686
  }
1634
1687
  }
1688
+ async getScoresBySpan({
1689
+ traceId,
1690
+ spanId,
1691
+ pagination
1692
+ }) {
1693
+ try {
1694
+ const request = this.pool.request();
1695
+ request.input("p1", traceId);
1696
+ request.input("p2", spanId);
1697
+ const totalResult = await request.query(
1698
+ `SELECT COUNT(*) as count FROM ${getTableName({ indexName: TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [traceId] = @p1 AND [spanId] = @p2`
1699
+ );
1700
+ const total = totalResult.recordset[0]?.count || 0;
1701
+ if (total === 0) {
1702
+ return {
1703
+ pagination: {
1704
+ total: 0,
1705
+ page: pagination.page,
1706
+ perPage: pagination.perPage,
1707
+ hasMore: false
1708
+ },
1709
+ scores: []
1710
+ };
1711
+ }
1712
+ const limit = pagination.perPage + 1;
1713
+ const dataRequest = this.pool.request();
1714
+ dataRequest.input("p1", traceId);
1715
+ dataRequest.input("p2", spanId);
1716
+ dataRequest.input("p3", limit);
1717
+ dataRequest.input("p4", pagination.page * pagination.perPage);
1718
+ const result = await dataRequest.query(
1719
+ `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`
1720
+ );
1721
+ return {
1722
+ pagination: {
1723
+ total: Number(total),
1724
+ page: pagination.page,
1725
+ perPage: pagination.perPage,
1726
+ hasMore: result.recordset.length > pagination.perPage
1727
+ },
1728
+ scores: result.recordset.slice(0, pagination.perPage).map((row) => transformScoreRow(row))
1729
+ };
1730
+ } catch (error) {
1731
+ throw new MastraError(
1732
+ {
1733
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_SPAN_FAILED",
1734
+ domain: ErrorDomain.STORAGE,
1735
+ category: ErrorCategory.THIRD_PARTY,
1736
+ details: { traceId, spanId }
1737
+ },
1738
+ error
1739
+ );
1740
+ }
1741
+ }
1635
1742
  };
1636
1743
  var TracesMSSQL = class extends TracesStorage {
1637
1744
  pool;
@@ -1832,9 +1939,26 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
1832
1939
  this.operations = operations;
1833
1940
  this.schema = schema;
1834
1941
  }
1942
+ updateWorkflowResults({
1943
+ // workflowName,
1944
+ // runId,
1945
+ // stepId,
1946
+ // result,
1947
+ // runtimeContext,
1948
+ }) {
1949
+ throw new Error("Method not implemented.");
1950
+ }
1951
+ updateWorkflowState({
1952
+ // workflowName,
1953
+ // runId,
1954
+ // opts,
1955
+ }) {
1956
+ throw new Error("Method not implemented.");
1957
+ }
1835
1958
  async persistWorkflowSnapshot({
1836
1959
  workflowName,
1837
1960
  runId,
1961
+ resourceId,
1838
1962
  snapshot
1839
1963
  }) {
1840
1964
  const table = getTableName({ indexName: TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
@@ -1843,6 +1967,7 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
1843
1967
  const request = this.pool.request();
1844
1968
  request.input("workflow_name", workflowName);
1845
1969
  request.input("run_id", runId);
1970
+ request.input("resourceId", resourceId);
1846
1971
  request.input("snapshot", JSON.stringify(snapshot));
1847
1972
  request.input("createdAt", sql2.DateTime2, new Date(now));
1848
1973
  request.input("updatedAt", sql2.DateTime2, new Date(now));
@@ -1850,10 +1975,11 @@ var WorkflowsMSSQL = class extends WorkflowsStorage {
1850
1975
  USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
1851
1976
  ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
1852
1977
  WHEN MATCHED THEN UPDATE SET
1978
+ resourceId = @resourceId,
1853
1979
  snapshot = @snapshot,
1854
1980
  [updatedAt] = @updatedAt
1855
- WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, snapshot, [createdAt], [updatedAt])
1856
- VALUES (@workflow_name, @run_id, @snapshot, @createdAt, @updatedAt);`;
1981
+ WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, resourceId, snapshot, [createdAt], [updatedAt])
1982
+ VALUES (@workflow_name, @run_id, @resourceId, @snapshot, @createdAt, @updatedAt);`;
1857
1983
  await request.query(mergeSql);
1858
1984
  } catch (error) {
1859
1985
  throw new MastraError(
@@ -2102,7 +2228,8 @@ var MSSQLStore = class extends MastraStorage {
2102
2228
  resourceWorkingMemory: true,
2103
2229
  hasColumn: true,
2104
2230
  createTable: true,
2105
- deleteMessages: true
2231
+ deleteMessages: true,
2232
+ getScoresBySpan: true
2106
2233
  };
2107
2234
  }
2108
2235
  /** @deprecated use getEvals instead */
@@ -2183,6 +2310,12 @@ var MSSQLStore = class extends MastraStorage {
2183
2310
  async getMessages(args) {
2184
2311
  return this.stores.memory.getMessages(args);
2185
2312
  }
2313
+ async getMessagesById({
2314
+ messageIds,
2315
+ format
2316
+ }) {
2317
+ return this.stores.memory.getMessagesById({ messageIds, format });
2318
+ }
2186
2319
  async getMessagesPaginated(args) {
2187
2320
  return this.stores.memory.getMessagesPaginated(args);
2188
2321
  }
@@ -2213,12 +2346,29 @@ var MSSQLStore = class extends MastraStorage {
2213
2346
  /**
2214
2347
  * Workflows
2215
2348
  */
2349
+ async updateWorkflowResults({
2350
+ workflowName,
2351
+ runId,
2352
+ stepId,
2353
+ result,
2354
+ runtimeContext
2355
+ }) {
2356
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2357
+ }
2358
+ async updateWorkflowState({
2359
+ workflowName,
2360
+ runId,
2361
+ opts
2362
+ }) {
2363
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2364
+ }
2216
2365
  async persistWorkflowSnapshot({
2217
2366
  workflowName,
2218
2367
  runId,
2368
+ resourceId,
2219
2369
  snapshot
2220
2370
  }) {
2221
- return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2371
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
2222
2372
  }
2223
2373
  async loadWorkflowSnapshot({
2224
2374
  workflowName,
@@ -2277,6 +2427,13 @@ var MSSQLStore = class extends MastraStorage {
2277
2427
  pagination: _pagination
2278
2428
  });
2279
2429
  }
2430
+ async getScoresBySpan({
2431
+ traceId,
2432
+ spanId,
2433
+ pagination: _pagination
2434
+ }) {
2435
+ return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination: _pagination });
2436
+ }
2280
2437
  };
2281
2438
 
2282
2439
  export { MSSQLStore };