@mastra/mssql 0.0.0-new-scorer-api-20250801075530 → 0.0.0-partial-response-backport-20251204204441

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.
Files changed (36) hide show
  1. package/CHANGELOG.md +548 -4
  2. package/README.md +315 -36
  3. package/dist/index.cjs +2956 -1125
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.ts +2 -1
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +2956 -1125
  8. package/dist/index.js.map +1 -1
  9. package/dist/storage/domains/legacy-evals/index.d.ts +20 -0
  10. package/dist/storage/domains/legacy-evals/index.d.ts.map +1 -0
  11. package/dist/storage/domains/memory/index.d.ts +98 -0
  12. package/dist/storage/domains/memory/index.d.ts.map +1 -0
  13. package/dist/storage/domains/observability/index.d.ts +44 -0
  14. package/dist/storage/domains/observability/index.d.ts.map +1 -0
  15. package/dist/storage/domains/operations/index.d.ts +114 -0
  16. package/dist/storage/domains/operations/index.d.ts.map +1 -0
  17. package/dist/storage/domains/scores/index.d.ts +55 -0
  18. package/dist/storage/domains/scores/index.d.ts.map +1 -0
  19. package/dist/storage/domains/traces/index.d.ts +37 -0
  20. package/dist/storage/domains/traces/index.d.ts.map +1 -0
  21. package/dist/storage/domains/utils.d.ts +25 -0
  22. package/dist/storage/domains/utils.d.ts.map +1 -0
  23. package/dist/storage/domains/workflows/index.d.ts +49 -0
  24. package/dist/storage/domains/workflows/index.d.ts.map +1 -0
  25. package/dist/storage/index.d.ts +144 -87
  26. package/dist/storage/index.d.ts.map +1 -1
  27. package/package.json +31 -10
  28. package/docker-compose.yaml +0 -14
  29. package/eslint.config.js +0 -6
  30. package/src/index.ts +0 -2
  31. package/src/storage/index.test.ts +0 -2228
  32. package/src/storage/index.ts +0 -2136
  33. package/tsconfig.build.json +0 -9
  34. package/tsconfig.json +0 -5
  35. package/tsup.config.ts +0 -22
  36. package/vitest.config.ts +0 -12
package/dist/index.cjs CHANGED
@@ -1,133 +1,131 @@
1
1
  'use strict';
2
2
 
3
- var agent = require('@mastra/core/agent');
4
3
  var error = require('@mastra/core/error');
5
4
  var storage = require('@mastra/core/storage');
5
+ var sql3 = require('mssql');
6
6
  var utils = require('@mastra/core/utils');
7
- var sql = require('mssql');
7
+ var agent = require('@mastra/core/agent');
8
+ var crypto = require('crypto');
9
+ var scores = require('@mastra/core/scores');
8
10
 
9
11
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
12
 
11
- var sql__default = /*#__PURE__*/_interopDefault(sql);
13
+ var sql3__default = /*#__PURE__*/_interopDefault(sql3);
12
14
 
13
15
  // src/storage/index.ts
