@mastra/mssql 1.2.2-alpha.1 → 1.3.0-alpha.2

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