@mastra/mssql 1.2.2-alpha.1 → 1.3.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 { BackgroundTasksStorage, TABLE_BACKGROUND_TASKS, TABLE_SCHEMAS, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, createStorageErrorId, normalizePerPage, calculatePagination, ObservabilityStorage, TABLE_SPANS, SPAN_SCHEMA, listTracesArgsSchema, toTraceSpans, ScoresStorage, TABLE_SCORERS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, MastraCompositeStore, getDefaultValue, transformScoreRow as transformScoreRow$1, TraceStatus } from '@mastra/core/storage';
2
+ import { AgentsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, AGENTS_SCHEMA, AGENT_VERSIONS_SCHEMA, createStorageErrorId, normalizePerPage, calculatePagination, BackgroundTasksStorage, TABLE_BACKGROUND_TASKS, TABLE_SCHEMAS, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, ObservabilityStorage, TABLE_SPANS, SPAN_SCHEMA, listTracesArgsSchema, toTraceSpans, ScoresStorage, TABLE_SCORERS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, MastraCompositeStore, getDefaultValue, transformScoreRow as transformScoreRow$1, TraceStatus } from '@mastra/core/storage';
3
3
  import sql from 'mssql';
4
- import { MastraBase } from '@mastra/core/base';
4
+ import { randomUUID } from 'crypto';
5
5
  import { parseSqlIdentifier } from '@mastra/core/utils';
6
+ import { MastraBase } from '@mastra/core/base';
6
7
  import { MessageList } from '@mastra/core/agent';
7
- import { randomUUID } from 'crypto';
8
8
  import { saveScorePayloadSchema } from '@mastra/core/evals';
9
9
 
10
10
  // src/storage/index.ts
