@mastra/mssql 0.0.0-add-libsql-changeset-20250910154739

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,2367 @@
1
+ 'use strict';
2
+
3
+ var error = require('@mastra/core/error');
4
+ var storage = require('@mastra/core/storage');
5
+ var sql2 = require('mssql');
6
+ var utils = require('@mastra/core/utils');
7
+ var agent = require('@mastra/core/agent');
8
+
9
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
+
11
+ var sql2__default = /*#__PURE__*/_interopDefault(sql2);
12
+
13
+ // src/storage/index.ts
14
+ function getSchemaName(schema) {
15
+ return schema ? `[${utils.parseSqlIdentifier(schema, "schema name")}]` : void 0;
16
+ }
17
+ function getTableName({ indexName, schemaName }) {
18
+ const parsedIndexName = utils.parseSqlIdentifier(indexName, "index name");
19
+ const quotedIndexName = `[${parsedIndexName}]`;
20
+ const quotedSchemaName = schemaName;
21
+ return quotedSchemaName ? `${quotedSchemaName}.${quotedIndexName}` : quotedIndexName;
22
+ }
23
+
24
+ // src/storage/domains/legacy-evals/index.ts
25
+ function transformEvalRow(row) {
26
+ let testInfoValue = null, resultValue = null;
27
+ if (row.test_info) {
28
+ try {
29
+ testInfoValue = typeof row.test_info === "string" ? JSON.parse(row.test_info) : row.test_info;
30
+ } catch {
31
+ }
32
+ }
33
+ if (row.test_info) {
34
+ try {
35
+ resultValue = typeof row.result === "string" ? JSON.parse(row.result) : row.result;
36
+ } catch {
37
+ }
38
+ }
39
+ return {
40
+ agentName: row.agent_name,
41
+ input: row.input,
42
+ output: row.output,
43
+ result: resultValue,
44
+ metricName: row.metric_name,
45
+ instructions: row.instructions,
46
+ testInfo: testInfoValue,
47
+ globalRunId: row.global_run_id,
48
+ runId: row.run_id,
49
+ createdAt: row.created_at
50
+ };
51
+ }
52
+ var LegacyEvalsMSSQL = class extends storage.LegacyEvalsStorage {
53
+ pool;
54
+ schema;
55
+ constructor({ pool, schema }) {
56
+ super();
57
+ this.pool = pool;
58
+ this.schema = schema;
59
+ }
60
+ /** @deprecated use getEvals instead */
61
+ async getEvalsByAgentName(agentName, type) {
62
+ try {
63
+ let query = `SELECT * FROM ${getTableName({ indexName: storage.TABLE_EVALS, schemaName: getSchemaName(this.schema) })} WHERE agent_name = @p1`;
64
+ if (type === "test") {
65
+ query += " AND test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL";
66
+ } else if (type === "live") {
67
+ query += " AND (test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)";
68
+ }
69
+ query += " ORDER BY created_at DESC";
70
+ const request = this.pool.request();
71
+ request.input("p1", agentName);
72
+ const result = await request.query(query);
73
+ const rows = result.recordset;
74
+ return typeof transformEvalRow === "function" ? rows?.map((row) => transformEvalRow(row)) ?? [] : rows ?? [];
75
+ } catch (error) {
76
+ if (error && error.number === 208 && error.message && error.message.includes("Invalid object name")) {
77
+ return [];
78
+ }
79
+ console.error("Failed to get evals for the specified agent: " + error?.message);
80
+ throw error;
81
+ }
82
+ }
83
+ async getEvals(options = {}) {
84
+ const { agentName, type, page = 0, perPage = 100, dateRange } = options;
85
+ const fromDate = dateRange?.start;
86
+ const toDate = dateRange?.end;
87
+ const where = [];
88
+ const params = {};
89
+ if (agentName) {
90
+ where.push("agent_name = @agentName");
91
+ params["agentName"] = agentName;
92
+ }
93
+ if (type === "test") {
94
+ where.push("test_info IS NOT NULL AND JSON_VALUE(test_info, '$.testPath') IS NOT NULL");
95
+ } else if (type === "live") {
96
+ where.push("(test_info IS NULL OR JSON_VALUE(test_info, '$.testPath') IS NULL)");
97
+ }
98
+ if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
99
+ where.push(`[created_at] >= @fromDate`);
100
+ params[`fromDate`] = fromDate.toISOString();
101
+ }
102
+ if (toDate instanceof Date && !isNaN(toDate.getTime())) {
103
+ where.push(`[created_at] <= @toDate`);
104
+ params[`toDate`] = toDate.toISOString();
105
+ }
106
+ const whereClause = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
107
+ const tableName = getTableName({ indexName: storage.TABLE_EVALS, schemaName: getSchemaName(this.schema) });
108
+ const offset = page * perPage;
109
+ const countQuery = `SELECT COUNT(*) as total FROM ${tableName} ${whereClause}`;
110
+ const dataQuery = `SELECT * FROM ${tableName} ${whereClause} ORDER BY seq_id DESC OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
111
+ try {
112
+ const countReq = this.pool.request();
113
+ Object.entries(params).forEach(([key, value]) => {
114
+ if (value instanceof Date) {
115
+ countReq.input(key, sql2__default.default.DateTime, value);
116
+ } else {
117
+ countReq.input(key, value);
118
+ }
119
+ });
120
+ const countResult = await countReq.query(countQuery);
121
+ const total = countResult.recordset[0]?.total || 0;
122
+ if (total === 0) {
123
+ return {
124
+ evals: [],
125
+ total: 0,
126
+ page,
127
+ perPage,
128
+ hasMore: false
129
+ };
130
+ }
131
+ const req = this.pool.request();
132
+ Object.entries(params).forEach(([key, value]) => {
133
+ if (value instanceof Date) {
134
+ req.input(key, sql2__default.default.DateTime, value);
135
+ } else {
136
+ req.input(key, value);
137
+ }
138
+ });
139
+ req.input("offset", offset);
140
+ req.input("perPage", perPage);
141
+ const result = await req.query(dataQuery);
142
+ const rows = result.recordset;
143
+ return {
144
+ evals: rows?.map((row) => transformEvalRow(row)) ?? [],
145
+ total,
146
+ page,
147
+ perPage,
148
+ hasMore: offset + (rows?.length ?? 0) < total
149
+ };
150
+ } catch (error$1) {
151
+ const mastraError = new error.MastraError(
152
+ {
153
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_EVALS_FAILED",
154
+ domain: error.ErrorDomain.STORAGE,
155
+ category: error.ErrorCategory.THIRD_PARTY,
156
+ details: {
157
+ agentName: agentName || "all",
158
+ type: type || "all",
159
+ page,
160
+ perPage
161
+ }
162
+ },
163
+ error$1
164
+ );
165
+ this.logger?.error?.(mastraError.toString());
166
+ this.logger?.trackException(mastraError);
167
+ throw mastraError;
168
+ }
169
+ }
170
+ };
171
+ var MemoryMSSQL = class extends storage.MemoryStorage {
172
+ pool;
173
+ schema;
174
+ operations;
175
+ _parseAndFormatMessages(messages, format) {
176
+ const messagesWithParsedContent = messages.map((message) => {
177
+ if (typeof message.content === "string") {
178
+ try {
179
+ return { ...message, content: JSON.parse(message.content) };
180
+ } catch {
181
+ return message;
182
+ }
183
+ }
184
+ return message;
185
+ });
186
+ const cleanMessages = messagesWithParsedContent.map(({ seq_id, ...rest }) => rest);
187
+ const list = new agent.MessageList().add(cleanMessages, "memory");
188
+ return format === "v2" ? list.get.all.v2() : list.get.all.v1();
189
+ }
190
+ constructor({
191
+ pool,
192
+ schema,
193
+ operations
194
+ }) {
195
+ super();
196
+ this.pool = pool;
197
+ this.schema = schema;
198
+ this.operations = operations;
199
+ }
200
+ async getThreadById({ threadId }) {
201
+ try {
202
+ const sql7 = `SELECT
203
+ id,
204
+ [resourceId],
205
+ title,
206
+ metadata,
207
+ [createdAt],
208
+ [updatedAt]
209
+ FROM ${getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) })}
210
+ WHERE id = @threadId`;
211
+ const request = this.pool.request();
212
+ request.input("threadId", threadId);
213
+ const resultSet = await request.query(sql7);
214
+ const thread = resultSet.recordset[0] || null;
215
+ if (!thread) {
216
+ return null;
217
+ }
218
+ return {
219
+ ...thread,
220
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
221
+ createdAt: thread.createdAt,
222
+ updatedAt: thread.updatedAt
223
+ };
224
+ } catch (error$1) {
225
+ throw new error.MastraError(
226
+ {
227
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREAD_BY_ID_FAILED",
228
+ domain: error.ErrorDomain.STORAGE,
229
+ category: error.ErrorCategory.THIRD_PARTY,
230
+ details: {
231
+ threadId
232
+ }
233
+ },
234
+ error$1
235
+ );
236
+ }
237
+ }
238
+ async getThreadsByResourceIdPaginated(args) {
239
+ const { resourceId, page = 0, perPage: perPageInput, orderBy = "createdAt", sortDirection = "DESC" } = args;
240
+ try {
241
+ const perPage = perPageInput !== void 0 ? perPageInput : 100;
242
+ const currentOffset = page * perPage;
243
+ const baseQuery = `FROM ${getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
244
+ const countQuery = `SELECT COUNT(*) as count ${baseQuery}`;
245
+ const countRequest = this.pool.request();
246
+ countRequest.input("resourceId", resourceId);
247
+ const countResult = await countRequest.query(countQuery);
248
+ const total = parseInt(countResult.recordset[0]?.count ?? "0", 10);
249
+ if (total === 0) {
250
+ return {
251
+ threads: [],
252
+ total: 0,
253
+ page,
254
+ perPage,
255
+ hasMore: false
256
+ };
257
+ }
258
+ const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
259
+ const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${sortDirection} OFFSET @offset ROWS FETCH NEXT @perPage ROWS ONLY`;
260
+ const dataRequest = this.pool.request();
261
+ dataRequest.input("resourceId", resourceId);
262
+ dataRequest.input("perPage", perPage);
263
+ dataRequest.input("offset", currentOffset);
264
+ const rowsResult = await dataRequest.query(dataQuery);
265
+ const rows = rowsResult.recordset || [];
266
+ const threads = rows.map((thread) => ({
267
+ ...thread,
268
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
269
+ createdAt: thread.createdAt,
270
+ updatedAt: thread.updatedAt
271
+ }));
272
+ return {
273
+ threads,
274
+ total,
275
+ page,
276
+ perPage,
277
+ hasMore: currentOffset + threads.length < total
278
+ };
279
+ } catch (error$1) {
280
+ const mastraError = new error.MastraError(
281
+ {
282
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
283
+ domain: error.ErrorDomain.STORAGE,
284
+ category: error.ErrorCategory.THIRD_PARTY,
285
+ details: {
286
+ resourceId,
287
+ page
288
+ }
289
+ },
290
+ error$1
291
+ );
292
+ this.logger?.error?.(mastraError.toString());
293
+ this.logger?.trackException?.(mastraError);
294
+ return { threads: [], total: 0, page, perPage: perPageInput || 100, hasMore: false };
295
+ }
296
+ }
297
+ async saveThread({ thread }) {
298
+ try {
299
+ const table = getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) });
300
+ const mergeSql = `MERGE INTO ${table} WITH (HOLDLOCK) AS target
301
+ USING (SELECT @id AS id) AS source
302
+ ON (target.id = source.id)
303
+ WHEN MATCHED THEN
304
+ UPDATE SET
305
+ [resourceId] = @resourceId,
306
+ title = @title,
307
+ metadata = @metadata,
308
+ [updatedAt] = @updatedAt
309
+ WHEN NOT MATCHED THEN
310
+ INSERT (id, [resourceId], title, metadata, [createdAt], [updatedAt])
311
+ VALUES (@id, @resourceId, @title, @metadata, @createdAt, @updatedAt);`;
312
+ const req = this.pool.request();
313
+ req.input("id", thread.id);
314
+ req.input("resourceId", thread.resourceId);
315
+ req.input("title", thread.title);
316
+ req.input("metadata", thread.metadata ? JSON.stringify(thread.metadata) : null);
317
+ req.input("createdAt", sql2__default.default.DateTime2, thread.createdAt);
318
+ req.input("updatedAt", sql2__default.default.DateTime2, thread.updatedAt);
319
+ await req.query(mergeSql);
320
+ return thread;
321
+ } catch (error$1) {
322
+ throw new error.MastraError(
323
+ {
324
+ id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_THREAD_FAILED",
325
+ domain: error.ErrorDomain.STORAGE,
326
+ category: error.ErrorCategory.THIRD_PARTY,
327
+ details: {
328
+ threadId: thread.id
329
+ }
330
+ },
331
+ error$1
332
+ );
333
+ }
334
+ }
335
+ /**
336
+ * @deprecated use getThreadsByResourceIdPaginated instead
337
+ */
338
+ async getThreadsByResourceId(args) {
339
+ const { resourceId, orderBy = "createdAt", sortDirection = "DESC" } = args;
340
+ try {
341
+ const baseQuery = `FROM ${getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) })} WHERE [resourceId] = @resourceId`;
342
+ const orderByField = orderBy === "createdAt" ? "[createdAt]" : "[updatedAt]";
343
+ const dataQuery = `SELECT id, [resourceId], title, metadata, [createdAt], [updatedAt] ${baseQuery} ORDER BY ${orderByField} ${sortDirection}`;
344
+ const request = this.pool.request();
345
+ request.input("resourceId", resourceId);
346
+ const resultSet = await request.query(dataQuery);
347
+ const rows = resultSet.recordset || [];
348
+ return rows.map((thread) => ({
349
+ ...thread,
350
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
351
+ createdAt: thread.createdAt,
352
+ updatedAt: thread.updatedAt
353
+ }));
354
+ } catch (error) {
355
+ this.logger?.error?.(`Error getting threads for resource ${resourceId}:`, error);
356
+ return [];
357
+ }
358
+ }
359
+ /**
360
+ * Updates a thread's title and metadata, merging with existing metadata. Returns the updated thread.
361
+ */
362
+ async updateThread({
363
+ id,
364
+ title,
365
+ metadata
366
+ }) {
367
+ const existingThread = await this.getThreadById({ threadId: id });
368
+ if (!existingThread) {
369
+ throw new error.MastraError({
370
+ id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_THREAD_FAILED",
371
+ domain: error.ErrorDomain.STORAGE,
372
+ category: error.ErrorCategory.USER,
373
+ text: `Thread ${id} not found`,
374
+ details: {
375
+ threadId: id,
376
+ title
377
+ }
378
+ });
379
+ }
380
+ const mergedMetadata = {
381
+ ...existingThread.metadata,
382
+ ...metadata
383
+ };
384
+ try {
385
+ const table = getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) });
386
+ const sql7 = `UPDATE ${table}
387
+ SET title = @title,
388
+ metadata = @metadata,
389
+ [updatedAt] = @updatedAt
390
+ OUTPUT INSERTED.*
391
+ WHERE id = @id`;
392
+ const req = this.pool.request();
393
+ req.input("id", id);
394
+ req.input("title", title);
395
+ req.input("metadata", JSON.stringify(mergedMetadata));
396
+ req.input("updatedAt", /* @__PURE__ */ new Date());
397
+ const result = await req.query(sql7);
398
+ let thread = result.recordset && result.recordset[0];
399
+ if (thread && "seq_id" in thread) {
400
+ const { seq_id, ...rest } = thread;
401
+ thread = rest;
402
+ }
403
+ if (!thread) {
404
+ throw new error.MastraError({
405
+ id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_THREAD_FAILED",
406
+ domain: error.ErrorDomain.STORAGE,
407
+ category: error.ErrorCategory.USER,
408
+ text: `Thread ${id} not found after update`,
409
+ details: {
410
+ threadId: id,
411
+ title
412
+ }
413
+ });
414
+ }
415
+ return {
416
+ ...thread,
417
+ metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata) : thread.metadata,
418
+ createdAt: thread.createdAt,
419
+ updatedAt: thread.updatedAt
420
+ };
421
+ } catch (error$1) {
422
+ throw new error.MastraError(
423
+ {
424
+ id: "MASTRA_STORAGE_MSSQL_STORE_UPDATE_THREAD_FAILED",
425
+ domain: error.ErrorDomain.STORAGE,
426
+ category: error.ErrorCategory.THIRD_PARTY,
427
+ details: {
428
+ threadId: id,
429
+ title
430
+ }
431
+ },
432
+ error$1
433
+ );
434
+ }
435
+ }
436
+ async deleteThread({ threadId }) {
437
+ const messagesTable = getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
438
+ const threadsTable = getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) });
439
+ const deleteMessagesSql = `DELETE FROM ${messagesTable} WHERE [thread_id] = @threadId`;
440
+ const deleteThreadSql = `DELETE FROM ${threadsTable} WHERE id = @threadId`;
441
+ const tx = this.pool.transaction();
442
+ try {
443
+ await tx.begin();
444
+ const req = tx.request();
445
+ req.input("threadId", threadId);
446
+ await req.query(deleteMessagesSql);
447
+ await req.query(deleteThreadSql);
448
+ await tx.commit();
449
+ } catch (error$1) {
450
+ await tx.rollback().catch(() => {
451
+ });
452
+ throw new error.MastraError(
453
+ {
454
+ id: "MASTRA_STORAGE_MSSQL_STORE_DELETE_THREAD_FAILED",
455
+ domain: error.ErrorDomain.STORAGE,
456
+ category: error.ErrorCategory.THIRD_PARTY,
457
+ details: {
458
+ threadId
459
+ }
460
+ },
461
+ error$1
462
+ );
463
+ }
464
+ }
465
+ async _getIncludedMessages({
466
+ threadId,
467
+ selectBy,
468
+ orderByStatement
469
+ }) {
470
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
471
+ const include = selectBy?.include;
472
+ if (!include) return null;
473
+ const unionQueries = [];
474
+ const paramValues = [];
475
+ let paramIdx = 1;
476
+ const paramNames = [];
477
+ for (const inc of include) {
478
+ const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
479
+ const searchId = inc.threadId || threadId;
480
+ const pThreadId = `@p${paramIdx}`;
481
+ const pId = `@p${paramIdx + 1}`;
482
+ const pPrev = `@p${paramIdx + 2}`;
483
+ const pNext = `@p${paramIdx + 3}`;
484
+ unionQueries.push(
485
+ `
486
+ SELECT
487
+ m.id,
488
+ m.content,
489
+ m.role,
490
+ m.type,
491
+ m.[createdAt],
492
+ m.thread_id AS threadId,
493
+ m.[resourceId],
494
+ m.seq_id
495
+ FROM (
496
+ SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
497
+ FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
498
+ WHERE [thread_id] = ${pThreadId}
499
+ ) AS m
500
+ WHERE m.id = ${pId}
501
+ OR EXISTS (
502
+ SELECT 1
503
+ FROM (
504
+ SELECT *, ROW_NUMBER() OVER (${orderByStatement}) as row_num
505
+ FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}
506
+ WHERE [thread_id] = ${pThreadId}
507
+ ) AS target
508
+ WHERE target.id = ${pId}
509
+ AND (
510
+ (m.row_num <= target.row_num + ${pPrev} AND m.row_num > target.row_num)
511
+ OR
512
+ (m.row_num >= target.row_num - ${pNext} AND m.row_num < target.row_num)
513
+ )
514
+ )
515
+ `
516
+ );
517
+ paramValues.push(searchId, id, withPreviousMessages, withNextMessages);
518
+ paramNames.push(`p${paramIdx}`, `p${paramIdx + 1}`, `p${paramIdx + 2}`, `p${paramIdx + 3}`);
519
+ paramIdx += 4;
520
+ }
521
+ const finalQuery = `
522
+ SELECT * FROM (
523
+ ${unionQueries.join(" UNION ALL ")}
524
+ ) AS union_result
525
+ ORDER BY [seq_id] ASC
526
+ `;
527
+ const req = this.pool.request();
528
+ for (let i = 0; i < paramValues.length; ++i) {
529
+ req.input(paramNames[i], paramValues[i]);
530
+ }
531
+ const result = await req.query(finalQuery);
532
+ const includedRows = result.recordset || [];
533
+ const seen = /* @__PURE__ */ new Set();
534
+ const dedupedRows = includedRows.filter((row) => {
535
+ if (seen.has(row.id)) return false;
536
+ seen.add(row.id);
537
+ return true;
538
+ });
539
+ return dedupedRows;
540
+ }
541
+ async getMessages(args) {
542
+ const { threadId, resourceId, format, selectBy } = args;
543
+ const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
544
+ const orderByStatement = `ORDER BY [seq_id] DESC`;
545
+ const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
546
+ try {
547
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
548
+ let rows = [];
549
+ const include = selectBy?.include || [];
550
+ if (include?.length) {
551
+ const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
552
+ if (includeMessages) {
553
+ rows.push(...includeMessages);
554
+ }
555
+ }
556
+ const excludeIds = rows.map((m) => m.id).filter(Boolean);
557
+ let query = `${selectStatement} FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [thread_id] = @threadId`;
558
+ const request = this.pool.request();
559
+ request.input("threadId", threadId);
560
+ if (excludeIds.length > 0) {
561
+ const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
562
+ query += ` AND id NOT IN (${excludeParams.join(", ")})`;
563
+ excludeIds.forEach((id, idx) => {
564
+ request.input(`id${idx}`, id);
565
+ });
566
+ }
567
+ query += ` ${orderByStatement} OFFSET 0 ROWS FETCH NEXT @limit ROWS ONLY`;
568
+ request.input("limit", limit);
569
+ const result = await request.query(query);
570
+ const remainingRows = result.recordset || [];
571
+ rows.push(...remainingRows);
572
+ rows.sort((a, b) => {
573
+ const timeDiff = a.seq_id - b.seq_id;
574
+ return timeDiff;
575
+ });
576
+ rows = rows.map(({ seq_id, ...rest }) => rest);
577
+ return this._parseAndFormatMessages(rows, format);
578
+ } catch (error$1) {
579
+ const mastraError = new error.MastraError(
580
+ {
581
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_FAILED",
582
+ domain: error.ErrorDomain.STORAGE,
583
+ category: error.ErrorCategory.THIRD_PARTY,
584
+ details: {
585
+ threadId,
586
+ resourceId: resourceId ?? ""
587
+ }
588
+ },
589
+ error$1
590
+ );
591
+ this.logger?.error?.(mastraError.toString());
592
+ this.logger?.trackException(mastraError);
593
+ return [];
594
+ }
595
+ }
596
+ async getMessagesById({
597
+ messageIds,
598
+ format
599
+ }) {
600
+ if (messageIds.length === 0) return [];
601
+ const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
602
+ const orderByStatement = `ORDER BY [seq_id] DESC`;
603
+ try {
604
+ let rows = [];
605
+ let query = `${selectStatement} FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} WHERE [id] IN (${messageIds.map((_, i) => `@id${i}`).join(", ")})`;
606
+ const request = this.pool.request();
607
+ messageIds.forEach((id, i) => request.input(`id${i}`, id));
608
+ query += ` ${orderByStatement}`;
609
+ const result = await request.query(query);
610
+ const remainingRows = result.recordset || [];
611
+ rows.push(...remainingRows);
612
+ rows.sort((a, b) => {
613
+ const timeDiff = a.seq_id - b.seq_id;
614
+ return timeDiff;
615
+ });
616
+ rows = rows.map(({ seq_id, ...rest }) => rest);
617
+ if (format === `v1`) return this._parseAndFormatMessages(rows, format);
618
+ return this._parseAndFormatMessages(rows, `v2`);
619
+ } catch (error$1) {
620
+ const mastraError = new error.MastraError(
621
+ {
622
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_BY_ID_FAILED",
623
+ domain: error.ErrorDomain.STORAGE,
624
+ category: error.ErrorCategory.THIRD_PARTY,
625
+ details: {
626
+ messageIds: JSON.stringify(messageIds)
627
+ }
628
+ },
629
+ error$1
630
+ );
631
+ this.logger?.error?.(mastraError.toString());
632
+ this.logger?.trackException(mastraError);
633
+ return [];
634
+ }
635
+ }
636
+ async getMessagesPaginated(args) {
637
+ const { threadId, resourceId, format, selectBy } = args;
638
+ const { page = 0, perPage: perPageInput, dateRange } = selectBy?.pagination || {};
639
+ try {
640
+ if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
641
+ const fromDate = dateRange?.start;
642
+ const toDate = dateRange?.end;
643
+ const selectStatement = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId`;
644
+ const orderByStatement = `ORDER BY [seq_id] DESC`;
645
+ let messages = [];
646
+ if (selectBy?.include?.length) {
647
+ const includeMessages = await this._getIncludedMessages({ threadId, selectBy, orderByStatement });
648
+ if (includeMessages) messages.push(...includeMessages);
649
+ }
650
+ const perPage = perPageInput !== void 0 ? perPageInput : storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
651
+ const currentOffset = page * perPage;
652
+ const conditions = ["[thread_id] = @threadId"];
653
+ const request = this.pool.request();
654
+ request.input("threadId", threadId);
655
+ if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
656
+ conditions.push("[createdAt] >= @fromDate");
657
+ request.input("fromDate", fromDate.toISOString());
658
+ }
659
+ if (toDate instanceof Date && !isNaN(toDate.getTime())) {
660
+ conditions.push("[createdAt] <= @toDate");
661
+ request.input("toDate", toDate.toISOString());
662
+ }
663
+ const whereClause = `WHERE ${conditions.join(" AND ")}`;
664
+ const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
665
+ const countResult = await request.query(countQuery);
666
+ const total = parseInt(countResult.recordset[0]?.total, 10) || 0;
667
+ if (total === 0 && messages.length > 0) {
668
+ const parsedIncluded = this._parseAndFormatMessages(messages, format);
669
+ return {
670
+ messages: parsedIncluded,
671
+ total: parsedIncluded.length,
672
+ page,
673
+ perPage,
674
+ hasMore: false
675
+ };
676
+ }
677
+ const excludeIds = messages.map((m) => m.id);
678
+ if (excludeIds.length > 0) {
679
+ const excludeParams = excludeIds.map((_, idx) => `@id${idx}`);
680
+ conditions.push(`id NOT IN (${excludeParams.join(", ")})`);
681
+ excludeIds.forEach((id, idx) => request.input(`id${idx}`, id));
682
+ }
683
+ const finalWhereClause = `WHERE ${conditions.join(" AND ")}`;
684
+ const dataQuery = `${selectStatement} FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} ${finalWhereClause} ${orderByStatement} OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
685
+ request.input("offset", currentOffset);
686
+ request.input("limit", perPage);
687
+ const rowsResult = await request.query(dataQuery);
688
+ const rows = rowsResult.recordset || [];
689
+ rows.sort((a, b) => a.seq_id - b.seq_id);
690
+ messages.push(...rows);
691
+ const parsed = this._parseAndFormatMessages(messages, format);
692
+ return {
693
+ messages: parsed,
694
+ total: total + excludeIds.length,
695
+ page,
696
+ perPage,
697
+ hasMore: currentOffset + rows.length < total
698
+ };
699
+ } catch (error$1) {
700
+ const mastraError = new error.MastraError(
701
+ {
702
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_MESSAGES_PAGINATED_FAILED",
703
+ domain: error.ErrorDomain.STORAGE,
704
+ category: error.ErrorCategory.THIRD_PARTY,
705
+ details: {
706
+ threadId,
707
+ resourceId: resourceId ?? "",
708
+ page
709
+ }
710
+ },
711
+ error$1
712
+ );
713
+ this.logger?.error?.(mastraError.toString());
714
+ this.logger?.trackException(mastraError);
715
+ return { messages: [], total: 0, page, perPage: perPageInput || 40, hasMore: false };
716
+ }
717
+ }
718
+ async saveMessages({
719
+ messages,
720
+ format
721
+ }) {
722
+ if (messages.length === 0) return messages;
723
+ const threadId = messages[0]?.threadId;
724
+ if (!threadId) {
725
+ throw new error.MastraError({
726
+ id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_MESSAGES_FAILED",
727
+ domain: error.ErrorDomain.STORAGE,
728
+ category: error.ErrorCategory.THIRD_PARTY,
729
+ text: `Thread ID is required`
730
+ });
731
+ }
732
+ const thread = await this.getThreadById({ threadId });
733
+ if (!thread) {
734
+ throw new error.MastraError({
735
+ id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_MESSAGES_FAILED",
736
+ domain: error.ErrorDomain.STORAGE,
737
+ category: error.ErrorCategory.THIRD_PARTY,
738
+ text: `Thread ${threadId} not found`,
739
+ details: { threadId }
740
+ });
741
+ }
742
+ const tableMessages = getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
743
+ const tableThreads = getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) });
744
+ try {
745
+ const transaction = this.pool.transaction();
746
+ await transaction.begin();
747
+ try {
748
+ for (const message of messages) {
749
+ if (!message.threadId) {
750
+ throw new Error(
751
+ `Expected to find a threadId for message, but couldn't find one. An unexpected error has occurred.`
752
+ );
753
+ }
754
+ if (!message.resourceId) {
755
+ throw new Error(
756
+ `Expected to find a resourceId for message, but couldn't find one. An unexpected error has occurred.`
757
+ );
758
+ }
759
+ const request = transaction.request();
760
+ request.input("id", message.id);
761
+ request.input("thread_id", message.threadId);
762
+ request.input(
763
+ "content",
764
+ typeof message.content === "string" ? message.content : JSON.stringify(message.content)
765
+ );
766
+ request.input("createdAt", sql2__default.default.DateTime2, message.createdAt);
767
+ request.input("role", message.role);
768
+ request.input("type", message.type || "v2");
769
+ request.input("resourceId", message.resourceId);
770
+ const mergeSql = `MERGE INTO ${tableMessages} AS target
771
+ USING (SELECT @id AS id) AS src
772
+ ON target.id = src.id
773
+ WHEN MATCHED THEN UPDATE SET
774
+ thread_id = @thread_id,
775
+ content = @content,
776
+ [createdAt] = @createdAt,
777
+ role = @role,
778
+ type = @type,
779
+ resourceId = @resourceId
780
+ WHEN NOT MATCHED THEN INSERT (id, thread_id, content, [createdAt], role, type, resourceId)
781
+ VALUES (@id, @thread_id, @content, @createdAt, @role, @type, @resourceId);`;
782
+ await request.query(mergeSql);
783
+ }
784
+ const threadReq = transaction.request();
785
+ threadReq.input("updatedAt", sql2__default.default.DateTime2, /* @__PURE__ */ new Date());
786
+ threadReq.input("id", threadId);
787
+ await threadReq.query(`UPDATE ${tableThreads} SET [updatedAt] = @updatedAt WHERE id = @id`);
788
+ await transaction.commit();
789
+ } catch (error) {
790
+ await transaction.rollback();
791
+ throw error;
792
+ }
793
+ const messagesWithParsedContent = messages.map((message) => {
794
+ if (typeof message.content === "string") {
795
+ try {
796
+ return { ...message, content: JSON.parse(message.content) };
797
+ } catch {
798
+ return message;
799
+ }
800
+ }
801
+ return message;
802
+ });
803
+ const list = new agent.MessageList().add(messagesWithParsedContent, "memory");
804
+ if (format === "v2") return list.get.all.v2();
805
+ return list.get.all.v1();
806
+ } catch (error$1) {
807
+ throw new error.MastraError(
808
+ {
809
+ id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_MESSAGES_FAILED",
810
+ domain: error.ErrorDomain.STORAGE,
811
+ category: error.ErrorCategory.THIRD_PARTY,
812
+ details: { threadId }
813
+ },
814
+ error$1
815
+ );
816
+ }
817
+ }
818
+ async updateMessages({
819
+ messages
820
+ }) {
821
+ if (!messages || messages.length === 0) {
822
+ return [];
823
+ }
824
+ const messageIds = messages.map((m) => m.id);
825
+ const idParams = messageIds.map((_, i) => `@id${i}`).join(", ");
826
+ let selectQuery = `SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId FROM ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })}`;
827
+ if (idParams.length > 0) {
828
+ selectQuery += ` WHERE id IN (${idParams})`;
829
+ } else {
830
+ return [];
831
+ }
832
+ const selectReq = this.pool.request();
833
+ messageIds.forEach((id, i) => selectReq.input(`id${i}`, id));
834
+ const existingMessagesDb = (await selectReq.query(selectQuery)).recordset;
835
+ if (!existingMessagesDb || existingMessagesDb.length === 0) {
836
+ return [];
837
+ }
838
+ const existingMessages = existingMessagesDb.map((msg) => {
839
+ if (typeof msg.content === "string") {
840
+ try {
841
+ msg.content = JSON.parse(msg.content);
842
+ } catch {
843
+ }
844
+ }
845
+ return msg;
846
+ });
847
+ const threadIdsToUpdate = /* @__PURE__ */ new Set();
848
+ const transaction = this.pool.transaction();
849
+ try {
850
+ await transaction.begin();
851
+ for (const existingMessage of existingMessages) {
852
+ const updatePayload = messages.find((m) => m.id === existingMessage.id);
853
+ if (!updatePayload) continue;
854
+ const { id, ...fieldsToUpdate } = updatePayload;
855
+ if (Object.keys(fieldsToUpdate).length === 0) continue;
856
+ threadIdsToUpdate.add(existingMessage.threadId);
857
+ if (updatePayload.threadId && updatePayload.threadId !== existingMessage.threadId) {
858
+ threadIdsToUpdate.add(updatePayload.threadId);
859
+ }
860
+ const setClauses = [];
861
+ const req = transaction.request();
862
+ req.input("id", id);
863
+ const columnMapping = { threadId: "thread_id" };
864
+ const updatableFields = { ...fieldsToUpdate };
865
+ if (updatableFields.content) {
866
+ const newContent = {
867
+ ...existingMessage.content,
868
+ ...updatableFields.content,
869
+ ...existingMessage.content?.metadata && updatableFields.content.metadata ? { metadata: { ...existingMessage.content.metadata, ...updatableFields.content.metadata } } : {}
870
+ };
871
+ setClauses.push(`content = @content`);
872
+ req.input("content", JSON.stringify(newContent));
873
+ delete updatableFields.content;
874
+ }
875
+ for (const key in updatableFields) {
876
+ if (Object.prototype.hasOwnProperty.call(updatableFields, key)) {
877
+ const dbColumn = columnMapping[key] || key;
878
+ setClauses.push(`[${dbColumn}] = @${dbColumn}`);
879
+ req.input(dbColumn, updatableFields[key]);
880
+ }
881
+ }
882
+ if (setClauses.length > 0) {
883
+ const updateSql = `UPDATE ${getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) })} SET ${setClauses.join(", ")} WHERE id = @id`;
884
+ await req.query(updateSql);
885
+ }
886
+ }
887
+ if (threadIdsToUpdate.size > 0) {
888
+ const threadIdParams = Array.from(threadIdsToUpdate).map((_, i) => `@tid${i}`).join(", ");
889
+ const threadReq = transaction.request();
890
+ Array.from(threadIdsToUpdate).forEach((tid, i) => threadReq.input(`tid${i}`, tid));
891
+ threadReq.input("updatedAt", (/* @__PURE__ */ new Date()).toISOString());
892
+ const threadSql = `UPDATE ${getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) })} SET updatedAt = @updatedAt WHERE id IN (${threadIdParams})`;
893
+ await threadReq.query(threadSql);
894
+ }
895
+ await transaction.commit();
896
+ } catch (error$1) {
897
+ await transaction.rollback();
898
+ throw new error.MastraError(
899
+ {
900
+ id: "MASTRA_STORAGE_MSSQL_UPDATE_MESSAGES_FAILED",
901
+ domain: error.ErrorDomain.STORAGE,
902
+ category: error.ErrorCategory.THIRD_PARTY
903
+ },
904
+ error$1
905
+ );
906
+ }
907
+ const refetchReq = this.pool.request();
908
+ messageIds.forEach((id, i) => refetchReq.input(`id${i}`, id));
909
+ const updatedMessages = (await refetchReq.query(selectQuery)).recordset;
910
+ return (updatedMessages || []).map((message) => {
911
+ if (typeof message.content === "string") {
912
+ try {
913
+ message.content = JSON.parse(message.content);
914
+ } catch {
915
+ }
916
+ }
917
+ return message;
918
+ });
919
+ }
920
+ async deleteMessages(messageIds) {
921
+ if (!messageIds || messageIds.length === 0) {
922
+ return;
923
+ }
924
+ try {
925
+ const messageTableName = getTableName({ indexName: storage.TABLE_MESSAGES, schemaName: getSchemaName(this.schema) });
926
+ const threadTableName = getTableName({ indexName: storage.TABLE_THREADS, schemaName: getSchemaName(this.schema) });
927
+ const placeholders = messageIds.map((_, idx) => `@p${idx + 1}`).join(",");
928
+ const request = this.pool.request();
929
+ messageIds.forEach((id, idx) => {
930
+ request.input(`p${idx + 1}`, id);
931
+ });
932
+ const messages = await request.query(
933
+ `SELECT DISTINCT [thread_id] FROM ${messageTableName} WHERE [id] IN (${placeholders})`
934
+ );
935
+ const threadIds = messages.recordset?.map((msg) => msg.thread_id).filter(Boolean) || [];
936
+ const transaction = this.pool.transaction();
937
+ await transaction.begin();
938
+ try {
939
+ const deleteRequest = transaction.request();
940
+ messageIds.forEach((id, idx) => {
941
+ deleteRequest.input(`p${idx + 1}`, id);
942
+ });
943
+ await deleteRequest.query(`DELETE FROM ${messageTableName} WHERE [id] IN (${placeholders})`);
944
+ if (threadIds.length > 0) {
945
+ for (const threadId of threadIds) {
946
+ const updateRequest = transaction.request();
947
+ updateRequest.input("p1", threadId);
948
+ await updateRequest.query(`UPDATE ${threadTableName} SET [updatedAt] = GETDATE() WHERE [id] = @p1`);
949
+ }
950
+ }
951
+ await transaction.commit();
952
+ } catch (error) {
953
+ try {
954
+ await transaction.rollback();
955
+ } catch {
956
+ }
957
+ throw error;
958
+ }
959
+ } catch (error$1) {
960
+ throw new error.MastraError(
961
+ {
962
+ id: "MASTRA_STORAGE_MSSQL_STORE_DELETE_MESSAGES_FAILED",
963
+ domain: error.ErrorDomain.STORAGE,
964
+ category: error.ErrorCategory.THIRD_PARTY,
965
+ details: { messageIds: messageIds.join(", ") }
966
+ },
967
+ error$1
968
+ );
969
+ }
970
+ }
971
+ async getResourceById({ resourceId }) {
972
+ const tableName = getTableName({ indexName: storage.TABLE_RESOURCES, schemaName: getSchemaName(this.schema) });
973
+ try {
974
+ const req = this.pool.request();
975
+ req.input("resourceId", resourceId);
976
+ const result = (await req.query(`SELECT * FROM ${tableName} WHERE id = @resourceId`)).recordset[0];
977
+ if (!result) {
978
+ return null;
979
+ }
980
+ return {
981
+ ...result,
982
+ workingMemory: typeof result.workingMemory === "object" ? JSON.stringify(result.workingMemory) : result.workingMemory,
983
+ metadata: typeof result.metadata === "string" ? JSON.parse(result.metadata) : result.metadata
984
+ };
985
+ } catch (error$1) {
986
+ const mastraError = new error.MastraError(
987
+ {
988
+ id: "MASTRA_STORAGE_MSSQL_GET_RESOURCE_BY_ID_FAILED",
989
+ domain: error.ErrorDomain.STORAGE,
990
+ category: error.ErrorCategory.THIRD_PARTY,
991
+ details: { resourceId }
992
+ },
993
+ error$1
994
+ );
995
+ this.logger?.error?.(mastraError.toString());
996
+ this.logger?.trackException(mastraError);
997
+ throw mastraError;
998
+ }
999
+ }
1000
+ async saveResource({ resource }) {
1001
+ await this.operations.insert({
1002
+ tableName: storage.TABLE_RESOURCES,
1003
+ record: {
1004
+ ...resource,
1005
+ metadata: JSON.stringify(resource.metadata)
1006
+ }
1007
+ });
1008
+ return resource;
1009
+ }
1010
+ async updateResource({
1011
+ resourceId,
1012
+ workingMemory,
1013
+ metadata
1014
+ }) {
1015
+ try {
1016
+ const existingResource = await this.getResourceById({ resourceId });
1017
+ if (!existingResource) {
1018
+ const newResource = {
1019
+ id: resourceId,
1020
+ workingMemory,
1021
+ metadata: metadata || {},
1022
+ createdAt: /* @__PURE__ */ new Date(),
1023
+ updatedAt: /* @__PURE__ */ new Date()
1024
+ };
1025
+ return this.saveResource({ resource: newResource });
1026
+ }
1027
+ const updatedResource = {
1028
+ ...existingResource,
1029
+ workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
1030
+ metadata: {
1031
+ ...existingResource.metadata,
1032
+ ...metadata
1033
+ },
1034
+ updatedAt: /* @__PURE__ */ new Date()
1035
+ };
1036
+ const tableName = getTableName({ indexName: storage.TABLE_RESOURCES, schemaName: getSchemaName(this.schema) });
1037
+ const updates = [];
1038
+ const req = this.pool.request();
1039
+ if (workingMemory !== void 0) {
1040
+ updates.push("workingMemory = @workingMemory");
1041
+ req.input("workingMemory", workingMemory);
1042
+ }
1043
+ if (metadata) {
1044
+ updates.push("metadata = @metadata");
1045
+ req.input("metadata", JSON.stringify(updatedResource.metadata));
1046
+ }
1047
+ updates.push("updatedAt = @updatedAt");
1048
+ req.input("updatedAt", updatedResource.updatedAt.toISOString());
1049
+ req.input("id", resourceId);
1050
+ await req.query(`UPDATE ${tableName} SET ${updates.join(", ")} WHERE id = @id`);
1051
+ return updatedResource;
1052
+ } catch (error$1) {
1053
+ const mastraError = new error.MastraError(
1054
+ {
1055
+ id: "MASTRA_STORAGE_MSSQL_UPDATE_RESOURCE_FAILED",
1056
+ domain: error.ErrorDomain.STORAGE,
1057
+ category: error.ErrorCategory.THIRD_PARTY,
1058
+ details: { resourceId }
1059
+ },
1060
+ error$1
1061
+ );
1062
+ this.logger?.error?.(mastraError.toString());
1063
+ this.logger?.trackException(mastraError);
1064
+ throw mastraError;
1065
+ }
1066
+ }
1067
+ };
1068
+ var StoreOperationsMSSQL = class extends storage.StoreOperations {
1069
+ pool;
1070
+ schemaName;
1071
+ setupSchemaPromise = null;
1072
+ schemaSetupComplete = void 0;
1073
+ getSqlType(type, isPrimaryKey = false) {
1074
+ switch (type) {
1075
+ case "text":
1076
+ return isPrimaryKey ? "NVARCHAR(255)" : "NVARCHAR(MAX)";
1077
+ case "timestamp":
1078
+ return "DATETIME2(7)";
1079
+ case "uuid":
1080
+ return "UNIQUEIDENTIFIER";
1081
+ case "jsonb":
1082
+ return "NVARCHAR(MAX)";
1083
+ case "integer":
1084
+ return "INT";
1085
+ case "bigint":
1086
+ return "BIGINT";
1087
+ case "float":
1088
+ return "FLOAT";
1089
+ default:
1090
+ throw new error.MastraError({
1091
+ id: "MASTRA_STORAGE_MSSQL_STORE_TYPE_NOT_SUPPORTED",
1092
+ domain: error.ErrorDomain.STORAGE,
1093
+ category: error.ErrorCategory.THIRD_PARTY
1094
+ });
1095
+ }
1096
+ }
1097
+ constructor({ pool, schemaName }) {
1098
+ super();
1099
+ this.pool = pool;
1100
+ this.schemaName = schemaName;
1101
+ }
1102
+ async hasColumn(table, column) {
1103
+ const schema = this.schemaName || "dbo";
1104
+ const request = this.pool.request();
1105
+ request.input("schema", schema);
1106
+ request.input("table", table);
1107
+ request.input("column", column);
1108
+ request.input("columnLower", column.toLowerCase());
1109
+ const result = await request.query(
1110
+ `SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @table AND (COLUMN_NAME = @column OR COLUMN_NAME = @columnLower)`
1111
+ );
1112
+ return result.recordset.length > 0;
1113
+ }
1114
+ async setupSchema() {
1115
+ if (!this.schemaName || this.schemaSetupComplete) {
1116
+ return;
1117
+ }
1118
+ if (!this.setupSchemaPromise) {
1119
+ this.setupSchemaPromise = (async () => {
1120
+ try {
1121
+ const checkRequest = this.pool.request();
1122
+ checkRequest.input("schemaName", this.schemaName);
1123
+ const checkResult = await checkRequest.query(`
1124
+ SELECT 1 AS found FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @schemaName
1125
+ `);
1126
+ const schemaExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
1127
+ if (!schemaExists) {
1128
+ try {
1129
+ await this.pool.request().query(`CREATE SCHEMA [${this.schemaName}]`);
1130
+ this.logger?.info?.(`Schema "${this.schemaName}" created successfully`);
1131
+ } catch (error) {
1132
+ this.logger?.error?.(`Failed to create schema "${this.schemaName}"`, { error });
1133
+ throw new Error(
1134
+ `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.`
1135
+ );
1136
+ }
1137
+ }
1138
+ this.schemaSetupComplete = true;
1139
+ this.logger?.debug?.(`Schema "${this.schemaName}" is ready for use`);
1140
+ } catch (error) {
1141
+ this.schemaSetupComplete = void 0;
1142
+ this.setupSchemaPromise = null;
1143
+ throw error;
1144
+ } finally {
1145
+ this.setupSchemaPromise = null;
1146
+ }
1147
+ })();
1148
+ }
1149
+ await this.setupSchemaPromise;
1150
+ }
1151
+ async insert({ tableName, record }) {
1152
+ try {
1153
+ const columns = Object.keys(record).map((col) => utils.parseSqlIdentifier(col, "column name"));
1154
+ const values = Object.values(record);
1155
+ const paramNames = values.map((_, i) => `@param${i}`);
1156
+ const insertSql = `INSERT INTO ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} (${columns.map((c) => `[${c}]`).join(", ")}) VALUES (${paramNames.join(", ")})`;
1157
+ const request = this.pool.request();
1158
+ values.forEach((value, i) => {
1159
+ if (value instanceof Date) {
1160
+ request.input(`param${i}`, sql2__default.default.DateTime2, value);
1161
+ } else if (typeof value === "object" && value !== null) {
1162
+ request.input(`param${i}`, JSON.stringify(value));
1163
+ } else {
1164
+ request.input(`param${i}`, value);
1165
+ }
1166
+ });
1167
+ await request.query(insertSql);
1168
+ } catch (error$1) {
1169
+ throw new error.MastraError(
1170
+ {
1171
+ id: "MASTRA_STORAGE_MSSQL_STORE_INSERT_FAILED",
1172
+ domain: error.ErrorDomain.STORAGE,
1173
+ category: error.ErrorCategory.THIRD_PARTY,
1174
+ details: {
1175
+ tableName
1176
+ }
1177
+ },
1178
+ error$1
1179
+ );
1180
+ }
1181
+ }
1182
+ async clearTable({ tableName }) {
1183
+ const fullTableName = getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) });
1184
+ try {
1185
+ try {
1186
+ await this.pool.request().query(`TRUNCATE TABLE ${fullTableName}`);
1187
+ } catch (truncateError) {
1188
+ if (truncateError.message && truncateError.message.includes("foreign key")) {
1189
+ await this.pool.request().query(`DELETE FROM ${fullTableName}`);
1190
+ } else {
1191
+ throw truncateError;
1192
+ }
1193
+ }
1194
+ } catch (error$1) {
1195
+ throw new error.MastraError(
1196
+ {
1197
+ id: "MASTRA_STORAGE_MSSQL_STORE_CLEAR_TABLE_FAILED",
1198
+ domain: error.ErrorDomain.STORAGE,
1199
+ category: error.ErrorCategory.THIRD_PARTY,
1200
+ details: {
1201
+ tableName
1202
+ }
1203
+ },
1204
+ error$1
1205
+ );
1206
+ }
1207
+ }
1208
+ getDefaultValue(type) {
1209
+ switch (type) {
1210
+ case "timestamp":
1211
+ return "DEFAULT SYSDATETIMEOFFSET()";
1212
+ case "jsonb":
1213
+ return "DEFAULT N'{}'";
1214
+ default:
1215
+ return super.getDefaultValue(type);
1216
+ }
1217
+ }
1218
+ async createTable({
1219
+ tableName,
1220
+ schema
1221
+ }) {
1222
+ try {
1223
+ const uniqueConstraintColumns = tableName === storage.TABLE_WORKFLOW_SNAPSHOT ? ["workflow_name", "run_id"] : [];
1224
+ const columns = Object.entries(schema).map(([name, def]) => {
1225
+ const parsedName = utils.parseSqlIdentifier(name, "column name");
1226
+ const constraints = [];
1227
+ if (def.primaryKey) constraints.push("PRIMARY KEY");
1228
+ if (!def.nullable) constraints.push("NOT NULL");
1229
+ const isIndexed = !!def.primaryKey || uniqueConstraintColumns.includes(name);
1230
+ return `[${parsedName}] ${this.getSqlType(def.type, isIndexed)} ${constraints.join(" ")}`.trim();
1231
+ }).join(",\n");
1232
+ if (this.schemaName) {
1233
+ await this.setupSchema();
1234
+ }
1235
+ const checkTableRequest = this.pool.request();
1236
+ checkTableRequest.input(
1237
+ "tableName",
1238
+ getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) }).replace(/[[\]]/g, "").split(".").pop()
1239
+ );
1240
+ const checkTableSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName`;
1241
+ checkTableRequest.input("schema", this.schemaName || "dbo");
1242
+ const checkTableResult = await checkTableRequest.query(checkTableSql);
1243
+ const tableExists = Array.isArray(checkTableResult.recordset) && checkTableResult.recordset.length > 0;
1244
+ if (!tableExists) {
1245
+ const createSql = `CREATE TABLE ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} (
1246
+ ${columns}
1247
+ )`;
1248
+ await this.pool.request().query(createSql);
1249
+ }
1250
+ const columnCheckSql = `
1251
+ SELECT 1 AS found
1252
+ FROM INFORMATION_SCHEMA.COLUMNS
1253
+ WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = 'seq_id'
1254
+ `;
1255
+ const checkColumnRequest = this.pool.request();
1256
+ checkColumnRequest.input("schema", this.schemaName || "dbo");
1257
+ checkColumnRequest.input(
1258
+ "tableName",
1259
+ getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) }).replace(/[[\]]/g, "").split(".").pop()
1260
+ );
1261
+ const columnResult = await checkColumnRequest.query(columnCheckSql);
1262
+ const columnExists = Array.isArray(columnResult.recordset) && columnResult.recordset.length > 0;
1263
+ if (!columnExists) {
1264
+ const alterSql = `ALTER TABLE ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} ADD seq_id BIGINT IDENTITY(1,1)`;
1265
+ await this.pool.request().query(alterSql);
1266
+ }
1267
+ if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
1268
+ const constraintName = "mastra_workflow_snapshot_workflow_name_run_id_key";
1269
+ const checkConstraintSql = `SELECT 1 AS found FROM sys.key_constraints WHERE name = @constraintName`;
1270
+ const checkConstraintRequest = this.pool.request();
1271
+ checkConstraintRequest.input("constraintName", constraintName);
1272
+ const constraintResult = await checkConstraintRequest.query(checkConstraintSql);
1273
+ const constraintExists = Array.isArray(constraintResult.recordset) && constraintResult.recordset.length > 0;
1274
+ if (!constraintExists) {
1275
+ const addConstraintSql = `ALTER TABLE ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} ADD CONSTRAINT ${constraintName} UNIQUE ([workflow_name], [run_id])`;
1276
+ await this.pool.request().query(addConstraintSql);
1277
+ }
1278
+ }
1279
+ } catch (error$1) {
1280
+ throw new error.MastraError(
1281
+ {
1282
+ id: "MASTRA_STORAGE_MSSQL_STORE_CREATE_TABLE_FAILED",
1283
+ domain: error.ErrorDomain.STORAGE,
1284
+ category: error.ErrorCategory.THIRD_PARTY,
1285
+ details: {
1286
+ tableName
1287
+ }
1288
+ },
1289
+ error$1
1290
+ );
1291
+ }
1292
+ }
1293
+ /**
1294
+ * Alters table schema to add columns if they don't exist
1295
+ * @param tableName Name of the table
1296
+ * @param schema Schema of the table
1297
+ * @param ifNotExists Array of column names to add if they don't exist
1298
+ */
1299
+ async alterTable({
1300
+ tableName,
1301
+ schema,
1302
+ ifNotExists
1303
+ }) {
1304
+ const fullTableName = getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) });
1305
+ try {
1306
+ for (const columnName of ifNotExists) {
1307
+ if (schema[columnName]) {
1308
+ const columnCheckRequest = this.pool.request();
1309
+ columnCheckRequest.input("tableName", fullTableName.replace(/[[\]]/g, "").split(".").pop());
1310
+ columnCheckRequest.input("columnName", columnName);
1311
+ columnCheckRequest.input("schema", this.schemaName || "dbo");
1312
+ const checkSql = `SELECT 1 AS found FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = @columnName`;
1313
+ const checkResult = await columnCheckRequest.query(checkSql);
1314
+ const columnExists = Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0;
1315
+ if (!columnExists) {
1316
+ const columnDef = schema[columnName];
1317
+ const sqlType = this.getSqlType(columnDef.type);
1318
+ const nullable = columnDef.nullable === false ? "NOT NULL" : "";
1319
+ const defaultValue = columnDef.nullable === false ? this.getDefaultValue(columnDef.type) : "";
1320
+ const parsedColumnName = utils.parseSqlIdentifier(columnName, "column name");
1321
+ const alterSql = `ALTER TABLE ${fullTableName} ADD [${parsedColumnName}] ${sqlType} ${nullable} ${defaultValue}`.trim();
1322
+ await this.pool.request().query(alterSql);
1323
+ this.logger?.debug?.(`Ensured column ${parsedColumnName} exists in table ${fullTableName}`);
1324
+ }
1325
+ }
1326
+ }
1327
+ } catch (error$1) {
1328
+ throw new error.MastraError(
1329
+ {
1330
+ id: "MASTRA_STORAGE_MSSQL_STORE_ALTER_TABLE_FAILED",
1331
+ domain: error.ErrorDomain.STORAGE,
1332
+ category: error.ErrorCategory.THIRD_PARTY,
1333
+ details: {
1334
+ tableName
1335
+ }
1336
+ },
1337
+ error$1
1338
+ );
1339
+ }
1340
+ }
1341
+ async load({ tableName, keys }) {
1342
+ try {
1343
+ const keyEntries = Object.entries(keys).map(([key, value]) => [utils.parseSqlIdentifier(key, "column name"), value]);
1344
+ const conditions = keyEntries.map(([key], i) => `[${key}] = @param${i}`).join(" AND ");
1345
+ const values = keyEntries.map(([_, value]) => value);
1346
+ const sql7 = `SELECT * FROM ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} WHERE ${conditions}`;
1347
+ const request = this.pool.request();
1348
+ values.forEach((value, i) => {
1349
+ request.input(`param${i}`, value);
1350
+ });
1351
+ const resultSet = await request.query(sql7);
1352
+ const result = resultSet.recordset[0] || null;
1353
+ if (!result) {
1354
+ return null;
1355
+ }
1356
+ if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT) {
1357
+ const snapshot = result;
1358
+ if (typeof snapshot.snapshot === "string") {
1359
+ snapshot.snapshot = JSON.parse(snapshot.snapshot);
1360
+ }
1361
+ return snapshot;
1362
+ }
1363
+ return result;
1364
+ } catch (error$1) {
1365
+ throw new error.MastraError(
1366
+ {
1367
+ id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_FAILED",
1368
+ domain: error.ErrorDomain.STORAGE,
1369
+ category: error.ErrorCategory.THIRD_PARTY,
1370
+ details: {
1371
+ tableName
1372
+ }
1373
+ },
1374
+ error$1
1375
+ );
1376
+ }
1377
+ }
1378
+ async batchInsert({ tableName, records }) {
1379
+ const transaction = this.pool.transaction();
1380
+ try {
1381
+ await transaction.begin();
1382
+ for (const record of records) {
1383
+ await this.insert({ tableName, record });
1384
+ }
1385
+ await transaction.commit();
1386
+ } catch (error$1) {
1387
+ await transaction.rollback();
1388
+ throw new error.MastraError(
1389
+ {
1390
+ id: "MASTRA_STORAGE_MSSQL_STORE_BATCH_INSERT_FAILED",
1391
+ domain: error.ErrorDomain.STORAGE,
1392
+ category: error.ErrorCategory.THIRD_PARTY,
1393
+ details: {
1394
+ tableName,
1395
+ numberOfRecords: records.length
1396
+ }
1397
+ },
1398
+ error$1
1399
+ );
1400
+ }
1401
+ }
1402
+ async dropTable({ tableName }) {
1403
+ try {
1404
+ const tableNameWithSchema = getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) });
1405
+ await this.pool.request().query(`DROP TABLE IF EXISTS ${tableNameWithSchema}`);
1406
+ } catch (error$1) {
1407
+ throw new error.MastraError(
1408
+ {
1409
+ id: "MASTRA_STORAGE_MSSQL_STORE_DROP_TABLE_FAILED",
1410
+ domain: error.ErrorDomain.STORAGE,
1411
+ category: error.ErrorCategory.THIRD_PARTY,
1412
+ details: {
1413
+ tableName
1414
+ }
1415
+ },
1416
+ error$1
1417
+ );
1418
+ }
1419
+ }
1420
+ };
1421
+ function parseJSON(jsonString) {
1422
+ try {
1423
+ return JSON.parse(jsonString);
1424
+ } catch {
1425
+ return jsonString;
1426
+ }
1427
+ }
1428
+ function transformScoreRow(row) {
1429
+ return {
1430
+ ...row,
1431
+ input: parseJSON(row.input),
1432
+ scorer: parseJSON(row.scorer),
1433
+ preprocessStepResult: parseJSON(row.preprocessStepResult),
1434
+ analyzeStepResult: parseJSON(row.analyzeStepResult),
1435
+ metadata: parseJSON(row.metadata),
1436
+ output: parseJSON(row.output),
1437
+ additionalContext: parseJSON(row.additionalContext),
1438
+ runtimeContext: parseJSON(row.runtimeContext),
1439
+ entity: parseJSON(row.entity),
1440
+ createdAt: row.createdAt,
1441
+ updatedAt: row.updatedAt
1442
+ };
1443
+ }
1444
+ var ScoresMSSQL = class extends storage.ScoresStorage {
1445
+ pool;
1446
+ operations;
1447
+ schema;
1448
+ constructor({
1449
+ pool,
1450
+ operations,
1451
+ schema
1452
+ }) {
1453
+ super();
1454
+ this.pool = pool;
1455
+ this.operations = operations;
1456
+ this.schema = schema;
1457
+ }
1458
+ async getScoreById({ id }) {
1459
+ try {
1460
+ const request = this.pool.request();
1461
+ request.input("p1", id);
1462
+ const result = await request.query(
1463
+ `SELECT * FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE id = @p1`
1464
+ );
1465
+ if (result.recordset.length === 0) {
1466
+ return null;
1467
+ }
1468
+ return transformScoreRow(result.recordset[0]);
1469
+ } catch (error$1) {
1470
+ throw new error.MastraError(
1471
+ {
1472
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORE_BY_ID_FAILED",
1473
+ domain: error.ErrorDomain.STORAGE,
1474
+ category: error.ErrorCategory.THIRD_PARTY,
1475
+ details: { id }
1476
+ },
1477
+ error$1
1478
+ );
1479
+ }
1480
+ }
1481
+ async saveScore(score) {
1482
+ try {
1483
+ const scoreId = crypto.randomUUID();
1484
+ const {
1485
+ scorer,
1486
+ preprocessStepResult,
1487
+ analyzeStepResult,
1488
+ metadata,
1489
+ input,
1490
+ output,
1491
+ additionalContext,
1492
+ runtimeContext,
1493
+ entity,
1494
+ ...rest
1495
+ } = score;
1496
+ await this.operations.insert({
1497
+ tableName: storage.TABLE_SCORERS,
1498
+ record: {
1499
+ id: scoreId,
1500
+ ...rest,
1501
+ input: JSON.stringify(input) || "",
1502
+ output: JSON.stringify(output) || "",
1503
+ preprocessStepResult: preprocessStepResult ? JSON.stringify(preprocessStepResult) : null,
1504
+ analyzeStepResult: analyzeStepResult ? JSON.stringify(analyzeStepResult) : null,
1505
+ metadata: metadata ? JSON.stringify(metadata) : null,
1506
+ additionalContext: additionalContext ? JSON.stringify(additionalContext) : null,
1507
+ runtimeContext: runtimeContext ? JSON.stringify(runtimeContext) : null,
1508
+ entity: entity ? JSON.stringify(entity) : null,
1509
+ scorer: scorer ? JSON.stringify(scorer) : null,
1510
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1511
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1512
+ }
1513
+ });
1514
+ const scoreFromDb = await this.getScoreById({ id: scoreId });
1515
+ return { score: scoreFromDb };
1516
+ } catch (error$1) {
1517
+ throw new error.MastraError(
1518
+ {
1519
+ id: "MASTRA_STORAGE_MSSQL_STORE_SAVE_SCORE_FAILED",
1520
+ domain: error.ErrorDomain.STORAGE,
1521
+ category: error.ErrorCategory.THIRD_PARTY
1522
+ },
1523
+ error$1
1524
+ );
1525
+ }
1526
+ }
1527
+ async getScoresByScorerId({
1528
+ scorerId,
1529
+ pagination
1530
+ }) {
1531
+ try {
1532
+ const request = this.pool.request();
1533
+ request.input("p1", scorerId);
1534
+ const totalResult = await request.query(
1535
+ `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [scorerId] = @p1`
1536
+ );
1537
+ const total = totalResult.recordset[0]?.count || 0;
1538
+ if (total === 0) {
1539
+ return {
1540
+ pagination: {
1541
+ total: 0,
1542
+ page: pagination.page,
1543
+ perPage: pagination.perPage,
1544
+ hasMore: false
1545
+ },
1546
+ scores: []
1547
+ };
1548
+ }
1549
+ const dataRequest = this.pool.request();
1550
+ dataRequest.input("p1", scorerId);
1551
+ dataRequest.input("p2", pagination.perPage);
1552
+ dataRequest.input("p3", pagination.page * pagination.perPage);
1553
+ const result = await dataRequest.query(
1554
+ `SELECT * FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [scorerId] = @p1 ORDER BY [createdAt] DESC OFFSET @p3 ROWS FETCH NEXT @p2 ROWS ONLY`
1555
+ );
1556
+ return {
1557
+ pagination: {
1558
+ total: Number(total),
1559
+ page: pagination.page,
1560
+ perPage: pagination.perPage,
1561
+ hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
1562
+ },
1563
+ scores: result.recordset.map((row) => transformScoreRow(row))
1564
+ };
1565
+ } catch (error$1) {
1566
+ throw new error.MastraError(
1567
+ {
1568
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_SCORER_ID_FAILED",
1569
+ domain: error.ErrorDomain.STORAGE,
1570
+ category: error.ErrorCategory.THIRD_PARTY,
1571
+ details: { scorerId }
1572
+ },
1573
+ error$1
1574
+ );
1575
+ }
1576
+ }
1577
+ async getScoresByRunId({
1578
+ runId,
1579
+ pagination
1580
+ }) {
1581
+ try {
1582
+ const request = this.pool.request();
1583
+ request.input("p1", runId);
1584
+ const totalResult = await request.query(
1585
+ `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [runId] = @p1`
1586
+ );
1587
+ const total = totalResult.recordset[0]?.count || 0;
1588
+ if (total === 0) {
1589
+ return {
1590
+ pagination: {
1591
+ total: 0,
1592
+ page: pagination.page,
1593
+ perPage: pagination.perPage,
1594
+ hasMore: false
1595
+ },
1596
+ scores: []
1597
+ };
1598
+ }
1599
+ const dataRequest = this.pool.request();
1600
+ dataRequest.input("p1", runId);
1601
+ dataRequest.input("p2", pagination.perPage);
1602
+ dataRequest.input("p3", pagination.page * pagination.perPage);
1603
+ const result = await dataRequest.query(
1604
+ `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`
1605
+ );
1606
+ return {
1607
+ pagination: {
1608
+ total: Number(total),
1609
+ page: pagination.page,
1610
+ perPage: pagination.perPage,
1611
+ hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
1612
+ },
1613
+ scores: result.recordset.map((row) => transformScoreRow(row))
1614
+ };
1615
+ } catch (error$1) {
1616
+ throw new error.MastraError(
1617
+ {
1618
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_RUN_ID_FAILED",
1619
+ domain: error.ErrorDomain.STORAGE,
1620
+ category: error.ErrorCategory.THIRD_PARTY,
1621
+ details: { runId }
1622
+ },
1623
+ error$1
1624
+ );
1625
+ }
1626
+ }
1627
+ async getScoresByEntityId({
1628
+ entityId,
1629
+ entityType,
1630
+ pagination
1631
+ }) {
1632
+ try {
1633
+ const request = this.pool.request();
1634
+ request.input("p1", entityId);
1635
+ request.input("p2", entityType);
1636
+ const totalResult = await request.query(
1637
+ `SELECT COUNT(*) as count FROM ${getTableName({ indexName: storage.TABLE_SCORERS, schemaName: getSchemaName(this.schema) })} WHERE [entityId] = @p1 AND [entityType] = @p2`
1638
+ );
1639
+ const total = totalResult.recordset[0]?.count || 0;
1640
+ if (total === 0) {
1641
+ return {
1642
+ pagination: {
1643
+ total: 0,
1644
+ page: pagination.page,
1645
+ perPage: pagination.perPage,
1646
+ hasMore: false
1647
+ },
1648
+ scores: []
1649
+ };
1650
+ }
1651
+ const dataRequest = this.pool.request();
1652
+ dataRequest.input("p1", entityId);
1653
+ dataRequest.input("p2", entityType);
1654
+ dataRequest.input("p3", pagination.perPage);
1655
+ dataRequest.input("p4", pagination.page * pagination.perPage);
1656
+ const result = await dataRequest.query(
1657
+ `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`
1658
+ );
1659
+ return {
1660
+ pagination: {
1661
+ total: Number(total),
1662
+ page: pagination.page,
1663
+ perPage: pagination.perPage,
1664
+ hasMore: Number(total) > (pagination.page + 1) * pagination.perPage
1665
+ },
1666
+ scores: result.recordset.map((row) => transformScoreRow(row))
1667
+ };
1668
+ } catch (error$1) {
1669
+ throw new error.MastraError(
1670
+ {
1671
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_SCORES_BY_ENTITY_ID_FAILED",
1672
+ domain: error.ErrorDomain.STORAGE,
1673
+ category: error.ErrorCategory.THIRD_PARTY,
1674
+ details: { entityId, entityType }
1675
+ },
1676
+ error$1
1677
+ );
1678
+ }
1679
+ }
1680
+ };
1681
+ var TracesMSSQL = class extends storage.TracesStorage {
1682
+ pool;
1683
+ operations;
1684
+ schema;
1685
+ constructor({
1686
+ pool,
1687
+ operations,
1688
+ schema
1689
+ }) {
1690
+ super();
1691
+ this.pool = pool;
1692
+ this.operations = operations;
1693
+ this.schema = schema;
1694
+ }
1695
+ /** @deprecated use getTracesPaginated instead*/
1696
+ async getTraces(args) {
1697
+ if (args.fromDate || args.toDate) {
1698
+ args.dateRange = {
1699
+ start: args.fromDate,
1700
+ end: args.toDate
1701
+ };
1702
+ }
1703
+ const result = await this.getTracesPaginated(args);
1704
+ return result.traces;
1705
+ }
1706
+ async getTracesPaginated(args) {
1707
+ const { name, scope, page = 0, perPage: perPageInput, attributes, filters, dateRange } = args;
1708
+ const fromDate = dateRange?.start;
1709
+ const toDate = dateRange?.end;
1710
+ const perPage = perPageInput !== void 0 ? perPageInput : 100;
1711
+ const currentOffset = page * perPage;
1712
+ const paramMap = {};
1713
+ const conditions = [];
1714
+ let paramIndex = 1;
1715
+ if (name) {
1716
+ const paramName = `p${paramIndex++}`;
1717
+ conditions.push(`[name] LIKE @${paramName}`);
1718
+ paramMap[paramName] = `${name}%`;
1719
+ }
1720
+ if (scope) {
1721
+ const paramName = `p${paramIndex++}`;
1722
+ conditions.push(`[scope] = @${paramName}`);
1723
+ paramMap[paramName] = scope;
1724
+ }
1725
+ if (attributes) {
1726
+ Object.entries(attributes).forEach(([key, value]) => {
1727
+ const parsedKey = utils.parseFieldKey(key);
1728
+ const paramName = `p${paramIndex++}`;
1729
+ conditions.push(`JSON_VALUE([attributes], '$.${parsedKey}') = @${paramName}`);
1730
+ paramMap[paramName] = value;
1731
+ });
1732
+ }
1733
+ if (filters) {
1734
+ Object.entries(filters).forEach(([key, value]) => {
1735
+ const parsedKey = utils.parseFieldKey(key);
1736
+ const paramName = `p${paramIndex++}`;
1737
+ conditions.push(`[${parsedKey}] = @${paramName}`);
1738
+ paramMap[paramName] = value;
1739
+ });
1740
+ }
1741
+ if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
1742
+ const paramName = `p${paramIndex++}`;
1743
+ conditions.push(`[createdAt] >= @${paramName}`);
1744
+ paramMap[paramName] = fromDate.toISOString();
1745
+ }
1746
+ if (toDate instanceof Date && !isNaN(toDate.getTime())) {
1747
+ const paramName = `p${paramIndex++}`;
1748
+ conditions.push(`[createdAt] <= @${paramName}`);
1749
+ paramMap[paramName] = toDate.toISOString();
1750
+ }
1751
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1752
+ const countQuery = `SELECT COUNT(*) as total FROM ${getTableName({ indexName: storage.TABLE_TRACES, schemaName: getSchemaName(this.schema) })} ${whereClause}`;
1753
+ let total = 0;
1754
+ try {
1755
+ const countRequest = this.pool.request();
1756
+ Object.entries(paramMap).forEach(([key, value]) => {
1757
+ if (value instanceof Date) {
1758
+ countRequest.input(key, sql2__default.default.DateTime, value);
1759
+ } else {
1760
+ countRequest.input(key, value);
1761
+ }
1762
+ });
1763
+ const countResult = await countRequest.query(countQuery);
1764
+ total = parseInt(countResult.recordset[0].total, 10);
1765
+ } catch (error$1) {
1766
+ throw new error.MastraError(
1767
+ {
1768
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TOTAL_COUNT",
1769
+ domain: error.ErrorDomain.STORAGE,
1770
+ category: error.ErrorCategory.THIRD_PARTY,
1771
+ details: {
1772
+ name: args.name ?? "",
1773
+ scope: args.scope ?? ""
1774
+ }
1775
+ },
1776
+ error$1
1777
+ );
1778
+ }
1779
+ if (total === 0) {
1780
+ return {
1781
+ traces: [],
1782
+ total: 0,
1783
+ page,
1784
+ perPage,
1785
+ hasMore: false
1786
+ };
1787
+ }
1788
+ 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`;
1789
+ const dataRequest = this.pool.request();
1790
+ Object.entries(paramMap).forEach(([key, value]) => {
1791
+ if (value instanceof Date) {
1792
+ dataRequest.input(key, sql2__default.default.DateTime, value);
1793
+ } else {
1794
+ dataRequest.input(key, value);
1795
+ }
1796
+ });
1797
+ dataRequest.input("offset", currentOffset);
1798
+ dataRequest.input("limit", perPage);
1799
+ try {
1800
+ const rowsResult = await dataRequest.query(dataQuery);
1801
+ const rows = rowsResult.recordset;
1802
+ const traces = rows.map((row) => ({
1803
+ id: row.id,
1804
+ parentSpanId: row.parentSpanId,
1805
+ traceId: row.traceId,
1806
+ name: row.name,
1807
+ scope: row.scope,
1808
+ kind: row.kind,
1809
+ status: JSON.parse(row.status),
1810
+ events: JSON.parse(row.events),
1811
+ links: JSON.parse(row.links),
1812
+ attributes: JSON.parse(row.attributes),
1813
+ startTime: row.startTime,
1814
+ endTime: row.endTime,
1815
+ other: row.other,
1816
+ createdAt: row.createdAt
1817
+ }));
1818
+ return {
1819
+ traces,
1820
+ total,
1821
+ page,
1822
+ perPage,
1823
+ hasMore: currentOffset + traces.length < total
1824
+ };
1825
+ } catch (error$1) {
1826
+ throw new error.MastraError(
1827
+ {
1828
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_TRACES_PAGINATED_FAILED_TO_RETRIEVE_TRACES",
1829
+ domain: error.ErrorDomain.STORAGE,
1830
+ category: error.ErrorCategory.THIRD_PARTY,
1831
+ details: {
1832
+ name: args.name ?? "",
1833
+ scope: args.scope ?? ""
1834
+ }
1835
+ },
1836
+ error$1
1837
+ );
1838
+ }
1839
+ }
1840
+ async batchTraceInsert({ records }) {
1841
+ this.logger.debug("Batch inserting traces", { count: records.length });
1842
+ await this.operations.batchInsert({
1843
+ tableName: storage.TABLE_TRACES,
1844
+ records
1845
+ });
1846
+ }
1847
+ };
1848
+ function parseWorkflowRun(row) {
1849
+ let parsedSnapshot = row.snapshot;
1850
+ if (typeof parsedSnapshot === "string") {
1851
+ try {
1852
+ parsedSnapshot = JSON.parse(row.snapshot);
1853
+ } catch (e) {
1854
+ console.warn(`Failed to parse snapshot for workflow ${row.workflow_name}: ${e}`);
1855
+ }
1856
+ }
1857
+ return {
1858
+ workflowName: row.workflow_name,
1859
+ runId: row.run_id,
1860
+ snapshot: parsedSnapshot,
1861
+ createdAt: row.createdAt,
1862
+ updatedAt: row.updatedAt,
1863
+ resourceId: row.resourceId
1864
+ };
1865
+ }
1866
+ var WorkflowsMSSQL = class extends storage.WorkflowsStorage {
1867
+ pool;
1868
+ operations;
1869
+ schema;
1870
+ constructor({
1871
+ pool,
1872
+ operations,
1873
+ schema
1874
+ }) {
1875
+ super();
1876
+ this.pool = pool;
1877
+ this.operations = operations;
1878
+ this.schema = schema;
1879
+ }
1880
+ updateWorkflowResults({
1881
+ // workflowName,
1882
+ // runId,
1883
+ // stepId,
1884
+ // result,
1885
+ // runtimeContext,
1886
+ }) {
1887
+ throw new Error("Method not implemented.");
1888
+ }
1889
+ updateWorkflowState({
1890
+ // workflowName,
1891
+ // runId,
1892
+ // opts,
1893
+ }) {
1894
+ throw new Error("Method not implemented.");
1895
+ }
1896
+ async persistWorkflowSnapshot({
1897
+ workflowName,
1898
+ runId,
1899
+ snapshot
1900
+ }) {
1901
+ const table = getTableName({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
1902
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1903
+ try {
1904
+ const request = this.pool.request();
1905
+ request.input("workflow_name", workflowName);
1906
+ request.input("run_id", runId);
1907
+ request.input("snapshot", JSON.stringify(snapshot));
1908
+ request.input("createdAt", sql2__default.default.DateTime2, new Date(now));
1909
+ request.input("updatedAt", sql2__default.default.DateTime2, new Date(now));
1910
+ const mergeSql = `MERGE INTO ${table} AS target
1911
+ USING (SELECT @workflow_name AS workflow_name, @run_id AS run_id) AS src
1912
+ ON target.workflow_name = src.workflow_name AND target.run_id = src.run_id
1913
+ WHEN MATCHED THEN UPDATE SET
1914
+ snapshot = @snapshot,
1915
+ [updatedAt] = @updatedAt
1916
+ WHEN NOT MATCHED THEN INSERT (workflow_name, run_id, snapshot, [createdAt], [updatedAt])
1917
+ VALUES (@workflow_name, @run_id, @snapshot, @createdAt, @updatedAt);`;
1918
+ await request.query(mergeSql);
1919
+ } catch (error$1) {
1920
+ throw new error.MastraError(
1921
+ {
1922
+ id: "MASTRA_STORAGE_MSSQL_STORE_PERSIST_WORKFLOW_SNAPSHOT_FAILED",
1923
+ domain: error.ErrorDomain.STORAGE,
1924
+ category: error.ErrorCategory.THIRD_PARTY,
1925
+ details: {
1926
+ workflowName,
1927
+ runId
1928
+ }
1929
+ },
1930
+ error$1
1931
+ );
1932
+ }
1933
+ }
1934
+ async loadWorkflowSnapshot({
1935
+ workflowName,
1936
+ runId
1937
+ }) {
1938
+ try {
1939
+ const result = await this.operations.load({
1940
+ tableName: storage.TABLE_WORKFLOW_SNAPSHOT,
1941
+ keys: {
1942
+ workflow_name: workflowName,
1943
+ run_id: runId
1944
+ }
1945
+ });
1946
+ if (!result) {
1947
+ return null;
1948
+ }
1949
+ return result.snapshot;
1950
+ } catch (error$1) {
1951
+ throw new error.MastraError(
1952
+ {
1953
+ id: "MASTRA_STORAGE_MSSQL_STORE_LOAD_WORKFLOW_SNAPSHOT_FAILED",
1954
+ domain: error.ErrorDomain.STORAGE,
1955
+ category: error.ErrorCategory.THIRD_PARTY,
1956
+ details: {
1957
+ workflowName,
1958
+ runId
1959
+ }
1960
+ },
1961
+ error$1
1962
+ );
1963
+ }
1964
+ }
1965
+ async getWorkflowRunById({
1966
+ runId,
1967
+ workflowName
1968
+ }) {
1969
+ try {
1970
+ const conditions = [];
1971
+ const paramMap = {};
1972
+ if (runId) {
1973
+ conditions.push(`[run_id] = @runId`);
1974
+ paramMap["runId"] = runId;
1975
+ }
1976
+ if (workflowName) {
1977
+ conditions.push(`[workflow_name] = @workflowName`);
1978
+ paramMap["workflowName"] = workflowName;
1979
+ }
1980
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
1981
+ const tableName = getTableName({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
1982
+ const query = `SELECT * FROM ${tableName} ${whereClause}`;
1983
+ const request = this.pool.request();
1984
+ Object.entries(paramMap).forEach(([key, value]) => request.input(key, value));
1985
+ const result = await request.query(query);
1986
+ if (!result.recordset || result.recordset.length === 0) {
1987
+ return null;
1988
+ }
1989
+ return parseWorkflowRun(result.recordset[0]);
1990
+ } catch (error$1) {
1991
+ throw new error.MastraError(
1992
+ {
1993
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUN_BY_ID_FAILED",
1994
+ domain: error.ErrorDomain.STORAGE,
1995
+ category: error.ErrorCategory.THIRD_PARTY,
1996
+ details: {
1997
+ runId,
1998
+ workflowName: workflowName || ""
1999
+ }
2000
+ },
2001
+ error$1
2002
+ );
2003
+ }
2004
+ }
2005
+ async getWorkflowRuns({
2006
+ workflowName,
2007
+ fromDate,
2008
+ toDate,
2009
+ limit,
2010
+ offset,
2011
+ resourceId
2012
+ } = {}) {
2013
+ try {
2014
+ const conditions = [];
2015
+ const paramMap = {};
2016
+ if (workflowName) {
2017
+ conditions.push(`[workflow_name] = @workflowName`);
2018
+ paramMap["workflowName"] = workflowName;
2019
+ }
2020
+ if (resourceId) {
2021
+ const hasResourceId = await this.operations.hasColumn(storage.TABLE_WORKFLOW_SNAPSHOT, "resourceId");
2022
+ if (hasResourceId) {
2023
+ conditions.push(`[resourceId] = @resourceId`);
2024
+ paramMap["resourceId"] = resourceId;
2025
+ } else {
2026
+ console.warn(`[${storage.TABLE_WORKFLOW_SNAPSHOT}] resourceId column not found. Skipping resourceId filter.`);
2027
+ }
2028
+ }
2029
+ if (fromDate instanceof Date && !isNaN(fromDate.getTime())) {
2030
+ conditions.push(`[createdAt] >= @fromDate`);
2031
+ paramMap[`fromDate`] = fromDate.toISOString();
2032
+ }
2033
+ if (toDate instanceof Date && !isNaN(toDate.getTime())) {
2034
+ conditions.push(`[createdAt] <= @toDate`);
2035
+ paramMap[`toDate`] = toDate.toISOString();
2036
+ }
2037
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2038
+ let total = 0;
2039
+ const tableName = getTableName({ indexName: storage.TABLE_WORKFLOW_SNAPSHOT, schemaName: getSchemaName(this.schema) });
2040
+ const request = this.pool.request();
2041
+ Object.entries(paramMap).forEach(([key, value]) => {
2042
+ if (value instanceof Date) {
2043
+ request.input(key, sql2__default.default.DateTime, value);
2044
+ } else {
2045
+ request.input(key, value);
2046
+ }
2047
+ });
2048
+ if (limit !== void 0 && offset !== void 0) {
2049
+ const countQuery = `SELECT COUNT(*) as count FROM ${tableName} ${whereClause}`;
2050
+ const countResult = await request.query(countQuery);
2051
+ total = Number(countResult.recordset[0]?.count || 0);
2052
+ }
2053
+ let query = `SELECT * FROM ${tableName} ${whereClause} ORDER BY [seq_id] DESC`;
2054
+ if (limit !== void 0 && offset !== void 0) {
2055
+ query += ` OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`;
2056
+ request.input("limit", limit);
2057
+ request.input("offset", offset);
2058
+ }
2059
+ const result = await request.query(query);
2060
+ const runs = (result.recordset || []).map((row) => parseWorkflowRun(row));
2061
+ return { runs, total: total || runs.length };
2062
+ } catch (error$1) {
2063
+ throw new error.MastraError(
2064
+ {
2065
+ id: "MASTRA_STORAGE_MSSQL_STORE_GET_WORKFLOW_RUNS_FAILED",
2066
+ domain: error.ErrorDomain.STORAGE,
2067
+ category: error.ErrorCategory.THIRD_PARTY,
2068
+ details: {
2069
+ workflowName: workflowName || "all"
2070
+ }
2071
+ },
2072
+ error$1
2073
+ );
2074
+ }
2075
+ }
2076
+ };
2077
+
2078
+ // src/storage/index.ts
2079
+ var MSSQLStore = class extends storage.MastraStorage {
2080
+ pool;
2081
+ schema;
2082
+ isConnected = null;
2083
+ stores;
2084
+ constructor(config) {
2085
+ super({ name: "MSSQLStore" });
2086
+ try {
2087
+ if ("connectionString" in config) {
2088
+ if (!config.connectionString || typeof config.connectionString !== "string" || config.connectionString.trim() === "") {
2089
+ throw new Error("MSSQLStore: connectionString must be provided and cannot be empty.");
2090
+ }
2091
+ } else {
2092
+ const required = ["server", "database", "user", "password"];
2093
+ for (const key of required) {
2094
+ if (!(key in config) || typeof config[key] !== "string" || config[key].trim() === "") {
2095
+ throw new Error(`MSSQLStore: ${key} must be provided and cannot be empty.`);
2096
+ }
2097
+ }
2098
+ }
2099
+ this.schema = config.schemaName || "dbo";
2100
+ this.pool = "connectionString" in config ? new sql2__default.default.ConnectionPool(config.connectionString) : new sql2__default.default.ConnectionPool({
2101
+ server: config.server,
2102
+ database: config.database,
2103
+ user: config.user,
2104
+ password: config.password,
2105
+ port: config.port,
2106
+ options: config.options || { encrypt: true, trustServerCertificate: true }
2107
+ });
2108
+ const legacyEvals = new LegacyEvalsMSSQL({ pool: this.pool, schema: this.schema });
2109
+ const operations = new StoreOperationsMSSQL({ pool: this.pool, schemaName: this.schema });
2110
+ const scores = new ScoresMSSQL({ pool: this.pool, operations, schema: this.schema });
2111
+ const traces = new TracesMSSQL({ pool: this.pool, operations, schema: this.schema });
2112
+ const workflows = new WorkflowsMSSQL({ pool: this.pool, operations, schema: this.schema });
2113
+ const memory = new MemoryMSSQL({ pool: this.pool, schema: this.schema, operations });
2114
+ this.stores = {
2115
+ operations,
2116
+ scores,
2117
+ traces,
2118
+ workflows,
2119
+ legacyEvals,
2120
+ memory
2121
+ };
2122
+ } catch (e) {
2123
+ throw new error.MastraError(
2124
+ {
2125
+ id: "MASTRA_STORAGE_MSSQL_STORE_INITIALIZATION_FAILED",
2126
+ domain: error.ErrorDomain.STORAGE,
2127
+ category: error.ErrorCategory.USER
2128
+ },
2129
+ e
2130
+ );
2131
+ }
2132
+ }
2133
+ async init() {
2134
+ if (this.isConnected === null) {
2135
+ this.isConnected = this._performInitializationAndStore();
2136
+ }
2137
+ try {
2138
+ await this.isConnected;
2139
+ await super.init();
2140
+ } catch (error$1) {
2141
+ this.isConnected = null;
2142
+ throw new error.MastraError(
2143
+ {
2144
+ id: "MASTRA_STORAGE_MSSQL_STORE_INIT_FAILED",
2145
+ domain: error.ErrorDomain.STORAGE,
2146
+ category: error.ErrorCategory.THIRD_PARTY
2147
+ },
2148
+ error$1
2149
+ );
2150
+ }
2151
+ }
2152
+ async _performInitializationAndStore() {
2153
+ try {
2154
+ await this.pool.connect();
2155
+ return true;
2156
+ } catch (err) {
2157
+ throw err;
2158
+ }
2159
+ }
2160
+ get supports() {
2161
+ return {
2162
+ selectByIncludeResourceScope: true,
2163
+ resourceWorkingMemory: true,
2164
+ hasColumn: true,
2165
+ createTable: true,
2166
+ deleteMessages: true
2167
+ };
2168
+ }
2169
+ /** @deprecated use getEvals instead */
2170
+ async getEvalsByAgentName(agentName, type) {
2171
+ return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2172
+ }
2173
+ async getEvals(options = {}) {
2174
+ return this.stores.legacyEvals.getEvals(options);
2175
+ }
2176
+ /**
2177
+ * @deprecated use getTracesPaginated instead
2178
+ */
2179
+ async getTraces(args) {
2180
+ return this.stores.traces.getTraces(args);
2181
+ }
2182
+ async getTracesPaginated(args) {
2183
+ return this.stores.traces.getTracesPaginated(args);
2184
+ }
2185
+ async batchTraceInsert({ records }) {
2186
+ return this.stores.traces.batchTraceInsert({ records });
2187
+ }
2188
+ async createTable({
2189
+ tableName,
2190
+ schema
2191
+ }) {
2192
+ return this.stores.operations.createTable({ tableName, schema });
2193
+ }
2194
+ async alterTable({
2195
+ tableName,
2196
+ schema,
2197
+ ifNotExists
2198
+ }) {
2199
+ return this.stores.operations.alterTable({ tableName, schema, ifNotExists });
2200
+ }
2201
+ async clearTable({ tableName }) {
2202
+ return this.stores.operations.clearTable({ tableName });
2203
+ }
2204
+ async dropTable({ tableName }) {
2205
+ return this.stores.operations.dropTable({ tableName });
2206
+ }
2207
+ async insert({ tableName, record }) {
2208
+ return this.stores.operations.insert({ tableName, record });
2209
+ }
2210
+ async batchInsert({ tableName, records }) {
2211
+ return this.stores.operations.batchInsert({ tableName, records });
2212
+ }
2213
+ async load({ tableName, keys }) {
2214
+ return this.stores.operations.load({ tableName, keys });
2215
+ }
2216
+ /**
2217
+ * Memory
2218
+ */
2219
+ async getThreadById({ threadId }) {
2220
+ return this.stores.memory.getThreadById({ threadId });
2221
+ }
2222
+ /**
2223
+ * @deprecated use getThreadsByResourceIdPaginated instead
2224
+ */
2225
+ async getThreadsByResourceId(args) {
2226
+ return this.stores.memory.getThreadsByResourceId(args);
2227
+ }
2228
+ async getThreadsByResourceIdPaginated(args) {
2229
+ return this.stores.memory.getThreadsByResourceIdPaginated(args);
2230
+ }
2231
+ async saveThread({ thread }) {
2232
+ return this.stores.memory.saveThread({ thread });
2233
+ }
2234
+ async updateThread({
2235
+ id,
2236
+ title,
2237
+ metadata
2238
+ }) {
2239
+ return this.stores.memory.updateThread({ id, title, metadata });
2240
+ }
2241
+ async deleteThread({ threadId }) {
2242
+ return this.stores.memory.deleteThread({ threadId });
2243
+ }
2244
+ async getMessages(args) {
2245
+ return this.stores.memory.getMessages(args);
2246
+ }
2247
+ async getMessagesById({
2248
+ messageIds,
2249
+ format
2250
+ }) {
2251
+ return this.stores.memory.getMessagesById({ messageIds, format });
2252
+ }
2253
+ async getMessagesPaginated(args) {
2254
+ return this.stores.memory.getMessagesPaginated(args);
2255
+ }
2256
+ async saveMessages(args) {
2257
+ return this.stores.memory.saveMessages(args);
2258
+ }
2259
+ async updateMessages({
2260
+ messages
2261
+ }) {
2262
+ return this.stores.memory.updateMessages({ messages });
2263
+ }
2264
+ async deleteMessages(messageIds) {
2265
+ return this.stores.memory.deleteMessages(messageIds);
2266
+ }
2267
+ async getResourceById({ resourceId }) {
2268
+ return this.stores.memory.getResourceById({ resourceId });
2269
+ }
2270
+ async saveResource({ resource }) {
2271
+ return this.stores.memory.saveResource({ resource });
2272
+ }
2273
+ async updateResource({
2274
+ resourceId,
2275
+ workingMemory,
2276
+ metadata
2277
+ }) {
2278
+ return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
2279
+ }
2280
+ /**
2281
+ * Workflows
2282
+ */
2283
+ async updateWorkflowResults({
2284
+ workflowName,
2285
+ runId,
2286
+ stepId,
2287
+ result,
2288
+ runtimeContext
2289
+ }) {
2290
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2291
+ }
2292
+ async updateWorkflowState({
2293
+ workflowName,
2294
+ runId,
2295
+ opts
2296
+ }) {
2297
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2298
+ }
2299
+ async persistWorkflowSnapshot({
2300
+ workflowName,
2301
+ runId,
2302
+ snapshot
2303
+ }) {
2304
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2305
+ }
2306
+ async loadWorkflowSnapshot({
2307
+ workflowName,
2308
+ runId
2309
+ }) {
2310
+ return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
2311
+ }
2312
+ async getWorkflowRuns({
2313
+ workflowName,
2314
+ fromDate,
2315
+ toDate,
2316
+ limit,
2317
+ offset,
2318
+ resourceId
2319
+ } = {}) {
2320
+ return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
2321
+ }
2322
+ async getWorkflowRunById({
2323
+ runId,
2324
+ workflowName
2325
+ }) {
2326
+ return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
2327
+ }
2328
+ async close() {
2329
+ await this.pool.close();
2330
+ }
2331
+ /**
2332
+ * Scorers
2333
+ */
2334
+ async getScoreById({ id: _id }) {
2335
+ return this.stores.scores.getScoreById({ id: _id });
2336
+ }
2337
+ async getScoresByScorerId({
2338
+ scorerId: _scorerId,
2339
+ pagination: _pagination
2340
+ }) {
2341
+ return this.stores.scores.getScoresByScorerId({ scorerId: _scorerId, pagination: _pagination });
2342
+ }
2343
+ async saveScore(_score) {
2344
+ return this.stores.scores.saveScore(_score);
2345
+ }
2346
+ async getScoresByRunId({
2347
+ runId: _runId,
2348
+ pagination: _pagination
2349
+ }) {
2350
+ return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
2351
+ }
2352
+ async getScoresByEntityId({
2353
+ entityId: _entityId,
2354
+ entityType: _entityType,
2355
+ pagination: _pagination
2356
+ }) {
2357
+ return this.stores.scores.getScoresByEntityId({
2358
+ entityId: _entityId,
2359
+ entityType: _entityType,
2360
+ pagination: _pagination
2361
+ });
2362
+ }
2363
+ };
2364
+
2365
+ exports.MSSQLStore = MSSQLStore;
2366
+ //# sourceMappingURL=index.cjs.map
2367
+ //# sourceMappingURL=index.cjs.map