@mastra/mssql 1.2.0 → 1.2.1-alpha.1

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,9 +1,9 @@
1
1
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, TABLE_SCHEMAS, 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 { 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';
3
3
  import sql from 'mssql';
4
- import { MessageList } from '@mastra/core/agent';
5
4
  import { MastraBase } from '@mastra/core/base';
6
5
  import { parseSqlIdentifier } from '@mastra/core/utils';
6
+ import { MessageList } from '@mastra/core/agent';
7
7
  import { randomUUID } from 'crypto';
8
8
  import { saveScorePayloadSchema } from '@mastra/core/evals';
9
9
 
@@ -1350,7 +1350,319 @@ function transformFromSqlRow({
1350
1350
  return result;
1351
1351
  }
1352
1352
 
1353
- // src/storage/domains/memory/index.ts
1353
+ // src/storage/domains/background-tasks/index.ts
1354
+ function serializeJson(v) {
1355
+ if (typeof v === "object" && v != null) return JSON.stringify(v);
1356
+ return v ?? null;
1357
+ }
1358
+ function rowToTask(row) {
1359
+ const parseJson = (val) => {
1360
+ if (val == null) return void 0;
1361
+ if (typeof val === "string") {
1362
+ try {
1363
+ return JSON.parse(val);
1364
+ } catch {
1365
+ return val;
1366
+ }
1367
+ }
1368
+ return val;
1369
+ };
1370
+ return {
1371
+ id: row.id,
1372
+ status: row.status,
1373
+ toolName: row.tool_name,
1374
+ toolCallId: row.tool_call_id,
1375
+ args: parseJson(row.args) ?? {},
1376
+ agentId: row.agent_id,
1377
+ threadId: row.thread_id ?? void 0,
1378
+ resourceId: row.resource_id ?? void 0,
1379
+ runId: row.run_id ?? "",
1380
+ result: parseJson(row.result),
1381
+ error: parseJson(row.error),
1382
+ retryCount: Number(row.retry_count),
1383
+ maxRetries: Number(row.max_retries),
1384
+ timeoutMs: Number(row.timeout_ms),
1385
+ createdAt: row.createdAt instanceof Date ? row.createdAt : new Date(row.createdAt),
1386
+ startedAt: row.startedAt ? row.startedAt instanceof Date ? row.startedAt : new Date(row.startedAt) : void 0,
1387
+ completedAt: row.completedAt ? row.completedAt instanceof Date ? row.completedAt : new Date(row.completedAt) : void 0
1388
+ };
1389
+ }
1390
+ var BackgroundTasksMSSQL = class _BackgroundTasksMSSQL extends BackgroundTasksStorage {
1391
+ pool;
1392
+ db;
1393
+ schema;
1394
+ needsConnect;
1395
+ skipDefaultIndexes;
1396
+ indexes;
1397
+ static MANAGED_TABLES = [TABLE_BACKGROUND_TASKS];
1398
+ constructor(config) {
1399
+ super();
1400
+ const { pool, schemaName, skipDefaultIndexes, indexes, needsConnect } = resolveMssqlConfig(config);
1401
+ this.pool = pool;
1402
+ this.schema = schemaName;
1403
+ this.db = new MssqlDB({ pool, schemaName, skipDefaultIndexes });
1404
+ this.needsConnect = needsConnect;
1405
+ this.skipDefaultIndexes = skipDefaultIndexes;
1406
+ this.indexes = indexes?.filter(
1407
+ (idx) => _BackgroundTasksMSSQL.MANAGED_TABLES.includes(idx.table)
1408
+ );
1409
+ }
1410
+ async init() {
1411
+ if (this.needsConnect) {
1412
+ await this.pool.connect();
1413
+ this.needsConnect = false;
1414
+ }
1415
+ await this.db.createTable({
1416
+ tableName: TABLE_BACKGROUND_TASKS,
1417
+ schema: TABLE_SCHEMAS[TABLE_BACKGROUND_TASKS]
1418
+ });
1419
+ await this.createDefaultIndexes();
1420
+ await this.createCustomIndexes();
1421
+ }
1422
+ getDefaultIndexDefinitions() {
1423
+ const schemaPrefix = this.schema ? `${this.schema}_` : "";
1424
+ return [
1425
+ {
1426
+ name: `${schemaPrefix}mastra_bg_tasks_status_created_at_idx`,
1427
+ table: TABLE_BACKGROUND_TASKS,
1428
+ columns: ["status", "createdAt"]
1429
+ },
1430
+ {
1431
+ name: `${schemaPrefix}mastra_bg_tasks_agent_status_idx`,
1432
+ table: TABLE_BACKGROUND_TASKS,
1433
+ columns: ["agent_id", "status"]
1434
+ },
1435
+ {
1436
+ name: `${schemaPrefix}mastra_bg_tasks_thread_idx`,
1437
+ table: TABLE_BACKGROUND_TASKS,
1438
+ columns: ["thread_id", "createdAt"]
1439
+ },
1440
+ {
1441
+ name: `${schemaPrefix}mastra_bg_tasks_tool_call_idx`,
1442
+ table: TABLE_BACKGROUND_TASKS,
1443
+ columns: ["tool_call_id"]
1444
+ }
1445
+ ];
1446
+ }
1447
+ async createDefaultIndexes() {
1448
+ if (this.skipDefaultIndexes) return;
1449
+ for (const indexDef of this.getDefaultIndexDefinitions()) {
1450
+ try {
1451
+ await this.db.createIndex(indexDef);
1452
+ } catch (error) {
1453
+ this.logger?.warn?.(`Failed to create index ${indexDef.name}:`, error);
1454
+ }
1455
+ }
1456
+ }
1457
+ async createCustomIndexes() {
1458
+ if (!this.indexes || this.indexes.length === 0) return;
1459
+ for (const indexDef of this.indexes) {
1460
+ try {
1461
+ await this.db.createIndex(indexDef);
1462
+ } catch (error) {
1463
+ this.logger?.warn?.(`Failed to create custom index ${indexDef.name}:`, error);
1464
+ }
1465
+ }
1466
+ }
1467
+ async dangerouslyClearAll() {
1468
+ await this.db.clearTable({ tableName: TABLE_BACKGROUND_TASKS });
1469
+ }
1470
+ tableName() {
1471
+ return getTableName2({ indexName: TABLE_BACKGROUND_TASKS, schemaName: getSchemaName2(this.schema) });
1472
+ }
1473
+ async createTask(task) {
1474
+ await this.db.insert({
1475
+ tableName: TABLE_BACKGROUND_TASKS,
1476
+ record: {
1477
+ id: task.id,
1478
+ tool_call_id: task.toolCallId,
1479
+ tool_name: task.toolName,
1480
+ agent_id: task.agentId,
1481
+ thread_id: task.threadId ?? null,
1482
+ resource_id: task.resourceId ?? null,
1483
+ run_id: task.runId,
1484
+ status: task.status,
1485
+ args: serializeJson(task.args),
1486
+ result: serializeJson(task.result),
1487
+ error: serializeJson(task.error),
1488
+ retry_count: task.retryCount,
1489
+ max_retries: task.maxRetries,
1490
+ timeout_ms: task.timeoutMs,
1491
+ createdAt: task.createdAt.toISOString(),
1492
+ startedAt: task.startedAt?.toISOString() ?? null,
1493
+ completedAt: task.completedAt?.toISOString() ?? null
1494
+ }
1495
+ });
1496
+ }
1497
+ async updateTask(taskId, update) {
1498
+ const setClauses = [];
1499
+ const params = {};
1500
+ let idx = 1;
1501
+ if ("status" in update) {
1502
+ setClauses.push(`[status] = @p${idx}`);
1503
+ params[`p${idx++}`] = update.status;
1504
+ }
1505
+ if ("result" in update) {
1506
+ setClauses.push(`[result] = @p${idx}`);
1507
+ params[`p${idx++}`] = serializeJson(update.result);
1508
+ }
1509
+ if ("error" in update) {
1510
+ setClauses.push(`[error] = @p${idx}`);
1511
+ params[`p${idx++}`] = serializeJson(update.error);
1512
+ }
1513
+ if ("retryCount" in update) {
1514
+ setClauses.push(`[retry_count] = @p${idx}`);
1515
+ params[`p${idx++}`] = update.retryCount;
1516
+ }
1517
+ if ("startedAt" in update) {
1518
+ setClauses.push(`[startedAt] = @p${idx}`);
1519
+ params[`p${idx++}`] = update.startedAt?.toISOString() ?? null;
1520
+ }
1521
+ if ("completedAt" in update) {
1522
+ setClauses.push(`[completedAt] = @p${idx}`);
1523
+ params[`p${idx++}`] = update.completedAt?.toISOString() ?? null;
1524
+ }
1525
+ if (setClauses.length === 0) return;
1526
+ setClauses.push(`[id] = [id]`);
1527
+ params[`p${idx}`] = taskId;
1528
+ const request = this.pool.request();
1529
+ for (const [name, value] of Object.entries(params)) {
1530
+ request.input(name, value);
1531
+ }
1532
+ await request.query(`UPDATE ${this.tableName()} SET ${setClauses.join(", ")} WHERE [id] = @p${idx}`);
1533
+ }
1534
+ async getTask(taskId) {
1535
+ const request = this.pool.request();
1536
+ request.input("p1", taskId);
1537
+ const result = await request.query(`SELECT * FROM ${this.tableName()} WHERE [id] = @p1`);
1538
+ if (result.recordset.length === 0) return null;
1539
+ return rowToTask(result.recordset[0]);
1540
+ }
1541
+ async listTasks(filter) {
1542
+ const conditions = [];
1543
+ const params = {};
1544
+ let idx = 1;
1545
+ if (filter.status) {
1546
+ const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
1547
+ const placeholders = statuses.map(() => {
1548
+ const name = `p${idx++}`;
1549
+ return `@${name}`;
1550
+ });
1551
+ statuses.forEach((s, i) => {
1552
+ params[`p${idx - statuses.length + i}`] = s;
1553
+ });
1554
+ conditions.push(`[status] IN (${placeholders.join(", ")})`);
1555
+ }
1556
+ if (filter.agentId) {
1557
+ params[`p${idx}`] = filter.agentId;
1558
+ conditions.push(`[agent_id] = @p${idx++}`);
1559
+ }
1560
+ if (filter.threadId) {
1561
+ params[`p${idx}`] = filter.threadId;
1562
+ conditions.push(`[thread_id] = @p${idx++}`);
1563
+ }
1564
+ if (filter.resourceId) {
1565
+ params[`p${idx}`] = filter.resourceId;
1566
+ conditions.push(`[resource_id] = @p${idx++}`);
1567
+ }
1568
+ if (filter.runId) {
1569
+ params[`p${idx}`] = filter.runId;
1570
+ conditions.push(`[run_id] = @p${idx++}`);
1571
+ }
1572
+ if (filter.toolName) {
1573
+ params[`p${idx}`] = filter.toolName;
1574
+ conditions.push(`[tool_name] = @p${idx++}`);
1575
+ }
1576
+ const dateCol = filter.dateFilterBy === "startedAt" ? "[startedAt]" : filter.dateFilterBy === "completedAt" ? "[completedAt]" : "[createdAt]";
1577
+ if (filter.fromDate) {
1578
+ params[`p${idx}`] = filter.fromDate.toISOString();
1579
+ conditions.push(`${dateCol} >= @p${idx++}`);
1580
+ }
1581
+ if (filter.toDate) {
1582
+ params[`p${idx}`] = filter.toDate.toISOString();
1583
+ conditions.push(`${dateCol} < @p${idx++}`);
1584
+ }
1585
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1586
+ const countRequest = this.pool.request();
1587
+ for (const [name, value] of Object.entries(params)) {
1588
+ countRequest.input(name, value);
1589
+ }
1590
+ const countResult = await countRequest.query(`SELECT COUNT(*) as count FROM ${this.tableName()} ${where}`);
1591
+ const total = Number(countResult.recordset[0]?.count ?? 0);
1592
+ const orderCol = filter.orderBy === "startedAt" ? "[startedAt]" : filter.orderBy === "completedAt" ? "[completedAt]" : "[createdAt]";
1593
+ const direction = filter.orderDirection === "desc" ? "DESC" : "ASC";
1594
+ let sql5 = `SELECT * FROM ${this.tableName()} ${where} ORDER BY ${orderCol} ${direction}`;
1595
+ if (filter.perPage != null) {
1596
+ const offset = filter.page != null ? filter.page * filter.perPage : 0;
1597
+ params[`p${idx}`] = offset;
1598
+ params[`p${idx + 1}`] = filter.perPage;
1599
+ sql5 += ` OFFSET @p${idx} ROWS FETCH NEXT @p${idx + 1} ROWS ONLY`;
1600
+ idx += 2;
1601
+ }
1602
+ const request = this.pool.request();
1603
+ for (const [name, value] of Object.entries(params)) {
1604
+ request.input(name, value);
1605
+ }
1606
+ const result = await request.query(sql5);
1607
+ return { tasks: result.recordset.map(rowToTask), total };
1608
+ }
1609
+ async deleteTask(taskId) {
1610
+ const request = this.pool.request();
1611
+ request.input("p1", taskId);
1612
+ await request.query(`DELETE FROM ${this.tableName()} WHERE [id] = @p1`);
1613
+ }
1614
+ async deleteTasks(filter) {
1615
+ const conditions = [];
1616
+ const params = {};
1617
+ let idx = 1;
1618
+ if (filter.status) {
1619
+ const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
1620
+ const placeholders = statuses.map(() => {
1621
+ const name = `p${idx++}`;
1622
+ return `@${name}`;
1623
+ });
1624
+ statuses.forEach((s, i) => {
1625
+ params[`p${idx - statuses.length + i}`] = s;
1626
+ });
1627
+ conditions.push(`[status] IN (${placeholders.join(", ")})`);
1628
+ }
1629
+ const dateCol = filter.dateFilterBy === "startedAt" ? "[startedAt]" : filter.dateFilterBy === "completedAt" ? "[completedAt]" : "[createdAt]";
1630
+ if (filter.fromDate) {
1631
+ params[`p${idx}`] = filter.fromDate.toISOString();
1632
+ conditions.push(`${dateCol} >= @p${idx++}`);
1633
+ }
1634
+ if (filter.toDate) {
1635
+ params[`p${idx}`] = filter.toDate.toISOString();
1636
+ conditions.push(`${dateCol} < @p${idx++}`);
1637
+ }
1638
+ if (filter.agentId) {
1639
+ params[`p${idx}`] = filter.agentId;
1640
+ conditions.push(`[agent_id] = @p${idx++}`);
1641
+ }
1642
+ if (filter.runId) {
1643
+ params[`p${idx}`] = filter.runId;
1644
+ conditions.push(`[run_id] = @p${idx++}`);
1645
+ }
1646
+ if (conditions.length === 0) return;
1647
+ const request = this.pool.request();
1648
+ for (const [name, value] of Object.entries(params)) {
1649
+ request.input(name, value);
1650
+ }
1651
+ await request.query(`DELETE FROM ${this.tableName()} WHERE ${conditions.join(" AND ")}`);
1652
+ }
1653
+ async getRunningCount() {
1654
+ const result = await this.pool.request().query(`SELECT COUNT(*) as count FROM ${this.tableName()} WHERE [status] = 'running'`);
1655
+ return Number(result.recordset[0]?.count ?? 0);
1656
+ }
1657
+ async getRunningCountByAgent(agentId) {
1658
+ const request = this.pool.request();
1659
+ request.input("p1", agentId);
1660
+ const result = await request.query(
1661
+ `SELECT COUNT(*) as count FROM ${this.tableName()} WHERE [status] = 'running' AND [agent_id] = @p1`
1662
+ );
1663
+ return Number(result.recordset[0]?.count ?? 0);
1664
+ }
1665
+ };
1354
1666
  var MemoryMSSQL = class _MemoryMSSQL extends MemoryStorage {
1355
1667
  pool;
1356
1668
  schema;
@@ -2624,6 +2936,51 @@ var ObservabilityMSSQL = class _ObservabilityMSSQL extends ObservabilityStorage
2624
2936
  );
2625
2937
  }
2626
2938
  }