14
- var MSSQLStore = class extends storage.MastraStorage {
15
- pool;
16
- schema;
17
- setupSchemaPromise = null;
18
- schemaSetupComplete = void 0;
19
- isConnected = null;
20
- constructor(config) {
21
- super({ name: "MSSQLStore" });
22
- try {
23
- if ("connectionString" in config) {
24
- if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") {
25
- throw new Error("MSSQLStore: connectionString must be provided and cannot be empty.");
26
- }
27
- } else {
28
- const required = ["server", "database", "user", "password"];
29
- for (const key of required) {
30
- if (!(key in config) || typeof config[key] !== "string" || config[key].trim() === "") {
31
- throw new Error(`MSSQLStore: ${key} must be provided and cannot be empty.`);
32
- }
33
- }
34
- }
35
- this.schema = config.schemaName;
36
- this.pool = "connectionString" in config ? new sql__default.default.ConnectionPool(config.connectionString) : new sql__default.default.ConnectionPool({
37
- server: config.server,
38
- database: config.database,
39
- user: config.user,
40
- password: config.password,
41
- port: config.port,
42
- options: config.options || { encrypt: true, trustServerCertificate: true }
43
- });
44
- } catch (e) {
45
- throw new error.MastraError(
46
- {
47
- id: "MASTRA_STORAGE_MSSQL_STORE_INITIALIZATION_FAILED",
48
- domain: error.ErrorDomain.STORAGE,
49
- category: error.ErrorCategory.USER
50
- },
51
- e
52
- );
53
- }
16
+ function getSchemaName(schema) {
17
+ return schema ? `[${utils.parseSqlIdentifier(schema, "schema name")}]` : void 0;
18
+ }
19
+ function getTableName({ indexName, schemaName }) {
20
+ const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
21
+ const quotedIndexName = `[${parsedIndexName}]`;
22
+ const quotedSchemaName = schemaName;
23
+ return quotedSchemaName ? `${quotedSchemaName}.${quotedIndexName}` : quotedIndexName;
24
+ }
25
+ function buildDateRangeFilter(dateRange, fieldName) {
26
+ const filters = {};
27
+ if (dateRange?.start) {
28
+ filters[`${fieldName}_gte`] = dateRange.start;
54
29
  }
55
- async init() {
56
- if (this.isConnected === null) {
57
- this.isConnected = this._performInitializationAndStore();
58
- }
59
- try {
60
- await this.isConnected;
61
- await super.init();
62
- } catch (error$1) {
63
- this.isConnected = null;
64
- throw new error.MastraError(
65
- {
66
- id: "MASTRA_STORAGE_MSSQL_STORE_INIT_FAILED",
67
- domain: error.ErrorDomain.STORAGE,
68
- category: error.ErrorCategory.THIRD_PARTY
69
- },
70
- error$1
71
- );
72
- }
30
+ if (dateRange?.end) {
31
+ filters[`${fieldName}_lte`] = dateRange.end;
73
32
  }
74
- async _performInitializationAndStore() {
75
- try {
76
- await this.pool.connect();
77
- return true;
78
- } catch (err) {
79
- throw err;
33
+ return filters;
34
+ }
35
+ function prepareWhereClause(filters, _schema) {
36
+ const conditions = [];
37
+ const params = {};
38
+ let paramIndex = 1;
39
+ Object.entries(filters).forEach(([key, value]) => {
40
+ if (value === void 0) return;
41
+ const paramName = `p${paramIndex++}`;
42
+ if (key.endsWith("_gte")) {
43
+ const fieldName = key.slice(0, -4);
44
+ conditions.push(`[${utils.parseSqlIdentifier(fieldName, "field name")}] >= @${paramName}`);
45
+ params[paramName] = value instanceof Date ? value.toISOString() : value;
46
+ } else if (key.endsWith("_lte")) {
47
+ const fieldName = key.slice(0, -4);
48
+ conditions.push(`[${utils.parseSqlIdentifier(fieldName, "field name")}] <= @${paramName}`);
49
+ params[paramName] = value instanceof Date ? value.toISOString() : value;
50
+ } else if (value === null) {
51
+ conditions.push(`[${utils.parseSqlIdentifier(key, "field name")}] IS NULL`);
52
+ } else {
53
+ conditions.push(`[${utils.parseSqlIdentifier(key, "field name")}] = @${paramName}`);
54
+ params[paramName] = value instanceof Date ? value.toISOString() : value;
80
55
  }
81
- }
82
- get supports() {
83
- return {
84
- selectByIncludeResourceScope: true,
85
- resourceWorkingMemory: true,
86
- hasColumn: true,
87
- createTable: true,
88
- deleteMessages: false
89
- };
90
- }
91
- getTableName(indexName) {
92
- const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
93
- const quotedIndexName = `[${parsedIndexName}]`;
94
- const quotedSchemaName = this.getSchemaName();
95
- return quotedSchemaName ? `${quotedSchemaName}.${quotedIndexName}` : quotedIndexName;
96
- }
97
- getSchemaName() {
98
- return this.schema ? `[${utils.parseSqlIdentifier(this.schema, "schema name")}]` : void 0;
99
- }
100
- transformEvalRow(row) {
101
- let testInfoValue = null, resultValue = null;
102
- if (row.test_info) {
56
+ });
57
+ return {
58
+ sql: conditions.length > 0 ? ` WHERE ${conditions.join(" AND ")}` : "",
59
+ params
60
+ };
61
+ }
62
+ function transformFromSqlRow({
63
+ tableName,
64
+ sqlRow
65
+ }) {
66
+ const schema = storage.TABLE_SCHEMAS[tableName];
67
+ const result = {};
68
+ Object.entries(sqlRow).forEach(([key, value]) => {
69
+ const columnSchema = schema?.[key];
70
+ if (columnSchema?.type === "jsonb" && typeof value === "string") {
103
71
  try {
104
- testInfoValue = typeof row.test_info === "string" ? JSON.parse(row.test_info) : row.test_info;
72
+ result[key] = JSON.parse(value);
105
73
  } catch {
74
+ result[key] = value;
106
75
  }
76
+ } else if (columnSchema?.type === "timestamp" && value && typeof value === "string") {
77
+ result[key] = new Date(value);
78
+ } else if (columnSchema?.type === "timestamp" && value instanceof Date) {
79
+ result[key] = value;
80
+ } else if (columnSchema?.type === "boolean") {
81
+ result[key] = Boolean(value);
82
+ } else {
83
+ result[key] = value;
107
84
  }
108
- if (row.test_info) {
109
- try {
110
- resultValue = typeof row.result === "string" ? JSON.parse(row.result) : row.result;
111
- } catch {
112
- }
85
+ });
86
+ return result;
87
+ }
88
+
89
+ // src/storage/domains/legacy-evals/index.ts
90
+ function transformEvalRow(row) {
91
+ let testInfoValue = null, resultValue = null;
92
+ if (row.test_info) {
93
+ try {
94
+ testInfoValue = typeof row.test_info === "string" ? JSON.parse(row.test_info) : row.test_info;
95
+ } catch {
96
+ }
97
+ }
98
+ if (row.result) {
99
+ try {
100
+ resultValue = typeof row.result === "string" ? JSON.parse(row.result) : row.result;
101
+ } catch {
113
102
  }
114
- return {
115
- agentName: row.agent_name,
116
- input: row.input,
117
- output: row.output,
118
- result: resultValue,
119
- metricName: row.metric_name,
120
- instructions: row.instructions,
121
- testInfo: testInfoValue,
122
- globalRunId: row.global_run_id,
123
- runId: row.run_id,
124
- createdAt: row.created_at
125
- };
103
+ }
104
+ return {
105
+ agentName: row.agent_name,
106
+ input: row.input,
107
+ output: row.output,
108
+ result: resultValue,
109
+ metricName: row.metric_name,
110
+ instructions: row.instructions,
111
+ testInfo: testInfoValue,
112
+ globalRunId: row.global_run_id,
113
+ runId: row.run_id,
114
+ createdAt: row.created_at
115
+ };
116
+ }
117
+ var LegacyEvalsMSSQL = class extends storage.LegacyEvalsStorage {
118
+ pool;
119
+ schema;
120
+ constructor({ pool, schema }) {
121
+ super();
122
+ this.pool = pool;
123
+ this.schema = schema;
126
124
  }
127
125
  /** @deprecated use getEvals instead */
128
126
  async getEvalsByAgentName(agentName, type) {
129
127
  try {
130
- let query = `SELECT * FROM ${this.getTableName(storage.TABLE_EVALS)} WHERE agent_name = @p1`;
128
+ let query = `SELECT * FROM ${getTableName({ indexName: storage.TABLE_EVALS, schemaName: getSchemaName(this.schema) })} WHERE agent_name = @p1`;
131
129
  if (type === "test") {
132
130
  query += " AND test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL";
133
131
  } else if (type === "live") {
@@ -138,606 +136,283 @@ var MSSQLStore = class extends storage.MastraStorage {
138
136
  request.input("p1", agentName);
139
137
  const result = await request.query(query);
140
138
  const rows = result.recordset;
141
- return typeof this.transformEvalRow === "function" ? rows?.map((row) => this.transformEvalRow(row)) ?? [] : rows ?? [];
139
+ return typeof transformEvalRow === "function" ? rows?.map((row) => transformEvalRow(row)) ?? [] : rows ?? [];
142
140
  } catch (error) {
143
141
  if (error && error.number === 208 && error.message && error.message.includes("Invalid object name")) {
144
142
  return [];
145
143
  }
146
- console.error("Failed to get evals for the specified agent: " + error?.message);
144
+ this.logger?.error?.("Failed to get evals for the specified agent:", error);
147
145
  throw error;
148
146
  }
149
147
  }
150
- async batchInsert({ tableName, records }) {
151
- const transaction = this.pool.transaction();
152
- try {
153
- await transaction.begin();
154
- for (const record of records) {
155
- await this.insert({ tableName, record });
156
- }
157
- await transaction.commit();
158
- } catch (error$1) {
159
- await transaction.rollback();
160
- throw new error.MastraError(
161
- {
162
- id: "MASTRA_STORAGE_MSSQL_STORE_BATCH_INSERT_FAILED",
163
- domain: error.ErrorDomain.STORAGE,
164
- category: error.ErrorCategory.THIRD_PARTY,
165
- details: {
166
- tableName,
167
- numberOfRecords: records.length
168
- }
169
- },
170
- error$1
171
- );
172
- }
173
- }
174
- /** @deprecated use getTracesPaginated instead*/
175
- async getTraces(args) {
176
- if (args.fromDate || args.toDate) {
177
- args.dateRange = {
178
- start: args.fromDate,
179
- end: args.toDate
180
- };
181
- }
182
- const result = await this.getTracesPaginated(args);
183
- return result.traces;
184
- }
185
- async getTracesPaginated(args) {
186
- const { name, scope, page = 0, perPage: perPageInput, attributes, filters, dateRange } = args;
148
+ async getEvals(options = {}) {
149
+ const { agentName, type, page = 0, perPage = 100, dateRange } = options;
187
150
  const fromDate = dateRange?.start;
188
151
  const toDate = dateRange?.end;
189
- const perPage = perPageInput !== void 0 ? perPageInput : 100;
190
- const currentOffset = page * perPage;
191
- const paramMap = {};
192
- const conditions = [];
193
- let paramIndex = 1;
194
- if (name) {
195
- const paramName = `p${paramIndex++}`;
196
- conditions.push(`[name] LIKE @${paramName}`);
197
- paramMap[paramName] = `${name}%`;
198
- }
199
- if (scope) {
200
- const paramName = `p${paramIndex++}`;
201
- conditions.push(`[scope] = @${paramName}`);
202
- paramMap[paramName] = scope;
203
- }
204
- if (attributes) {
205
- Object.entries(attributes).forEach(([key, value]) => {
206
- const parsedKey = utils.parseFieldKey(key);
207
- const paramName = `p${paramIndex++}`;
208
- conditions.push(`JSON_VALUE([attributes], '$.${parsedKey}') = @${paramName}`);
209
- paramMap[paramName] = value;
210
- });
152
+ const where = [];
153
+ const params = {};
154
+ if (agentName) {
155
+ where.push("agent_name = @agentName");
156
+ params["agentName"] = agentName;
211
157
  }
212
- if (filters) {
213
- Object.entries(filters).forEach(([key, value]) => {
214
- const parsedKey = utils.parseFieldKey(key);
215
- const paramName = `p${paramIndex++}`;
216
- conditions.push(`[${parsedKey}] = @${paramName}`);
217
- paramMap[paramName] = value;
218
- });
158
+ if (type === "test") {
159
+ where.push("test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL");
160
+ } else if (type === "live") {
161
+ where.push("(test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)");
219
162
  }
220
163
  if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
221
- const paramName = `p${paramIndex++}`;
222
- conditions.push(`[createdAt] >= @${paramName}`);
223
- paramMap[paramName] = fromDate.toISOString();
164
+ where.push(`[created_at] >= @fromDate`);
165
+ params[`fromDate`] = fromDate.toISOString();
224
166
  }
225
167
  if (toDate instanceof Date && !isNaN(toDate.getTime())) {
226
- const paramName = `p${paramIndex++}`;
227
- conditions.push(`[createdAt] <= @${paramName}`);
228
- paramMap[paramName] = toDate.toISOString();
168
+ where.push(`[created_at] <= @toDate`);
169
+ params[`toDate`] = toDate.toISOString();
229
170
  }
230
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
231
- const countQuery = `SELECT COUNT(*) as total FROM ${this.getTableName(storage.TABLE_TRACES)} ${whereClause}`;
232
- let total = 0;
171
+ const whereClause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
172
+ const tableName = getTableName({ indexName: storage.TABLE_EVALS, schemaName: getSchemaName(this.schema) });
173
+ const offset = page * perPage;
174
+ const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
175
+ const dataQuery = `SELECT * FROM ${tableName} ${whereClause} ORDER BY seq_id DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
233
176
  try {
234
- const countRequest = this.pool.request();
235
- Object.entries(paramMap).forEach(([key, value]) => {
177
+ const countReq = this.pool.request();
178
+ Object.entries(params).forEach(([key, value]) => {
236
179
  if (value instanceof Date) {
237
- countRequest.input(key, sql__default.default.DateTime, value);
180
+ countReq.input(key, sql3__default.default.DateTime, value);
238
181
  } else {
239
- countRequest.input(key, value);
182
+ countReq.input(key, value);
240
183
  }
241
184
  });
242
- const countResult = await countRequest.query(countQuery);
243
- total = parseInt(countResult.recordset[0].total, 10);
185
+ const countResult = await countReq.query(countQuery);
186
+ const total = countResult.recordset[0]?.total || 0;
187
+ if (total === 0) {
188
+ return {
189
+ evals: [],
190
+ total: 0,
191
+ page,
192
+ perPage,
193
+ hasMore: false
194
+ };
195
+ }
196
+ const req = this.pool.request();
197
+ Object.entries(params).forEach(([key, value]) => {
198
+ if (value instanceof Date) {
199
+ req.input(key, sql3__default.default.DateTime, value);
200
+ } else {
201
+ req.input(key, value);
202
+ }
203
+ });
204
+ req.input("offset", offset);
205
+ req.input("perPage", perPage);
206
+ const result = await req.query(dataQuery);
207
+ const rows = result.recordset;
208
+ return {
209
+ evals: rows?.map((row) => transformEvalRow(row)) ?? [],
210
+ total,
211
+ page,
212
+ perPage,
213
+ hasMore: offset + (rows?.length ?? 0) < total
214
+ };
244
215
  } catch (error$1) {
245
- throw new error.MastraError(
216
+ const mastraError = new error.MastraError(
246
217
  {
247
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TOTAL_COUNT",
218
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_EVALS_FAILED",
248
219
  domain: error.ErrorDomain.STORAGE,
249
220
  category: error.ErrorCategory.THIRD_PARTY,
250
221
  details: {
251
- name: args.name ?? "",
252
- scope: args.scope ?? ""
222
+ agentName: agentName || "all",
223
+ type: type || "all",
224
+ page,
225
+ perPage
253
226
  }
254
227
  },
255
228
  error$1
256
229
  );
230
+ this.logger?.error?.(mastraError.toString());
231
+ this.logger?.trackException?.(mastraError);
232
+ throw mastraError;
257
233
  }
258
- if (total === 0) {
259
- return {
260
- traces: [],
261
- total: 0,
262
- page,
263
- perPage,
264
- hasMore: false
265
- };
266
- }
267
- const dataQuery = `SELECT * FROM ${this.getTableName(storage.TABLE_TRACES)} ${whereClause} ORDER BY [seq_id] DESC OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
268
- const dataRequest = this.pool.request();
269
- Object.entries(paramMap).forEach(([key, value]) => {
270
- if (value instanceof Date) {
271
- dataRequest.input(key, sql__default.default.DateTime, value);
272
- } else {
273
- dataRequest.input(key, value);
234
+ }
235
+ };
236
+ var MemoryMSSQL = class extends storage.MemoryStorage {
237
+ pool;
238
+ schema;
239
+ operations;
240
+ _parseAndFormatMessages(messages, format) {
241
+ const messagesWithParsedContent = messages.map((message) => {
242
+ if (typeof message.content === "string") {
243
+ try {
244
+ return { ...message, content: JSON.parse(message.content) };
245
+ } catch {
246
+ return message;
247
+ }
274
248
  }
249
+ return message;
275
250
  });
276
- dataRequest.input("offset", currentOffset);
277
- dataRequest.input("limit", perPage);
251
+ const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
252
+ const list = new agent.MessageList().add(cleanMessages, "memory");
253
+ return format === "v2" ? list.get.all.v2() : list.get.all.v1();
254
+ }
255
+ constructor({
256
+ pool,
257
+ schema,
258
+ operations
259
+ }) {
260
+ super();
261
+ this.pool = pool;
262
+ this.schema = schema;
263
+ this.operations = operations;
264
+ }
265
+ async getThreadById({ threadId }) {
278
266
  try {
279
- const rowsResult = await dataRequest.query(dataQuery);
280
- const rows = rowsResult.recordset;
281
- const traces = rows.map((row) => ({
282
- id: row.id,
283
- parentSpanId: row.parentSpanId,
284
- traceId: row.traceId,
285
- name: row.name,
286
- scope: row.scope,
287
- kind: row.kind,
288
- status: JSON.parse(row.status),
289
- events: JSON.parse(row.events),
290
- links: JSON.parse(row.links),
291
- attributes: JSON.parse(row.attributes),
292
- startTime: row.startTime,
293
- endTime: row.endTime,
294
- other: row.other,
295
- createdAt: row.createdAt
296
- }));
267
+ const sql7 = `SELECT
268
+ id,
269
+ [resourceId],
270
+ title,
271
+ metadata,
272
+ [createdAt],
273
+ [updatedAt]
274
+ FROM ${getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) })}
275
+ WHERE id = @threadId`;
276
+ const request = this.pool.request();
277
+ request.input("threadId", threadId);
278
+ const resultSet = await request.query(sql7);
279
+ const thread = resultSet.recordset[0] || null;
280
+ if (!thread) {
281
+ return null;
282
+ }
297
283
  return {
298
- traces,
299
- total,
300
- page,
301
- perPage,
302
- hasMore: currentOffset + traces.length < total
284
+ ...thread,
285
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
286
+ createdAt: thread.createdAt,
287
+ updatedAt: thread.updatedAt
303
288
  };
304
289
  } catch (error$1) {
305
290
  throw new error.MastraError(
306
291
  {
307
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TRACES",
292
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREAD_BY_ID_FAILED",
308
293
  domain: error.ErrorDomain.STORAGE,
309
294
  category: error.ErrorCategory.THIRD_PARTY,
310
295
  details: {
311
- name: args.name ?? "",
312
- scope: args.scope ?? ""
296
+ threadId
313
297
  }
314
298
  },
315
299
  error$1
316
300
  );
317
301
  }
318
302
  }
319
- async setupSchema() {
320
- if (!this.schema || this.schemaSetupComplete) {
321
- return;
322
- }
323
- if (!this.setupSchemaPromise) {
324
- this.setupSchemaPromise = (async () => {
325
- try {
326
- const checkRequest = this.pool.request();
327
- checkRequest.input("schemaName", this.schema);
328
- const checkResult = await checkRequest.query(`
329
- SELECT 1 AS found FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @schemaName
330
- `);
331
- const schemaExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
332
- if (!schemaExists) {
333
- try {
334
- await this.pool.request().query(`CREATE SCHEMA [${this.schema}]`);
335
- this.logger?.info?.(`Schema "${this.schema}" created successfully`);
336
- } catch (error) {
337
- this.logger?.error?.(`Failed to create schema "${this.schema}"`, { error });
338
- throw new Error(
339
- `Unable to create schema "${this.schema}". This requires CREATE privilege on the database. Either create the schema manually or grant CREATE privilege to the user.`
340
- );
341
- }
342
- }
343
- this.schemaSetupComplete = true;
344
- this.logger?.debug?.(`Schema "${this.schema}" is ready for use`);
345
- } catch (error) {
346
- this.schemaSetupComplete = void 0;
347
- this.setupSchemaPromise = null;
348
- throw error;
349
- } finally {
350
- this.setupSchemaPromise = null;
351
- }
352
- })();
353
- }
354
- await this.setupSchemaPromise;
355
- }
356
- getSqlType(type, isPrimaryKey = false) {
357
- switch (type) {
358
- case "text":
359
- return isPrimaryKey ? "NVARCHAR(255)" : "NVARCHAR(MAX)";
360
- case "timestamp":
361
- return "DATETIME2(7)";
362
- case "uuid":
363
- return "UNIQUEIDENTIFIER";
364
- case "jsonb":
365
- return "NVARCHAR(MAX)";
366
- case "integer":
367
- return "INT";
368
- case "bigint":
369
- return "BIGINT";
370
- default:
371
- throw new error.MastraError({
372
- id: "MASTRA_STORAGE_MSSQL_STORE_TYPE_NOT_SUPPORTED",
373
- domain: error.ErrorDomain.STORAGE,
374
- category: error.ErrorCategory.THIRD_PARTY
375
- });
376
- }
377
- }
378
- async createTable({
379
- tableName,
380
- schema
381
- }) {
303
+ async getThreadsByResourceIdPaginated(args) {
304
+ const { resourceId, page = 0, perPage: perPageInput, orderBy = "createdAt", sortDirection = "DESC" } = args;
382
305
  try {
383
- const uniqueConstraintColumns = tableName === storage.TABLE_WORKFLOW_SNAPSHOT ? ["workflow_name", "run_id"] : [];
384
- const columns = Object.entries(schema).map(([name, def]) => {
385
- const parsedName = utils.parseSqlIdentifier(name, "column name");
386
- const constraints = [];
387
- if (def.primaryKey) constraints.push("PRIMARY KEY");
388
- if (!def.nullable) constraints.push("NOT NULL");
389
- const isIndexed = !!def.primaryKey || uniqueConstraintColumns.includes(name);
390
- return `[${parsedName}] ${this.getSqlType(def.type, isIndexed)} ${constraints.join(" ")}`.trim();
391
- }).join(",\n");
392
- if (this.schema) {
393
- await this.setupSchema();
394
- }
395
- const checkTableRequest = this.pool.request();
396
- checkTableRequest.input("tableName", this.getTableName(tableName).replace(/[[\]]/g, "").split(".").pop());
397
- const checkTableSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName`;
398
- checkTableRequest.input("schema", this.schema || "dbo");
399
- const checkTableResult = await checkTableRequest.query(checkTableSql);
400
- const tableExists = Array.isArray(checkTableResult.recordset) && checkTableResult.recordset.length > 0;
401
- if (!tableExists) {
402
- const createSql = `CREATE TABLE ${this.getTableName(tableName)} (
403
- ${columns}
404
- )`;
405
- await this.pool.request().query(createSql);
406
- }
407
- const columnCheckSql = `
408
- SELECT 1 AS found
409
- FROM INFORMATION_SCHEMA.COLUMNS
410
- WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = 'seq_id'
411
- `;
412
- const checkColumnRequest = this.pool.request();
413
- checkColumnRequest.input("schema", this.schema || "dbo");
414
- checkColumnRequest.input("tableName", this.getTableName(tableName).replace(/[[\]]/g, "").split(".").pop());
415
- const columnResult = await checkColumnRequest.query(columnCheckSql);
416
- const columnExists = Array.isArray(columnResult.recordset) && columnResult.recordset.length > 0;
417
- if (!columnExists) {
418
- const alterSql = `ALTER TABLE ${this.getTableName(tableName)} ADD seq_id BIGINT IDENTITY(1,1)`;
419
- await this.pool.request().query(alterSql);
420
- }
421
- if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
422
- const constraintName = "mastra_workflow_snapshot_workflow_name_run_id_key";
423
- const checkConstraintSql = `SELECT 1 AS found FROM sys.key_constraints WHERE name = @constraintName`;
424
- const checkConstraintRequest = this.pool.request();
425
- checkConstraintRequest.input("constraintName", constraintName);
426
- const constraintResult = await checkConstraintRequest.query(checkConstraintSql);
427
- const constraintExists = Array.isArray(constraintResult.recordset) && constraintResult.recordset.length > 0;
428
- if (!constraintExists) {
429
- const addConstraintSql = `ALTER TABLE ${this.getTableName(tableName)} ADD CONSTRAINT ${constraintName} UNIQUE ([workflow_name], [run_id])`;
430
- await this.pool.request().query(addConstraintSql);
431
- }
306
+ const perPage = perPageInput !== void 0 ? perPageInput : 100;
307
+ const currentOffset = page * perPage;
308
+ const baseQuery = `FROM ${getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
309
+ const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
310
+ const countRequest = this.pool.request();
311
+ countRequest.input("resourceId", resourceId);
312
+ const countResult = await countRequest.query(countQuery);
313
+ const total = parseInt(countResult.recordset[0]?.count ?? "0", 10);
314
+ if (total === 0) {
315
+ return {
316
+ threads: [],
317
+ total: 0,
318
+ page,
319
+ perPage,
320
+ hasMore: false
321
+ };
432
322
  }
323
+ const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
324
+ const dir = (sortDirection || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
325
+ const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${dir} OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
326
+ const dataRequest = this.pool.request();
327
+ dataRequest.input("resourceId", resourceId);
328
+ dataRequest.input("perPage", perPage);
329
+ dataRequest.input("offset", currentOffset);
330
+ const rowsResult = await dataRequest.query(dataQuery);
331
+ const rows = rowsResult.recordset || [];
332
+ const threads = rows.map((thread) => ({
333
+ ...thread,
334
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
335
+ createdAt: thread.createdAt,
336
+ updatedAt: thread.updatedAt
337
+ }));
338
+ return {
339
+ threads,
340
+ total,
341
+ page,
342
+ perPage,
343
+ hasMore: currentOffset + threads.length < total
344
+ };
433
345
  } catch (error$1) {
434
- throw new error.MastraError(
346
+ const mastraError = new error.MastraError(
435
347
  {
436
- id: "MASTRA_STORAGE_MSSQL_STORE_CREATE_TABLE_FAILED",
348
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
437
349
  domain: error.ErrorDomain.STORAGE,
438
350
  category: error.ErrorCategory.THIRD_PARTY,
439
351
  details: {
440
- tableName
352
+ resourceId,
353
+ page
441
354
  }
442
355
  },
443
356
  error$1
444
357
  );
358
+ this.logger?.error?.(mastraError.toString());
359
+ this.logger?.trackException?.(mastraError);
360
+ return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
445
361
  }
446
362
  }
447
- getDefaultValue(type) {
448
- switch (type) {
449
- case "timestamp":
450
- return "DEFAULT SYSDATETIMEOFFSET()";
451
- case "jsonb":
452
- return "DEFAULT N'{}'";
453
- default:
454
- return super.getDefaultValue(type);
455
- }
456
- }
457
- async alterTable({
458
- tableName,
459
- schema,
460
- ifNotExists
461
- }) {
462
- const fullTableName = this.getTableName(tableName);
363
+ async saveThread({ thread }) {
463
364
  try {
464
- for (const columnName of ifNotExists) {
465
- if (schema[columnName]) {
466
- const columnCheckRequest = this.pool.request();
467
- columnCheckRequest.input("tableName", fullTableName.replace(/[[\]]/g, "").split(".").pop());
468
- columnCheckRequest.input("columnName", columnName);
469
- columnCheckRequest.input("schema", this.schema || "dbo");
470
- const checkSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = @columnName`;
471
- const checkResult = await columnCheckRequest.query(checkSql);
472
- const columnExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
473
- if (!columnExists) {
474
- const columnDef = schema[columnName];
475
- const sqlType = this.getSqlType(columnDef.type);
476
- const nullable = columnDef.nullable === false ? "NOT NULL" : "";
477
- const defaultValue = columnDef.nullable === false ? this.getDefaultValue(columnDef.type) : "";
478
- const parsedColumnName = utils.parseSqlIdentifier(columnName, "column name");
479
- const alterSql = `ALTER TABLE ${fullTableName} ADD [${parsedColumnName}] ${sqlType} ${nullable} ${defaultValue}`.trim();
480
- await this.pool.request().query(alterSql);
481
- this.logger?.debug?.(`Ensured column ${parsedColumnName} exists in table ${fullTableName}`);
482
- }
483
- }
365
+ const table = getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) });
366
+ const mergeSql = `MERGE INTO ${table} WITH (HOLDLOCK) AS target
367
+ USING (SELECT @id AS id) AS source
368
+ ON (target.id = source.id)
369
+ WHEN MATCHED THEN
370
+ UPDATE SET
371
+ [resourceId] = @resourceId,
372
+ title = @title,
373
+ metadata = @metadata,
374
+ [updatedAt] = @updatedAt
375
+ WHEN NOT MATCHED THEN
376
+ INSERT (id, [resourceId], title, metadata, [createdAt], [updatedAt])
377
+ VALUES (@id, @resourceId, @title, @metadata, @createdAt, @updatedAt);`;
378
+ const req = this.pool.request();
379
+ req.input("id", thread.id);
380
+ req.input("resourceId", thread.resourceId);
381
+ req.input("title", thread.title);
382
+ const metadata = thread.metadata ? JSON.stringify(thread.metadata) : null;
383
+ if (metadata === null) {
384
+ req.input("metadata", sql3__default.default.NVarChar, null);
385
+ } else {
386
+ req.input("metadata", metadata);
484
387
  }
388
+ req.input("createdAt", sql3__default.default.DateTime2, thread.createdAt);
389
+ req.input("updatedAt", sql3__default.default.DateTime2, thread.updatedAt);
390
+ await req.query(mergeSql);
391
+ return thread;
485
392
  } catch (error$1) {
486
393
  throw new error.MastraError(
487
394
  {
488
- id: "MASTRA_STORAGE_MSSQL_STORE_ALTER_TABLE_FAILED",
395
+ id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_THREAD_FAILED",
489
396
  domain: error.ErrorDomain.STORAGE,
490
397
  category: error.ErrorCategory.THIRD_PARTY,
491
398
  details: {
492
- tableName
399
+ threadId: thread.id
493
400
  }
494
401
  },
495
402
  error$1
496
403
  );
497
404
  }
498
405
  }
499
- async clearTable({ tableName }) {
500
- const fullTableName = this.getTableName(tableName);
406
+ /**
407
+ * @deprecated use getThreadsByResourceIdPaginated instead
408
+ */
409
+ async getThreadsByResourceId(args) {
410
+ const { resourceId, orderBy = "createdAt", sortDirection = "DESC" } = args;
501
411
  try {
502
- const fkQuery = `
503
- SELECT
504
- OBJECT_SCHEMA_NAME(fk.parent_object_id) AS schema_name,
505
- OBJECT_NAME(fk.parent_object_id) AS table_name
506
- FROM sys.foreign_keys fk
507
- WHERE fk.referenced_object_id = OBJECT_ID(@fullTableName)
508
- `;
509
- const fkResult = await this.pool.request().input("fullTableName", fullTableName).query(fkQuery);
510
- const childTables = fkResult.recordset || [];
511
- for (const child of childTables) {
512
- const childTableName = this.schema ? `[${child.schema_name}].[${child.table_name}]` : `[${child.table_name}]`;
513
- await this.clearTable({ tableName: childTableName });
514
- }
515
- await this.pool.request().query(`TRUNCATE TABLE ${fullTableName}`);
516
- } catch (error$1) {
517
- throw new error.MastraError(
518
- {
519
- id: "MASTRA_STORAGE_MSSQL_STORE_CLEAR_TABLE_FAILED",
520
- domain: error.ErrorDomain.STORAGE,
521
- category: error.ErrorCategory.THIRD_PARTY,
522
- details: {
523
- tableName
524
- }
525
- },
526
- error$1
527
- );
528
- }
529
- }
530
- async insert({ tableName, record }) {
531
- try {
532
- const columns = Object.keys(record).map((col) => utils.parseSqlIdentifier(col, "column name"));
533
- const values = Object.values(record);
534
- const paramNames = values.map((_, i) => `@param${i}`);
535
- const insertSql = `INSERT INTO ${this.getTableName(tableName)} (${columns.map((c) => `[${c}]`).join(", ")}) VALUES (${paramNames.join(", ")})`;
536
- const request = this.pool.request();
537
- values.forEach((value, i) => {
538
- if (value instanceof Date) {
539
- request.input(`param${i}`, sql__default.default.DateTime2, value);
540
- } else if (typeof value === "object" && value !== null) {
541
- request.input(`param${i}`, JSON.stringify(value));
542
- } else {
543
- request.input(`param${i}`, value);
544
- }
545
- });
546
- await request.query(insertSql);
547
- } catch (error$1) {
548
- throw new error.MastraError(
549
- {
550
- id: "MASTRA_STORAGE_MSSQL_STORE_INSERT_FAILED",
551
- domain: error.ErrorDomain.STORAGE,
552
- category: error.ErrorCategory.THIRD_PARTY,
553
- details: {
554
- tableName
555
- }
556
- },
557
- error$1
558
- );
559
- }
560
- }
561
- async load({ tableName, keys }) {
562
- try {
563
- const keyEntries = Object.entries(keys).map(([key, value]) => [utils.parseSqlIdentifier(key, "column name"), value]);
564
- const conditions = keyEntries.map(([key], i) => `[${key}] = @param${i}`).join(" AND ");
565
- const values = keyEntries.map(([_, value]) => value);
566
- const sql2 = `SELECT * FROM ${this.getTableName(tableName)} WHERE ${conditions}`;
567
- const request = this.pool.request();
568
- values.forEach((value, i) => {
569
- request.input(`param${i}`, value);
570
- });
571
- const resultSet = await request.query(sql2);
572
- const result = resultSet.recordset[0] || null;
573
- if (!result) {
574
- return null;
575
- }
576
- if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
577
- const snapshot = result;
578
- if (typeof snapshot.snapshot === "string") {
579
- snapshot.snapshot = JSON.parse(snapshot.snapshot);
580
- }
581
- return snapshot;
582
- }
583
- return result;
584
- } catch (error$1) {
585
- throw new error.MastraError(
586
- {
587
- id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_FAILED",
588
- domain: error.ErrorDomain.STORAGE,
589
- category: error.ErrorCategory.THIRD_PARTY,
590
- details: {
591
- tableName
592
- }
593
- },
594
- error$1
595
- );
596
- }
597
- }
598
- async getThreadById({ threadId }) {
599
- try {
600
- const sql2 = `SELECT
601
- id,
602
- [resourceId],
603
- title,
604
- metadata,
605
- [createdAt],
606
- [updatedAt]
607
- FROM ${this.getTableName(storage.TABLE_THREADS)}
608
- WHERE id = @threadId`;
609
- const request = this.pool.request();
610
- request.input("threadId", threadId);
611
- const resultSet = await request.query(sql2);
612
- const thread = resultSet.recordset[0] || null;
613
- if (!thread) {
614
- return null;
615
- }
616
- return {
617
- ...thread,
618
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
619
- createdAt: thread.createdAt,
620
- updatedAt: thread.updatedAt
621
- };
622
- } catch (error$1) {
623
- throw new error.MastraError(
624
- {
625
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREAD_BY_ID_FAILED",
626
- domain: error.ErrorDomain.STORAGE,
627
- category: error.ErrorCategory.THIRD_PARTY,
628
- details: {
629
- threadId
630
- }
631
- },
632
- error$1
633
- );
634
- }
635
- }
636
- async getThreadsByResourceIdPaginated(args) {
637
- const { resourceId, page = 0, perPage: perPageInput } = args;
638
- try {
639
- const perPage = perPageInput !== void 0 ? perPageInput : 100;
640
- const currentOffset = page * perPage;
641
- const baseQuery = `FROM ${this.getTableName(storage.TABLE_THREADS)} WHERE [resourceId] = @resourceId`;
642
- const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
643
- const countRequest = this.pool.request();
644
- countRequest.input("resourceId", resourceId);
645
- const countResult = await countRequest.query(countQuery);
646
- const total = parseInt(countResult.recordset[0]?.count ?? "0", 10);
647
- if (total === 0) {
648
- return {
649
- threads: [],
650
- total: 0,
651
- page,
652
- perPage,
653
- hasMore: false
654
- };
655
- }
656
- const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY [seq_id] DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
657
- const dataRequest = this.pool.request();
658
- dataRequest.input("resourceId", resourceId);
659
- dataRequest.input("perPage", perPage);
660
- dataRequest.input("offset", currentOffset);
661
- const rowsResult = await dataRequest.query(dataQuery);
662
- const rows = rowsResult.recordset || [];
663
- const threads = rows.map((thread) => ({
664
- ...thread,
665
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
666
- createdAt: thread.createdAt,
667
- updatedAt: thread.updatedAt
668
- }));
669
- return {
670
- threads,
671
- total,
672
- page,
673
- perPage,
674
- hasMore: currentOffset + threads.length < total
675
- };
676
- } catch (error$1) {
677
- const mastraError = new error.MastraError(
678
- {
679
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
680
- domain: error.ErrorDomain.STORAGE,
681
- category: error.ErrorCategory.THIRD_PARTY,
682
- details: {
683
- resourceId,
684
- page
685
- }
686
- },
687
- error$1
688
- );
689
- this.logger?.error?.(mastraError.toString());
690
- this.logger?.trackException?.(mastraError);
691
- return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
692
- }
693
- }
694
- async saveThread({ thread }) {
695
- try {
696
- const table = this.getTableName(storage.TABLE_THREADS);
697
- const mergeSql = `MERGE INTO ${table} WITH (HOLDLOCK) AS target
698
- USING (SELECT @id AS id) AS source
699
- ON (target.id = source.id)
700
- WHEN MATCHED THEN
701
- UPDATE SET
702
- [resourceId] = @resourceId,
703
- title = @title,
704
- metadata = @metadata,
705
- [createdAt] = @createdAt,
706
- [updatedAt] = @updatedAt
707
- WHEN NOT MATCHED THEN
708
- INSERT (id, [resourceId], title, metadata, [createdAt], [updatedAt])
709
- VALUES (@id, @resourceId, @title, @metadata, @createdAt, @updatedAt);`;
710
- const req = this.pool.request();
711
- req.input("id", thread.id);
712
- req.input("resourceId", thread.resourceId);
713
- req.input("title", thread.title);
714
- req.input("metadata", thread.metadata ? JSON.stringify(thread.metadata) : null);
715
- req.input("createdAt", thread.createdAt);
716
- req.input("updatedAt", thread.updatedAt);
717
- await req.query(mergeSql);
718
- return thread;
719
- } catch (error$1) {
720
- throw new error.MastraError(
721
- {
722
- id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_THREAD_FAILED",
723
- domain: error.ErrorDomain.STORAGE,
724
- category: error.ErrorCategory.THIRD_PARTY,
725
- details: {
726
- threadId: thread.id
727
- }
728
- },
729
- error$1
730
- );
731
- }
732
- }
733
- /**
734
- * @deprecated use getThreadsByResourceIdPaginated instead
735
- */
736
- async getThreadsByResourceId(args) {
737
- const { resourceId } = args;
738
- try {
739
- const baseQuery = `FROM ${this.getTableName(storage.TABLE_THREADS)} WHERE [resourceId] = @resourceId`;
740
- const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY [seq_id] DESC`;
412
+ const baseQuery = `FROM ${getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
413
+ const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
414
+ const dir = (sortDirection || "DESC").toUpperCase() === "ASC" ? "ASC" : "DESC";
415
+ const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${dir}`;
741
416
  const request = this.pool.request();
742
417
  request.input("resourceId", resourceId);
743
418
  const resultSet = await request.query(dataQuery);
@@ -779,8 +454,8 @@ ${columns}
779
454
  ...metadata
780
455
  };
781
456
  try {
782
- const table = this.getTableName(storage.TABLE_THREADS);
783
- const sql2 = `UPDATE ${table}
457
+ const table = getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) });
458
+ const sql7 = `UPDATE ${table}
784
459
  SET title = @title,
785
460
  metadata = @metadata,
786
461
  [updatedAt] = @updatedAt
@@ -790,8 +465,8 @@ ${columns}
790
465
  req.input("id", id);
791
466
  req.input("title", title);
792
467
  req.input("metadata", JSON.stringify(mergedMetadata));
793
- req.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
794
- const result = await req.query(sql2);
468
+ req.input("updatedAt", /* @__PURE__ */ new Date());
469
+ const result = await req.query(sql7);
795
470
  let thread = result.recordset && result.recordset[0];
796
471
  if (thread && "seq_id" in thread) {
797
472
  const { seq_id, ...rest } = thread;
@@ -831,8 +506,8 @@ ${columns}
831
506
  }
832
507
  }
833
508
  async deleteThread({ threadId }) {
834
- const messagesTable = this.getTableName(storage.TABLE_MESSAGES);
835
- const threadsTable = this.getTableName(storage.TABLE_THREADS);
509
+ const messagesTable = getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
510
+ const threadsTable = getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) });
836
511
  const deleteMessagesSql = `DELETE FROM ${messagesTable} WHERE [thread_id] = @threadId`;
837
512
  const deleteThreadSql = `DELETE FROM ${threadsTable} WHERE id = @threadId`;
838
513
  const tx = this.pool.transaction();
@@ -864,6 +539,7 @@ ${columns}
864
539
  selectBy,
865
540
  orderByStatement
866
541
  }) {
542
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
867
543
  const include = selectBy?.include;
868
544
  if (!include) return null;
869
545
  const unionQueries = [];
@@ -890,7 +566,7 @@ ${columns}
890
566
  m.seq_id
891
567
  FROM (
892
568
  SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
893
- FROM ${this.getTableName(storage.TABLE_MESSAGES)}
569
+ FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
894
570
  WHERE [thread_id] = ${pThreadId}
895
571
  ) AS m
896
572
  WHERE m.id = ${pId}
@@ -898,7 +574,7 @@ ${columns}
898
574
  SELECT 1
899
575
  FROM (
900
576
  SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
901
- FROM ${this.getTableName(storage.TABLE_MESSAGES)}
577
+ FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
902
578
  WHERE [thread_id] = ${pThreadId}
903
579
  ) AS target
904
580
  WHERE target.id = ${pId}
@@ -935,11 +611,12 @@ ${columns}
935
611
  return dedupedRows;
936
612
  }
937
613
  async getMessages(args) {
938
- const { threadId, format, selectBy } = args;
939
- const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId`;
614
+ const { threadId, resourceId, format, selectBy } = args;
615
+ const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
940
616
  const orderByStatement = `ORDER BY [seq_id] DESC`;
941
- const limit = this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
617
+ const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
942
618
  try {
619
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
943
620
  let rows = [];
944
621
  const include = selectBy?.include || [];
945
622
  if (include?.length) {
@@ -949,7 +626,7 @@ ${columns}
949
626
  }
950
627
  }
951
628
  const excludeIds = rows.map((m) => m.id).filter(Boolean);
952
- let query = `${selectStatement} FROM ${this.getTableName(storage.TABLE_MESSAGES)} WHERE [thread_id] = @threadId`;
629
+ let query = `${selectStatement} FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [thread_id] = @threadId`;
953
630
  const request = this.pool.request();
954
631
  request.input("threadId", threadId);
955
632
  if (excludeIds.length > 0) {
@@ -969,30 +646,7 @@ ${columns}
969
646
  return timeDiff;
970
647
  });
971
648
  rows = rows.map(({ seq_id, ...rest }) => rest);
972
- const fetchedMessages = (rows || []).map((message) => {
973
- if (typeof message.content === "string") {
974
- try {
975
- message.content = JSON.parse(message.content);
976
- } catch {
977
- }
978
- }
979
- if (format === "v1") {
980
- if (Array.isArray(message.content)) ; else if (typeof message.content === "object" && message.content && Array.isArray(message.content.parts)) {
981
- message.content = message.content.parts;
982
- } else {
983
- message.content = [{ type: "text", text: "" }];
984
- }
985
- } else {
986
- if (typeof message.content !== "object" || !message.content || !("parts" in message.content)) {
987
- message.content = { format: 2, parts: [{ type: "text", text: "" }] };
988
- }
989
- }
990
- if (message.type === "v2") delete message.type;
991
- return message;
992
- });
993
- return format === "v2" ? fetchedMessages.map(
994
- (m) => ({ ...m, content: m.content || { format: 2, parts: [{ type: "text", text: "" }] } })
995
- ) : fetchedMessages;
649
+ return this._parseAndFormatMessages(rows, format);
996
650
  } catch (error$1) {
997
651
  const mastraError = new error.MastraError(
998
652
  {
@@ -1000,40 +654,76 @@ ${columns}
1000
654
  domain: error.ErrorDomain.STORAGE,
1001
655
  category: error.ErrorCategory.THIRD_PARTY,
1002
656
  details: {
1003
- threadId
657
+ threadId,
658
+ resourceId: resourceId ?? ""
1004
659
  }
1005
660
  },
1006
661
  error$1
1007
662
  );
1008
663
  this.logger?.error?.(mastraError.toString());
1009
- this.logger?.trackException(mastraError);
664
+ this.logger?.trackException?.(mastraError);
1010
665
  return [];
1011
666
  }
1012
667
  }
1013
- async getMessagesPaginated(args) {
1014
- const { threadId, selectBy } = args;
1015
- const { page = 0, perPage: perPageInput } = selectBy?.pagination || {};
668
+ async getMessagesById({
669
+ messageIds,
670
+ format
671
+ }) {
672
+ if (messageIds.length === 0) return [];
673
+ const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
1016
674
  const orderByStatement = `ORDER BY [seq_id] DESC`;
1017
- if (selectBy?.include?.length) {
1018
- await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
675
+ try {
676
+ let rows = [];
677
+ let query = `${selectStatement} FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [id] IN (${messageIds.map((_, i) => `@id${i}`).join(", ")})`;
678
+ const request = this.pool.request();
679
+ messageIds.forEach((id, i) => request.input(`id${i}`, id));
680
+ query += ` ${orderByStatement}`;
681
+ const result = await request.query(query);
682
+ const remainingRows = result.recordset || [];
683
+ rows.push(...remainingRows);
684
+ rows.sort((a, b) => {
685
+ const timeDiff = a.seq_id - b.seq_id;
686
+ return timeDiff;
687
+ });
688
+ rows = rows.map(({ seq_id, ...rest }) => rest);
689
+ if (format === `v1`) return this._parseAndFormatMessages(rows, format);
690
+ return this._parseAndFormatMessages(rows, `v2`);
691
+ } catch (error$1) {
692
+ const mastraError = new error.MastraError(
693
+ {
694
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_BY_ID_FAILED",
695
+ domain: error.ErrorDomain.STORAGE,
696
+ category: error.ErrorCategory.THIRD_PARTY,
697
+ details: {
698
+ messageIds: JSON.stringify(messageIds)
699
+ }
700
+ },
701
+ error$1
702
+ );
703
+ this.logger?.error?.(mastraError.toString());
704
+ this.logger?.trackException?.(mastraError);
705
+ return [];
1019
706
  }
707
+ }
708
+ async getMessagesPaginated(args) {
709
+ const { threadId, resourceId, format, selectBy } = args;
710
+ const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
1020
711
  try {
1021
- const { threadId: threadId2, format, selectBy: selectBy2 } = args;
1022
- const { page: page2 = 0, perPage: perPageInput2, dateRange } = selectBy2?.pagination || {};
712
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
1023
713
  const fromDate = dateRange?.start;
1024
714
  const toDate = dateRange?.end;
1025
- const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId`;
1026
- const orderByStatement2 = `ORDER BY [seq_id] DESC`;
1027
- let messages2 = [];
1028
- if (selectBy2?.include?.length) {
1029
- const includeMessages = await this._getIncludedMessages({ threadId: threadId2, selectBy: selectBy2, orderByStatement: orderByStatement2 });
1030
- if (includeMessages) messages2.push(...includeMessages);
1031
- }
1032
- const perPage = perPageInput2 !== void 0 ? perPageInput2 : this.resolveMessageLimit({ last: selectBy2?.last, defaultLimit: 40 });
1033
- const currentOffset = page2 * perPage;
715
+ const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
716
+ const orderByStatement = `ORDER BY [seq_id] DESC`;
717
+ let messages = [];
718
+ if (selectBy?.include?.length) {
719
+ const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
720
+ if (includeMessages) messages.push(...includeMessages);
721
+ }
722
+ const perPage = perPageInput !== void 0 ? perPageInput : storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
723
+ const currentOffset = page * perPage;
1034
724
  const conditions = ["[thread_id] = @threadId"];
1035
725
  const request = this.pool.request();
1036
- request.input("threadId", threadId2);
726
+ request.input("threadId", threadId);
1037
727
  if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
1038
728
  conditions.push("[createdAt] >= @fromDate");
1039
729
  request.input("fromDate", fromDate.toISOString());
@@ -1043,38 +733,39 @@ ${columns}
1043
733
  request.input("toDate", toDate.toISOString());
1044
734
  }
1045
735
  const whereClause = `WHERE ${conditions.join(" AND ")}`;
1046
- const countQuery = `SELECT COUNT(*) as total FROM ${this.getTableName(storage.TABLE_MESSAGES)} ${whereClause}`;
736
+ const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
1047
737
  const countResult = await request.query(countQuery);
1048
738
  const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
1049
- if (total === 0 && messages2.length > 0) {
1050
- const parsedIncluded = this._parseAndFormatMessages(messages2, format);
739
+ if (total === 0 && messages.length > 0) {
740
+ const parsedIncluded = this._parseAndFormatMessages(messages, format);
1051
741
  return {
1052
742
  messages: parsedIncluded,
1053
743
  total: parsedIncluded.length,
1054
- page: page2,
744
+ page,
1055
745
  perPage,
1056
746
  hasMore: false
1057
747
  };
1058
748
  }
1059
- const excludeIds = messages2.map((m) => m.id);
749
+ const excludeIds = messages.map((m) => m.id);
1060
750
  if (excludeIds.length > 0) {
1061
751
  const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
1062
752
  conditions.push(`id NOT IN (${excludeParams.join(", ")})`);
1063
753
  excludeIds.forEach((id, idx) => request.input(`id${idx}`, id));
1064
754
  }
1065
755
  const finalWhereClause = `WHERE ${conditions.join(" AND ")}`;
1066
- const dataQuery = `${selectStatement} FROM ${this.getTableName(storage.TABLE_MESSAGES)} ${finalWhereClause} ${orderByStatement2} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
756
+ const dataQuery = `${selectStatement} FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${finalWhereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
1067
757
  request.input("offset", currentOffset);
1068
758
  request.input("limit", perPage);
1069
759
  const rowsResult = await request.query(dataQuery);
1070
760
  const rows = rowsResult.recordset || [];
1071
761
  rows.sort((a, b) => a.seq_id - b.seq_id);
1072
- messages2.push(...rows);
1073
- const parsed = this._parseAndFormatMessages(messages2, format);
762
+ messages.push(...rows);
763
+ let parsed = this._parseAndFormatMessages(messages, format);
764
+ parsed = parsed.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
1074
765
  return {
1075
766
  messages: parsed,
1076
- total: total + excludeIds.length,
1077
- page: page2,
767
+ total,
768
+ page,
1078
769
  perPage,
1079
770
  hasMore: currentOffset + rows.length < total
1080
771
  };
@@ -1086,41 +777,17 @@ ${columns}
1086
777
  category: error.ErrorCategory.THIRD_PARTY,
1087
778
  details: {
1088
779
  threadId,
780
+ resourceId: resourceId ?? "",
1089
781
  page
1090
782
  }
1091
783
  },
1092
784
  error$1
1093
785
  );
1094
786
  this.logger?.error?.(mastraError.toString());
1095
- this.logger?.trackException(mastraError);
787
+ this.logger?.trackException?.(mastraError);
1096
788
  return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
1097
789
  }
1098
790
  }
1099
- _parseAndFormatMessages(messages, format) {
1100
- const parsedMessages = messages.map((message) => {
1101
- let parsed = message;
1102
- if (typeof parsed.content === "string") {
1103
- try {
1104
- parsed = { ...parsed, content: JSON.parse(parsed.content) };
1105
- } catch {
1106
- }
1107
- }
1108
- if (format === "v1") {
1109
- if (Array.isArray(parsed.content)) ; else if (parsed.content?.parts) {
1110
- parsed.content = parsed.content.parts;
1111
- } else {
1112
- parsed.content = [{ type: "text", text: "" }];
1113
- }
1114
- } else {
1115
- if (!parsed.content?.parts) {
1116
- parsed = { ...parsed, content: { format: 2, parts: [{ type: "text", text: "" }] } };
1117
- }
1118
- }
1119
- return parsed;
1120
- });
1121
- const list = new agent.MessageList().add(parsedMessages, "memory");
1122
- return format === "v2" ? list.get.all.v2() : list.get.all.v1();
1123
- }
1124
791
  async saveMessages({
1125
792
  messages,
1126
793
  format
@@ -1145,8 +812,8 @@ ${columns}
1145
812
  details: { threadId }
1146
813
  });
1147
814
  }
1148
- const tableMessages = this.getTableName(storage.TABLE_MESSAGES);
1149
- const tableThreads = this.getTableName(storage.TABLE_THREADS);
815
+ const tableMessages = getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
816
+ const tableThreads = getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) });
1150
817
  try {
1151
818
  const transaction = this.pool.transaction();
1152
819
  await transaction.begin();
@@ -1169,7 +836,7 @@ ${columns}
1169
836
  "content",
1170
837
  typeof message.content === "string" ? message.content : JSON.stringify(message.content)
1171
838
  );
1172
- request.input("createdAt", message.createdAt.toISOString() || (/* @__PURE__ */ new Date()).toISOString());
839
+ request.input("createdAt", sql3__default.default.DateTime2, message.createdAt);
1173
840
  request.input("role", message.role);
1174
841
  request.input("type", message.type || "v2");
1175
842
  request.input("resourceId", message.resourceId);
@@ -1188,7 +855,7 @@ ${columns}
1188
855
  await request.query(mergeSql);
1189
856
  }
1190
857
  const threadReq = transaction.request();
1191
- threadReq.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
858
+ threadReq.input("updatedAt", sql3__default.default.DateTime2, /* @__PURE__ */ new Date());
1192
859
  threadReq.input("id", threadId);
1193
860
  await threadReq.query(`UPDATE ${tableThreads} SET [updatedAt] = @updatedAt WHERE id = @id`);
1194
861
  await transaction.commit();
@@ -1221,216 +888,6 @@ ${columns}
1221
888
  );
1222
889
  }
1223
890
  }
1224
- async persistWorkflowSnapshot({
1225
- workflowName,
1226
- runId,
1227
- snapshot
1228
- }) {
1229
- const table = this.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
1230
- const now = (/* @__PURE__ */ new Date()).toISOString();
1231
- try {
1232
- const request = this.pool.request();
1233
- request.input("workflow_name", workflowName);
1234
- request.input("run_id", runId);
1235
- request.input("snapshot", JSON.stringify(snapshot));
1236
- request.input("createdAt", now);
1237
- request.input("updatedAt", now);
1238
- const mergeSql = `MERGE INTO ${table} AS target
1239
- USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
1240
- ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
1241
- WHEN MATCHED THEN UPDATE SET
1242
- snapshot = @snapshot,
1243
- [updatedAt] = @updatedAt
1244
- WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, snapshot, [createdAt], [updatedAt])
1245
- VALUES (@workflow_name, @run_id, @snapshot, @createdAt, @updatedAt);`;
1246
- await request.query(mergeSql);
1247
- } catch (error$1) {
1248
- throw new error.MastraError(
1249
- {
1250
- id: "MASTRA_STORAGE_MSSQL_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
1251
- domain: error.ErrorDomain.STORAGE,
1252
- category: error.ErrorCategory.THIRD_PARTY,
1253
- details: {
1254
- workflowName,
1255
- runId
1256
- }
1257
- },
1258
- error$1
1259
- );
1260
- }
1261
- }
1262
- async loadWorkflowSnapshot({
1263
- workflowName,
1264
- runId
1265
- }) {
1266
- try {
1267
- const result = await this.load({
1268
- tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
1269
- keys: {
1270
- workflow_name: workflowName,
1271
- run_id: runId
1272
- }
1273
- });
1274
- if (!result) {
1275
- return null;
1276
- }
1277
- return result.snapshot;
1278
- } catch (error$1) {
1279
- throw new error.MastraError(
1280
- {
1281
- id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
1282
- domain: error.ErrorDomain.STORAGE,
1283
- category: error.ErrorCategory.THIRD_PARTY,
1284
- details: {
1285
- workflowName,
1286
- runId
1287
- }
1288
- },
1289
- error$1
1290
- );
1291
- }
1292
- }
1293
- async hasColumn(table, column) {
1294
- const schema = this.schema || "dbo";
1295
- const request = this.pool.request();
1296
- request.input("schema", schema);
1297
- request.input("table", table);
1298
- request.input("column", column);
1299
- request.input("columnLower", column.toLowerCase());
1300
- const result = await request.query(
1301
- `SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table AND (COLUMN_NAME = @column OR COLUMN_NAME = @columnLower)`
1302
- );
1303
- return result.recordset.length > 0;
1304
- }
1305
- parseWorkflowRun(row) {
1306
- let parsedSnapshot = row.snapshot;
1307
- if (typeof parsedSnapshot === "string") {
1308
- try {
1309
- parsedSnapshot = JSON.parse(row.snapshot);
1310
- } catch (e) {
1311
- console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
1312
- }
1313
- }
1314
- return {
1315
- workflowName: row.workflow_name,
1316
- runId: row.run_id,
1317
- snapshot: parsedSnapshot,
1318
- createdAt: row.createdAt,
1319
- updatedAt: row.updatedAt,
1320
- resourceId: row.resourceId
1321
- };
1322
- }
1323
- async getWorkflowRuns({
1324
- workflowName,
1325
- fromDate,
1326
- toDate,
1327
- limit,
1328
- offset,
1329
- resourceId
1330
- } = {}) {
1331
- try {
1332
- const conditions = [];
1333
- const paramMap = {};
1334
- if (workflowName) {
1335
- conditions.push(`[workflow_name] = @workflowName`);
1336
- paramMap["workflowName"] = workflowName;
1337
- }
1338
- if (resourceId) {
1339
- const hasResourceId = await this.hasColumn(storage.TABLE_WORKFLOW_SNAPSHOT, "resourceId");
1340
- if (hasResourceId) {
1341
- conditions.push(`[resourceId] = @resourceId`);
1342
- paramMap["resourceId"] = resourceId;
1343
- } else {
1344
- console.warn(`[${storage.TABLE_WORKFLOW_SNAPSHOT}] resourceId column not found. Skipping resourceId filter.`);
1345
- }
1346
- }
1347
- if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
1348
- conditions.push(`[createdAt] >= @fromDate`);
1349
- paramMap[`fromDate`] = fromDate.toISOString();
1350
- }
1351
- if (toDate instanceof Date && !isNaN(toDate.getTime())) {
1352
- conditions.push(`[createdAt] <= @toDate`);
1353
- paramMap[`toDate`] = toDate.toISOString();
1354
- }
1355
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1356
- let total = 0;
1357
- const tableName = this.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
1358
- const request = this.pool.request();
1359
- Object.entries(paramMap).forEach(([key, value]) => {
1360
- if (value instanceof Date) {
1361
- request.input(key, sql__default.default.DateTime, value);
1362
- } else {
1363
- request.input(key, value);
1364
- }
1365
- });
1366
- if (limit !== void 0 && offset !== void 0) {
1367
- const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
1368
- const countResult = await request.query(countQuery);
1369
- total = Number(countResult.recordset[0]?.count || 0);
1370
- }
1371
- let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
1372
- if (limit !== void 0 && offset !== void 0) {
1373
- query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
1374
- request.input("limit", limit);
1375
- request.input("offset", offset);
1376
- }
1377
- const result = await request.query(query);
1378
- const runs = (result.recordset || []).map((row) => this.parseWorkflowRun(row));
1379
- return { runs, total: total || runs.length };
1380
- } catch (error$1) {
1381
- throw new error.MastraError(
1382
- {
1383
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
1384
- domain: error.ErrorDomain.STORAGE,
1385
- category: error.ErrorCategory.THIRD_PARTY,
1386
- details: {
1387
- workflowName: workflowName || "all"
1388
- }
1389
- },
1390
- error$1
1391
- );
1392
- }
1393
- }
1394
- async getWorkflowRunById({
1395
- runId,
1396
- workflowName
1397
- }) {
1398
- try {
1399
- const conditions = [];
1400
- const paramMap = {};
1401
- if (runId) {
1402
- conditions.push(`[run_id] = @runId`);
1403
- paramMap["runId"] = runId;
1404
- }
1405
- if (workflowName) {
1406
- conditions.push(`[workflow_name] = @workflowName`);
1407
- paramMap["workflowName"] = workflowName;
1408
- }
1409
- const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1410
- const tableName = this.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
1411
- const query = `SELECT * FROM ${tableName} ${whereClause}`;
1412
- const request = this.pool.request();
1413
- Object.entries(paramMap).forEach(([key, value]) => request.input(key, value));
1414
- const result = await request.query(query);
1415
- if (!result.recordset || result.recordset.length === 0) {
1416
- return null;
1417
- }
1418
- return this.parseWorkflowRun(result.recordset[0]);
1419
- } catch (error$1) {
1420
- throw new error.MastraError(
1421
- {
1422
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
1423
- domain: error.ErrorDomain.STORAGE,
1424
- category: error.ErrorCategory.THIRD_PARTY,
1425
- details: {
1426
- runId,
1427
- workflowName: workflowName || ""
1428
- }
1429
- },
1430
- error$1
1431
- );
1432
- }
1433
- }
1434
891
  async updateMessages({
1435
892
  messages
1436
893
  }) {
@@ -1439,7 +896,7 @@ ${columns}
1439
896
  }
1440
897
  const messageIds = messages.map((m) => m.id);
1441
898
  const idParams = messageIds.map((_, i) => `@id${i}`).join(", ");
1442
- let selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${this.getTableName(storage.TABLE_MESSAGES)}`;
899
+ let selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}`;
1443
900
  if (idParams.length > 0) {
1444
901
  selectQuery += ` WHERE id IN (${idParams})`;
1445
902
  } else {
@@ -1496,7 +953,7 @@ ${columns}
1496
953
  }
1497
954
  }
1498
955
  if (setClauses.length > 0) {
1499
- const updateSql = `UPDATE ${this.getTableName(storage.TABLE_MESSAGES)} SET ${setClauses.join(", ")} WHERE id = @id`;
956
+ const updateSql = `UPDATE ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} SET ${setClauses.join(", ")} WHERE id = @id`;
1500
957
  await req.query(updateSql);
1501
958
  }
1502
959
  }
@@ -1505,7 +962,7 @@ ${columns}
1505
962
  const threadReq = transaction.request();
1506
963
  Array.from(threadIdsToUpdate).forEach((tid, i) => threadReq.input(`tid${i}`, tid));
1507
964
  threadReq.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
1508
- const threadSql = `UPDATE ${this.getTableName(storage.TABLE_THREADS)} SET updatedAt = @updatedAt WHERE id IN (${threadIdParams})`;
965
+ const threadSql = `UPDATE ${getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) })} SET updatedAt = @updatedAt WHERE id IN (${threadIdParams})`;
1509
966
  await threadReq.query(threadSql);
1510
967
  }
1511
968
  await transaction.commit();
@@ -1533,136 +990,97 @@ ${columns}
1533
990
  return message;
1534
991
  });
1535
992
  }
1536
- async close() {
1537
- if (this.pool) {
993
+ async deleteMessages(messageIds) {
994
+ if (!messageIds || messageIds.length === 0) {
995
+ return;
996
+ }
997
+ try {
998
+ const messageTableName = getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
999
+ const threadTableName = getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) });
1000
+ const placeholders = messageIds.map((_, idx) => `@p${idx + 1}`).join(",");
1001
+ const request = this.pool.request();
1002
+ messageIds.forEach((id, idx) => {
1003
+ request.input(`p${idx + 1}`, id);
1004
+ });
1005
+ const messages = await request.query(
1006
+ `SELECT DISTINCT [thread_id] FROM ${messageTableName} WHERE [id] IN (${placeholders})`
1007
+ );
1008
+ const threadIds = messages.recordset?.map((msg) => msg.thread_id).filter(Boolean) || [];
1009
+ const transaction = this.pool.transaction();
1010
+ await transaction.begin();
1538
1011
  try {
1539
- if (this.pool.connected) {
1540
- await this.pool.close();
1541
- } else if (this.pool.connecting) {
1542
- await this.pool.connect();
1543
- await this.pool.close();
1012
+ const deleteRequest = transaction.request();
1013
+ messageIds.forEach((id, idx) => {
1014
+ deleteRequest.input(`p${idx + 1}`, id);
1015
+ });
1016
+ await deleteRequest.query(`DELETE FROM ${messageTableName} WHERE [id] IN (${placeholders})`);
1017
+ if (threadIds.length > 0) {
1018
+ for (const threadId of threadIds) {
1019
+ const updateRequest = transaction.request();
1020
+ updateRequest.input("p1", threadId);
1021
+ await updateRequest.query(`UPDATE ${threadTableName} SET [updatedAt] = GETDATE() WHERE [id] = @p1`);
1022
+ }
1544
1023
  }
1545
- } catch (err) {
1546
- if (err.message && err.message.includes("Cannot close a pool while it is connecting")) ; else {
1547
- throw err;
1024
+ await transaction.commit();
1025
+ } catch (error) {
1026
+ try {
1027
+ await transaction.rollback();
1028
+ } catch {
1548
1029
  }
1030
+ throw error;
1549
1031
  }
1032
+ } catch (error$1) {
1033
+ throw new error.MastraError(
1034
+ {
1035
+ id: "MASTRA_STORAGE_MSSQL_STORE_DELETE_MESSAGES_FAILED",
1036
+ domain: error.ErrorDomain.STORAGE,
1037
+ category: error.ErrorCategory.THIRD_PARTY,
1038
+ details: { messageIds: messageIds.join(", ") }
1039
+ },
1040
+ error$1
1041
+ );
1550
1042
  }
1551
1043
  }
1552
- async getEvals(options = {}) {
1553
- const { agentName, type, page = 0, perPage = 100, dateRange } = options;
1554
- const fromDate = dateRange?.start;
1555
- const toDate = dateRange?.end;
1556
- const where = [];
1557
- const params = {};
1558
- if (agentName) {
1559
- where.push("agent_name = @agentName");
1560
- params["agentName"] = agentName;
1561
- }
1562
- if (type === "test") {
1563
- where.push("test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL");
1564
- } else if (type === "live") {
1565
- where.push("(test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)");
1566
- }
1567
- if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
1568
- where.push(`[created_at] >= @fromDate`);
1569
- params[`fromDate`] = fromDate.toISOString();
1570
- }
1571
- if (toDate instanceof Date && !isNaN(toDate.getTime())) {
1572
- where.push(`[created_at] <= @toDate`);
1573
- params[`toDate`] = toDate.toISOString();
1574
- }
1575
- const whereClause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
1576
- const tableName = this.getTableName(storage.TABLE_EVALS);
1577
- const offset = page * perPage;
1578
- const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
1579
- const dataQuery = `SELECT * FROM ${tableName} ${whereClause} ORDER BY seq_id DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
1044
+ async getResourceById({ resourceId }) {
1045
+ const tableName = getTableName({ indexName: storage.TABLE_RESOURCES, schemaName: getSchemaName(this.schema) });
1580
1046
  try {
1581
- const countReq = this.pool.request();
1582
- Object.entries(params).forEach(([key, value]) => {
1583
- if (value instanceof Date) {
1584
- countReq.input(key, sql__default.default.DateTime, value);
1585
- } else {
1586
- countReq.input(key, value);
1587
- }
1588
- });
1589
- const countResult = await countReq.query(countQuery);
1590
- const total = countResult.recordset[0]?.total || 0;
1591
- if (total === 0) {
1592
- return {
1593
- evals: [],
1594
- total: 0,
1595
- page,
1596
- perPage,
1597
- hasMore: false
1598
- };
1599
- }
1600
1047
  const req = this.pool.request();
1601
- Object.entries(params).forEach(([key, value]) => {
1602
- if (value instanceof Date) {
1603
- req.input(key, sql__default.default.DateTime, value);
1604
- } else {
1605
- req.input(key, value);
1606
- }
1607
- });
1608
- req.input("offset", offset);
1609
- req.input("perPage", perPage);
1610
- const result = await req.query(dataQuery);
1611
- const rows = result.recordset;
1048
+ req.input("resourceId", resourceId);
1049
+ const result = (await req.query(`SELECT * FROM ${tableName} WHERE id = @resourceId`)).recordset[0];
1050
+ if (!result) {
1051
+ return null;
1052
+ }
1612
1053
  return {
1613
- evals: rows?.map((row) => this.transformEvalRow(row)) ?? [],
1614
- total,
1615
- page,
1616
- perPage,
1617
- hasMore: offset + (rows?.length ?? 0) < total
1054
+ id: result.id,
1055
+ createdAt: result.createdAt,
1056
+ updatedAt: result.updatedAt,
1057
+ workingMemory: result.workingMemory,
1058
+ metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
1618
1059
  };
1619
1060
  } catch (error$1) {
1620
1061
  const mastraError = new error.MastraError(
1621
1062
  {
1622
- id: "MASTRA_STORAGE_MSSQL_STORE_GET_EVALS_FAILED",
1063
+ id: "MASTRA_STORAGE_MSSQL_GET_RESOURCE_BY_ID_FAILED",
1623
1064
  domain: error.ErrorDomain.STORAGE,
1624
1065
  category: error.ErrorCategory.THIRD_PARTY,
1625
- details: {
1626
- agentName: agentName || "all",
1627
- type: type || "all",
1628
- page,
1629
- perPage
1630
- }
1066
+ details: { resourceId }
1631
1067
  },
1632
1068
  error$1
1633
1069
  );
1634
1070
  this.logger?.error?.(mastraError.toString());
1635
- this.logger?.trackException(mastraError);
1071
+ this.logger?.trackException?.(mastraError);
1636
1072
  throw mastraError;
1637
1073
  }
1638
1074
  }
1639
1075
  async saveResource({ resource }) {
1640
- const tableName = this.getTableName(storage.TABLE_RESOURCES);
1641
- try {
1642
- const req = this.pool.request();
1643
- req.input("id", resource.id);
1644
- req.input("workingMemory", resource.workingMemory);
1645
- req.input("metadata", JSON.stringify(resource.metadata));
1646
- req.input("createdAt", resource.createdAt.toISOString());
1647
- req.input("updatedAt", resource.updatedAt.toISOString());
1648
- await req.query(
1649
- `INSERT INTO ${tableName} (id, workingMemory, metadata, createdAt, updatedAt) VALUES (@id, @workingMemory, @metadata, @createdAt, @updatedAt)`
1650
- );
1651
- return resource;
1652
- } catch (error$1) {
1653
- const mastraError = new error.MastraError(
1654
- {
1655
- id: "MASTRA_STORAGE_MSSQL_SAVE_RESOURCE_FAILED",
1656
- domain: error.ErrorDomain.STORAGE,
1657
- category: error.ErrorCategory.THIRD_PARTY,
1658
- details: { resourceId: resource.id }
1659
- },
1660
- error$1
1661
- );
1662
- this.logger?.error?.(mastraError.toString());
1663
- this.logger?.trackException(mastraError);
1664
- throw mastraError;
1665
- }
1076
+ await this.operations.insert({
1077
+ tableName: storage.TABLE_RESOURCES,
1078
+ record: {
1079
+ ...resource,
1080
+ metadata: resource.metadata
1081
+ }
1082
+ });
1083
+ return resource;
1666
1084
  }
1667
1085
  async updateResource({
1668
1086
  resourceId,
@@ -1690,7 +1108,7 @@ ${columns}
1690
1108
  },
1691
1109
  updatedAt: /* @__PURE__ */ new Date()
1692
1110
  };
1693
- const tableName = this.getTableName(storage.TABLE_RESOURCES);
1111
+ const tableName = getTableName({ indexName: storage.TABLE_RESOURCES, schemaName: getSchemaName(this.schema) });
1694
1112
  const updates = [];
1695
1113
  const req = this.pool.request();
1696
1114
  if (workingMemory !== void 0) {
@@ -1717,104 +1135,2517 @@ ${columns}
1717
1135
  error$1
1718
1136
  );
1719
1137
  this.logger?.error?.(mastraError.toString());
1720
- this.logger?.trackException(mastraError);
1138
+ this.logger?.trackException?.(mastraError);
1721
1139
  throw mastraError;
1722
1140
  }
1723
1141
  }
1724
- async getResourceById({ resourceId }) {
1725
- const tableName = this.getTableName(storage.TABLE_RESOURCES);
1142
+ };
1143
+ var ObservabilityMSSQL = class extends storage.ObservabilityStorage {
1144
+ pool;
1145
+ operations;
1146
+ schema;
1147
+ constructor({
1148
+ pool,
1149
+ operations,
1150
+ schema
1151
+ }) {
1152
+ super();
1153
+ this.pool = pool;
1154
+ this.operations = operations;
1155
+ this.schema = schema;
1156
+ }
1157
+ get aiTracingStrategy() {
1158
+ return {
1159
+ preferred: "batch-with-updates",
1160
+ supported: ["batch-with-updates", "insert-only"]
1161
+ };
1162
+ }
1163
+ async createAISpan(span) {
1726
1164
  try {
1727
- const req = this.pool.request();
1728
- req.input("resourceId", resourceId);
1729
- const result = (await req.query(`SELECT * FROM ${tableName} WHERE id = @resourceId`)).recordset[0];
1730
- if (!result) {
1165
+ const startedAt = span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt;
1166
+ const endedAt = span.endedAt instanceof Date ? span.endedAt.toISOString() : span.endedAt;
1167
+ const record = {
1168
+ ...span,
1169
+ startedAt,
1170
+ endedAt
1171
+ // Note: createdAt/updatedAt will be set by default values
1172
+ };
1173
+ return this.operations.insert({ tableName: storage.TABLE_AI_SPANS, record });
1174
+ } catch (error$1) {
1175
+ throw new error.MastraError(
1176
+ {
1177
+ id: "MSSQL_STORE_CREATE_AI_SPAN_FAILED",
1178
+ domain: error.ErrorDomain.STORAGE,
1179
+ category: error.ErrorCategory.USER,
1180
+ details: {
1181
+ spanId: span.spanId,
1182
+ traceId: span.traceId,
1183
+ spanType: span.spanType,
1184
+ spanName: span.name
1185
+ }
1186
+ },
1187
+ error$1
1188
+ );
1189
+ }
1190
+ }
1191
+ async getAITrace(traceId) {
1192
+ try {
1193
+ const tableName = getTableName({
1194
+ indexName: storage.TABLE_AI_SPANS,
1195
+ schemaName: getSchemaName(this.schema)
1196
+ });
1197
+ const request = this.pool.request();
1198
+ request.input("traceId", traceId);
1199
+ const result = await request.query(
1200
+ `SELECT
1201
+ [traceId], [spanId], [parentSpanId], [name], [scope], [spanType],
1202
+ [attributes], [metadata], [links], [input], [output], [error], [isEvent],
1203
+ [startedAt], [endedAt], [createdAt], [updatedAt]
1204
+ FROM ${tableName}
1205
+ WHERE [traceId] = @traceId
1206
+ ORDER BY [startedAt] DESC`
1207
+ );
1208
+ if (!result.recordset || result.recordset.length === 0) {
1731
1209
  return null;
1732
1210
  }
1733
1211
  return {
1734
- ...result,
1735
- workingMemory: typeof result.workingMemory === "object" ? JSON.stringify(result.workingMemory) : result.workingMemory,
1736
- metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
1212
+ traceId,
1213
+ spans: result.recordset.map(
1214
+ (span) => transformFromSqlRow({
1215
+ tableName: storage.TABLE_AI_SPANS,
1216
+ sqlRow: span
1217
+ })
1218
+ )
1737
1219
  };
1738
1220
  } catch (error$1) {
1739
- const mastraError = new error.MastraError(
1221
+ throw new error.MastraError(
1740
1222
  {
1741
- id: "MASTRA_STORAGE_MSSQL_GET_RESOURCE_BY_ID_FAILED",
1223
+ id: "MSSQL_STORE_GET_AI_TRACE_FAILED",
1742
1224
  domain: error.ErrorDomain.STORAGE,
1743
- category: error.ErrorCategory.THIRD_PARTY,
1744
- details: { resourceId }
1225
+ category: error.ErrorCategory.USER,
1226
+ details: {
1227
+ traceId
1228
+ }
1745
1229
  },
1746
1230
  error$1
1747
1231
  );
1748
- this.logger?.error?.(mastraError.toString());
1749
- this.logger?.trackException(mastraError);
1750
- throw mastraError;
1751
1232
  }
1752
1233
  }
1753
- async getScoreById({ id }) {
1754
- throw new error.MastraError({
1755
- id: "STORAGE_MONGODB_STORE_GET_SCORE_BY_ID_FAILED",
1756
- domain: error.ErrorDomain.STORAGE,
1757
- category: error.ErrorCategory.THIRD_PARTY,
1758
- details: { id },
1759
- text: "getScoreById is not implemented yet in MongoDBStore"
1760
- });
1761
- }
1762
- async saveScore(_score) {
1763
- throw new error.MastraError({
1764
- id: "STORAGE_MONGODB_STORE_SAVE_SCORE_FAILED",
1765
- domain: error.ErrorDomain.STORAGE,
1766
- category: error.ErrorCategory.THIRD_PARTY,
1767
- details: {},
1768
- text: "saveScore is not implemented yet in MongoDBStore"
1769
- });
1770
- }
1771
- async getScoresByScorerId({
1772
- scorerId,
1773
- pagination: _pagination,
1774
- entityId,
1775
- entityType
1234
+ async updateAISpan({
1235
+ spanId,
1236
+ traceId,
1237
+ updates
1776
1238
  }) {
1777
- throw new error.MastraError({
1778
- id: "STORAGE_MONGODB_STORE_GET_SCORES_BY_SCORER_ID_FAILED",
1779
- domain: error.ErrorDomain.STORAGE,
1780
- category: error.ErrorCategory.THIRD_PARTY,
1781
- details: { scorerId, entityId: entityId || "", entityType: entityType || "" },
1782
- text: "getScoresByScorerId is not implemented yet in MongoDBStore"
1783
- });
1239
+ try {
1240
+ const data = { ...updates };
1241
+ if (data.endedAt instanceof Date) {
1242
+ data.endedAt = data.endedAt.toISOString();
1243
+ }
1244
+ if (data.startedAt instanceof Date) {
1245
+ data.startedAt = data.startedAt.toISOString();
1246
+ }
1247
+ await this.operations.update({
1248
+ tableName: storage.TABLE_AI_SPANS,
1249
+ keys: { spanId, traceId },
1250
+ data
1251
+ });
1252
+ } catch (error$1) {
1253
+ throw new error.MastraError(
1254
+ {
1255
+ id: "MSSQL_STORE_UPDATE_AI_SPAN_FAILED",
1256
+ domain: error.ErrorDomain.STORAGE,
1257
+ category: error.ErrorCategory.USER,
1258
+ details: {
1259
+ spanId,
1260
+ traceId
1261
+ }
1262
+ },
1263
+ error$1
1264
+ );
1265
+ }
1784
1266
  }
1785
- async getScoresByRunId({
1786
- runId,
1787
- pagination: _pagination
1267
+ async getAITracesPaginated({
1268
+ filters,
1269
+ pagination
1788
1270
  }) {
1789
- throw new error.MastraError({
1790
- id: "STORAGE_MONGODB_STORE_GET_SCORES_BY_RUN_ID_FAILED",
1791
- domain: error.ErrorDomain.STORAGE,
1792
- category: error.ErrorCategory.THIRD_PARTY,
1793
- details: { runId },
1794
- text: "getScoresByRunId is not implemented yet in MongoDBStore"
1271
+ const page = pagination?.page ?? 0;
1272
+ const perPage = pagination?.perPage ?? 10;
1273
+ const { entityId, entityType, ...actualFilters } = filters || {};
1274
+ const filtersWithDateRange = {
1275
+ ...actualFilters,
1276
+ ...buildDateRangeFilter(pagination?.dateRange, "startedAt"),
1277
+ parentSpanId: null
1278
+ // Only get root spans for traces
1279
+ };
1280
+ const whereClause = prepareWhereClause(filtersWithDateRange);
1281
+ let actualWhereClause = whereClause.sql;
1282
+ const params = { ...whereClause.params };
1283
+ let currentParamIndex = Object.keys(params).length + 1;
1284
+ if (entityId && entityType) {
1285
+ let name = "";
1286
+ if (entityType === "workflow") {
1287
+ name = `workflow run: '${entityId}'`;
1288
+ } else if (entityType === "agent") {
1289
+ name = `agent run: '${entityId}'`;
1290
+ } else {
1291
+ const error$1 = new error.MastraError({
1292
+ id: "MSSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1293
+ domain: error.ErrorDomain.STORAGE,
1294
+ category: error.ErrorCategory.USER,
1295
+ details: {
1296
+ entityType
1297
+ },
1298
+ text: `Cannot filter by entity type: ${entityType}`
1299
+ });
1300
+ throw error$1;
1301
+ }
1302
+ const entityParam = `p${currentParamIndex++}`;
1303
+ if (actualWhereClause) {
1304
+ actualWhereClause += ` AND [name] = @${entityParam}`;
1305
+ } else {
1306
+ actualWhereClause = ` WHERE [name] = @${entityParam}`;
1307
+ }
1308
+ params[entityParam] = name;
1309
+ }
1310
+ const tableName = getTableName({
1311
+ indexName: storage.TABLE_AI_SPANS,
1312
+ schemaName: getSchemaName(this.schema)
1795
1313
  });
1314
+ try {
1315
+ const countRequest = this.pool.request();
1316
+ Object.entries(params).forEach(([key, value]) => {
1317
+ countRequest.input(key, value);
1318
+ });
1319
+ const countResult = await countRequest.query(
1320
+ `SELECT COUNT(*) as count FROM ${tableName}${actualWhereClause}`
1321
+ );
1322
+ const total = countResult.recordset[0]?.count ?? 0;
1323
+ if (total === 0) {
1324
+ return {
1325
+ pagination: {
1326
+ total: 0,
1327
+ page,
1328
+ perPage,
1329
+ hasMore: false
1330
+ },
1331
+ spans: []
1332
+ };
1333
+ }
1334
+ const dataRequest = this.pool.request();
1335
+ Object.entries(params).forEach(([key, value]) => {
1336
+ dataRequest.input(key, value);
1337
+ });
1338
+ dataRequest.input("offset", page * perPage);
1339
+ dataRequest.input("limit", perPage);
1340
+ const dataResult = await dataRequest.query(
1341
+ `SELECT * FROM ${tableName}${actualWhereClause} ORDER BY [startedAt] DESC OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`
1342
+ );
1343
+ const spans = dataResult.recordset.map(
1344
+ (row) => transformFromSqlRow({
1345
+ tableName: storage.TABLE_AI_SPANS,
1346
+ sqlRow: row
1347
+ })
1348
+ );
1349
+ return {
1350
+ pagination: {
1351
+ total,
1352
+ page,
1353
+ perPage,
1354
+ hasMore: (page + 1) * perPage < total
1355
+ },
1356
+ spans
1357
+ };
1358
+ } catch (error$1) {
1359
+ throw new error.MastraError(
1360
+ {
1361
+ id: "MSSQL_STORE_GET_AI_TRACES_PAGINATED_FAILED",
1362
+ domain: error.ErrorDomain.STORAGE,
1363
+ category: error.ErrorCategory.USER
1364
+ },
1365
+ error$1
1366
+ );
1367
+ }
1796
1368
  }
1797
- async getScoresByEntityId({
1798
- entityId,
1799
- entityType,
1800
- pagination: _pagination
1801
- }) {
1802
- throw new error.MastraError({
1803
- id: "STORAGE_MONGODB_STORE_GET_SCORES_BY_ENTITY_ID_FAILED",
1804
- domain: error.ErrorDomain.STORAGE,
1805
- category: error.ErrorCategory.THIRD_PARTY,
1806
- details: { entityId, entityType },
1807
- text: "getScoresByEntityId is not implemented yet in MongoDBStore"
1808
- });
1369
+ async batchCreateAISpans(args) {
1370
+ if (!args.records || args.records.length === 0) {
1371
+ return;
1372
+ }
1373
+ try {
1374
+ await this.operations.batchInsert({
1375
+ tableName: storage.TABLE_AI_SPANS,
1376
+ records: args.records.map((span) => ({
1377
+ ...span,
1378
+ startedAt: span.startedAt instanceof Date ? span.startedAt.toISOString() : span.startedAt,
1379
+ endedAt: span.endedAt instanceof Date ? span.endedAt.toISOString() : span.endedAt
1380
+ }))
1381
+ });
1382
+ } catch (error$1) {
1383
+ throw new error.MastraError(
1384
+ {
1385
+ id: "MSSQL_STORE_BATCH_CREATE_AI_SPANS_FAILED",
1386
+ domain: error.ErrorDomain.STORAGE,
1387
+ category: error.ErrorCategory.USER,
1388
+ details: {
1389
+ count: args.records.length
1390
+ }
1391
+ },
1392
+ error$1
1393
+ );
1394
+ }
1809
1395
  }
1810
- async dropTable({ tableName }) {
1811
- throw new error.MastraError({
1812
- id: "STORAGE_MONGODB_STORE_DROP_TABLE_FAILED",
1813
- domain: error.ErrorDomain.STORAGE,
1814
- category: error.ErrorCategory.THIRD_PARTY,
1815
- details: { tableName },
1816
- text: "dropTable is not implemented yet in MongoDBStore"
1817
- });
1396
+ async batchUpdateAISpans(args) {
1397
+ if (!args.records || args.records.length === 0) {
1398
+ return;
1399
+ }
1400
+ try {
1401
+ const updates = args.records.map(({ traceId, spanId, updates: data }) => {
1402
+ const processedData = { ...data };
1403
+ if (processedData.endedAt instanceof Date) {
1404
+ processedData.endedAt = processedData.endedAt.toISOString();
1405
+ }
1406
+ if (processedData.startedAt instanceof Date) {
1407
+ processedData.startedAt = processedData.startedAt.toISOString();
1408
+ }
1409
+ return {
1410
+ keys: { spanId, traceId },
1411
+ data: processedData
1412
+ };
1413
+ });
1414
+ await this.operations.batchUpdate({
1415
+ tableName: storage.TABLE_AI_SPANS,
1416
+ updates
1417
+ });
1418
+ } catch (error$1) {
1419
+ throw new error.MastraError(
1420
+ {
1421
+ id: "MSSQL_STORE_BATCH_UPDATE_AI_SPANS_FAILED",
1422
+ domain: error.ErrorDomain.STORAGE,
1423
+ category: error.ErrorCategory.USER,
1424
+ details: {
1425
+ count: args.records.length
1426
+ }
1427
+ },
1428
+ error$1
1429
+ );
1430
+ }
1431
+ }
1432
+ async batchDeleteAITraces(args) {
1433
+ if (!args.traceIds || args.traceIds.length === 0) {
1434
+ return;
1435
+ }
1436
+ try {
1437
+ const keys = args.traceIds.map((traceId) => ({ traceId }));
1438
+ await this.operations.batchDelete({
1439
+ tableName: storage.TABLE_AI_SPANS,
1440
+ keys
1441
+ });
1442
+ } catch (error$1) {
1443
+ throw new error.MastraError(
1444
+ {
1445
+ id: "MSSQL_STORE_BATCH_DELETE_AI_TRACES_FAILED",
1446
+ domain: error.ErrorDomain.STORAGE,
1447
+ category: error.ErrorCategory.USER,
1448
+ details: {
1449
+ count: args.traceIds.length
1450
+ }
1451
+ },
1452
+ error$1
1453
+ );
1454
+ }
1455
+ }
1456
+ };
1457
+ var StoreOperationsMSSQL = class extends storage.StoreOperations {
1458
+ pool;
1459
+ schemaName;
1460
+ setupSchemaPromise = null;
1461
+ schemaSetupComplete = void 0;
1462
+ getSqlType(type, isPrimaryKey = false, useLargeStorage = false) {
1463
+ switch (type) {
1464
+ case "text":
1465
+ if (useLargeStorage) {
1466
+ return "NVARCHAR(MAX)";
1467
+ }
1468
+ return isPrimaryKey ? "NVARCHAR(255)" : "NVARCHAR(400)";
1469
+ case "timestamp":
1470
+ return "DATETIME2(7)";
1471
+ case "uuid":
1472
+ return "UNIQUEIDENTIFIER";
1473
+ case "jsonb":
1474
+ return "NVARCHAR(MAX)";
1475
+ case "integer":
1476
+ return "INT";
1477
+ case "bigint":
1478
+ return "BIGINT";
1479
+ case "float":
1480
+ return "FLOAT";
1481
+ case "boolean":
1482
+ return "BIT";
1483
+ default:
1484
+ throw new error.MastraError({
1485
+ id: "MASTRA_STORAGE_MSSQL_STORE_TYPE_NOT_SUPPORTED",
1486
+ domain: error.ErrorDomain.STORAGE,
1487
+ category: error.ErrorCategory.THIRD_PARTY
1488
+ });
1489
+ }
1490
+ }
1491
+ constructor({ pool, schemaName }) {
1492
+ super();
1493
+ this.pool = pool;
1494
+ this.schemaName = schemaName;
1495
+ }
1496
+ async hasColumn(table, column) {
1497
+ const schema = this.schemaName || "dbo";
1498
+ const request = this.pool.request();
1499
+ request.input("schema", schema);
1500
+ request.input("table", table);
1501
+ request.input("column", column);
1502
+ request.input("columnLower", column.toLowerCase());
1503
+ const result = await request.query(
1504
+ `SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table AND (COLUMN_NAME = @column OR COLUMN_NAME = @columnLower)`
1505
+ );
1506
+ return result.recordset.length > 0;
1507
+ }
1508
+ async setupSchema() {
1509
+ if (!this.schemaName || this.schemaSetupComplete) {
1510
+ return;
1511
+ }
1512
+ if (!this.setupSchemaPromise) {
1513
+ this.setupSchemaPromise = (async () => {
1514
+ try {
1515
+ const checkRequest = this.pool.request();
1516
+ checkRequest.input("schemaName", this.schemaName);
1517
+ const checkResult = await checkRequest.query(`
1518
+ SELECT 1 AS found FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @schemaName
1519
+ `);
1520
+ const schemaExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
1521
+ if (!schemaExists) {
1522
+ try {
1523
+ await this.pool.request().query(`CREATE SCHEMA [${this.schemaName}]`);
1524
+ this.logger?.info?.(`Schema "${this.schemaName}" created successfully`);
1525
+ } catch (error) {
1526
+ this.logger?.error?.(`Failed to create schema "${this.schemaName}"`, { error });
1527
+ throw new Error(
1528
+ `Unable to create schema "${this.schemaName}". This requires CREATE privilege on the database. Either create the schema manually or grant CREATE privilege to the user.`
1529
+ );
1530
+ }
1531
+ }
1532
+ this.schemaSetupComplete = true;
1533
+ this.logger?.debug?.(`Schema "${this.schemaName}" is ready for use`);
1534
+ } catch (error) {
1535
+ this.schemaSetupComplete = void 0;
1536
+ this.setupSchemaPromise = null;
1537
+ throw error;
1538
+ } finally {
1539
+ this.setupSchemaPromise = null;
1540
+ }
1541
+ })();
1542
+ }
1543
+ await this.setupSchemaPromise;
1544
+ }
1545
+ async insert({
1546
+ tableName,
1547
+ record,
1548
+ transaction
1549
+ }) {
1550
+ try {
1551
+ const columns = Object.keys(record);
1552
+ const parsedColumns = columns.map((col) => utils.parseSqlIdentifier(col, "column name"));
1553
+ const paramNames = columns.map((_, i) => `@param${i}`);
1554
+ const insertSql = `INSERT INTO ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} (${parsedColumns.map((c) => `[${c}]`).join(", ")}) VALUES (${paramNames.join(", ")})`;
1555
+ const request = transaction ? transaction.request() : this.pool.request();
1556
+ columns.forEach((col, i) => {
1557
+ const value = record[col];
1558
+ const preparedValue = this.prepareValue(value, col, tableName);
1559
+ if (preparedValue instanceof Date) {
1560
+ request.input(`param${i}`, sql3__default.default.DateTime2, preparedValue);
1561
+ } else if (preparedValue === null || preparedValue === void 0) {
1562
+ request.input(`param${i}`, this.getMssqlType(tableName, col), null);
1563
+ } else {
1564
+ request.input(`param${i}`, preparedValue);
1565
+ }
1566
+ });
1567
+ await request.query(insertSql);
1568
+ } catch (error$1) {
1569
+ throw new error.MastraError(
1570
+ {
1571
+ id: "MASTRA_STORAGE_MSSQL_STORE_INSERT_FAILED",
1572
+ domain: error.ErrorDomain.STORAGE,
1573
+ category: error.ErrorCategory.THIRD_PARTY,
1574
+ details: {
1575
+ tableName
1576
+ }
1577
+ },
1578
+ error$1
1579
+ );
1580
+ }
1581
+ }
1582
+ async clearTable({ tableName }) {
1583
+ const fullTableName = getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) });
1584
+ try {
1585
+ try {
1586
+ await this.pool.request().query(`TRUNCATE TABLE ${fullTableName}`);
1587
+ } catch (truncateError) {
1588
+ if (truncateError?.number === 4712) {
1589
+ await this.pool.request().query(`DELETE FROM ${fullTableName}`);
1590
+ } else {
1591
+ throw truncateError;
1592
+ }
1593
+ }
1594
+ } catch (error$1) {
1595
+ throw new error.MastraError(
1596
+ {
1597
+ id: "MASTRA_STORAGE_MSSQL_STORE_CLEAR_TABLE_FAILED",
1598
+ domain: error.ErrorDomain.STORAGE,
1599
+ category: error.ErrorCategory.THIRD_PARTY,
1600
+ details: {
1601
+ tableName
1602
+ }
1603
+ },
1604
+ error$1
1605
+ );
1606
+ }
1607
+ }
1608
+ getDefaultValue(type) {
1609
+ switch (type) {
1610
+ case "timestamp":
1611
+ return "DEFAULT SYSUTCDATETIME()";
1612
+ case "jsonb":
1613
+ return "DEFAULT N'{}'";
1614
+ case "boolean":
1615
+ return "DEFAULT 0";
1616
+ default:
1617
+ return super.getDefaultValue(type);
1618
+ }
1619
+ }
1620
+ async createTable({
1621
+ tableName,
1622
+ schema
1623
+ }) {
1624
+ try {
1625
+ const uniqueConstraintColumns = tableName === storage.TABLE_WORKFLOW_SNAPSHOT ? ["workflow_name", "run_id"] : [];
1626
+ const largeDataColumns = [
1627
+ "workingMemory",
1628
+ "snapshot",
1629
+ "metadata",
1630
+ "content",
1631
+ // messages.content - can be very long conversation content
1632
+ "input",
1633
+ // evals.input - test input data
1634
+ "output",
1635
+ // evals.output - test output data
1636
+ "instructions",
1637
+ // evals.instructions - evaluation instructions
1638
+ "other"
1639
+ // traces.other - additional trace data
1640
+ ];
1641
+ const columns = Object.entries(schema).map(([name, def]) => {
1642
+ const parsedName = utils.parseSqlIdentifier(name, "column name");
1643
+ const constraints = [];
1644
+ if (def.primaryKey) constraints.push("PRIMARY KEY");
1645
+ if (!def.nullable) constraints.push("NOT NULL");
1646
+ const isIndexed = !!def.primaryKey || uniqueConstraintColumns.includes(name);
1647
+ const useLargeStorage = largeDataColumns.includes(name);
1648
+ return `[${parsedName}] ${this.getSqlType(def.type, isIndexed, useLargeStorage)} ${constraints.join(" ")}`.trim();
1649
+ }).join(",\n");
1650
+ if (this.schemaName) {
1651
+ await this.setupSchema();
1652
+ }
1653
+ const checkTableRequest = this.pool.request();
1654
+ checkTableRequest.input(
1655
+ "tableName",
1656
+ getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) }).replace(/[[\]]/g, "").split(".").pop()
1657
+ );
1658
+ const checkTableSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName`;
1659
+ checkTableRequest.input("schema", this.schemaName || "dbo");
1660
+ const checkTableResult = await checkTableRequest.query(checkTableSql);
1661
+ const tableExists = Array.isArray(checkTableResult.recordset) && checkTableResult.recordset.length > 0;
1662
+ if (!tableExists) {
1663
+ const createSql = `CREATE TABLE ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} (
1664
+ ${columns}
1665
+ )`;
1666
+ await this.pool.request().query(createSql);
1667
+ }
1668
+ const columnCheckSql = `
1669
+ SELECT 1 AS found
1670
+ FROM INFORMATION_SCHEMA.COLUMNS
1671
+ WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = 'seq_id'
1672
+ `;
1673
+ const checkColumnRequest = this.pool.request();
1674
+ checkColumnRequest.input("schema", this.schemaName || "dbo");
1675
+ checkColumnRequest.input(
1676
+ "tableName",
1677
+ getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) }).replace(/[[\]]/g, "").split(".").pop()
1678
+ );
1679
+ const columnResult = await checkColumnRequest.query(columnCheckSql);
1680
+ const columnExists = Array.isArray(columnResult.recordset) && columnResult.recordset.length > 0;
1681
+ if (!columnExists) {
1682
+ const alterSql = `ALTER TABLE ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} ADD seq_id BIGINT IDENTITY(1,1)`;
1683
+ await this.pool.request().query(alterSql);
1684
+ }
1685
+ if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
1686
+ const constraintName = "mastra_workflow_snapshot_workflow_name_run_id_key";
1687
+ const checkConstraintSql = `SELECT 1 AS found FROM sys.key_constraints WHERE name = @constraintName`;
1688
+ const checkConstraintRequest = this.pool.request();
1689
+ checkConstraintRequest.input("constraintName", constraintName);
1690
+ const constraintResult = await checkConstraintRequest.query(checkConstraintSql);
1691
+ const constraintExists = Array.isArray(constraintResult.recordset) && constraintResult.recordset.length > 0;
1692
+ if (!constraintExists) {
1693
+ const addConstraintSql = `ALTER TABLE ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} ADD CONSTRAINT ${constraintName} UNIQUE ([workflow_name], [run_id])`;
1694
+ await this.pool.request().query(addConstraintSql);
1695
+ }
1696
+ }
1697
+ } catch (error$1) {
1698
+ throw new error.MastraError(
1699
+ {
1700
+ id: "MASTRA_STORAGE_MSSQL_STORE_CREATE_TABLE_FAILED",
1701
+ domain: error.ErrorDomain.STORAGE,
1702
+ category: error.ErrorCategory.THIRD_PARTY,
1703
+ details: {
1704
+ tableName
1705
+ }
1706
+ },
1707
+ error$1
1708
+ );
1709
+ }
1710
+ }
1711
+ /**
1712
+ * Alters table schema to add columns if they don't exist
1713
+ * @param tableName Name of the table
1714
+ * @param schema Schema of the table
1715
+ * @param ifNotExists Array of column names to add if they don't exist
1716
+ */
1717
+ async alterTable({
1718
+ tableName,
1719
+ schema,
1720
+ ifNotExists
1721
+ }) {
1722
+ const fullTableName = getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) });
1723
+ try {
1724
+ for (const columnName of ifNotExists) {
1725
+ if (schema[columnName]) {
1726
+ const columnCheckRequest = this.pool.request();
1727
+ columnCheckRequest.input("tableName", fullTableName.replace(/[[\]]/g, "").split(".").pop());
1728
+ columnCheckRequest.input("columnName", columnName);
1729
+ columnCheckRequest.input("schema", this.schemaName || "dbo");
1730
+ const checkSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = @columnName`;
1731
+ const checkResult = await columnCheckRequest.query(checkSql);
1732
+ const columnExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
1733
+ if (!columnExists) {
1734
+ const columnDef = schema[columnName];
1735
+ const largeDataColumns = [
1736
+ "workingMemory",
1737
+ "snapshot",
1738
+ "metadata",
1739
+ "content",
1740
+ "input",
1741
+ "output",
1742
+ "instructions",
1743
+ "other"
1744
+ ];
1745
+ const useLargeStorage = largeDataColumns.includes(columnName);
1746
+ const isIndexed = !!columnDef.primaryKey;
1747
+ const sqlType = this.getSqlType(columnDef.type, isIndexed, useLargeStorage);
1748
+ const nullable = columnDef.nullable === false ? "NOT NULL" : "";
1749
+ const defaultValue = columnDef.nullable === false ? this.getDefaultValue(columnDef.type) : "";
1750
+ const parsedColumnName = utils.parseSqlIdentifier(columnName, "column name");
1751
+ const alterSql = `ALTER TABLE ${fullTableName} ADD [${parsedColumnName}] ${sqlType} ${nullable} ${defaultValue}`.trim();
1752
+ await this.pool.request().query(alterSql);
1753
+ this.logger?.debug?.(`Ensured column ${parsedColumnName} exists in table ${fullTableName}`);
1754
+ }
1755
+ }
1756
+ }
1757
+ } catch (error$1) {
1758
+ throw new error.MastraError(
1759
+ {
1760
+ id: "MASTRA_STORAGE_MSSQL_STORE_ALTER_TABLE_FAILED",
1761
+ domain: error.ErrorDomain.STORAGE,
1762
+ category: error.ErrorCategory.THIRD_PARTY,
1763
+ details: {
1764
+ tableName
1765
+ }
1766
+ },
1767
+ error$1
1768
+ );
1769
+ }
1770
+ }
1771
+ async load({ tableName, keys }) {
1772
+ try {
1773
+ const keyEntries = Object.entries(keys).map(([key, value]) => [utils.parseSqlIdentifier(key, "column name"), value]);
1774
+ const conditions = keyEntries.map(([key], i) => `[${key}] = @param${i}`).join(" AND ");
1775
+ const sql7 = `SELECT * FROM ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} WHERE ${conditions}`;
1776
+ const request = this.pool.request();
1777
+ keyEntries.forEach(([key, value], i) => {
1778
+ const preparedValue = this.prepareValue(value, key, tableName);
1779
+ if (preparedValue === null || preparedValue === void 0) {
1780
+ request.input(`param${i}`, this.getMssqlType(tableName, key), null);
1781
+ } else {
1782
+ request.input(`param${i}`, preparedValue);
1783
+ }
1784
+ });
1785
+ const resultSet = await request.query(sql7);
1786
+ const result = resultSet.recordset[0] || null;
1787
+ if (!result) {
1788
+ return null;
1789
+ }
1790
+ if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
1791
+ const snapshot = result;
1792
+ if (typeof snapshot.snapshot === "string") {
1793
+ snapshot.snapshot = JSON.parse(snapshot.snapshot);
1794
+ }
1795
+ return snapshot;
1796
+ }
1797
+ return result;
1798
+ } catch (error$1) {
1799
+ throw new error.MastraError(
1800
+ {
1801
+ id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_FAILED",
1802
+ domain: error.ErrorDomain.STORAGE,
1803
+ category: error.ErrorCategory.THIRD_PARTY,
1804
+ details: {
1805
+ tableName
1806
+ }
1807
+ },
1808
+ error$1
1809
+ );
1810
+ }
1811
+ }
1812
+ async batchInsert({ tableName, records }) {
1813
+ const transaction = this.pool.transaction();
1814
+ try {
1815
+ await transaction.begin();
1816
+ for (const record of records) {
1817
+ await this.insert({ tableName, record, transaction });
1818
+ }
1819
+ await transaction.commit();
1820
+ } catch (error$1) {
1821
+ await transaction.rollback();
1822
+ throw new error.MastraError(
1823
+ {
1824
+ id: "MASTRA_STORAGE_MSSQL_STORE_BATCH_INSERT_FAILED",
1825
+ domain: error.ErrorDomain.STORAGE,
1826
+ category: error.ErrorCategory.THIRD_PARTY,
1827
+ details: {
1828
+ tableName,
1829
+ numberOfRecords: records.length
1830
+ }
1831
+ },
1832
+ error$1
1833
+ );
1834
+ }
1835
+ }
1836
+ async dropTable({ tableName }) {
1837
+ try {
1838
+ const tableNameWithSchema = getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) });
1839
+ await this.pool.request().query(`DROP TABLE IF EXISTS ${tableNameWithSchema}`);
1840
+ } catch (error$1) {
1841
+ throw new error.MastraError(
1842
+ {
1843
+ id: "MASTRA_STORAGE_MSSQL_STORE_DROP_TABLE_FAILED",
1844
+ domain: error.ErrorDomain.STORAGE,
1845
+ category: error.ErrorCategory.THIRD_PARTY,
1846
+ details: {
1847
+ tableName
1848
+ }
1849
+ },
1850
+ error$1
1851
+ );
1852
+ }
1853
+ }
1854
+ /**
1855
+ * Prepares a value for database operations, handling Date objects and JSON serialization
1856
+ */
1857
+ prepareValue(value, columnName, tableName) {
1858
+ if (value === null || value === void 0) {
1859
+ return value;
1860
+ }
1861
+ if (value instanceof Date) {
1862
+ return value;
1863
+ }
1864
+ const schema = storage.TABLE_SCHEMAS[tableName];
1865
+ const columnSchema = schema?.[columnName];
1866
+ if (columnSchema?.type === "boolean") {
1867
+ return value ? 1 : 0;
1868
+ }
1869
+ if (columnSchema?.type === "jsonb") {
1870
+ if (typeof value === "string") {
1871
+ const trimmed = value.trim();
1872
+ if (trimmed.length > 0) {
1873
+ try {
1874
+ JSON.parse(trimmed);
1875
+ return trimmed;
1876
+ } catch {
1877
+ }
1878
+ }
1879
+ return JSON.stringify(value);
1880
+ }
1881
+ if (typeof value === "bigint") {
1882
+ return value.toString();
1883
+ }
1884
+ return JSON.stringify(value);
1885
+ }
1886
+ if (typeof value === "object") {
1887
+ return JSON.stringify(value);
1888
+ }
1889
+ return value;
1890
+ }
1891
+ /**
1892
+ * Maps TABLE_SCHEMAS types to mssql param types (used when value is null)
1893
+ */
1894
+ getMssqlType(tableName, columnName) {
1895
+ const col = storage.TABLE_SCHEMAS[tableName]?.[columnName];
1896
+ switch (col?.type) {
1897
+ case "text":
1898
+ return sql3__default.default.NVarChar;
1899
+ case "timestamp":
1900
+ return sql3__default.default.DateTime2;
1901
+ case "uuid":
1902
+ return sql3__default.default.UniqueIdentifier;
1903
+ case "jsonb":
1904
+ return sql3__default.default.NVarChar;
1905
+ case "integer":
1906
+ return sql3__default.default.Int;
1907
+ case "bigint":
1908
+ return sql3__default.default.BigInt;
1909
+ case "float":
1910
+ return sql3__default.default.Float;
1911
+ case "boolean":
1912
+ return sql3__default.default.Bit;
1913
+ default:
1914
+ return sql3__default.default.NVarChar;
1915
+ }
1916
+ }
1917
+ /**
1918
+ * Update a single record in the database
1919
+ */
1920
+ async update({
1921
+ tableName,
1922
+ keys,
1923
+ data,
1924
+ transaction
1925
+ }) {
1926
+ try {
1927
+ if (!data || Object.keys(data).length === 0) {
1928
+ throw new error.MastraError({
1929
+ id: "MASTRA_STORAGE_MSSQL_UPDATE_EMPTY_DATA",
1930
+ domain: error.ErrorDomain.STORAGE,
1931
+ category: error.ErrorCategory.USER,
1932
+ text: "Cannot update with empty data payload"
1933
+ });
1934
+ }
1935
+ if (!keys || Object.keys(keys).length === 0) {
1936
+ throw new error.MastraError({
1937
+ id: "MASTRA_STORAGE_MSSQL_UPDATE_EMPTY_KEYS",
1938
+ domain: error.ErrorDomain.STORAGE,
1939
+ category: error.ErrorCategory.USER,
1940
+ text: "Cannot update without keys to identify records"
1941
+ });
1942
+ }
1943
+ const setClauses = [];
1944
+ const request = transaction ? transaction.request() : this.pool.request();
1945
+ let paramIndex = 0;
1946
+ Object.entries(data).forEach(([key, value]) => {
1947
+ const parsedKey = utils.parseSqlIdentifier(key, "column name");
1948
+ const paramName = `set${paramIndex++}`;
1949
+ setClauses.push(`[${parsedKey}] = @${paramName}`);
1950
+ const preparedValue = this.prepareValue(value, key, tableName);
1951
+ if (preparedValue === null || preparedValue === void 0) {
1952
+ request.input(paramName, this.getMssqlType(tableName, key), null);
1953
+ } else {
1954
+ request.input(paramName, preparedValue);
1955
+ }
1956
+ });
1957
+ const whereConditions = [];
1958
+ Object.entries(keys).forEach(([key, value]) => {
1959
+ const parsedKey = utils.parseSqlIdentifier(key, "column name");
1960
+ const paramName = `where${paramIndex++}`;
1961
+ whereConditions.push(`[${parsedKey}] = @${paramName}`);
1962
+ const preparedValue = this.prepareValue(value, key, tableName);
1963
+ if (preparedValue === null || preparedValue === void 0) {
1964
+ request.input(paramName, this.getMssqlType(tableName, key), null);
1965
+ } else {
1966
+ request.input(paramName, preparedValue);
1967
+ }
1968
+ });
1969
+ const tableName_ = getTableName({
1970
+ indexName: tableName,
1971
+ schemaName: getSchemaName(this.schemaName)
1972
+ });
1973
+ const updateSql = `UPDATE ${tableName_} SET ${setClauses.join(", ")} WHERE ${whereConditions.join(" AND ")}`;
1974
+ await request.query(updateSql);
1975
+ } catch (error$1) {
1976
+ throw new error.MastraError(
1977
+ {
1978
+ id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_FAILED",
1979
+ domain: error.ErrorDomain.STORAGE,
1980
+ category: error.ErrorCategory.THIRD_PARTY,
1981
+ details: {
1982
+ tableName
1983
+ }
1984
+ },
1985
+ error$1
1986
+ );
1987
+ }
1988
+ }
1989
+ /**
1990
+ * Update multiple records in a single batch transaction
1991
+ */
1992
+ async batchUpdate({
1993
+ tableName,
1994
+ updates
1995
+ }) {
1996
+ const transaction = this.pool.transaction();
1997
+ try {
1998
+ await transaction.begin();
1999
+ for (const { keys, data } of updates) {
2000
+ await this.update({ tableName, keys, data, transaction });
2001
+ }
2002
+ await transaction.commit();
2003
+ } catch (error$1) {
2004
+ await transaction.rollback();
2005
+ throw new error.MastraError(
2006
+ {
2007
+ id: "MASTRA_STORAGE_MSSQL_STORE_BATCH_UPDATE_FAILED",
2008
+ domain: error.ErrorDomain.STORAGE,
2009
+ category: error.ErrorCategory.THIRD_PARTY,
2010
+ details: {
2011
+ tableName,
2012
+ numberOfRecords: updates.length
2013
+ }
2014
+ },
2015
+ error$1
2016
+ );
2017
+ }
2018
+ }
2019
+ /**
2020
+ * Delete multiple records by keys
2021
+ */
2022
+ async batchDelete({ tableName, keys }) {
2023
+ if (keys.length === 0) {
2024
+ return;
2025
+ }
2026
+ const tableName_ = getTableName({
2027
+ indexName: tableName,
2028
+ schemaName: getSchemaName(this.schemaName)
2029
+ });
2030
+ const transaction = this.pool.transaction();
2031
+ try {
2032
+ await transaction.begin();
2033
+ for (const keySet of keys) {
2034
+ const conditions = [];
2035
+ const request = transaction.request();
2036
+ let paramIndex = 0;
2037
+ Object.entries(keySet).forEach(([key, value]) => {
2038
+ const parsedKey = utils.parseSqlIdentifier(key, "column name");
2039
+ const paramName = `p${paramIndex++}`;
2040
+ conditions.push(`[${parsedKey}] = @${paramName}`);
2041
+ const preparedValue = this.prepareValue(value, key, tableName);
2042
+ if (preparedValue === null || preparedValue === void 0) {
2043
+ request.input(paramName, this.getMssqlType(tableName, key), null);
2044
+ } else {
2045
+ request.input(paramName, preparedValue);
2046
+ }
2047
+ });
2048
+ const deleteSql = `DELETE FROM ${tableName_} WHERE ${conditions.join(" AND ")}`;
2049
+ await request.query(deleteSql);
2050
+ }
2051
+ await transaction.commit();
2052
+ } catch (error$1) {
2053
+ await transaction.rollback();
2054
+ throw new error.MastraError(
2055
+ {
2056
+ id: "MASTRA_STORAGE_MSSQL_STORE_BATCH_DELETE_FAILED",
2057
+ domain: error.ErrorDomain.STORAGE,
2058
+ category: error.ErrorCategory.THIRD_PARTY,
2059
+ details: {
2060
+ tableName,
2061
+ numberOfRecords: keys.length
2062
+ }
2063
+ },
2064
+ error$1
2065
+ );
2066
+ }
2067
+ }
2068
+ /**
2069
+ * Create a new index on a table
2070
+ */
2071
+ async createIndex(options) {
2072
+ try {
2073
+ const { name, table, columns, unique = false, where } = options;
2074
+ const schemaName = this.schemaName || "dbo";
2075
+ const fullTableName = getTableName({
2076
+ indexName: table,
2077
+ schemaName: getSchemaName(this.schemaName)
2078
+ });
2079
+ const indexNameSafe = utils.parseSqlIdentifier(name, "index name");
2080
+ const checkRequest = this.pool.request();
2081
+ checkRequest.input("indexName", indexNameSafe);
2082
+ checkRequest.input("schemaName", schemaName);
2083
+ checkRequest.input("tableName", table);
2084
+ const indexExists = await checkRequest.query(`
2085
+ SELECT 1 as found
2086
+ FROM sys.indexes i
2087
+ INNER JOIN sys.tables t ON i.object_id = t.object_id
2088
+ INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
2089
+ WHERE i.name = @indexName
2090
+ AND s.name = @schemaName
2091
+ AND t.name = @tableName
2092
+ `);
2093
+ if (indexExists.recordset && indexExists.recordset.length > 0) {
2094
+ return;
2095
+ }
2096
+ const uniqueStr = unique ? "UNIQUE " : "";
2097
+ const columnsStr = columns.map((col) => {
2098
+ if (col.includes(" DESC") || col.includes(" ASC")) {
2099
+ const [colName, ...modifiers] = col.split(" ");
2100
+ if (!colName) {
2101
+ throw new Error(`Invalid column specification: ${col}`);
2102
+ }
2103
+ return `[${utils.parseSqlIdentifier(colName, "column name")}] ${modifiers.join(" ")}`;
2104
+ }
2105
+ return `[${utils.parseSqlIdentifier(col, "column name")}]`;
2106
+ }).join(", ");
2107
+ const whereStr = where ? ` WHERE ${where}` : "";
2108
+ const createIndexSql = `CREATE ${uniqueStr}INDEX [${indexNameSafe}] ON ${fullTableName} (${columnsStr})${whereStr}`;
2109
+ await this.pool.request().query(createIndexSql);
2110
+ } catch (error$1) {
2111
+ throw new error.MastraError(
2112
+ {
2113
+ id: "MASTRA_STORAGE_MSSQL_INDEX_CREATE_FAILED",
2114
+ domain: error.ErrorDomain.STORAGE,
2115
+ category: error.ErrorCategory.THIRD_PARTY,
2116
+ details: {
2117
+ indexName: options.name,
2118
+ tableName: options.table
2119
+ }
2120
+ },
2121
+ error$1
2122
+ );
2123
+ }
2124
+ }
2125
+ /**
2126
+ * Drop an existing index
2127
+ */
2128
+ async dropIndex(indexName) {
2129
+ try {
2130
+ const schemaName = this.schemaName || "dbo";
2131
+ const indexNameSafe = utils.parseSqlIdentifier(indexName, "index name");
2132
+ const checkRequest = this.pool.request();
2133
+ checkRequest.input("indexName", indexNameSafe);
2134
+ checkRequest.input("schemaName", schemaName);
2135
+ const result = await checkRequest.query(`
2136
+ SELECT t.name as table_name
2137
+ FROM sys.indexes i
2138
+ INNER JOIN sys.tables t ON i.object_id = t.object_id
2139
+ INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
2140
+ WHERE i.name = @indexName
2141
+ AND s.name = @schemaName
2142
+ `);
2143
+ if (!result.recordset || result.recordset.length === 0) {
2144
+ return;
2145
+ }
2146
+ if (result.recordset.length > 1) {
2147
+ const tables = result.recordset.map((r) => r.table_name).join(", ");
2148
+ throw new error.MastraError({
2149
+ id: "MASTRA_STORAGE_MSSQL_INDEX_AMBIGUOUS",
2150
+ domain: error.ErrorDomain.STORAGE,
2151
+ category: error.ErrorCategory.USER,
2152
+ text: `Index "${indexNameSafe}" exists on multiple tables (${tables}) in schema "${schemaName}". Please drop indexes manually or ensure unique index names.`
2153
+ });
2154
+ }
2155
+ const tableName = result.recordset[0].table_name;
2156
+ const fullTableName = getTableName({
2157
+ indexName: tableName,
2158
+ schemaName: getSchemaName(this.schemaName)
2159
+ });
2160
+ const dropSql = `DROP INDEX [${indexNameSafe}] ON ${fullTableName}`;
2161
+ await this.pool.request().query(dropSql);
2162
+ } catch (error$1) {
2163
+ throw new error.MastraError(
2164
+ {
2165
+ id: "MASTRA_STORAGE_MSSQL_INDEX_DROP_FAILED",
2166
+ domain: error.ErrorDomain.STORAGE,
2167
+ category: error.ErrorCategory.THIRD_PARTY,
2168
+ details: {
2169
+ indexName
2170
+ }
2171
+ },
2172
+ error$1
2173
+ );
2174
+ }
2175
+ }
2176
+ /**
2177
+ * List indexes for a specific table or all tables
2178
+ */
2179
+ async listIndexes(tableName) {
2180
+ try {
2181
+ const schemaName = this.schemaName || "dbo";
2182
+ let query;
2183
+ const request = this.pool.request();
2184
+ request.input("schemaName", schemaName);
2185
+ if (tableName) {
2186
+ query = `
2187
+ SELECT
2188
+ i.name as name,
2189
+ o.name as [table],
2190
+ i.is_unique as is_unique,
2191
+ CAST(SUM(s.used_page_count) * 8 / 1024.0 AS VARCHAR(50)) + ' MB' as size
2192
+ FROM sys.indexes i
2193
+ INNER JOIN sys.objects o ON i.object_id = o.object_id
2194
+ INNER JOIN sys.schemas sch ON o.schema_id = sch.schema_id
2195
+ LEFT JOIN sys.dm_db_partition_stats s ON i.object_id = s.object_id AND i.index_id = s.index_id
2196
+ WHERE sch.name = @schemaName
2197
+ AND o.name = @tableName
2198
+ AND i.name IS NOT NULL
2199
+ GROUP BY i.name, o.name, i.is_unique
2200
+ `;
2201
+ request.input("tableName", tableName);
2202
+ } else {
2203
+ query = `
2204
+ SELECT
2205
+ i.name as name,
2206
+ o.name as [table],
2207
+ i.is_unique as is_unique,
2208
+ CAST(SUM(s.used_page_count) * 8 / 1024.0 AS VARCHAR(50)) + ' MB' as size
2209
+ FROM sys.indexes i
2210
+ INNER JOIN sys.objects o ON i.object_id = o.object_id
2211
+ INNER JOIN sys.schemas sch ON o.schema_id = sch.schema_id
2212
+ LEFT JOIN sys.dm_db_partition_stats s ON i.object_id = s.object_id AND i.index_id = s.index_id
2213
+ WHERE sch.name = @schemaName
2214
+ AND i.name IS NOT NULL
2215
+ GROUP BY i.name, o.name, i.is_unique
2216
+ `;
2217
+ }
2218
+ const result = await request.query(query);
2219
+ const indexes = [];
2220
+ for (const row of result.recordset) {
2221
+ const colRequest = this.pool.request();
2222
+ colRequest.input("indexName", row.name);
2223
+ colRequest.input("schemaName", schemaName);
2224
+ const colResult = await colRequest.query(`
2225
+ SELECT c.name as column_name
2226
+ FROM sys.indexes i
2227
+ INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
2228
+ INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
2229
+ INNER JOIN sys.objects o ON i.object_id = o.object_id
2230
+ INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
2231
+ WHERE i.name = @indexName
2232
+ AND s.name = @schemaName
2233
+ ORDER BY ic.key_ordinal
2234
+ `);
2235
+ indexes.push({
2236
+ name: row.name,
2237
+ table: row.table,
2238
+ columns: colResult.recordset.map((c) => c.column_name),
2239
+ unique: row.is_unique || false,
2240
+ size: row.size || "0 MB",
2241
+ definition: ""
2242
+ // MSSQL doesn't store definition like PG
2243
+ });
2244
+ }
2245
+ return indexes;
2246
+ } catch (error$1) {
2247
+ throw new error.MastraError(
2248
+ {
2249
+ id: "MASTRA_STORAGE_MSSQL_INDEX_LIST_FAILED",
2250
+ domain: error.ErrorDomain.STORAGE,
2251
+ category: error.ErrorCategory.THIRD_PARTY,
2252
+ details: tableName ? {
2253
+ tableName
2254
+ } : {}
2255
+ },
2256
+ error$1
2257
+ );
2258
+ }
2259
+ }
2260
+ /**
2261
+ * Get detailed statistics for a specific index
2262
+ */
2263
+ async describeIndex(indexName) {
2264
+ try {
2265
+ const schemaName = this.schemaName || "dbo";
2266
+ const request = this.pool.request();
2267
+ request.input("indexName", indexName);
2268
+ request.input("schemaName", schemaName);
2269
+ const query = `
2270
+ SELECT
2271
+ i.name as name,
2272
+ o.name as [table],
2273
+ i.is_unique as is_unique,
2274
+ CAST(SUM(s.used_page_count) * 8 / 1024.0 AS VARCHAR(50)) + ' MB' as size,
2275
+ i.type_desc as method,
2276
+ ISNULL(us.user_scans, 0) as scans,
2277
+ ISNULL(us.user_seeks + us.user_scans, 0) as tuples_read,
2278
+ ISNULL(us.user_lookups, 0) as tuples_fetched
2279
+ FROM sys.indexes i
2280
+ INNER JOIN sys.objects o ON i.object_id = o.object_id
2281
+ INNER JOIN sys.schemas sch ON o.schema_id = sch.schema_id
2282
+ LEFT JOIN sys.dm_db_partition_stats s ON i.object_id = s.object_id AND i.index_id = s.index_id
2283
+ LEFT JOIN sys.dm_db_index_usage_stats us ON i.object_id = us.object_id AND i.index_id = us.index_id
2284
+ WHERE i.name = @indexName
2285
+ AND sch.name = @schemaName
2286
+ GROUP BY i.name, o.name, i.is_unique, i.type_desc, us.user_seeks, us.user_scans, us.user_lookups
2287
+ `;
2288
+ const result = await request.query(query);
2289
+ if (!result.recordset || result.recordset.length === 0) {
2290
+ throw new Error(`Index "${indexName}" not found in schema "${schemaName}"`);
2291
+ }
2292
+ const row = result.recordset[0];
2293
+ const colRequest = this.pool.request();
2294
+ colRequest.input("indexName", indexName);
2295
+ colRequest.input("schemaName", schemaName);
2296
+ const colResult = await colRequest.query(`
2297
+ SELECT c.name as column_name
2298
+ FROM sys.indexes i
2299
+ INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
2300
+ INNER JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
2301
+ INNER JOIN sys.objects o ON i.object_id = o.object_id
2302
+ INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
2303
+ WHERE i.name = @indexName
2304
+ AND s.name = @schemaName
2305
+ ORDER BY ic.key_ordinal
2306
+ `);
2307
+ return {
2308
+ name: row.name,
2309
+ table: row.table,
2310
+ columns: colResult.recordset.map((c) => c.column_name),
2311
+ unique: row.is_unique || false,
2312
+ size: row.size || "0 MB",
2313
+ definition: "",
2314
+ method: row.method?.toLowerCase() || "nonclustered",
2315
+ scans: Number(row.scans) || 0,
2316
+ tuples_read: Number(row.tuples_read) || 0,
2317
+ tuples_fetched: Number(row.tuples_fetched) || 0
2318
+ };
2319
+ } catch (error$1) {
2320
+ throw new error.MastraError(
2321
+ {
2322
+ id: "MASTRA_STORAGE_MSSQL_INDEX_DESCRIBE_FAILED",
2323
+ domain: error.ErrorDomain.STORAGE,
2324
+ category: error.ErrorCategory.THIRD_PARTY,
2325
+ details: {
2326
+ indexName
2327
+ }
2328
+ },
2329
+ error$1
2330
+ );
2331
+ }
2332
+ }
2333
+ /**
2334
+ * Returns definitions for automatic performance indexes
2335
+ * IMPORTANT: Uses seq_id DESC instead of createdAt DESC for MSSQL due to millisecond accuracy limitations
2336
+ * NOTE: Using NVARCHAR(400) for text columns (800 bytes) leaves room for composite indexes
2337
+ */
2338
+ getAutomaticIndexDefinitions() {
2339
+ const schemaPrefix = this.schemaName ? `${this.schemaName}_` : "";
2340
+ return [
2341
+ // Composite indexes for optimal filtering + sorting performance
2342
+ // NVARCHAR(400) = 800 bytes, plus BIGINT (8 bytes) = 808 bytes total (under 900-byte limit)
2343
+ {
2344
+ name: `${schemaPrefix}mastra_threads_resourceid_seqid_idx`,
2345
+ table: storage.TABLE_THREADS,
2346
+ columns: ["resourceId", "seq_id DESC"]
2347
+ },
2348
+ {
2349
+ name: `${schemaPrefix}mastra_messages_thread_id_seqid_idx`,
2350
+ table: storage.TABLE_MESSAGES,
2351
+ columns: ["thread_id", "seq_id DESC"]
2352
+ },
2353
+ {
2354
+ name: `${schemaPrefix}mastra_traces_name_seqid_idx`,
2355
+ table: storage.TABLE_TRACES,
2356
+ columns: ["name", "seq_id DESC"]
2357
+ },
2358
+ {
2359
+ name: `${schemaPrefix}mastra_evals_agent_name_seqid_idx`,
2360
+ table: storage.TABLE_EVALS,
2361
+ columns: ["agent_name", "seq_id DESC"]
2362
+ },
2363
+ {
2364
+ name: `${schemaPrefix}mastra_scores_trace_id_span_id_seqid_idx`,
2365
+ table: storage.TABLE_SCORERS,
2366
+ columns: ["traceId", "spanId", "seq_id DESC"]
2367
+ },
2368
+ // AI Spans indexes for optimal trace querying
2369
+ {
2370
+ name: `${schemaPrefix}mastra_ai_spans_traceid_startedat_idx`,
2371
+ table: storage.TABLE_AI_SPANS,
2372
+ columns: ["traceId", "startedAt DESC"]
2373
+ },
2374
+ {
2375
+ name: `${schemaPrefix}mastra_ai_spans_parentspanid_startedat_idx`,
2376
+ table: storage.TABLE_AI_SPANS,
2377
+ columns: ["parentSpanId", "startedAt DESC"]
2378
+ },
2379
+ {
2380
+ name: `${schemaPrefix}mastra_ai_spans_name_idx`,
2381
+ table: storage.TABLE_AI_SPANS,
2382
+ columns: ["name"]
2383
+ },
2384
+ {
2385
+ name: `${schemaPrefix}mastra_ai_spans_spantype_startedat_idx`,
2386
+ table: storage.TABLE_AI_SPANS,
2387
+ columns: ["spanType", "startedAt DESC"]
2388
+ }
2389
+ ];
2390
+ }
2391
+ /**
2392
+ * Creates automatic indexes for optimal query performance
2393
+ * Uses getAutomaticIndexDefinitions() to determine which indexes to create
2394
+ */
2395
+ async createAutomaticIndexes() {
2396
+ try {
2397
+ const indexes = this.getAutomaticIndexDefinitions();
2398
+ for (const indexOptions of indexes) {
2399
+ try {
2400
+ await this.createIndex(indexOptions);
2401
+ } catch (error) {
2402
+ this.logger?.warn?.(`Failed to create index ${indexOptions.name}:`, error);
2403
+ }
2404
+ }
2405
+ } catch (error$1) {
2406
+ throw new error.MastraError(
2407
+ {
2408
+ id: "MASTRA_STORAGE_MSSQL_STORE_CREATE_PERFORMANCE_INDEXES_FAILED",
2409
+ domain: error.ErrorDomain.STORAGE,
2410
+ category: error.ErrorCategory.THIRD_PARTY
2411
+ },
2412
+ error$1
2413
+ );
2414
+ }
2415
+ }
2416
+ };
2417
+ function transformScoreRow(row) {
2418
+ return {
2419
+ ...row,
2420
+ input: storage.safelyParseJSON(row.input),
2421
+ scorer: storage.safelyParseJSON(row.scorer),
2422
+ preprocessStepResult: storage.safelyParseJSON(row.preprocessStepResult),
2423
+ analyzeStepResult: storage.safelyParseJSON(row.analyzeStepResult),
2424
+ metadata: storage.safelyParseJSON(row.metadata),
2425
+ output: storage.safelyParseJSON(row.output),
2426
+ additionalContext: storage.safelyParseJSON(row.additionalContext),
2427
+ runtimeContext: storage.safelyParseJSON(row.runtimeContext),
2428
+ entity: storage.safelyParseJSON(row.entity),
2429
+ createdAt: new Date(row.createdAt),
2430
+ updatedAt: new Date(row.updatedAt)
2431
+ };
2432
+ }
2433
+ var ScoresMSSQL = class extends storage.ScoresStorage {
2434
+ pool;
2435
+ operations;
2436
+ schema;
2437
+ constructor({
2438
+ pool,
2439
+ operations,
2440
+ schema
2441
+ }) {
2442
+ super();
2443
+ this.pool = pool;
2444
+ this.operations = operations;
2445
+ this.schema = schema;
2446
+ }
2447
+ async getScoreById({ id }) {
2448
+ try {
2449
+ const request = this.pool.request();
2450
+ request.input("p1", id);
2451
+ const result = await request.query(
2452
+ `SELECT * FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE id = @p1`
2453
+ );
2454
+ if (result.recordset.length === 0) {
2455
+ return null;
2456
+ }
2457
+ return transformScoreRow(result.recordset[0]);
2458
+ } catch (error$1) {
2459
+ throw new error.MastraError(
2460
+ {
2461
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORE_BY_ID_FAILED",
2462
+ domain: error.ErrorDomain.STORAGE,
2463
+ category: error.ErrorCategory.THIRD_PARTY,
2464
+ details: { id }
2465
+ },
2466
+ error$1
2467
+ );
2468
+ }
2469
+ }
2470
+ async saveScore(score) {
2471
+ let validatedScore;
2472
+ try {
2473
+ validatedScore = scores.saveScorePayloadSchema.parse(score);
2474
+ } catch (error$1) {
2475
+ throw new error.MastraError(
2476
+ {
2477
+ id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_SCORE_VALIDATION_FAILED",
2478
+ domain: error.ErrorDomain.STORAGE,
2479
+ category: error.ErrorCategory.THIRD_PARTY
2480
+ },
2481
+ error$1
2482
+ );
2483
+ }
2484
+ try {
2485
+ const scoreId = crypto.randomUUID();
2486
+ const {
2487
+ scorer,
2488
+ preprocessStepResult,
2489
+ analyzeStepResult,
2490
+ metadata,
2491
+ input,
2492
+ output,
2493
+ additionalContext,
2494
+ runtimeContext,
2495
+ entity,
2496
+ ...rest
2497
+ } = validatedScore;
2498
+ await this.operations.insert({
2499
+ tableName: storage.TABLE_SCORERS,
2500
+ record: {
2501
+ id: scoreId,
2502
+ ...rest,
2503
+ input: input || "",
2504
+ output: output || "",
2505
+ preprocessStepResult: preprocessStepResult || null,
2506
+ analyzeStepResult: analyzeStepResult || null,
2507
+ metadata: metadata || null,
2508
+ additionalContext: additionalContext || null,
2509
+ runtimeContext: runtimeContext || null,
2510
+ entity: entity || null,
2511
+ scorer: scorer || null,
2512
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2513
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2514
+ }
2515
+ });
2516
+ const scoreFromDb = await this.getScoreById({ id: scoreId });
2517
+ return { score: scoreFromDb };
2518
+ } catch (error$1) {
2519
+ throw new error.MastraError(
2520
+ {
2521
+ id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_SCORE_FAILED",
2522
+ domain: error.ErrorDomain.STORAGE,
2523
+ category: error.ErrorCategory.THIRD_PARTY
2524
+ },
2525
+ error$1
2526
+ );
2527
+ }
2528
+ }
2529
+ async getScoresByScorerId({
2530
+ scorerId,
2531
+ pagination,
2532
+ entityId,
2533
+ entityType,
2534
+ source
2535
+ }) {
2536
+ try {
2537
+ const conditions = ["[scorerId] = @p1"];
2538
+ const params = { p1: scorerId };
2539
+ let paramIndex = 2;
2540
+ if (entityId) {
2541
+ conditions.push(`[entityId] = @p${paramIndex}`);
2542
+ params[`p${paramIndex}`] = entityId;
2543
+ paramIndex++;
2544
+ }
2545
+ if (entityType) {
2546
+ conditions.push(`[entityType] = @p${paramIndex}`);
2547
+ params[`p${paramIndex}`] = entityType;
2548
+ paramIndex++;
2549
+ }
2550
+ if (source) {
2551
+ conditions.push(`[source] = @p${paramIndex}`);
2552
+ params[`p${paramIndex}`] = source;
2553
+ paramIndex++;
2554
+ }
2555
+ const whereClause = conditions.join(" AND ");
2556
+ const tableName = getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) });
2557
+ const countRequest = this.pool.request();
2558
+ Object.entries(params).forEach(([key, value]) => {
2559
+ countRequest.input(key, value);
2560
+ });
2561
+ const totalResult = await countRequest.query(`SELECT COUNT(*) as count FROM ${tableName} WHERE ${whereClause}`);
2562
+ const total = totalResult.recordset[0]?.count || 0;
2563
+ if (total === 0) {
2564
+ return {
2565
+ pagination: {
2566
+ total: 0,
2567
+ page: pagination.page,
2568
+ perPage: pagination.perPage,
2569
+ hasMore: false
2570
+ },
2571
+ scores: []
2572
+ };
2573
+ }
2574
+ const dataRequest = this.pool.request();
2575
+ Object.entries(params).forEach(([key, value]) => {
2576
+ dataRequest.input(key, value);
2577
+ });
2578
+ dataRequest.input("perPage", pagination.perPage);
2579
+ dataRequest.input("offset", pagination.page * pagination.perPage);
2580
+ const dataQuery = `SELECT * FROM ${tableName} WHERE ${whereClause} ORDER BY [createdAt] DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
2581
+ const result = await dataRequest.query(dataQuery);
2582
+ return {
2583
+ pagination: {
2584
+ total: Number(total),
2585
+ page: pagination.page,
2586
+ perPage: pagination.perPage,
2587
+ hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2588
+ },
2589
+ scores: result.recordset.map((row) => transformScoreRow(row))
2590
+ };
2591
+ } catch (error$1) {
2592
+ throw new error.MastraError(
2593
+ {
2594
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_SCORER_ID_FAILED",
2595
+ domain: error.ErrorDomain.STORAGE,
2596
+ category: error.ErrorCategory.THIRD_PARTY,
2597
+ details: { scorerId }
2598
+ },
2599
+ error$1
2600
+ );
2601
+ }
2602
+ }
2603
+ async getScoresByRunId({
2604
+ runId,
2605
+ pagination
2606
+ }) {
2607
+ try {
2608
+ const request = this.pool.request();
2609
+ request.input("p1", runId);
2610
+ const totalResult = await request.query(
2611
+ `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [runId] = @p1`
2612
+ );
2613
+ const total = totalResult.recordset[0]?.count || 0;
2614
+ if (total === 0) {
2615
+ return {
2616
+ pagination: {
2617
+ total: 0,
2618
+ page: pagination.page,
2619
+ perPage: pagination.perPage,
2620
+ hasMore: false
2621
+ },
2622
+ scores: []
2623
+ };
2624
+ }
2625
+ const dataRequest = this.pool.request();
2626
+ dataRequest.input("p1", runId);
2627
+ dataRequest.input("p2", pagination.perPage);
2628
+ dataRequest.input("p3", pagination.page * pagination.perPage);
2629
+ const result = await dataRequest.query(
2630
+ `SELECT * FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [runId] = @p1 ORDER BY [createdAt] DESC OFFSET @p3 ROWS FETCH NEXT @p2 ROWS ONLY`
2631
+ );
2632
+ return {
2633
+ pagination: {
2634
+ total: Number(total),
2635
+ page: pagination.page,
2636
+ perPage: pagination.perPage,
2637
+ hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2638
+ },
2639
+ scores: result.recordset.map((row) => transformScoreRow(row))
2640
+ };
2641
+ } catch (error$1) {
2642
+ throw new error.MastraError(
2643
+ {
2644
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_RUN_ID_FAILED",
2645
+ domain: error.ErrorDomain.STORAGE,
2646
+ category: error.ErrorCategory.THIRD_PARTY,
2647
+ details: { runId }
2648
+ },
2649
+ error$1
2650
+ );
2651
+ }
2652
+ }
2653
+ async getScoresByEntityId({
2654
+ entityId,
2655
+ entityType,
2656
+ pagination
2657
+ }) {
2658
+ try {
2659
+ const request = this.pool.request();
2660
+ request.input("p1", entityId);
2661
+ request.input("p2", entityType);
2662
+ const totalResult = await request.query(
2663
+ `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [entityId] = @p1 AND [entityType] = @p2`
2664
+ );
2665
+ const total = totalResult.recordset[0]?.count || 0;
2666
+ if (total === 0) {
2667
+ return {
2668
+ pagination: {
2669
+ total: 0,
2670
+ page: pagination.page,
2671
+ perPage: pagination.perPage,
2672
+ hasMore: false
2673
+ },
2674
+ scores: []
2675
+ };
2676
+ }
2677
+ const dataRequest = this.pool.request();
2678
+ dataRequest.input("p1", entityId);
2679
+ dataRequest.input("p2", entityType);
2680
+ dataRequest.input("p3", pagination.perPage);
2681
+ dataRequest.input("p4", pagination.page * pagination.perPage);
2682
+ const result = await dataRequest.query(
2683
+ `SELECT * FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [entityId] = @p1 AND [entityType] = @p2 ORDER BY [createdAt] DESC OFFSET @p4 ROWS FETCH NEXT @p3 ROWS ONLY`
2684
+ );
2685
+ return {
2686
+ pagination: {
2687
+ total: Number(total),
2688
+ page: pagination.page,
2689
+ perPage: pagination.perPage,
2690
+ hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
2691
+ },
2692
+ scores: result.recordset.map((row) => transformScoreRow(row))
2693
+ };
2694
+ } catch (error$1) {
2695
+ throw new error.MastraError(
2696
+ {
2697
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_ENTITY_ID_FAILED",
2698
+ domain: error.ErrorDomain.STORAGE,
2699
+ category: error.ErrorCategory.THIRD_PARTY,
2700
+ details: { entityId, entityType }
2701
+ },
2702
+ error$1
2703
+ );
2704
+ }
2705
+ }
2706
+ async getScoresBySpan({
2707
+ traceId,
2708
+ spanId,
2709
+ pagination
2710
+ }) {
2711
+ try {
2712
+ const request = this.pool.request();
2713
+ request.input("p1", traceId);
2714
+ request.input("p2", spanId);
2715
+ const totalResult = await request.query(
2716
+ `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [traceId] = @p1 AND [spanId] = @p2`
2717
+ );
2718
+ const total = totalResult.recordset[0]?.count || 0;
2719
+ if (total === 0) {
2720
+ return {
2721
+ pagination: {
2722
+ total: 0,
2723
+ page: pagination.page,
2724
+ perPage: pagination.perPage,
2725
+ hasMore: false
2726
+ },
2727
+ scores: []
2728
+ };
2729
+ }
2730
+ const limit = pagination.perPage + 1;
2731
+ const dataRequest = this.pool.request();
2732
+ dataRequest.input("p1", traceId);
2733
+ dataRequest.input("p2", spanId);
2734
+ dataRequest.input("p3", limit);
2735
+ dataRequest.input("p4", pagination.page * pagination.perPage);
2736
+ const result = await dataRequest.query(
2737
+ `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`
2738
+ );
2739
+ return {
2740
+ pagination: {
2741
+ total: Number(total),
2742
+ page: pagination.page,
2743
+ perPage: pagination.perPage,
2744
+ hasMore: result.recordset.length > pagination.perPage
2745
+ },
2746
+ scores: result.recordset.slice(0, pagination.perPage).map((row) => transformScoreRow(row))
2747
+ };
2748
+ } catch (error$1) {
2749
+ throw new error.MastraError(
2750
+ {
2751
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_SPAN_FAILED",
2752
+ domain: error.ErrorDomain.STORAGE,
2753
+ category: error.ErrorCategory.THIRD_PARTY,
2754
+ details: { traceId, spanId }
2755
+ },
2756
+ error$1
2757
+ );
2758
+ }
2759
+ }
2760
+ };
2761
+ var TracesMSSQL = class extends storage.TracesStorage {
2762
+ pool;
2763
+ operations;
2764
+ schema;
2765
+ constructor({
2766
+ pool,
2767
+ operations,
2768
+ schema
2769
+ }) {
2770
+ super();
2771
+ this.pool = pool;
2772
+ this.operations = operations;
2773
+ this.schema = schema;
2774
+ }
2775
+ /** @deprecated use getTracesPaginated instead*/
2776
+ async getTraces(args) {
2777
+ if (args.fromDate || args.toDate) {
2778
+ args.dateRange = {
2779
+ start: args.fromDate,
2780
+ end: args.toDate
2781
+ };
2782
+ }
2783
+ const result = await this.getTracesPaginated(args);
2784
+ return result.traces;
2785
+ }
2786
+ async getTracesPaginated(args) {
2787
+ const { name, scope, page = 0, perPage: perPageInput, attributes, filters, dateRange } = args;
2788
+ const fromDate = dateRange?.start;
2789
+ const toDate = dateRange?.end;
2790
+ const perPage = perPageInput !== void 0 ? perPageInput : 100;
2791
+ const currentOffset = page * perPage;
2792
+ const paramMap = {};
2793
+ const conditions = [];
2794
+ let paramIndex = 1;
2795
+ if (name) {
2796
+ const paramName = `p${paramIndex++}`;
2797
+ conditions.push(`[name] LIKE @${paramName}`);
2798
+ paramMap[paramName] = `${name}%`;
2799
+ }
2800
+ if (scope) {
2801
+ const paramName = `p${paramIndex++}`;
2802
+ conditions.push(`[scope] = @${paramName}`);
2803
+ paramMap[paramName] = scope;
2804
+ }
2805
+ if (attributes) {
2806
+ Object.entries(attributes).forEach(([key, value]) => {
2807
+ const parsedKey = utils.parseFieldKey(key);
2808
+ const paramName = `p${paramIndex++}`;
2809
+ conditions.push(`JSON_VALUE([attributes], '$.${parsedKey}') = @${paramName}`);
2810
+ paramMap[paramName] = value;
2811
+ });
2812
+ }
2813
+ if (filters) {
2814
+ Object.entries(filters).forEach(([key, value]) => {
2815
+ const parsedKey = utils.parseFieldKey(key);
2816
+ const paramName = `p${paramIndex++}`;
2817
+ conditions.push(`[${parsedKey}] = @${paramName}`);
2818
+ paramMap[paramName] = value;
2819
+ });
2820
+ }
2821
+ if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
2822
+ const paramName = `p${paramIndex++}`;
2823
+ conditions.push(`[createdAt] >= @${paramName}`);
2824
+ paramMap[paramName] = fromDate.toISOString();
2825
+ }
2826
+ if (toDate instanceof Date && !isNaN(toDate.getTime())) {
2827
+ const paramName = `p${paramIndex++}`;
2828
+ conditions.push(`[createdAt] <= @${paramName}`);
2829
+ paramMap[paramName] = toDate.toISOString();
2830
+ }
2831
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2832
+ const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: storage.TABLE_TRACES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
2833
+ let total = 0;
2834
+ try {
2835
+ const countRequest = this.pool.request();
2836
+ Object.entries(paramMap).forEach(([key, value]) => {
2837
+ if (value instanceof Date) {
2838
+ countRequest.input(key, sql3__default.default.DateTime, value);
2839
+ } else {
2840
+ countRequest.input(key, value);
2841
+ }
2842
+ });
2843
+ const countResult = await countRequest.query(countQuery);
2844
+ total = parseInt(countResult.recordset[0].total, 10);
2845
+ } catch (error$1) {
2846
+ throw new error.MastraError(
2847
+ {
2848
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TOTAL_COUNT",
2849
+ domain: error.ErrorDomain.STORAGE,
2850
+ category: error.ErrorCategory.THIRD_PARTY,
2851
+ details: {
2852
+ name: args.name ?? "",
2853
+ scope: args.scope ?? ""
2854
+ }
2855
+ },
2856
+ error$1
2857
+ );
2858
+ }
2859
+ if (total === 0) {
2860
+ return {
2861
+ traces: [],
2862
+ total: 0,
2863
+ page,
2864
+ perPage,
2865
+ hasMore: false
2866
+ };
2867
+ }
2868
+ const dataQuery = `SELECT * FROM ${getTableName({ indexName: storage.TABLE_TRACES, schemaName: getSchemaName(this.schema) })} ${whereClause} ORDER BY [seq_id] DESC OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
2869
+ const dataRequest = this.pool.request();
2870
+ Object.entries(paramMap).forEach(([key, value]) => {
2871
+ if (value instanceof Date) {
2872
+ dataRequest.input(key, sql3__default.default.DateTime, value);
2873
+ } else {
2874
+ dataRequest.input(key, value);
2875
+ }
2876
+ });
2877
+ dataRequest.input("offset", currentOffset);
2878
+ dataRequest.input("limit", perPage);
2879
+ try {
2880
+ const rowsResult = await dataRequest.query(dataQuery);
2881
+ const rows = rowsResult.recordset;
2882
+ const traces = rows.map((row) => ({
2883
+ id: row.id,
2884
+ parentSpanId: row.parentSpanId,
2885
+ traceId: row.traceId,
2886
+ name: row.name,
2887
+ scope: row.scope,
2888
+ kind: row.kind,
2889
+ status: JSON.parse(row.status),
2890
+ events: JSON.parse(row.events),
2891
+ links: JSON.parse(row.links),
2892
+ attributes: JSON.parse(row.attributes),
2893
+ startTime: row.startTime,
2894
+ endTime: row.endTime,
2895
+ other: row.other,
2896
+ createdAt: row.createdAt
2897
+ }));
2898
+ return {
2899
+ traces,
2900
+ total,
2901
+ page,
2902
+ perPage,
2903
+ hasMore: currentOffset + traces.length < total
2904
+ };
2905
+ } catch (error$1) {
2906
+ throw new error.MastraError(
2907
+ {
2908
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TRACES",
2909
+ domain: error.ErrorDomain.STORAGE,
2910
+ category: error.ErrorCategory.THIRD_PARTY,
2911
+ details: {
2912
+ name: args.name ?? "",
2913
+ scope: args.scope ?? ""
2914
+ }
2915
+ },
2916
+ error$1
2917
+ );
2918
+ }
2919
+ }
2920
+ async batchTraceInsert({ records }) {
2921
+ this.logger.debug("Batch inserting traces", { count: records.length });
2922
+ await this.operations.batchInsert({
2923
+ tableName: storage.TABLE_TRACES,
2924
+ records
2925
+ });
2926
+ }
2927
+ };
2928
+ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
2929
+ pool;
2930
+ operations;
2931
+ schema;
2932
+ constructor({
2933
+ pool,
2934
+ operations,
2935
+ schema
2936
+ }) {
2937
+ super();
2938
+ this.pool = pool;
2939
+ this.operations = operations;
2940
+ this.schema = schema;
2941
+ }
2942
+ parseWorkflowRun(row) {
2943
+ let parsedSnapshot = row.snapshot;
2944
+ if (typeof parsedSnapshot === "string") {
2945
+ try {
2946
+ parsedSnapshot = JSON.parse(row.snapshot);
2947
+ } catch (e) {
2948
+ this.logger?.warn?.(`Failed to parse snapshot for workflow ${row.workflow_name}:`, e);
2949
+ }
2950
+ }
2951
+ return {
2952
+ workflowName: row.workflow_name,
2953
+ runId: row.run_id,
2954
+ snapshot: parsedSnapshot,
2955
+ createdAt: row.createdAt,
2956
+ updatedAt: row.updatedAt,
2957
+ resourceId: row.resourceId
2958
+ };
2959
+ }
2960
+ async updateWorkflowResults({
2961
+ workflowName,
2962
+ runId,
2963
+ stepId,
2964
+ result,
2965
+ runtimeContext
2966
+ }) {
2967
+ const table = getTableName({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
2968
+ const transaction = this.pool.transaction();
2969
+ try {
2970
+ await transaction.begin();
2971
+ const selectRequest = new sql3__default.default.Request(transaction);
2972
+ selectRequest.input("workflow_name", workflowName);
2973
+ selectRequest.input("run_id", runId);
2974
+ const existingSnapshotResult = await selectRequest.query(
2975
+ `SELECT snapshot FROM ${table} WITH (UPDLOCK, HOLDLOCK) WHERE workflow_name = @workflow_name AND run_id = @run_id`
2976
+ );
2977
+ let snapshot;
2978
+ if (!existingSnapshotResult.recordset || existingSnapshotResult.recordset.length === 0) {
2979
+ snapshot = {
2980
+ context: {},
2981
+ activePaths: [],
2982
+ activeStepsPath: {},
2983
+ timestamp: Date.now(),
2984
+ suspendedPaths: {},
2985
+ resumeLabels: {},
2986
+ serializedStepGraph: [],
2987
+ status: "pending",
2988
+ value: {},
2989
+ waitingPaths: {},
2990
+ runId,
2991
+ runtimeContext: {}
2992
+ };
2993
+ } else {
2994
+ const existingSnapshot = existingSnapshotResult.recordset[0].snapshot;
2995
+ snapshot = typeof existingSnapshot === "string" ? JSON.parse(existingSnapshot) : existingSnapshot;
2996
+ }
2997
+ snapshot.context[stepId] = result;
2998
+ snapshot.runtimeContext = { ...snapshot.runtimeContext, ...runtimeContext };
2999
+ const upsertReq = new sql3__default.default.Request(transaction);
3000
+ upsertReq.input("workflow_name", workflowName);
3001
+ upsertReq.input("run_id", runId);
3002
+ upsertReq.input("snapshot", JSON.stringify(snapshot));
3003
+ upsertReq.input("createdAt", sql3__default.default.DateTime2, /* @__PURE__ */ new Date());
3004
+ upsertReq.input("updatedAt", sql3__default.default.DateTime2, /* @__PURE__ */ new Date());
3005
+ await upsertReq.query(
3006
+ `MERGE ${table} AS target
3007
+ USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
3008
+ ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
3009
+ WHEN MATCHED THEN UPDATE SET snapshot = @snapshot, [updatedAt] = @updatedAt
3010
+ WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, snapshot, [createdAt], [updatedAt])
3011
+ VALUES (@workflow_name, @run_id, @snapshot, @createdAt, @updatedAt);`
3012
+ );
3013
+ await transaction.commit();
3014
+ return snapshot.context;
3015
+ } catch (error$1) {
3016
+ try {
3017
+ await transaction.rollback();
3018
+ } catch {
3019
+ }
3020
+ throw new error.MastraError(
3021
+ {
3022
+ id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_WORKFLOW_RESULTS_FAILED",
3023
+ domain: error.ErrorDomain.STORAGE,
3024
+ category: error.ErrorCategory.THIRD_PARTY,
3025
+ details: {
3026
+ workflowName,
3027
+ runId,
3028
+ stepId
3029
+ }
3030
+ },
3031
+ error$1
3032
+ );
3033
+ }
3034
+ }
3035
+ async updateWorkflowState({
3036
+ workflowName,
3037
+ runId,
3038
+ opts
3039
+ }) {
3040
+ const table = getTableName({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
3041
+ const transaction = this.pool.transaction();
3042
+ try {
3043
+ await transaction.begin();
3044
+ const selectRequest = new sql3__default.default.Request(transaction);
3045
+ selectRequest.input("workflow_name", workflowName);
3046
+ selectRequest.input("run_id", runId);
3047
+ const existingSnapshotResult = await selectRequest.query(
3048
+ `SELECT snapshot FROM ${table} WITH (UPDLOCK, HOLDLOCK) WHERE workflow_name = @workflow_name AND run_id = @run_id`
3049
+ );
3050
+ if (!existingSnapshotResult.recordset || existingSnapshotResult.recordset.length === 0) {
3051
+ await transaction.rollback();
3052
+ return void 0;
3053
+ }
3054
+ const existingSnapshot = existingSnapshotResult.recordset[0].snapshot;
3055
+ const snapshot = typeof existingSnapshot === "string" ? JSON.parse(existingSnapshot) : existingSnapshot;
3056
+ if (!snapshot || !snapshot?.context) {
3057
+ await transaction.rollback();
3058
+ throw new error.MastraError(
3059
+ {
3060
+ id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_WORKFLOW_STATE_SNAPSHOT_NOT_FOUND",
3061
+ domain: error.ErrorDomain.STORAGE,
3062
+ category: error.ErrorCategory.SYSTEM,
3063
+ details: {
3064
+ workflowName,
3065
+ runId
3066
+ }
3067
+ },
3068
+ new Error(`Snapshot not found for runId ${runId}`)
3069
+ );
3070
+ }
3071
+ const updatedSnapshot = { ...snapshot, ...opts };
3072
+ const updateRequest = new sql3__default.default.Request(transaction);
3073
+ updateRequest.input("snapshot", JSON.stringify(updatedSnapshot));
3074
+ updateRequest.input("workflow_name", workflowName);
3075
+ updateRequest.input("run_id", runId);
3076
+ updateRequest.input("updatedAt", sql3__default.default.DateTime2, /* @__PURE__ */ new Date());
3077
+ await updateRequest.query(
3078
+ `UPDATE ${table} SET snapshot = @snapshot, [updatedAt] = @updatedAt WHERE workflow_name = @workflow_name AND run_id = @run_id`
3079
+ );
3080
+ await transaction.commit();
3081
+ return updatedSnapshot;
3082
+ } catch (error$1) {
3083
+ try {
3084
+ await transaction.rollback();
3085
+ } catch {
3086
+ }
3087
+ throw new error.MastraError(
3088
+ {
3089
+ id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_WORKFLOW_STATE_FAILED",
3090
+ domain: error.ErrorDomain.STORAGE,
3091
+ category: error.ErrorCategory.THIRD_PARTY,
3092
+ details: {
3093
+ workflowName,
3094
+ runId
3095
+ }
3096
+ },
3097
+ error$1
3098
+ );
3099
+ }
3100
+ }
3101
+ async persistWorkflowSnapshot({
3102
+ workflowName,
3103
+ runId,
3104
+ resourceId,
3105
+ snapshot
3106
+ }) {
3107
+ const table = getTableName({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
3108
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3109
+ try {
3110
+ const request = this.pool.request();
3111
+ request.input("workflow_name", workflowName);
3112
+ request.input("run_id", runId);
3113
+ request.input("resourceId", resourceId);
3114
+ request.input("snapshot", JSON.stringify(snapshot));
3115
+ request.input("createdAt", sql3__default.default.DateTime2, new Date(now));
3116
+ request.input("updatedAt", sql3__default.default.DateTime2, new Date(now));
3117
+ const mergeSql = `MERGE INTO ${table} AS target
3118
+ USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
3119
+ ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
3120
+ WHEN MATCHED THEN UPDATE SET
3121
+ resourceId = @resourceId,
3122
+ snapshot = @snapshot,
3123
+ [updatedAt] = @updatedAt
3124
+ WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, resourceId, snapshot, [createdAt], [updatedAt])
3125
+ VALUES (@workflow_name, @run_id, @resourceId, @snapshot, @createdAt, @updatedAt);`;
3126
+ await request.query(mergeSql);
3127
+ } catch (error$1) {
3128
+ throw new error.MastraError(
3129
+ {
3130
+ id: "MASTRA_STORAGE_MSSQL_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
3131
+ domain: error.ErrorDomain.STORAGE,
3132
+ category: error.ErrorCategory.THIRD_PARTY,
3133
+ details: {
3134
+ workflowName,
3135
+ runId
3136
+ }
3137
+ },
3138
+ error$1
3139
+ );
3140
+ }
3141
+ }
3142
+ async loadWorkflowSnapshot({
3143
+ workflowName,
3144
+ runId
3145
+ }) {
3146
+ try {
3147
+ const result = await this.operations.load({
3148
+ tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
3149
+ keys: {
3150
+ workflow_name: workflowName,
3151
+ run_id: runId
3152
+ }
3153
+ });
3154
+ if (!result) {
3155
+ return null;
3156
+ }
3157
+ return result.snapshot;
3158
+ } catch (error$1) {
3159
+ throw new error.MastraError(
3160
+ {
3161
+ id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
3162
+ domain: error.ErrorDomain.STORAGE,
3163
+ category: error.ErrorCategory.THIRD_PARTY,
3164
+ details: {
3165
+ workflowName,
3166
+ runId
3167
+ }
3168
+ },
3169
+ error$1
3170
+ );
3171
+ }
3172
+ }
3173
+ async getWorkflowRunById({
3174
+ runId,
3175
+ workflowName
3176
+ }) {
3177
+ try {
3178
+ const conditions = [];
3179
+ const paramMap = {};
3180
+ if (runId) {
3181
+ conditions.push(`[run_id] = @runId`);
3182
+ paramMap["runId"] = runId;
3183
+ }
3184
+ if (workflowName) {
3185
+ conditions.push(`[workflow_name] = @workflowName`);
3186
+ paramMap["workflowName"] = workflowName;
3187
+ }
3188
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
3189
+ const tableName = getTableName({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
3190
+ const query = `SELECT * FROM ${tableName} ${whereClause}`;
3191
+ const request = this.pool.request();
3192
+ Object.entries(paramMap).forEach(([key, value]) => request.input(key, value));
3193
+ const result = await request.query(query);
3194
+ if (!result.recordset || result.recordset.length === 0) {
3195
+ return null;
3196
+ }
3197
+ return this.parseWorkflowRun(result.recordset[0]);
3198
+ } catch (error$1) {
3199
+ throw new error.MastraError(
3200
+ {
3201
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
3202
+ domain: error.ErrorDomain.STORAGE,
3203
+ category: error.ErrorCategory.THIRD_PARTY,
3204
+ details: {
3205
+ runId,
3206
+ workflowName: workflowName || ""
3207
+ }
3208
+ },
3209
+ error$1
3210
+ );
3211
+ }
3212
+ }
3213
+ async getWorkflowRuns({
3214
+ workflowName,
3215
+ fromDate,
3216
+ toDate,
3217
+ limit,
3218
+ offset,
3219
+ resourceId,
3220
+ status
3221
+ } = {}) {
3222
+ try {
3223
+ const conditions = [];
3224
+ const paramMap = {};
3225
+ if (workflowName) {
3226
+ conditions.push(`[workflow_name] = @workflowName`);
3227
+ paramMap["workflowName"] = workflowName;
3228
+ }
3229
+ if (status) {
3230
+ conditions.push(`JSON_VALUE([snapshot], '$.status') = @status`);
3231
+ paramMap["status"] = status;
3232
+ }
3233
+ if (resourceId) {
3234
+ const hasResourceId = await this.operations.hasColumn(storage.TABLE_WORKFLOW_SNAPSHOT, "resourceId");
3235
+ if (hasResourceId) {
3236
+ conditions.push(`[resourceId] = @resourceId`);
3237
+ paramMap["resourceId"] = resourceId;
3238
+ } else {
3239
+ this.logger?.warn?.(`[${storage.TABLE_WORKFLOW_SNAPSHOT}] resourceId column not found. Skipping resourceId filter.`);
3240
+ }
3241
+ }
3242
+ if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
3243
+ conditions.push(`[createdAt] >= @fromDate`);
3244
+ paramMap[`fromDate`] = fromDate.toISOString();
3245
+ }
3246
+ if (toDate instanceof Date && !isNaN(toDate.getTime())) {
3247
+ conditions.push(`[createdAt] <= @toDate`);
3248
+ paramMap[`toDate`] = toDate.toISOString();
3249
+ }
3250
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
3251
+ let total = 0;
3252
+ const tableName = getTableName({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
3253
+ const request = this.pool.request();
3254
+ Object.entries(paramMap).forEach(([key, value]) => {
3255
+ if (value instanceof Date) {
3256
+ request.input(key, sql3__default.default.DateTime, value);
3257
+ } else {
3258
+ request.input(key, value);
3259
+ }
3260
+ });
3261
+ if (limit !== void 0 && offset !== void 0) {
3262
+ const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
3263
+ const countResult = await request.query(countQuery);
3264
+ total = Number(countResult.recordset[0]?.count || 0);
3265
+ }
3266
+ let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
3267
+ if (limit !== void 0 && offset !== void 0) {
3268
+ query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
3269
+ request.input("limit", limit);
3270
+ request.input("offset", offset);
3271
+ }
3272
+ const result = await request.query(query);
3273
+ const runs = (result.recordset || []).map((row) => this.parseWorkflowRun(row));
3274
+ return { runs, total: total || runs.length };
3275
+ } catch (error$1) {
3276
+ throw new error.MastraError(
3277
+ {
3278
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
3279
+ domain: error.ErrorDomain.STORAGE,
3280
+ category: error.ErrorCategory.THIRD_PARTY,
3281
+ details: {
3282
+ workflowName: workflowName || "all"
3283
+ }
3284
+ },
3285
+ error$1
3286
+ );
3287
+ }
3288
+ }
3289
+ };
3290
+
3291
+ // src/storage/index.ts
3292
+ var MSSQLStore = class extends storage.MastraStorage {
3293
+ pool;
3294
+ schema;
3295
+ isConnected = null;
3296
+ stores;
3297
+ constructor(config) {
3298
+ super({ name: "MSSQLStore" });
3299
+ try {
3300
+ if ("connectionString" in config) {
3301
+ if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") {
3302
+ throw new Error("MSSQLStore: connectionString must be provided and cannot be empty.");
3303
+ }
3304
+ } else {
3305
+ const required = ["server", "database", "user", "password"];
3306
+ for (const key of required) {
3307
+ if (!(key in config) || typeof config[key] !== "string" || config[key].trim() === "") {
3308
+ throw new Error(`MSSQLStore: ${key} must be provided and cannot be empty.`);
3309
+ }
3310
+ }
3311
+ }
3312
+ this.schema = config.schemaName || "dbo";
3313
+ this.pool = "connectionString" in config ? new sql3__default.default.ConnectionPool(config.connectionString) : new sql3__default.default.ConnectionPool({
3314
+ server: config.server,
3315
+ database: config.database,
3316
+ user: config.user,
3317
+ password: config.password,
3318
+ port: config.port,
3319
+ options: config.options || { encrypt: true, trustServerCertificate: true }
3320
+ });
3321
+ const legacyEvals = new LegacyEvalsMSSQL({ pool: this.pool, schema: this.schema });
3322
+ const operations = new StoreOperationsMSSQL({ pool: this.pool, schemaName: this.schema });
3323
+ const scores = new ScoresMSSQL({ pool: this.pool, operations, schema: this.schema });
3324
+ const traces = new TracesMSSQL({ pool: this.pool, operations, schema: this.schema });
3325
+ const workflows = new WorkflowsMSSQL({ pool: this.pool, operations, schema: this.schema });
3326
+ const memory = new MemoryMSSQL({ pool: this.pool, schema: this.schema, operations });
3327
+ const observability = new ObservabilityMSSQL({ pool: this.pool, operations, schema: this.schema });
3328
+ this.stores = {
3329
+ operations,
3330
+ scores,
3331
+ traces,
3332
+ workflows,
3333
+ legacyEvals,
3334
+ memory,
3335
+ observability
3336
+ };
3337
+ } catch (e) {
3338
+ throw new error.MastraError(
3339
+ {
3340
+ id: "MASTRA_STORAGE_MSSQL_STORE_INITIALIZATION_FAILED",
3341
+ domain: error.ErrorDomain.STORAGE,
3342
+ category: error.ErrorCategory.USER
3343
+ },
3344
+ e
3345
+ );
3346
+ }
3347
+ }
3348
+ async init() {
3349
+ if (this.isConnected === null) {
3350
+ this.isConnected = this._performInitializationAndStore();
3351
+ }
3352
+ try {
3353
+ await this.isConnected;
3354
+ await super.init();
3355
+ try {
3356
+ await this.stores.operations.createAutomaticIndexes();
3357
+ } catch (indexError) {
3358
+ this.logger?.warn?.("Failed to create indexes:", indexError);
3359
+ }
3360
+ } catch (error$1) {
3361
+ this.isConnected = null;
3362
+ throw new error.MastraError(
3363
+ {
3364
+ id: "MASTRA_STORAGE_MSSQL_STORE_INIT_FAILED",
3365
+ domain: error.ErrorDomain.STORAGE,
3366
+ category: error.ErrorCategory.THIRD_PARTY
3367
+ },
3368
+ error$1
3369
+ );
3370
+ }
3371
+ }
3372
+ async _performInitializationAndStore() {
3373
+ try {
3374
+ await this.pool.connect();
3375
+ return true;
3376
+ } catch (err) {
3377
+ throw err;
3378
+ }
3379
+ }
3380
+ get supports() {
3381
+ return {
3382
+ selectByIncludeResourceScope: true,
3383
+ resourceWorkingMemory: true,
3384
+ hasColumn: true,
3385
+ createTable: true,
3386
+ deleteMessages: true,
3387
+ getScoresBySpan: true,
3388
+ aiTracing: true,
3389
+ indexManagement: true
3390
+ };
3391
+ }
3392
+ /** @deprecated use getEvals instead */
3393
+ async getEvalsByAgentName(agentName, type) {
3394
+ return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
3395
+ }
3396
+ async getEvals(options = {}) {
3397
+ return this.stores.legacyEvals.getEvals(options);
3398
+ }
3399
+ /**
3400
+ * @deprecated use getTracesPaginated instead
3401
+ */
3402
+ async getTraces(args) {
3403
+ return this.stores.traces.getTraces(args);
3404
+ }
3405
+ async getTracesPaginated(args) {
3406
+ return this.stores.traces.getTracesPaginated(args);
3407
+ }
3408
+ async batchTraceInsert({ records }) {
3409
+ return this.stores.traces.batchTraceInsert({ records });
3410
+ }
3411
+ async createTable({
3412
+ tableName,
3413
+ schema
3414
+ }) {
3415
+ return this.stores.operations.createTable({ tableName, schema });
3416
+ }
3417
+ async alterTable({
3418
+ tableName,
3419
+ schema,
3420
+ ifNotExists
3421
+ }) {
3422
+ return this.stores.operations.alterTable({ tableName, schema, ifNotExists });
3423
+ }
3424
+ async clearTable({ tableName }) {
3425
+ return this.stores.operations.clearTable({ tableName });
3426
+ }
3427
+ async dropTable({ tableName }) {
3428
+ return this.stores.operations.dropTable({ tableName });
3429
+ }
3430
+ async insert({ tableName, record }) {
3431
+ return this.stores.operations.insert({ tableName, record });
3432
+ }
3433
+ async batchInsert({ tableName, records }) {
3434
+ return this.stores.operations.batchInsert({ tableName, records });
3435
+ }
3436
+ async load({ tableName, keys }) {
3437
+ return this.stores.operations.load({ tableName, keys });
3438
+ }
3439
+ /**
3440
+ * Memory
3441
+ */
3442
+ async getThreadById({ threadId }) {
3443
+ return this.stores.memory.getThreadById({ threadId });
3444
+ }
3445
+ /**
3446
+ * @deprecated use getThreadsByResourceIdPaginated instead
3447
+ */
3448
+ async getThreadsByResourceId(args) {
3449
+ return this.stores.memory.getThreadsByResourceId(args);
3450
+ }
3451
+ async getThreadsByResourceIdPaginated(args) {
3452
+ return this.stores.memory.getThreadsByResourceIdPaginated(args);
3453
+ }
3454
+ async saveThread({ thread }) {
3455
+ return this.stores.memory.saveThread({ thread });
3456
+ }
3457
+ async updateThread({
3458
+ id,
3459
+ title,
3460
+ metadata
3461
+ }) {
3462
+ return this.stores.memory.updateThread({ id, title, metadata });
3463
+ }
3464
+ async deleteThread({ threadId }) {
3465
+ return this.stores.memory.deleteThread({ threadId });
3466
+ }
3467
+ async getMessages(args) {
3468
+ return this.stores.memory.getMessages(args);
3469
+ }
3470
+ async getMessagesById({
3471
+ messageIds,
3472
+ format
3473
+ }) {
3474
+ return this.stores.memory.getMessagesById({ messageIds, format });
3475
+ }
3476
+ async getMessagesPaginated(args) {
3477
+ return this.stores.memory.getMessagesPaginated(args);
3478
+ }
3479
+ async saveMessages(args) {
3480
+ return this.stores.memory.saveMessages(args);
3481
+ }
3482
+ async updateMessages({
3483
+ messages
3484
+ }) {
3485
+ return this.stores.memory.updateMessages({ messages });
3486
+ }
3487
+ async deleteMessages(messageIds) {
3488
+ return this.stores.memory.deleteMessages(messageIds);
3489
+ }
3490
+ async getResourceById({ resourceId }) {
3491
+ return this.stores.memory.getResourceById({ resourceId });
3492
+ }
3493
+ async saveResource({ resource }) {
3494
+ return this.stores.memory.saveResource({ resource });
3495
+ }
3496
+ async updateResource({
3497
+ resourceId,
3498
+ workingMemory,
3499
+ metadata
3500
+ }) {
3501
+ return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
3502
+ }
3503
+ /**
3504
+ * Workflows
3505
+ */
3506
+ async updateWorkflowResults({
3507
+ workflowName,
3508
+ runId,
3509
+ stepId,
3510
+ result,
3511
+ runtimeContext
3512
+ }) {
3513
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
3514
+ }
3515
+ async updateWorkflowState({
3516
+ workflowName,
3517
+ runId,
3518
+ opts
3519
+ }) {
3520
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
3521
+ }
3522
+ async persistWorkflowSnapshot({
3523
+ workflowName,
3524
+ runId,
3525
+ resourceId,
3526
+ snapshot
3527
+ }) {
3528
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
3529
+ }
3530
+ async loadWorkflowSnapshot({
3531
+ workflowName,
3532
+ runId
3533
+ }) {
3534
+ return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
3535
+ }
3536
+ async getWorkflowRuns(args = {}) {
3537
+ return this.stores.workflows.getWorkflowRuns(args);
3538
+ }
3539
+ async getWorkflowRunById({
3540
+ runId,
3541
+ workflowName
3542
+ }) {
3543
+ return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
3544
+ }
3545
+ async close() {
3546
+ await this.pool.close();
3547
+ }
3548
+ /**
3549
+ * Index Management
3550
+ */
3551
+ async createIndex(options) {
3552
+ return this.stores.operations.createIndex(options);
3553
+ }
3554
+ async listIndexes(tableName) {
3555
+ return this.stores.operations.listIndexes(tableName);
3556
+ }
3557
+ async describeIndex(indexName) {
3558
+ return this.stores.operations.describeIndex(indexName);
3559
+ }
3560
+ async dropIndex(indexName) {
3561
+ return this.stores.operations.dropIndex(indexName);
3562
+ }
3563
+ /**
3564
+ * AI Tracing / Observability
3565
+ */
3566
+ getObservabilityStore() {
3567
+ if (!this.stores.observability) {
3568
+ throw new error.MastraError({
3569
+ id: "MSSQL_STORE_OBSERVABILITY_NOT_INITIALIZED",
3570
+ domain: error.ErrorDomain.STORAGE,
3571
+ category: error.ErrorCategory.SYSTEM,
3572
+ text: "Observability storage is not initialized"
3573
+ });
3574
+ }
3575
+ return this.stores.observability;
3576
+ }
3577
+ async createAISpan(span) {
3578
+ return this.getObservabilityStore().createAISpan(span);
3579
+ }
3580
+ async updateAISpan({
3581
+ spanId,
3582
+ traceId,
3583
+ updates
3584
+ }) {
3585
+ return this.getObservabilityStore().updateAISpan({ spanId, traceId, updates });
3586
+ }
3587
+ async getAITrace(traceId) {
3588
+ return this.getObservabilityStore().getAITrace(traceId);
3589
+ }
3590
+ async getAITracesPaginated(args) {
3591
+ return this.getObservabilityStore().getAITracesPaginated(args);
3592
+ }
3593
+ async batchCreateAISpans(args) {
3594
+ return this.getObservabilityStore().batchCreateAISpans(args);
3595
+ }
3596
+ async batchUpdateAISpans(args) {
3597
+ return this.getObservabilityStore().batchUpdateAISpans(args);
3598
+ }
3599
+ async batchDeleteAITraces(args) {
3600
+ return this.getObservabilityStore().batchDeleteAITraces(args);
3601
+ }
3602
+ /**
3603
+ * Scorers
3604
+ */
3605
+ async getScoreById({ id: _id }) {
3606
+ return this.stores.scores.getScoreById({ id: _id });
3607
+ }
3608
+ async getScoresByScorerId({
3609
+ scorerId: _scorerId,
3610
+ pagination: _pagination,
3611
+ entityId: _entityId,
3612
+ entityType: _entityType,
3613
+ source: _source
3614
+ }) {
3615
+ return this.stores.scores.getScoresByScorerId({
3616
+ scorerId: _scorerId,
3617
+ pagination: _pagination,
3618
+ entityId: _entityId,
3619
+ entityType: _entityType,
3620
+ source: _source
3621
+ });
3622
+ }
3623
+ async saveScore(_score) {
3624
+ return this.stores.scores.saveScore(_score);
3625
+ }
3626
+ async getScoresByRunId({
3627
+ runId: _runId,
3628
+ pagination: _pagination
3629
+ }) {
3630
+ return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
3631
+ }
3632
+ async getScoresByEntityId({
3633
+ entityId: _entityId,
3634
+ entityType: _entityType,
3635
+ pagination: _pagination
3636
+ }) {
3637
+ return this.stores.scores.getScoresByEntityId({
3638
+ entityId: _entityId,
3639
+ entityType: _entityType,
3640
+ pagination: _pagination
3641
+ });
3642
+ }
3643
+ async getScoresBySpan({
3644
+ traceId,
3645
+ spanId,
3646
+ pagination: _pagination
3647
+ }) {
3648
+ return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination: _pagination });
1818
3649
  }
1819
3650
  };
1820
3651