@@ -1350,7 +1350,609 @@ function transformFromSqlRow({
1350
1350
  return result;
1351
1351
  }
1352
1352
 
1353
- // src/storage/domains/background-tasks/index.ts
1353
+ // src/storage/domains/agents/index.ts
1354
+ var AgentsMSSQL = class _AgentsMSSQL extends AgentsStorage {
1355
+ pool;
1356
+ schema;
1357
+ db;
1358
+ needsConnect;
1359
+ skipDefaultIndexes;
1360
+ indexes;
1361
+ /** Tables managed by this domain. */
1362
+ static MANAGED_TABLES = [TABLE_AGENTS, TABLE_AGENT_VERSIONS];
1363
+ constructor(config) {
1364
+ super();
1365
+ const { pool, schemaName, skipDefaultIndexes, indexes, needsConnect } = resolveMssqlConfig(config);
1366
+ this.pool = pool;
1367
+ this.schema = schemaName;
1368
+ this.db = new MssqlDB({ pool, schemaName, skipDefaultIndexes });
1369
+ this.needsConnect = needsConnect;
1370
+ this.skipDefaultIndexes = skipDefaultIndexes;
1371
+ this.indexes = indexes?.filter((idx) => _AgentsMSSQL.MANAGED_TABLES.includes(idx.table));
1372
+ }
1373
+ async init() {
1374
+ if (this.needsConnect) {
1375
+ await this.pool.connect();
1376
+ this.needsConnect = false;
1377
+ }
1378
+ await this.db.createTable({ tableName: TABLE_AGENTS, schema: AGENTS_SCHEMA });
1379
+ await this.db.createTable({ tableName: TABLE_AGENT_VERSIONS, schema: AGENT_VERSIONS_SCHEMA });
1380
+ await this.createDefaultIndexes();
1381
+ await this.createCustomIndexes();
1382
+ }
1383
+ /** Default index definitions for the agents domain tables. */
1384
+ getDefaultIndexDefinitions() {
1385
+ const schemaPrefix = this.schema && this.schema !== "dbo" ? `${this.schema}_` : "";
1386
+ return [
1387
+ {
1388
+ name: `${schemaPrefix}mastra_agents_createdat_idx`,
1389
+ table: TABLE_AGENTS,
1390
+ columns: ["createdAt DESC"]
1391
+ },
1392
+ {
1393
+ name: `${schemaPrefix}mastra_agent_versions_agentid_versionnumber_uniq`,
1394
+ table: TABLE_AGENT_VERSIONS,
1395
+ columns: ["agentId", "versionNumber DESC"],
1396
+ unique: true
1397
+ },
1398
+ {
1399
+ name: `${schemaPrefix}mastra_agent_versions_agentid_createdat_idx`,
1400
+ table: TABLE_AGENT_VERSIONS,
1401
+ columns: ["agentId", "createdAt DESC"]
1402
+ }
1403
+ ];
1404
+ }
1405
+ async createDefaultIndexes() {
1406
+ if (this.skipDefaultIndexes) return;
1407
+ for (const indexDef of this.getDefaultIndexDefinitions()) {
1408
+ try {
1409
+ await this.db.createIndex(indexDef);
1410
+ } catch (error) {
1411
+ this.logger?.warn?.(`Failed to create index ${indexDef.name}:`, error);
1412
+ }
1413
+ }
1414
+ }
1415
+ async createCustomIndexes() {
1416
+ if (!this.indexes || this.indexes.length === 0) return;
1417
+ for (const indexDef of this.indexes) {
1418
+ try {
1419
+ await this.db.createIndex(indexDef);
1420
+ } catch (error) {
1421
+ this.logger?.warn?.(`Failed to create custom index ${indexDef.name}:`, error);
1422
+ }
1423
+ }
1424
+ }
1425
+ async dangerouslyClearAll() {
1426
+ await this.db.clearTable({ tableName: TABLE_AGENT_VERSIONS });
1427
+ await this.db.clearTable({ tableName: TABLE_AGENTS });
1428
+ }
1429
+ parseJson(value, fieldName) {
1430
+ if (value === null || value === void 0) return void 0;
1431
+ if (typeof value !== "string") return value;
1432
+ try {
1433
+ return JSON.parse(value);
1434
+ } catch (error) {
1435
+ throw new MastraError(
1436
+ {
1437
+ id: createStorageErrorId("MSSQL", "PARSE_JSON", "INVALID_JSON"),
1438
+ domain: ErrorDomain.STORAGE,
1439
+ category: ErrorCategory.SYSTEM,
1440
+ text: `Failed to parse JSON${fieldName ? ` for field "${fieldName}"` : ""}: ${error instanceof Error ? error.message : "Unknown error"}`,
1441
+ details: { field: fieldName ?? "", valueLen: value.length }
1442
+ },
1443
+ error
1444
+ );
1445
+ }
1446
+ }
1447
+ serializeInstructions(instructions) {
1448
+ if (instructions === void 0) return void 0;
1449
+ return Array.isArray(instructions) ? JSON.stringify(instructions) : instructions;
1450
+ }
1451
+ deserializeInstructions(raw) {
1452
+ if (!raw) return raw ?? void 0;
1453
+ try {
1454
+ const parsed = JSON.parse(raw);
1455
+ if (Array.isArray(parsed)) return parsed;
1456
+ } catch {
1457
+ }
1458
+ return raw;
1459
+ }
1460
+ parseRow(row) {
1461
+ return {
1462
+ id: row.id,
1463
+ status: row.status,
1464
+ activeVersionId: row.activeVersionId ?? void 0,
1465
+ authorId: row.authorId ?? void 0,
1466
+ metadata: this.parseJson(row.metadata, "metadata"),
1467
+ createdAt: row.createdAt instanceof Date ? row.createdAt : new Date(row.createdAt),
1468
+ updatedAt: row.updatedAt instanceof Date ? row.updatedAt : new Date(row.updatedAt)
1469
+ };
1470
+ }
1471
+ parseVersionRow(row) {
1472
+ return {
1473
+ id: row.id,
1474
+ agentId: row.agentId,
1475
+ versionNumber: row.versionNumber,
1476
+ name: row.name,
1477
+ description: row.description ?? void 0,
1478
+ instructions: this.deserializeInstructions(
1479
+ row.instructions
1480
+ ),
1481
+ model: this.parseJson(row.model, "model"),
1482
+ tools: this.parseJson(row.tools, "tools"),
1483
+ defaultOptions: this.parseJson(row.defaultOptions, "defaultOptions"),
1484
+ workflows: this.parseJson(row.workflows, "workflows"),
1485
+ agents: this.parseJson(row.agents, "agents"),
1486
+ integrationTools: this.parseJson(row.integrationTools, "integrationTools"),
1487
+ inputProcessors: this.parseJson(row.inputProcessors, "inputProcessors"),
1488
+ outputProcessors: this.parseJson(row.outputProcessors, "outputProcessors"),
1489
+ memory: this.parseJson(row.memory, "memory"),
1490
+ scorers: this.parseJson(row.scorers, "scorers"),
1491
+ mcpClients: this.parseJson(row.mcpClients, "mcpClients"),
1492
+ requestContextSchema: this.parseJson(
1493
+ row.requestContextSchema,
1494
+ "requestContextSchema"
1495
+ ),
1496
+ workspace: this.parseJson(row.workspace, "workspace"),
1497
+ skills: this.parseJson(row.skills, "skills"),
1498
+ skillsFormat: row.skillsFormat ?? void 0,
1499
+ changedFields: this.parseJson(row.changedFields, "changedFields"),
1500
+ changeMessage: row.changeMessage ?? void 0,
1501
+ createdAt: row.createdAt instanceof Date ? row.createdAt : new Date(row.createdAt)
1502
+ };
1503
+ }
1504
+ async getById(id) {
1505
+ try {
1506
+ const result = await this.db.load({ tableName: TABLE_AGENTS, keys: { id } });
1507
+ return result ? this.parseRow(result) : null;
1508
+ } catch (error) {
1509
+ if (error instanceof MastraError) throw error;
1510
+ throw new MastraError(
1511
+ {
1512
+ id: createStorageErrorId("MSSQL", "GET_AGENT_BY_ID", "FAILED"),
1513
+ domain: ErrorDomain.STORAGE,
1514
+ category: ErrorCategory.THIRD_PARTY,
1515
+ details: { agentId: id }
1516
+ },
1517
+ error
1518
+ );
1519
+ }
1520
+ }
1521
+ async create(input) {
1522
+ const { agent } = input;
1523
+ try {
1524
+ const now = /* @__PURE__ */ new Date();
1525
+ await this.db.insert({
1526
+ tableName: TABLE_AGENTS,
1527
+ record: {
1528
+ id: agent.id,
1529
+ status: "draft",
1530
+ activeVersionId: null,
1531
+ authorId: agent.authorId ?? null,
1532
+ metadata: agent.metadata ?? null,
1533
+ createdAt: now,
1534
+ updatedAt: now
1535
+ }
1536
+ });
1537
+ const { id: _id, authorId: _authorId, metadata: _metadata, ...snapshotConfig } = agent;
1538
+ const versionId = randomUUID();
1539
+ await this.createVersion({
1540
+ id: versionId,
1541
+ agentId: agent.id,
1542
+ versionNumber: 1,
1543
+ ...snapshotConfig,
1544
+ changedFields: Object.keys(snapshotConfig),
1545
+ changeMessage: "Initial version"
1546
+ });
1547
+ const created = await this.getById(agent.id);
1548
+ if (!created) {
1549
+ throw new MastraError({
1550
+ id: createStorageErrorId("MSSQL", "CREATE_AGENT", "NOT_FOUND_AFTER_CREATE"),
1551
+ domain: ErrorDomain.STORAGE,
1552
+ category: ErrorCategory.SYSTEM,
1553
+ text: `Agent ${agent.id} not found after creation`,
1554
+ details: { agentId: agent.id }
1555
+ });
1556
+ }
1557
+ return created;
1558
+ } catch (error) {
1559
+ if (error instanceof MastraError) throw error;
1560
+ throw new MastraError(
1561
+ {
1562
+ id: createStorageErrorId("MSSQL", "CREATE_AGENT", "FAILED"),
1563
+ domain: ErrorDomain.STORAGE,
1564
+ category: ErrorCategory.THIRD_PARTY,
1565
+ details: { agentId: agent.id }
1566
+ },
1567
+ error
1568
+ );
1569
+ }
1570
+ }
1571
+ async update(input) {
1572
+ const { id, ...updates } = input;
1573
+ try {
1574
+ const existing = await this.getById(id);
1575
+ if (!existing) {
1576
+ throw new MastraError({
1577
+ id: createStorageErrorId("MSSQL", "UPDATE_AGENT", "NOT_FOUND"),
1578
+ domain: ErrorDomain.STORAGE,
1579
+ category: ErrorCategory.USER,
1580
+ text: `Agent ${id} not found`,
1581
+ details: { agentId: id }
1582
+ });
1583
+ }
1584
+ const { authorId, activeVersionId, metadata, status } = updates;
1585
+ const data = { updatedAt: /* @__PURE__ */ new Date() };
1586
+ if (authorId !== void 0) data.authorId = authorId;
1587
+ if (activeVersionId !== void 0) data.activeVersionId = activeVersionId;
1588
+ if (status !== void 0) data.status = status;
1589
+ if (metadata !== void 0) data.metadata = { ...existing.metadata, ...metadata };
1590
+ await this.db.update({ tableName: TABLE_AGENTS, keys: { id }, data });
1591
+ const updated = await this.getById(id);
1592
+ if (!updated) {
1593
+ throw new MastraError({
1594
+ id: createStorageErrorId("MSSQL", "UPDATE_AGENT", "NOT_FOUND_AFTER_UPDATE"),
1595
+ domain: ErrorDomain.STORAGE,
1596
+ category: ErrorCategory.SYSTEM,
1597
+ text: `Agent ${id} not found after update`,
1598
+ details: { agentId: id }
1599
+ });
1600
+ }
1601
+ return updated;
1602
+ } catch (error) {
1603
+ if (error instanceof MastraError) throw error;
1604
+ throw new MastraError(
1605
+ {
1606
+ id: createStorageErrorId("MSSQL", "UPDATE_AGENT", "FAILED"),
1607
+ domain: ErrorDomain.STORAGE,
1608
+ category: ErrorCategory.THIRD_PARTY,
1609
+ details: { agentId: id }
1610
+ },
1611
+ error
1612
+ );
1613
+ }
1614
+ }
1615
+ async delete(id) {
1616
+ try {
1617
+ await this.deleteVersionsByParentId(id);
1618
+ const fullName = getTableName2({ indexName: TABLE_AGENTS, schemaName: getSchemaName2(this.schema) });
1619
+ const request = this.pool.request();
1620
+ request.input("id", id);
1621
+ await request.query(`DELETE FROM ${fullName} WHERE [id] = @id`);
1622
+ } catch (error) {
1623
+ if (error instanceof MastraError) throw error;
1624
+ throw new MastraError(
1625
+ {
1626
+ id: createStorageErrorId("MSSQL", "DELETE_AGENT", "FAILED"),
1627
+ domain: ErrorDomain.STORAGE,
1628
+ category: ErrorCategory.THIRD_PARTY,
1629
+ details: { agentId: id }
1630
+ },
1631
+ error
1632
+ );
1633
+ }
1634
+ }
1635
+ async list(args) {
1636
+ const { page = 0, perPage: perPageInput, orderBy, authorId, metadata, status } = args || {};
1637
+ const { field, direction } = this.parseOrderBy(orderBy);
1638
+ if (page < 0) {
1639
+ throw new MastraError(
1640
+ {
1641
+ id: createStorageErrorId("MSSQL", "LIST_AGENTS", "INVALID_PAGE"),
1642
+ domain: ErrorDomain.STORAGE,
1643
+ category: ErrorCategory.USER,
1644
+ details: { page }
1645
+ },
1646
+ new Error("page must be >= 0")
1647
+ );
1648
+ }
1649
+ const perPage = normalizePerPage(perPageInput, 100);
1650
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1651
+ try {
1652
+ const conditions = [];
1653
+ const inputs = [];
1654
+ if (status !== void 0) {
1655
+ conditions.push("[status] = @status");
1656
+ inputs.push(["status", status]);
1657
+ }
1658
+ if (authorId !== void 0) {
1659
+ conditions.push("[authorId] = @authorId");
1660
+ inputs.push(["authorId", authorId]);
1661
+ }
1662
+ if (metadata && Object.keys(metadata).length > 0) {
1663
+ let metaIdx = 0;
1664
+ for (const [key, value] of Object.entries(metadata)) {
1665
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
1666
+ throw new MastraError({
1667
+ id: createStorageErrorId("MSSQL", "LIST_AGENTS", "INVALID_METADATA_KEY"),
1668
+ domain: ErrorDomain.STORAGE,
1669
+ category: ErrorCategory.USER,
1670
+ text: `Invalid metadata key: ${key}. Keys must be alphanumeric with underscores.`,
1671
+ details: { key }
1672
+ });
1673
+ }
1674
+ if (value !== null && typeof value === "object") {
1675
+ throw new MastraError({
1676
+ id: createStorageErrorId("MSSQL", "LIST_AGENTS", "NON_PRIMITIVE_METADATA"),
1677
+ domain: ErrorDomain.STORAGE,
1678
+ category: ErrorCategory.USER,
1679
+ text: `Metadata filter for key "${key}" must be a primitive (string/number/boolean/null); received ${Array.isArray(value) ? "array" : "object"}.`,
1680
+ details: { key }
1681
+ });
1682
+ }
1683
+ if (value === null) {
1684
+ conditions.push(`JSON_VALUE([metadata], '$.${key}') IS NULL`);
1685
+ continue;
1686
+ }
1687
+ const paramName = `meta_${metaIdx++}`;
1688
+ conditions.push(`JSON_VALUE([metadata], '$.${key}') = @${paramName}`);
1689
+ inputs.push([paramName, typeof value === "string" ? value : String(value)]);
1690
+ }
1691
+ }
1692
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1693
+ const fullName = getTableName2({ indexName: TABLE_AGENTS, schemaName: getSchemaName2(this.schema) });
1694
+ const countRequest = this.pool.request();
1695
+ for (const [k, v] of inputs) countRequest.input(k, v);
1696
+ const countResult = await countRequest.query(`SELECT COUNT(*) AS [count] FROM ${fullName} ${whereClause}`);
1697
+ const total = Number(countResult.recordset?.[0]?.count ?? 0);
1698
+ if (total === 0) {
1699
+ return { agents: [], total: 0, page, perPage: perPageForResponse, hasMore: false };
1700
+ }
1701
+ const limitValue = perPageInput === false ? total : perPage;
1702
+ const fieldSafe = parseSqlIdentifier(field, "order column");
1703
+ const dirSafe = direction === "ASC" ? "ASC" : "DESC";
1704
+ const listRequest = this.pool.request();
1705
+ for (const [k, v] of inputs) listRequest.input(k, v);
1706
+ listRequest.input("offset", offset);
1707
+ listRequest.input("limit", limitValue);
1708
+ const listSql = `SELECT * FROM ${fullName} ${whereClause} ORDER BY [${fieldSafe}] ${dirSafe} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
1709
+ const listResult = await listRequest.query(listSql);
1710
+ const agents = (listResult.recordset || []).map((row) => this.parseRow(row));
1711
+ return {
1712
+ agents,
1713
+ total,
1714
+ page,
1715
+ perPage: perPageForResponse,
1716
+ hasMore: perPageInput === false ? false : offset + perPage < total
1717
+ };
1718
+ } catch (error) {
1719
+ if (error instanceof MastraError) throw error;
1720
+ throw new MastraError(
1721
+ {
1722
+ id: createStorageErrorId("MSSQL", "LIST_AGENTS", "FAILED"),
1723
+ domain: ErrorDomain.STORAGE,
1724
+ category: ErrorCategory.THIRD_PARTY
1725
+ },
1726
+ error
1727
+ );
1728
+ }
1729
+ }
1730
+ async createVersion(input) {
1731
+ try {
1732
+ const now = /* @__PURE__ */ new Date();
1733
+ await this.db.insert({
1734
+ tableName: TABLE_AGENT_VERSIONS,
1735
+ record: {
1736
+ id: input.id,
1737
+ agentId: input.agentId,
1738
+ versionNumber: input.versionNumber,
1739
+ name: input.name ?? null,
1740
+ description: input.description ?? null,
1741
+ instructions: this.serializeInstructions(input.instructions) ?? null,
1742
+ model: input.model,
1743
+ tools: input.tools ?? null,
1744
+ defaultOptions: input.defaultOptions ?? null,
1745
+ workflows: input.workflows ?? null,
1746
+ agents: input.agents ?? null,
1747
+ integrationTools: input.integrationTools ?? null,
1748
+ inputProcessors: input.inputProcessors ?? null,
1749
+ outputProcessors: input.outputProcessors ?? null,
1750
+ memory: input.memory ?? null,
1751
+ scorers: input.scorers ?? null,
1752
+ mcpClients: input.mcpClients ?? null,
1753
+ requestContextSchema: input.requestContextSchema ?? null,
1754
+ workspace: input.workspace ?? null,
1755
+ skills: input.skills ?? null,
1756
+ skillsFormat: input.skillsFormat ?? null,
1757
+ changedFields: input.changedFields ?? null,
1758
+ changeMessage: input.changeMessage ?? null,
1759
+ createdAt: now
1760
+ }
1761
+ });
1762
+ return { ...input, createdAt: now };
1763
+ } catch (error) {
1764
+ if (error instanceof MastraError) throw error;
1765
+ throw new MastraError(
1766
+ {
1767
+ id: createStorageErrorId("MSSQL", "CREATE_VERSION", "FAILED"),
1768
+ domain: ErrorDomain.STORAGE,
1769
+ category: ErrorCategory.THIRD_PARTY,
1770
+ details: { versionId: input.id, agentId: input.agentId }
1771
+ },
1772
+ error
1773
+ );
1774
+ }
1775
+ }
1776
+ async getVersion(id) {
1777
+ try {
1778
+ const result = await this.db.load({ tableName: TABLE_AGENT_VERSIONS, keys: { id } });
1779
+ return result ? this.parseVersionRow(result) : null;
1780
+ } catch (error) {
1781
+ if (error instanceof MastraError) throw error;
1782
+ throw new MastraError(
1783
+ {
1784
+ id: createStorageErrorId("MSSQL", "GET_VERSION", "FAILED"),
1785
+ domain: ErrorDomain.STORAGE,
1786
+ category: ErrorCategory.THIRD_PARTY,
1787
+ details: { versionId: id }
1788
+ },
1789
+ error
1790
+ );
1791
+ }
1792
+ }
1793
+ async getVersionByNumber(agentId, versionNumber) {
1794
+ try {
1795
+ const fullName = getTableName2({ indexName: TABLE_AGENT_VERSIONS, schemaName: getSchemaName2(this.schema) });
1796
+ const request = this.pool.request();
1797
+ request.input("agentId", agentId);
1798
+ request.input("versionNumber", versionNumber);
1799
+ const result = await request.query(
1800
+ `SELECT TOP 1 * FROM ${fullName} WHERE [agentId] = @agentId AND [versionNumber] = @versionNumber`
1801
+ );
1802
+ const row = result.recordset?.[0];
1803
+ return row ? this.parseVersionRow(row) : null;
1804
+ } catch (error) {
1805
+ if (error instanceof MastraError) throw error;
1806
+ throw new MastraError(
1807
+ {
1808
+ id: createStorageErrorId("MSSQL", "GET_VERSION_BY_NUMBER", "FAILED"),
1809
+ domain: ErrorDomain.STORAGE,
1810
+ category: ErrorCategory.THIRD_PARTY,
1811
+ details: { agentId, versionNumber }
1812
+ },
1813
+ error
1814
+ );
1815
+ }
1816
+ }
1817
+ async getLatestVersion(agentId) {
1818
+ try {
1819
+ const fullName = getTableName2({ indexName: TABLE_AGENT_VERSIONS, schemaName: getSchemaName2(this.schema) });
1820
+ const request = this.pool.request();
1821
+ request.input("agentId", agentId);
1822
+ const result = await request.query(
1823
+ `SELECT TOP 1 * FROM ${fullName} WHERE [agentId] = @agentId ORDER BY [versionNumber] DESC`
1824
+ );
1825
+ const row = result.recordset?.[0];
1826
+ return row ? this.parseVersionRow(row) : null;
1827
+ } catch (error) {
1828
+ if (error instanceof MastraError) throw error;
1829
+ throw new MastraError(
1830
+ {
1831
+ id: createStorageErrorId("MSSQL", "GET_LATEST_VERSION", "FAILED"),
1832
+ domain: ErrorDomain.STORAGE,
1833
+ category: ErrorCategory.THIRD_PARTY,
1834
+ details: { agentId }
1835
+ },
1836
+ error
1837
+ );
1838
+ }
1839
+ }
1840
+ async listVersions(input) {
1841
+ const { agentId, page = 0, perPage: perPageInput, orderBy } = input;
1842
+ if (page < 0) {
1843
+ throw new MastraError(
1844
+ {
1845
+ id: createStorageErrorId("MSSQL", "LIST_VERSIONS", "INVALID_PAGE"),
1846
+ domain: ErrorDomain.STORAGE,
1847
+ category: ErrorCategory.USER,
1848
+ details: { page }
1849
+ },
1850
+ new Error("page must be >= 0")
1851
+ );
1852
+ }
1853
+ const perPage = normalizePerPage(perPageInput, 20);
1854
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1855
+ try {
1856
+ const { field, direction } = this.parseVersionOrderBy(orderBy);
1857
+ const fullName = getTableName2({ indexName: TABLE_AGENT_VERSIONS, schemaName: getSchemaName2(this.schema) });
1858
+ const countRequest = this.pool.request();
1859
+ countRequest.input("agentId", agentId);
1860
+ const countResult = await countRequest.query(
1861
+ `SELECT COUNT(*) AS [count] FROM ${fullName} WHERE [agentId] = @agentId`
1862
+ );
1863
+ const total = Number(countResult.recordset?.[0]?.count ?? 0);
1864
+ if (total === 0) {
1865
+ return { versions: [], total: 0, page, perPage: perPageForResponse, hasMore: false };
1866
+ }
1867
+ const limitValue = perPageInput === false ? total : perPage;
1868
+ const fieldSafe = parseSqlIdentifier(field, "order column");
1869
+ const dirSafe = direction === "ASC" ? "ASC" : "DESC";
1870
+ const listRequest = this.pool.request();
1871
+ listRequest.input("agentId", agentId);
1872
+ listRequest.input("offset", offset);
1873
+ listRequest.input("limit", limitValue);
1874
+ const listSql = `SELECT * FROM ${fullName} WHERE [agentId] = @agentId ORDER BY [${fieldSafe}] ${dirSafe} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
1875
+ const listResult = await listRequest.query(listSql);
1876
+ const versions = (listResult.recordset || []).map((row) => this.parseVersionRow(row));
1877
+ return {
1878
+ versions,
1879
+ total,
1880
+ page,
1881
+ perPage: perPageForResponse,
1882
+ hasMore: perPageInput === false ? false : offset + perPage < total
1883
+ };
1884
+ } catch (error) {
1885
+ if (error instanceof MastraError) throw error;
1886
+ throw new MastraError(
1887
+ {
1888
+ id: createStorageErrorId("MSSQL", "LIST_VERSIONS", "FAILED"),
1889
+ domain: ErrorDomain.STORAGE,
1890
+ category: ErrorCategory.THIRD_PARTY,
1891
+ details: { agentId }
1892
+ },
1893
+ error
1894
+ );
1895
+ }
1896
+ }
1897
+ async deleteVersion(id) {
1898
+ try {
1899
+ const fullName = getTableName2({ indexName: TABLE_AGENT_VERSIONS, schemaName: getSchemaName2(this.schema) });
1900
+ const request = this.pool.request();
1901
+ request.input("id", id);
1902
+ await request.query(`DELETE FROM ${fullName} WHERE [id] = @id`);
1903
+ } catch (error) {
1904
+ if (error instanceof MastraError) throw error;
1905
+ throw new MastraError(
1906
+ {
1907
+ id: createStorageErrorId("MSSQL", "DELETE_VERSION", "FAILED"),
1908
+ domain: ErrorDomain.STORAGE,
1909
+ category: ErrorCategory.THIRD_PARTY,
1910
+ details: { versionId: id }
1911
+ },
1912
+ error
1913
+ );
1914
+ }
1915
+ }
1916
+ async deleteVersionsByParentId(entityId) {
1917
+ try {
1918
+ const fullName = getTableName2({ indexName: TABLE_AGENT_VERSIONS, schemaName: getSchemaName2(this.schema) });
1919
+ const request = this.pool.request();
1920
+ request.input("agentId", entityId);
1921
+ await request.query(`DELETE FROM ${fullName} WHERE [agentId] = @agentId`);
1922
+ } catch (error) {
1923
+ if (error instanceof MastraError) throw error;
1924
+ throw new MastraError(
1925
+ {
1926
+ id: createStorageErrorId("MSSQL", "DELETE_VERSIONS_BY_AGENT_ID", "FAILED"),
1927
+ domain: ErrorDomain.STORAGE,
1928
+ category: ErrorCategory.THIRD_PARTY,
1929
+ details: { agentId: entityId }
1930
+ },
1931
+ error
1932
+ );
1933
+ }
1934
+ }
1935
+ async countVersions(agentId) {
1936
+ try {
1937
+ const fullName = getTableName2({ indexName: TABLE_AGENT_VERSIONS, schemaName: getSchemaName2(this.schema) });
1938
+ const request = this.pool.request();
1939
+ request.input("agentId", agentId);
1940
+ const result = await request.query(`SELECT COUNT(*) AS [count] FROM ${fullName} WHERE [agentId] = @agentId`);
1941
+ return Number(result.recordset?.[0]?.count ?? 0);
1942
+ } catch (error) {
1943
+ if (error instanceof MastraError) throw error;
1944
+ throw new MastraError(
1945
+ {
1946
+ id: createStorageErrorId("MSSQL", "COUNT_VERSIONS", "FAILED"),
1947
+ domain: ErrorDomain.STORAGE,
1948
+ category: ErrorCategory.THIRD_PARTY,
1949
+ details: { agentId }
1950
+ },
1951
+ error
1952
+ );
1953
+ }
1954
+ }
1955
+ };
1354
1956
  function serializeJson(v) {
1355
1957
  if (typeof v === "object" && v != null) return JSON.stringify(v);
1356
1958
  return v ?? null;
@@ -4370,12 +4972,14 @@ var MSSQLStore = class extends MastraCompositeStore {
4370
4972
  const memory = new MemoryMSSQL(domainConfig);
4371
4973
  const observability = new ObservabilityMSSQL(domainConfig);
4372
4974
  const backgroundTasks = new BackgroundTasksMSSQL(domainConfig);
4975
+ const agents = new AgentsMSSQL(domainConfig);
4373
4976
  this.stores = {
4374
4977
  scores,
4375
4978
  workflows,
4376
4979
  memory,
4377
4980
  observability,
4378
- backgroundTasks
4981
+ backgroundTasks,
4982
+ agents
4379
4983
  };
4380
4984
  } catch (e) {
4381
4985
  throw new MastraError(
@@ -4428,6 +5032,6 @@ var MSSQLStore = class extends MastraCompositeStore {
4428
5032
  }
4429
5033
  };
4430
5034
 
4431
- export { BackgroundTasksMSSQL, MSSQLStore, MemoryMSSQL, ObservabilityMSSQL, ScoresMSSQL, WorkflowsMSSQL };
5035
+ export { AgentsMSSQL, BackgroundTasksMSSQL, MSSQLStore, MemoryMSSQL, ObservabilityMSSQL, ScoresMSSQL, WorkflowsMSSQL };
4432
5036
  //# sourceMappingURL=index.js.map
4433
5037
  //# sourceMappingURL=index.js.map