2939
+ async getTraceLight(args) {
2940
+ const { traceId } = args;
2941
+ try {
2942
+ const tableName = getTableName2({
2943
+ indexName: TABLE_SPANS,
2944
+ schemaName: getSchemaName2(this.schema)
2945
+ });
2946
+ const request = this.pool.request();
2947
+ request.input("traceId", traceId);
2948
+ const result = await request.query(
2949
+ `SELECT
2950
+ [traceId], [spanId], [parentSpanId], [name],
2951
+ [entityType], [entityId], [entityName],
2952
+ [spanType], [error], [isEvent],
2953
+ [startedAt], [endedAt], [createdAt], [updatedAt]
2954
+ FROM ${tableName}
2955
+ WHERE [traceId] = @traceId
2956
+ ORDER BY [startedAt] ASC`
2957
+ );
2958
+ if (!result.recordset || result.recordset.length === 0) {
2959
+ return null;
2960
+ }
2961
+ return {
2962
+ traceId,
2963
+ spans: result.recordset.map(
2964
+ (span) => transformFromSqlRow({
2965
+ tableName: TABLE_SPANS,
2966
+ sqlRow: span
2967
+ })
2968
+ )
2969
+ };
2970
+ } catch (error) {
2971
+ throw new MastraError(
2972
+ {
2973
+ id: createStorageErrorId("MSSQL", "GET_TRACE_LIGHT", "FAILED"),
2974
+ domain: ErrorDomain.STORAGE,
2975
+ category: ErrorCategory.USER,
2976
+ details: {
2977
+ traceId
2978
+ }
2979
+ },
2980
+ error
2981
+ );
2982
+ }
2983
+ }
2627
2984
  async getSpan(args) {
2628
2985
  const { traceId, spanId } = args;
2629
2986
  try {
@@ -3988,11 +4345,13 @@ var MSSQLStore = class extends MastraCompositeStore {
3988
4345
  const workflows = new WorkflowsMSSQL(domainConfig);
3989
4346
  const memory = new MemoryMSSQL(domainConfig);
3990
4347
  const observability = new ObservabilityMSSQL(domainConfig);
4348
+ const backgroundTasks = new BackgroundTasksMSSQL(domainConfig);
3991
4349
  this.stores = {
3992
4350
  scores,
3993
4351
  workflows,
3994
4352
  memory,
3995
- observability
4353
+ observability,
4354
+ backgroundTasks
3996
4355
  };
3997
4356
  } catch (e) {
3998
4357
  throw new MastraError(
@@ -4045,6 +4404,6 @@ var MSSQLStore = class extends MastraCompositeStore {
4045
4404
  }
4046
4405
  };
4047
4406
 
4048
- export { MSSQLStore, MemoryMSSQL, ObservabilityMSSQL, ScoresMSSQL, WorkflowsMSSQL };
4407
+ export { BackgroundTasksMSSQL, MSSQLStore, MemoryMSSQL, ObservabilityMSSQL, ScoresMSSQL, WorkflowsMSSQL };
4049
4408
  //# sourceMappingURL=index.js.map
4050
4409
  //# sourceMappingURL=index.js.map